blob: ce66c3c0fc293540d64d804b3c1bacf24989f9f9 [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
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCall7cd088e2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000026#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor661b4932010-09-12 04:28:07 +000028#include "llvm/ADT/DenseSet.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000029#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000030#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000031#include <algorithm>
32
33namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000034using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000035
John McCallf89e55a2010-11-18 06:31:45 +000036/// A convenience routine for creating a decayed reference to a
37/// function.
38static Expr *
39CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
40 SourceLocation Loc = SourceLocation()) {
41 Expr *E = new (S.Context) DeclRefExpr(Fn, Fn->getType(), VK_LValue, Loc);
42 S.DefaultFunctionArrayConversion(E);
43 return E;
44}
45
John McCall120d63c2010-08-24 20:38:10 +000046static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
47 bool InOverloadResolution,
48 StandardConversionSequence &SCS);
49static OverloadingResult
50IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
51 UserDefinedConversionSequence& User,
52 OverloadCandidateSet& Conversions,
53 bool AllowExplicit);
54
55
56static ImplicitConversionSequence::CompareKind
57CompareStandardConversionSequences(Sema &S,
58 const StandardConversionSequence& SCS1,
59 const StandardConversionSequence& SCS2);
60
61static ImplicitConversionSequence::CompareKind
62CompareQualificationConversions(Sema &S,
63 const StandardConversionSequence& SCS1,
64 const StandardConversionSequence& SCS2);
65
66static ImplicitConversionSequence::CompareKind
67CompareDerivedToBaseConversions(Sema &S,
68 const StandardConversionSequence& SCS1,
69 const StandardConversionSequence& SCS2);
70
71
72
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000073/// GetConversionCategory - Retrieve the implicit conversion
74/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000075ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000076GetConversionCategory(ImplicitConversionKind Kind) {
77 static const ImplicitConversionCategory
78 Category[(int)ICK_Num_Conversion_Kinds] = {
79 ICC_Identity,
80 ICC_Lvalue_Transformation,
81 ICC_Lvalue_Transformation,
82 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +000083 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000084 ICC_Qualification_Adjustment,
85 ICC_Promotion,
86 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000087 ICC_Promotion,
88 ICC_Conversion,
89 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000090 ICC_Conversion,
91 ICC_Conversion,
92 ICC_Conversion,
93 ICC_Conversion,
94 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000095 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000096 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +000097 ICC_Conversion,
98 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000099 ICC_Conversion
100 };
101 return Category[(int)Kind];
102}
103
104/// GetConversionRank - Retrieve the implicit conversion rank
105/// corresponding to the given implicit conversion kind.
106ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
107 static const ImplicitConversionRank
108 Rank[(int)ICK_Num_Conversion_Kinds] = {
109 ICR_Exact_Match,
110 ICR_Exact_Match,
111 ICR_Exact_Match,
112 ICR_Exact_Match,
113 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000114 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000115 ICR_Promotion,
116 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000117 ICR_Promotion,
118 ICR_Conversion,
119 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000120 ICR_Conversion,
121 ICR_Conversion,
122 ICR_Conversion,
123 ICR_Conversion,
124 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000125 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000126 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000127 ICR_Conversion,
128 ICR_Conversion,
Chandler Carruth23a370f2010-02-25 07:20:54 +0000129 ICR_Complex_Real_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000130 };
131 return Rank[(int)Kind];
132}
133
134/// GetImplicitConversionName - Return the name of this kind of
135/// implicit conversion.
136const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000137 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000138 "No conversion",
139 "Lvalue-to-rvalue",
140 "Array-to-pointer",
141 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000142 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000143 "Qualification",
144 "Integral promotion",
145 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000146 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000147 "Integral conversion",
148 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000149 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000150 "Floating-integral conversion",
151 "Pointer conversion",
152 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000153 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000154 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000155 "Derived-to-base conversion",
156 "Vector conversion",
157 "Vector splat",
158 "Complex-real conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000159 };
160 return Name[Kind];
161}
162
Douglas Gregor60d62c22008-10-31 16:23:19 +0000163/// StandardConversionSequence - Set the standard conversion
164/// sequence to the identity conversion.
165void StandardConversionSequence::setAsIdentityConversion() {
166 First = ICK_Identity;
167 Second = ICK_Identity;
168 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000169 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000170 ReferenceBinding = false;
171 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000172 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000173 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000174}
175
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000176/// getRank - Retrieve the rank of this standard conversion sequence
177/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
178/// implicit conversions.
179ImplicitConversionRank StandardConversionSequence::getRank() const {
180 ImplicitConversionRank Rank = ICR_Exact_Match;
181 if (GetConversionRank(First) > Rank)
182 Rank = GetConversionRank(First);
183 if (GetConversionRank(Second) > Rank)
184 Rank = GetConversionRank(Second);
185 if (GetConversionRank(Third) > Rank)
186 Rank = GetConversionRank(Third);
187 return Rank;
188}
189
190/// isPointerConversionToBool - Determines whether this conversion is
191/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000192/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000193/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000194bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000195 // Note that FromType has not necessarily been transformed by the
196 // array-to-pointer or function-to-pointer implicit conversions, so
197 // check for their presence as well as checking whether FromType is
198 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000199 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000200 (getFromType()->isPointerType() ||
201 getFromType()->isObjCObjectPointerType() ||
202 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000203 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000204 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
205 return true;
206
207 return false;
208}
209
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000210/// isPointerConversionToVoidPointer - Determines whether this
211/// conversion is a conversion of a pointer to a void pointer. This is
212/// used as part of the ranking of standard conversion sequences (C++
213/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000214bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000215StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000216isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000217 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000218 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000219
220 // Note that FromType has not necessarily been transformed by the
221 // array-to-pointer implicit conversion, so check for its presence
222 // and redo the conversion to get a pointer.
223 if (First == ICK_Array_To_Pointer)
224 FromType = Context.getArrayDecayedType(FromType);
225
John McCall202422e2010-10-26 06:40:27 +0000226 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000227 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000228 return ToPtrType->getPointeeType()->isVoidType();
229
230 return false;
231}
232
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000233/// DebugPrint - Print this standard conversion sequence to standard
234/// error. Useful for debugging overloading issues.
235void StandardConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000236 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000237 bool PrintedSomething = false;
238 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000239 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000240 PrintedSomething = true;
241 }
242
243 if (Second != ICK_Identity) {
244 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000245 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000246 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000247 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000248
249 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000250 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000251 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000252 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000253 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000254 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000255 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000256 PrintedSomething = true;
257 }
258
259 if (Third != ICK_Identity) {
260 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000261 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000262 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000263 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000264 PrintedSomething = true;
265 }
266
267 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000268 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000269 }
270}
271
272/// DebugPrint - Print this user-defined conversion sequence to standard
273/// error. Useful for debugging overloading issues.
274void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000275 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000276 if (Before.First || Before.Second || Before.Third) {
277 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000278 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000279 }
Benjamin Kramer900fc632010-04-17 09:33:03 +0000280 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000281 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000282 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000283 After.DebugPrint();
284 }
285}
286
287/// DebugPrint - Print this implicit conversion sequence to standard
288/// error. Useful for debugging overloading issues.
289void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000290 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000291 switch (ConversionKind) {
292 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000293 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000294 Standard.DebugPrint();
295 break;
296 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000297 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000298 UserDefined.DebugPrint();
299 break;
300 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000301 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000302 break;
John McCall1d318332010-01-12 00:44:57 +0000303 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000304 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000305 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000306 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000307 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000308 break;
309 }
310
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000311 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000312}
313
John McCall1d318332010-01-12 00:44:57 +0000314void AmbiguousConversionSequence::construct() {
315 new (&conversions()) ConversionSet();
316}
317
318void AmbiguousConversionSequence::destruct() {
319 conversions().~ConversionSet();
320}
321
322void
323AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
324 FromTypePtr = O.FromTypePtr;
325 ToTypePtr = O.ToTypePtr;
326 new (&conversions()) ConversionSet(O.conversions());
327}
328
Douglas Gregora9333192010-05-08 17:41:32 +0000329namespace {
330 // Structure used by OverloadCandidate::DeductionFailureInfo to store
331 // template parameter and template argument information.
332 struct DFIParamWithArguments {
333 TemplateParameter Param;
334 TemplateArgument FirstArg;
335 TemplateArgument SecondArg;
336 };
337}
338
339/// \brief Convert from Sema's representation of template deduction information
340/// to the form used in overload-candidate information.
341OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000342static MakeDeductionFailureInfo(ASTContext &Context,
343 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000344 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000345 OverloadCandidate::DeductionFailureInfo Result;
346 Result.Result = static_cast<unsigned>(TDK);
347 Result.Data = 0;
348 switch (TDK) {
349 case Sema::TDK_Success:
350 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000351 case Sema::TDK_TooManyArguments:
352 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000353 break;
354
355 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000356 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000357 Result.Data = Info.Param.getOpaqueValue();
358 break;
359
Douglas Gregora9333192010-05-08 17:41:32 +0000360 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000361 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000362 // FIXME: Should allocate from normal heap so that we can free this later.
363 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000364 Saved->Param = Info.Param;
365 Saved->FirstArg = Info.FirstArg;
366 Saved->SecondArg = Info.SecondArg;
367 Result.Data = Saved;
368 break;
369 }
370
371 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000372 Result.Data = Info.take();
373 break;
374
Douglas Gregora9333192010-05-08 17:41:32 +0000375 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000376 case Sema::TDK_FailedOverloadResolution:
377 break;
378 }
379
380 return Result;
381}
John McCall1d318332010-01-12 00:44:57 +0000382
Douglas Gregora9333192010-05-08 17:41:32 +0000383void OverloadCandidate::DeductionFailureInfo::Destroy() {
384 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
385 case Sema::TDK_Success:
386 case Sema::TDK_InstantiationDepth:
387 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000388 case Sema::TDK_TooManyArguments:
389 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000390 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000391 break;
392
Douglas Gregora9333192010-05-08 17:41:32 +0000393 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000394 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000395 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000396 Data = 0;
397 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000398
399 case Sema::TDK_SubstitutionFailure:
400 // FIXME: Destroy the template arugment list?
401 Data = 0;
402 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000403
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000404 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000405 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000406 case Sema::TDK_FailedOverloadResolution:
407 break;
408 }
409}
410
411TemplateParameter
412OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
413 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
414 case Sema::TDK_Success:
415 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000416 case Sema::TDK_TooManyArguments:
417 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000418 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000419 return TemplateParameter();
420
421 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000422 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000423 return TemplateParameter::getFromOpaqueValue(Data);
424
425 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000426 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000427 return static_cast<DFIParamWithArguments*>(Data)->Param;
428
429 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000430 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000431 case Sema::TDK_FailedOverloadResolution:
432 break;
433 }
434
435 return TemplateParameter();
436}
Douglas Gregorec20f462010-05-08 20:07:26 +0000437
438TemplateArgumentList *
439OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
440 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
441 case Sema::TDK_Success:
442 case Sema::TDK_InstantiationDepth:
443 case Sema::TDK_TooManyArguments:
444 case Sema::TDK_TooFewArguments:
445 case Sema::TDK_Incomplete:
446 case Sema::TDK_InvalidExplicitArguments:
447 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000448 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000449 return 0;
450
451 case Sema::TDK_SubstitutionFailure:
452 return static_cast<TemplateArgumentList*>(Data);
453
454 // Unhandled
455 case Sema::TDK_NonDeducedMismatch:
456 case Sema::TDK_FailedOverloadResolution:
457 break;
458 }
459
460 return 0;
461}
462
Douglas Gregora9333192010-05-08 17:41:32 +0000463const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
464 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
465 case Sema::TDK_Success:
466 case Sema::TDK_InstantiationDepth:
467 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000468 case Sema::TDK_TooManyArguments:
469 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000470 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000471 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000472 return 0;
473
Douglas Gregora9333192010-05-08 17:41:32 +0000474 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000475 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000476 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
477
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000478 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000479 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000480 case Sema::TDK_FailedOverloadResolution:
481 break;
482 }
483
484 return 0;
485}
486
487const TemplateArgument *
488OverloadCandidate::DeductionFailureInfo::getSecondArg() {
489 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
490 case Sema::TDK_Success:
491 case Sema::TDK_InstantiationDepth:
492 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000493 case Sema::TDK_TooManyArguments:
494 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000495 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000496 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000497 return 0;
498
Douglas Gregora9333192010-05-08 17:41:32 +0000499 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000500 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000501 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
502
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000503 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000504 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000505 case Sema::TDK_FailedOverloadResolution:
506 break;
507 }
508
509 return 0;
510}
511
512void OverloadCandidateSet::clear() {
Douglas Gregora9333192010-05-08 17:41:32 +0000513 inherited::clear();
514 Functions.clear();
515}
516
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000517// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000518// overload of the declarations in Old. This routine returns false if
519// New and Old cannot be overloaded, e.g., if New has the same
520// signature as some function in Old (C++ 1.3.10) or if the Old
521// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000522// it does return false, MatchedDecl will point to the decl that New
523// cannot be overloaded with. This decl may be a UsingShadowDecl on
524// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000525//
526// Example: Given the following input:
527//
528// void f(int, float); // #1
529// void f(int, int); // #2
530// int f(int, int); // #3
531//
532// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000533// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000534//
John McCall51fa86f2009-12-02 08:47:38 +0000535// When we process #2, Old contains only the FunctionDecl for #1. By
536// comparing the parameter types, we see that #1 and #2 are overloaded
537// (since they have different signatures), so this routine returns
538// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000539//
John McCall51fa86f2009-12-02 08:47:38 +0000540// When we process #3, Old is an overload set containing #1 and #2. We
541// compare the signatures of #3 to #1 (they're overloaded, so we do
542// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
543// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000544// signature), IsOverload returns false and MatchedDecl will be set to
545// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000546//
547// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
548// into a class by a using declaration. The rules for whether to hide
549// shadow declarations ignore some properties which otherwise figure
550// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000551Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000552Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
553 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000554 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000555 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000556 NamedDecl *OldD = *I;
557
558 bool OldIsUsingDecl = false;
559 if (isa<UsingShadowDecl>(OldD)) {
560 OldIsUsingDecl = true;
561
562 // We can always introduce two using declarations into the same
563 // context, even if they have identical signatures.
564 if (NewIsUsingDecl) continue;
565
566 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
567 }
568
569 // If either declaration was introduced by a using declaration,
570 // we'll need to use slightly different rules for matching.
571 // Essentially, these rules are the normal rules, except that
572 // function templates hide function templates with different
573 // return types or template parameter lists.
574 bool UseMemberUsingDeclRules =
575 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
576
John McCall51fa86f2009-12-02 08:47:38 +0000577 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000578 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
579 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
580 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
581 continue;
582 }
583
John McCall871b2e72009-12-09 03:35:25 +0000584 Match = *I;
585 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000586 }
John McCall51fa86f2009-12-02 08:47:38 +0000587 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000588 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
589 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
590 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
591 continue;
592 }
593
John McCall871b2e72009-12-09 03:35:25 +0000594 Match = *I;
595 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000596 }
John McCalld7945c62010-11-10 03:01:53 +0000597 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000598 // We can overload with these, which can show up when doing
599 // redeclaration checks for UsingDecls.
600 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000601 } else if (isa<TagDecl>(OldD)) {
602 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000603 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
604 // Optimistically assume that an unresolved using decl will
605 // overload; if it doesn't, we'll have to diagnose during
606 // template instantiation.
607 } else {
John McCall68263142009-11-18 22:49:29 +0000608 // (C++ 13p1):
609 // Only function declarations can be overloaded; object and type
610 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000611 Match = *I;
612 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000613 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000614 }
John McCall68263142009-11-18 22:49:29 +0000615
John McCall871b2e72009-12-09 03:35:25 +0000616 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000617}
618
John McCallad00b772010-06-16 08:42:20 +0000619bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
620 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000621 // If both of the functions are extern "C", then they are not
622 // overloads.
623 if (Old->isExternC() && New->isExternC())
624 return false;
625
John McCall68263142009-11-18 22:49:29 +0000626 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
627 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
628
629 // C++ [temp.fct]p2:
630 // A function template can be overloaded with other function templates
631 // and with normal (non-template) functions.
632 if ((OldTemplate == 0) != (NewTemplate == 0))
633 return true;
634
635 // Is the function New an overload of the function Old?
636 QualType OldQType = Context.getCanonicalType(Old->getType());
637 QualType NewQType = Context.getCanonicalType(New->getType());
638
639 // Compare the signatures (C++ 1.3.10) of the two functions to
640 // determine whether they are overloads. If we find any mismatch
641 // in the signature, they are overloads.
642
643 // If either of these functions is a K&R-style function (no
644 // prototype), then we consider them to have matching signatures.
645 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
646 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
647 return false;
648
649 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
650 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
651
652 // The signature of a function includes the types of its
653 // parameters (C++ 1.3.10), which includes the presence or absence
654 // of the ellipsis; see C++ DR 357).
655 if (OldQType != NewQType &&
656 (OldType->getNumArgs() != NewType->getNumArgs() ||
657 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000658 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000659 return true;
660
661 // C++ [temp.over.link]p4:
662 // The signature of a function template consists of its function
663 // signature, its return type and its template parameter list. The names
664 // of the template parameters are significant only for establishing the
665 // relationship between the template parameters and the rest of the
666 // signature.
667 //
668 // We check the return type and template parameter lists for function
669 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000670 //
671 // However, we don't consider either of these when deciding whether
672 // a member introduced by a shadow declaration is hidden.
673 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000674 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
675 OldTemplate->getTemplateParameters(),
676 false, TPL_TemplateMatch) ||
677 OldType->getResultType() != NewType->getResultType()))
678 return true;
679
680 // If the function is a class member, its signature includes the
681 // cv-qualifiers (if any) on the function itself.
682 //
683 // As part of this, also check whether one of the member functions
684 // is static, in which case they are not overloads (C++
685 // 13.1p2). While not part of the definition of the signature,
686 // this check is important to determine whether these functions
687 // can be overloaded.
688 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
689 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
690 if (OldMethod && NewMethod &&
691 !OldMethod->isStatic() && !NewMethod->isStatic() &&
692 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
693 return true;
694
695 // The signatures match; this is not an overload.
696 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000697}
698
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000699/// TryImplicitConversion - Attempt to perform an implicit conversion
700/// from the given expression (Expr) to the given type (ToType). This
701/// function returns an implicit conversion sequence that can be used
702/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000703///
704/// void f(float f);
705/// void g(int i) { f(i); }
706///
707/// this routine would produce an implicit conversion sequence to
708/// describe the initialization of f from i, which will be a standard
709/// conversion sequence containing an lvalue-to-rvalue conversion (C++
710/// 4.1) followed by a floating-integral conversion (C++ 4.9).
711//
712/// Note that this routine only determines how the conversion can be
713/// performed; it does not actually perform the conversion. As such,
714/// it will not produce any diagnostics if no conversion is available,
715/// but will instead return an implicit conversion sequence of kind
716/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000717///
718/// If @p SuppressUserConversions, then user-defined conversions are
719/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000720/// If @p AllowExplicit, then explicit user-defined conversions are
721/// permitted.
John McCall120d63c2010-08-24 20:38:10 +0000722static ImplicitConversionSequence
723TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
724 bool SuppressUserConversions,
725 bool AllowExplicit,
726 bool InOverloadResolution) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000727 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +0000728 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
729 ICS.Standard)) {
John McCall1d318332010-01-12 00:44:57 +0000730 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +0000731 return ICS;
732 }
733
John McCall120d63c2010-08-24 20:38:10 +0000734 if (!S.getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +0000735 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +0000736 return ICS;
737 }
738
Douglas Gregor604eb652010-08-11 02:15:33 +0000739 // C++ [over.ics.user]p4:
740 // A conversion of an expression of class type to the same class
741 // type is given Exact Match rank, and a conversion of an
742 // expression of class type to a base class of that type is
743 // given Conversion rank, in spite of the fact that a copy/move
744 // constructor (i.e., a user-defined conversion function) is
745 // called for those cases.
746 QualType FromType = From->getType();
747 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +0000748 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
749 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000750 ICS.setStandard();
751 ICS.Standard.setAsIdentityConversion();
752 ICS.Standard.setFromType(FromType);
753 ICS.Standard.setAllToTypes(ToType);
754
755 // We don't actually check at this point whether there is a valid
756 // copy/move constructor, since overloading just assumes that it
757 // exists. When we actually perform initialization, we'll find the
758 // appropriate constructor to copy the returned object, if needed.
759 ICS.Standard.CopyConstructor = 0;
Douglas Gregor604eb652010-08-11 02:15:33 +0000760
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000761 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +0000762 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000763 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor604eb652010-08-11 02:15:33 +0000764
765 return ICS;
766 }
767
768 if (SuppressUserConversions) {
769 // We're not in the case above, so there is no conversion that
770 // we can perform.
771 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000772 return ICS;
773 }
774
775 // Attempt user-defined conversion.
John McCall5769d612010-02-08 23:07:23 +0000776 OverloadCandidateSet Conversions(From->getExprLoc());
777 OverloadingResult UserDefResult
John McCall120d63c2010-08-24 20:38:10 +0000778 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000779 AllowExplicit);
John McCall5769d612010-02-08 23:07:23 +0000780
781 if (UserDefResult == OR_Success) {
John McCall1d318332010-01-12 00:44:57 +0000782 ICS.setUserDefined();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000783 // C++ [over.ics.user]p4:
784 // A conversion of an expression of class type to the same class
785 // type is given Exact Match rank, and a conversion of an
786 // expression of class type to a base class of that type is
787 // given Conversion rank, in spite of the fact that a copy
788 // constructor (i.e., a user-defined conversion function) is
789 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000790 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000791 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000792 QualType FromCanon
John McCall120d63c2010-08-24 20:38:10 +0000793 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
794 QualType ToCanon
795 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000796 if (Constructor->isCopyConstructor() &&
John McCall120d63c2010-08-24 20:38:10 +0000797 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000798 // Turn this into a "standard" conversion sequence, so that it
799 // gets ranked with standard conversion sequences.
John McCall1d318332010-01-12 00:44:57 +0000800 ICS.setStandard();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000801 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +0000802 ICS.Standard.setFromType(From->getType());
Douglas Gregorad323a82010-01-27 03:51:04 +0000803 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000804 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000805 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000806 ICS.Standard.Second = ICK_Derived_To_Base;
807 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000808 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000809
810 // C++ [over.best.ics]p4:
811 // However, when considering the argument of a user-defined
812 // conversion function that is a candidate by 13.3.1.3 when
813 // invoked for the copying of the temporary in the second step
814 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
815 // 13.3.1.6 in all cases, only standard conversion sequences and
816 // ellipsis conversion sequences are allowed.
John McCalladbb8f82010-01-13 09:16:55 +0000817 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCallb1bdc622010-02-25 01:37:24 +0000818 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCalladbb8f82010-01-13 09:16:55 +0000819 }
John McCallcefd3ad2010-01-13 22:30:33 +0000820 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall1d318332010-01-12 00:44:57 +0000821 ICS.setAmbiguous();
822 ICS.Ambiguous.setFromType(From->getType());
823 ICS.Ambiguous.setToType(ToType);
824 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
825 Cand != Conversions.end(); ++Cand)
826 if (Cand->Viable)
827 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000828 } else {
John McCallb1bdc622010-02-25 01:37:24 +0000829 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000830 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000831
832 return ICS;
833}
834
John McCall120d63c2010-08-24 20:38:10 +0000835bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
836 const InitializedEntity &Entity,
837 Expr *Initializer,
838 bool SuppressUserConversions,
839 bool AllowExplicitConversions,
840 bool InOverloadResolution) {
841 ImplicitConversionSequence ICS
842 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
843 SuppressUserConversions,
844 AllowExplicitConversions,
845 InOverloadResolution);
846 if (ICS.isBad()) return true;
847
848 // Perform the actual conversion.
849 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
850 return false;
851}
852
Douglas Gregor575c63a2010-04-16 22:27:05 +0000853/// PerformImplicitConversion - Perform an implicit conversion of the
854/// expression From to the type ToType. Returns true if there was an
855/// error, false otherwise. The expression From is replaced with the
856/// converted expression. Flavor is the kind of conversion we're
857/// performing, used in the error message. If @p AllowExplicit,
858/// explicit user-defined conversions are permitted.
859bool
860Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
861 AssignmentAction Action, bool AllowExplicit) {
862 ImplicitConversionSequence ICS;
863 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
864}
865
866bool
867Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
868 AssignmentAction Action, bool AllowExplicit,
869 ImplicitConversionSequence& ICS) {
John McCall120d63c2010-08-24 20:38:10 +0000870 ICS = clang::TryImplicitConversion(*this, From, ToType,
871 /*SuppressUserConversions=*/false,
872 AllowExplicit,
873 /*InOverloadResolution=*/false);
Douglas Gregor575c63a2010-04-16 22:27:05 +0000874 return PerformImplicitConversion(From, ToType, ICS, Action);
875}
876
Douglas Gregor43c79c22009-12-09 00:47:37 +0000877/// \brief Determine whether the conversion from FromType to ToType is a valid
878/// conversion that strips "noreturn" off the nested function type.
879static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
880 QualType ToType, QualType &ResultTy) {
881 if (Context.hasSameUnqualifiedType(FromType, ToType))
882 return false;
883
884 // Strip the noreturn off the type we're converting from; noreturn can
885 // safely be removed.
886 FromType = Context.getNoReturnType(FromType, false);
887 if (!Context.hasSameUnqualifiedType(FromType, ToType))
888 return false;
889
890 ResultTy = FromType;
891 return true;
892}
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000893
894/// \brief Determine whether the conversion from FromType to ToType is a valid
895/// vector conversion.
896///
897/// \param ICK Will be set to the vector conversion kind, if this is a vector
898/// conversion.
899static bool IsVectorConversion(ASTContext &Context, QualType FromType,
900 QualType ToType, ImplicitConversionKind &ICK) {
901 // We need at least one of these types to be a vector type to have a vector
902 // conversion.
903 if (!ToType->isVectorType() && !FromType->isVectorType())
904 return false;
905
906 // Identical types require no conversions.
907 if (Context.hasSameUnqualifiedType(FromType, ToType))
908 return false;
909
910 // There are no conversions between extended vector types, only identity.
911 if (ToType->isExtVectorType()) {
912 // There are no conversions between extended vector types other than the
913 // identity conversion.
914 if (FromType->isExtVectorType())
915 return false;
916
917 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +0000918 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000919 ICK = ICK_Vector_Splat;
920 return true;
921 }
922 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000923
924 // We can perform the conversion between vector types in the following cases:
925 // 1)vector types are equivalent AltiVec and GCC vector types
926 // 2)lax vector conversions are permitted and the vector types are of the
927 // same size
928 if (ToType->isVectorType() && FromType->isVectorType()) {
929 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruthc45eb9c2010-08-08 05:02:51 +0000930 (Context.getLangOptions().LaxVectorConversions &&
931 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +0000932 ICK = ICK_Vector_Conversion;
933 return true;
934 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000935 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000936
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000937 return false;
938}
Douglas Gregor43c79c22009-12-09 00:47:37 +0000939
Douglas Gregor60d62c22008-10-31 16:23:19 +0000940/// IsStandardConversion - Determines whether there is a standard
941/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
942/// expression From to the type ToType. Standard conversion sequences
943/// only consider non-class types; for conversions that involve class
944/// types, use TryImplicitConversion. If a conversion exists, SCS will
945/// contain the standard conversion sequence required to perform this
946/// conversion and this routine will return true. Otherwise, this
947/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +0000948static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
949 bool InOverloadResolution,
950 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000951 QualType FromType = From->getType();
John McCall120d63c2010-08-24 20:38:10 +0000952
Douglas Gregor60d62c22008-10-31 16:23:19 +0000953 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000954 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +0000955 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000956 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +0000957 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000958 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000959
Douglas Gregorf9201e02009-02-11 23:02:49 +0000960 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000961 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000962 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall120d63c2010-08-24 20:38:10 +0000963 if (S.getLangOptions().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000964 return false;
965
Mike Stump1eb44332009-09-09 15:08:12 +0000966 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000967 }
968
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000969 // The first conversion can be an lvalue-to-rvalue conversion,
970 // array-to-pointer conversion, or function-to-pointer conversion
971 // (C++ 4p1).
972
John McCall120d63c2010-08-24 20:38:10 +0000973 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000974 DeclAccessPair AccessPair;
975 if (FunctionDecl *Fn
John McCall120d63c2010-08-24 20:38:10 +0000976 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
977 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000978 // We were able to resolve the address of the overloaded function,
979 // so we can convert to the type of that function.
980 FromType = Fn->getType();
981 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
982 if (!Method->isStatic()) {
983 Type *ClassType
John McCall120d63c2010-08-24 20:38:10 +0000984 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
985 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000986 }
987 }
988
989 // If the "from" expression takes the address of the overloaded
990 // function, update the type of the resulting expression accordingly.
991 if (FromType->getAs<FunctionType>())
992 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
John McCall2de56d12010-08-25 11:45:40 +0000993 if (UnOp->getOpcode() == UO_AddrOf)
John McCall120d63c2010-08-24 20:38:10 +0000994 FromType = S.Context.getPointerType(FromType);
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000995
996 // Check that we've computed the proper type after overload resolution.
John McCall120d63c2010-08-24 20:38:10 +0000997 assert(S.Context.hasSameType(FromType,
998 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000999 } else {
1000 return false;
1001 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001002 }
Mike Stump1eb44332009-09-09 15:08:12 +00001003 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001004 // An lvalue (3.10) of a non-function, non-array type T can be
1005 // converted to an rvalue.
John McCall7eb0a9e2010-11-24 05:12:34 +00001006 bool argIsLValue = From->isLValue();
1007 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001008 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001009 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001010 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001011
1012 // If T is a non-class type, the type of the rvalue is the
1013 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001014 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1015 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001016 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001017 } else if (FromType->isArrayType()) {
1018 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001019 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001020
1021 // An lvalue or rvalue of type "array of N T" or "array of unknown
1022 // bound of T" can be converted to an rvalue of type "pointer to
1023 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001024 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001025
John McCall120d63c2010-08-24 20:38:10 +00001026 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001027 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001028 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001029
1030 // For the purpose of ranking in overload resolution
1031 // (13.3.3.1.1), this conversion is considered an
1032 // array-to-pointer conversion followed by a qualification
1033 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001034 SCS.Second = ICK_Identity;
1035 SCS.Third = ICK_Qualification;
Douglas Gregorad323a82010-01-27 03:51:04 +00001036 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001037 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001038 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001039 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001040 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001041 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001042
1043 // An lvalue of function type T can be converted to an rvalue of
1044 // type "pointer to T." The result is a pointer to the
1045 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001046 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001047 } else {
1048 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001049 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001050 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001051 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001052
1053 // The second conversion can be an integral promotion, floating
1054 // point promotion, integral conversion, floating point conversion,
1055 // floating-integral conversion, pointer conversion,
1056 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001057 // For overloading in C, this can also be a "compatible-type"
1058 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001059 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001060 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001061 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001062 // The unqualified versions of the types are the same: there's no
1063 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001064 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001065 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001066 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001067 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001068 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001069 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001070 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001071 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001072 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001073 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001074 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001075 SCS.Second = ICK_Complex_Promotion;
1076 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001077 } else if (ToType->isBooleanType() &&
1078 (FromType->isArithmeticType() ||
1079 FromType->isAnyPointerType() ||
1080 FromType->isBlockPointerType() ||
1081 FromType->isMemberPointerType() ||
1082 FromType->isNullPtrType())) {
1083 // Boolean conversions (C++ 4.12).
1084 SCS.Second = ICK_Boolean_Conversion;
1085 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001086 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001087 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001088 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001089 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001090 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001091 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001092 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001093 SCS.Second = ICK_Complex_Conversion;
1094 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001095 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1096 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001097 // Complex-real conversions (C99 6.3.1.7)
1098 SCS.Second = ICK_Complex_Real;
1099 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001100 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001101 // Floating point conversions (C++ 4.8).
1102 SCS.Second = ICK_Floating_Conversion;
1103 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001104 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001105 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001106 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001107 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001108 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001109 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001110 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001111 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1112 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001113 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001114 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001115 SCS.IncompatibleObjC = IncompatibleObjC;
John McCall120d63c2010-08-24 20:38:10 +00001116 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1117 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001118 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001119 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001120 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001121 SCS.Second = SecondICK;
1122 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001123 } else if (!S.getLangOptions().CPlusPlus &&
1124 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001125 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001126 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001127 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001128 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001129 // Treat a conversion that strips "noreturn" as an identity conversion.
1130 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001131 } else {
1132 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001133 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001134 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001135 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001136
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001137 QualType CanonFrom;
1138 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001139 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall120d63c2010-08-24 20:38:10 +00001140 if (S.IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001141 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001142 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001143 CanonFrom = S.Context.getCanonicalType(FromType);
1144 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001145 } else {
1146 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001147 SCS.Third = ICK_Identity;
1148
Mike Stump1eb44332009-09-09 15:08:12 +00001149 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001150 // [...] Any difference in top-level cv-qualification is
1151 // subsumed by the initialization itself and does not constitute
1152 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001153 CanonFrom = S.Context.getCanonicalType(FromType);
1154 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00001155 if (CanonFrom.getLocalUnqualifiedType()
1156 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001157 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1158 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001159 FromType = ToType;
1160 CanonFrom = CanonTo;
1161 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001162 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001163 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001164
1165 // If we have not converted the argument type to the parameter type,
1166 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001167 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001168 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001169
Douglas Gregor60d62c22008-10-31 16:23:19 +00001170 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001171}
1172
1173/// IsIntegralPromotion - Determines whether the conversion from the
1174/// expression From (whose potentially-adjusted type is FromType) to
1175/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1176/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001177bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001178 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001179 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001180 if (!To) {
1181 return false;
1182 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001183
1184 // An rvalue of type char, signed char, unsigned char, short int, or
1185 // unsigned short int can be converted to an rvalue of type int if
1186 // int can represent all the values of the source type; otherwise,
1187 // the source rvalue can be converted to an rvalue of type unsigned
1188 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001189 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1190 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001191 if (// We can promote any signed, promotable integer type to an int
1192 (FromType->isSignedIntegerType() ||
1193 // We can promote any unsigned integer type whose size is
1194 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001195 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001196 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001197 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001198 }
1199
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001200 return To->getKind() == BuiltinType::UInt;
1201 }
1202
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001203 // C++0x [conv.prom]p3:
1204 // A prvalue of an unscoped enumeration type whose underlying type is not
1205 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1206 // following types that can represent all the values of the enumeration
1207 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1208 // unsigned int, long int, unsigned long int, long long int, or unsigned
1209 // long long int. If none of the types in that list can represent all the
1210 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1211 // type can be converted to an rvalue a prvalue of the extended integer type
1212 // with lowest integer conversion rank (4.13) greater than the rank of long
1213 // long in which all the values of the enumeration can be represented. If
1214 // there are two such extended types, the signed one is chosen.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001215 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1216 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1217 // provided for a scoped enumeration.
1218 if (FromEnumType->getDecl()->isScoped())
1219 return false;
1220
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001221 // We have already pre-calculated the promotion type, so this is trivial.
Douglas Gregor5dde1602010-09-12 03:38:25 +00001222 if (ToType->isIntegerType() &&
1223 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall842aef82009-12-09 09:09:27 +00001224 return Context.hasSameUnqualifiedType(ToType,
1225 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001226 }
John McCall842aef82009-12-09 09:09:27 +00001227
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001228 // C++0x [conv.prom]p2:
1229 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1230 // to an rvalue a prvalue of the first of the following types that can
1231 // represent all the values of its underlying type: int, unsigned int,
1232 // long int, unsigned long int, long long int, or unsigned long long int.
1233 // If none of the types in that list can represent all the values of its
1234 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1235 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1236 // type.
1237 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1238 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001239 // Determine whether the type we're converting from is signed or
1240 // unsigned.
1241 bool FromIsSigned;
1242 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +00001243
1244 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1245 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001246
1247 // The types we'll try to promote to, in the appropriate
1248 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001249 QualType PromoteTypes[6] = {
1250 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001251 Context.LongTy, Context.UnsignedLongTy ,
1252 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001253 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001254 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001255 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1256 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001257 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001258 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1259 // We found the type that we can promote to. If this is the
1260 // type we wanted, we have a promotion. Otherwise, no
1261 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001262 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001263 }
1264 }
1265 }
1266
1267 // An rvalue for an integral bit-field (9.6) can be converted to an
1268 // rvalue of type int if int can represent all the values of the
1269 // bit-field; otherwise, it can be converted to unsigned int if
1270 // unsigned int can represent all the values of the bit-field. If
1271 // the bit-field is larger yet, no integral promotion applies to
1272 // it. If the bit-field has an enumerated type, it is treated as any
1273 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001274 // FIXME: We should delay checking of bit-fields until we actually perform the
1275 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001276 using llvm::APSInt;
1277 if (From)
1278 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001279 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001280 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001281 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1282 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1283 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001284
Douglas Gregor86f19402008-12-20 23:49:58 +00001285 // Are we promoting to an int from a bitfield that fits in an int?
1286 if (BitWidth < ToSize ||
1287 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1288 return To->getKind() == BuiltinType::Int;
1289 }
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Douglas Gregor86f19402008-12-20 23:49:58 +00001291 // Are we promoting to an unsigned int from an unsigned bitfield
1292 // that fits into an unsigned int?
1293 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1294 return To->getKind() == BuiltinType::UInt;
1295 }
Mike Stump1eb44332009-09-09 15:08:12 +00001296
Douglas Gregor86f19402008-12-20 23:49:58 +00001297 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001298 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001299 }
Mike Stump1eb44332009-09-09 15:08:12 +00001300
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001301 // An rvalue of type bool can be converted to an rvalue of type int,
1302 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001303 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001304 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001305 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001306
1307 return false;
1308}
1309
1310/// IsFloatingPointPromotion - Determines whether the conversion from
1311/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1312/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001313bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001314 /// An rvalue of type float can be converted to an rvalue of type
1315 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +00001316 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1317 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001318 if (FromBuiltin->getKind() == BuiltinType::Float &&
1319 ToBuiltin->getKind() == BuiltinType::Double)
1320 return true;
1321
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001322 // C99 6.3.1.5p1:
1323 // When a float is promoted to double or long double, or a
1324 // double is promoted to long double [...].
1325 if (!getLangOptions().CPlusPlus &&
1326 (FromBuiltin->getKind() == BuiltinType::Float ||
1327 FromBuiltin->getKind() == BuiltinType::Double) &&
1328 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1329 return true;
1330 }
1331
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001332 return false;
1333}
1334
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001335/// \brief Determine if a conversion is a complex promotion.
1336///
1337/// A complex promotion is defined as a complex -> complex conversion
1338/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001339/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001340bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001341 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001342 if (!FromComplex)
1343 return false;
1344
John McCall183700f2009-09-21 23:43:11 +00001345 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001346 if (!ToComplex)
1347 return false;
1348
1349 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001350 ToComplex->getElementType()) ||
1351 IsIntegralPromotion(0, FromComplex->getElementType(),
1352 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001353}
1354
Douglas Gregorcb7de522008-11-26 23:31:11 +00001355/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1356/// the pointer type FromPtr to a pointer to type ToPointee, with the
1357/// same type qualifiers as FromPtr has on its pointee type. ToType,
1358/// if non-empty, will be a pointer to ToType that may or may not have
1359/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +00001360static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001361BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001362 QualType ToPointee, QualType ToType,
1363 ASTContext &Context) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001364 assert((FromPtr->getTypeClass() == Type::Pointer ||
1365 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1366 "Invalid similarly-qualified pointer type");
1367 QualType CanonFromPointee
1368 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001369 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001370 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001371
1372 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001373 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001374 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001375 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001376 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001377
1378 // Build a pointer to ToPointee. It has the right qualifiers
1379 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001380 if (isa<ObjCObjectPointerType>(ToType))
1381 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001382 return Context.getPointerType(ToPointee);
1383 }
1384
1385 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001386 QualType QualifiedCanonToPointee
1387 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001388
Douglas Gregorda80f742010-12-01 21:43:58 +00001389 if (isa<ObjCObjectPointerType>(ToType))
1390 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1391 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001392}
1393
Mike Stump1eb44332009-09-09 15:08:12 +00001394static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001395 bool InOverloadResolution,
1396 ASTContext &Context) {
1397 // Handle value-dependent integral null pointer constants correctly.
1398 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1399 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001400 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001401 return !InOverloadResolution;
1402
Douglas Gregorce940492009-09-25 04:25:58 +00001403 return Expr->isNullPointerConstant(Context,
1404 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1405 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001406}
Mike Stump1eb44332009-09-09 15:08:12 +00001407
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001408/// IsPointerConversion - Determines whether the conversion of the
1409/// expression From, which has the (possibly adjusted) type FromType,
1410/// can be converted to the type ToType via a pointer conversion (C++
1411/// 4.10). If so, returns true and places the converted type (that
1412/// might differ from ToType in its cv-qualifiers at some level) into
1413/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001414///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001415/// This routine also supports conversions to and from block pointers
1416/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1417/// pointers to interfaces. FIXME: Once we've determined the
1418/// appropriate overloading rules for Objective-C, we may want to
1419/// split the Objective-C checks into a different routine; however,
1420/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001421/// conversions, so for now they live here. IncompatibleObjC will be
1422/// set if the conversion is an allowed Objective-C conversion that
1423/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001424bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001425 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001426 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001427 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001428 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +00001429 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1430 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001431
Mike Stump1eb44332009-09-09 15:08:12 +00001432 // Conversion from a null pointer constant to any Objective-C pointer type.
1433 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001434 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001435 ConvertedType = ToType;
1436 return true;
1437 }
1438
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001439 // Blocks: Block pointers can be converted to void*.
1440 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001441 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001442 ConvertedType = ToType;
1443 return true;
1444 }
1445 // Blocks: A null pointer constant can be converted to a block
1446 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001447 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001448 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001449 ConvertedType = ToType;
1450 return true;
1451 }
1452
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001453 // If the left-hand-side is nullptr_t, the right side can be a null
1454 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001455 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001456 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001457 ConvertedType = ToType;
1458 return true;
1459 }
1460
Ted Kremenek6217b802009-07-29 21:53:49 +00001461 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001462 if (!ToTypePtr)
1463 return false;
1464
1465 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001466 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001467 ConvertedType = ToType;
1468 return true;
1469 }
Sebastian Redl07779722008-10-31 14:43:28 +00001470
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001471 // Beyond this point, both types need to be pointers
1472 // , including objective-c pointers.
1473 QualType ToPointeeType = ToTypePtr->getPointeeType();
1474 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001475 ConvertedType = BuildSimilarlyQualifiedPointerType(
1476 FromType->getAs<ObjCObjectPointerType>(),
1477 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001478 ToType, Context);
1479 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001480 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001481 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001482 if (!FromTypePtr)
1483 return false;
1484
1485 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001486
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001487 // If the unqualified pointee types are the same, this can't be a
1488 // pointer conversion, so don't do all of the work below.
1489 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1490 return false;
1491
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001492 // An rvalue of type "pointer to cv T," where T is an object type,
1493 // can be converted to an rvalue of type "pointer to cv void" (C++
1494 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001495 if (FromPointeeType->isIncompleteOrObjectType() &&
1496 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001497 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001498 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001499 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001500 return true;
1501 }
1502
Douglas Gregorf9201e02009-02-11 23:02:49 +00001503 // When we're overloading in C, we allow a special kind of pointer
1504 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001505 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001506 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001507 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001508 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001509 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001510 return true;
1511 }
1512
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001513 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001514 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001515 // An rvalue of type "pointer to cv D," where D is a class type,
1516 // can be converted to an rvalue of type "pointer to cv B," where
1517 // B is a base class (clause 10) of D. If B is an inaccessible
1518 // (clause 11) or ambiguous (10.2) base class of D, a program that
1519 // necessitates this conversion is ill-formed. The result of the
1520 // conversion is a pointer to the base class sub-object of the
1521 // derived class object. The null pointer value is converted to
1522 // the null pointer value of the destination type.
1523 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001524 // Note that we do not check for ambiguity or inaccessibility
1525 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001526 if (getLangOptions().CPlusPlus &&
1527 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001528 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001529 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001530 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001531 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001532 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001533 ToType, Context);
1534 return true;
1535 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001536
Douglas Gregorc7887512008-12-19 19:13:09 +00001537 return false;
1538}
1539
1540/// isObjCPointerConversion - Determines whether this is an
1541/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1542/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001543bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001544 QualType& ConvertedType,
1545 bool &IncompatibleObjC) {
1546 if (!getLangOptions().ObjC1)
1547 return false;
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001548
Steve Naroff14108da2009-07-10 23:34:53 +00001549 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001550 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001551 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001552 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001553
Steve Naroff14108da2009-07-10 23:34:53 +00001554 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001555 // If the pointee types are the same (ignoring qualifications),
1556 // then this is not a pointer conversion.
1557 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1558 FromObjCPtr->getPointeeType()))
1559 return false;
1560
Steve Naroffde2e22d2009-07-15 18:40:39 +00001561 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001562 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001563 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001564 ConvertedType = ToType;
1565 return true;
1566 }
1567 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001568 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001569 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001570 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001571 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001572 ConvertedType = ToType;
1573 return true;
1574 }
1575 // Objective C++: We're able to convert from a pointer to an
1576 // interface to a pointer to a different interface.
1577 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00001578 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1579 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1580 if (getLangOptions().CPlusPlus && LHS && RHS &&
1581 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1582 FromObjCPtr->getPointeeType()))
1583 return false;
Douglas Gregorda80f742010-12-01 21:43:58 +00001584 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1585 ToObjCPtr->getPointeeType(),
1586 ToType, Context);
Steve Naroff14108da2009-07-10 23:34:53 +00001587 return true;
1588 }
1589
1590 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1591 // Okay: this is some kind of implicit downcast of Objective-C
1592 // interfaces, which is permitted. However, we're going to
1593 // complain about it.
1594 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00001595 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1596 ToObjCPtr->getPointeeType(),
1597 ToType, Context);
Steve Naroff14108da2009-07-10 23:34:53 +00001598 return true;
1599 }
Mike Stump1eb44332009-09-09 15:08:12 +00001600 }
Steve Naroff14108da2009-07-10 23:34:53 +00001601 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001602 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001603 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001604 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001605 else if (const BlockPointerType *ToBlockPtr =
1606 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001607 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001608 // to a block pointer type.
1609 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1610 ConvertedType = ToType;
1611 return true;
1612 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001613 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001614 }
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001615 else if (FromType->getAs<BlockPointerType>() &&
1616 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1617 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001618 // pointer to any object.
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001619 ConvertedType = ToType;
1620 return true;
1621 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001622 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001623 return false;
1624
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001625 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001626 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001627 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001628 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001629 FromPointeeType = FromBlockPtr->getPointeeType();
1630 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001631 return false;
1632
Douglas Gregorc7887512008-12-19 19:13:09 +00001633 // If we have pointers to pointers, recursively check whether this
1634 // is an Objective-C conversion.
1635 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1636 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1637 IncompatibleObjC)) {
1638 // We always complain about this conversion.
1639 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00001640 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregorc7887512008-12-19 19:13:09 +00001641 return true;
1642 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001643 // Allow conversion of pointee being objective-c pointer to another one;
1644 // as in I* to id.
1645 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1646 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1647 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1648 IncompatibleObjC)) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001649 ConvertedType = Context.getPointerType(ConvertedType);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001650 return true;
1651 }
1652
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001653 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001654 // differences in the argument and result types are in Objective-C
1655 // pointer conversions. If so, we permit the conversion (but
1656 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001657 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001658 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001659 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001660 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001661 if (FromFunctionType && ToFunctionType) {
1662 // If the function types are exactly the same, this isn't an
1663 // Objective-C pointer conversion.
1664 if (Context.getCanonicalType(FromPointeeType)
1665 == Context.getCanonicalType(ToPointeeType))
1666 return false;
1667
1668 // Perform the quick checks that will tell us whether these
1669 // function types are obviously different.
1670 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1671 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1672 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1673 return false;
1674
1675 bool HasObjCConversion = false;
1676 if (Context.getCanonicalType(FromFunctionType->getResultType())
1677 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1678 // Okay, the types match exactly. Nothing to do.
1679 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1680 ToFunctionType->getResultType(),
1681 ConvertedType, IncompatibleObjC)) {
1682 // Okay, we have an Objective-C pointer conversion.
1683 HasObjCConversion = true;
1684 } else {
1685 // Function types are too different. Abort.
1686 return false;
1687 }
Mike Stump1eb44332009-09-09 15:08:12 +00001688
Douglas Gregorc7887512008-12-19 19:13:09 +00001689 // Check argument types.
1690 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1691 ArgIdx != NumArgs; ++ArgIdx) {
1692 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1693 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1694 if (Context.getCanonicalType(FromArgType)
1695 == Context.getCanonicalType(ToArgType)) {
1696 // Okay, the types match exactly. Nothing to do.
1697 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1698 ConvertedType, IncompatibleObjC)) {
1699 // Okay, we have an Objective-C pointer conversion.
1700 HasObjCConversion = true;
1701 } else {
1702 // Argument types are too different. Abort.
1703 return false;
1704 }
1705 }
1706
1707 if (HasObjCConversion) {
1708 // We had an Objective-C conversion. Allow this pointer
1709 // conversion, but complain about it.
1710 ConvertedType = ToType;
1711 IncompatibleObjC = true;
1712 return true;
1713 }
1714 }
1715
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001716 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001717}
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001718
1719/// FunctionArgTypesAreEqual - This routine checks two function proto types
1720/// for equlity of their argument types. Caller has already checked that
1721/// they have same number of arguments. This routine assumes that Objective-C
1722/// pointer types which only differ in their protocol qualifiers are equal.
1723bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1724 FunctionProtoType* NewType){
1725 if (!getLangOptions().ObjC1)
1726 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1727 NewType->arg_type_begin());
1728
1729 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1730 N = NewType->arg_type_begin(),
1731 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1732 QualType ToType = (*O);
1733 QualType FromType = (*N);
1734 if (ToType != FromType) {
1735 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1736 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00001737 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1738 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1739 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1740 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001741 continue;
1742 }
John McCallc12c5bb2010-05-15 11:32:37 +00001743 else if (const ObjCObjectPointerType *PTTo =
1744 ToType->getAs<ObjCObjectPointerType>()) {
1745 if (const ObjCObjectPointerType *PTFr =
1746 FromType->getAs<ObjCObjectPointerType>())
1747 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1748 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001749 }
1750 return false;
1751 }
1752 }
1753 return true;
1754}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001755
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001756/// CheckPointerConversion - Check the pointer conversion from the
1757/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001758/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001759/// conversions for which IsPointerConversion has already returned
1760/// true. It returns true and produces a diagnostic if there was an
1761/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001762bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00001763 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001764 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001765 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001766 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00001767 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001768
John McCalldaa8e4e2010-11-15 09:13:47 +00001769 Kind = CK_BitCast;
1770
Douglas Gregord7a95972010-06-08 17:35:15 +00001771 if (CXXBoolLiteralExpr* LitBool
1772 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00001773 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Douglas Gregord7a95972010-06-08 17:35:15 +00001774 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1775 << ToType;
1776
Ted Kremenek6217b802009-07-29 21:53:49 +00001777 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1778 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001779 QualType FromPointeeType = FromPtrType->getPointeeType(),
1780 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001781
Douglas Gregor5fccd362010-03-03 23:55:11 +00001782 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1783 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001784 // We must have a derived-to-base conversion. Check an
1785 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001786 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1787 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001788 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001789 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001790 return true;
1791
1792 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00001793 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001794 }
1795 }
Mike Stump1eb44332009-09-09 15:08:12 +00001796 if (const ObjCObjectPointerType *FromPtrType =
John McCalldaa8e4e2010-11-15 09:13:47 +00001797 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001798 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001799 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001800 // Objective-C++ conversions are always okay.
1801 // FIXME: We should have a different class of conversions for the
1802 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001803 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001804 return false;
John McCalldaa8e4e2010-11-15 09:13:47 +00001805 }
Steve Naroff14108da2009-07-10 23:34:53 +00001806 }
John McCalldaa8e4e2010-11-15 09:13:47 +00001807
1808 // We shouldn't fall into this case unless it's valid for other
1809 // reasons.
1810 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
1811 Kind = CK_NullToPointer;
1812
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001813 return false;
1814}
1815
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001816/// IsMemberPointerConversion - Determines whether the conversion of the
1817/// expression From, which has the (possibly adjusted) type FromType, can be
1818/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1819/// If so, returns true and places the converted type (that might differ from
1820/// ToType in its cv-qualifiers at some level) into ConvertedType.
1821bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001822 QualType ToType,
1823 bool InOverloadResolution,
1824 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001825 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001826 if (!ToTypePtr)
1827 return false;
1828
1829 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001830 if (From->isNullPointerConstant(Context,
1831 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1832 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001833 ConvertedType = ToType;
1834 return true;
1835 }
1836
1837 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001838 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001839 if (!FromTypePtr)
1840 return false;
1841
1842 // A pointer to member of B can be converted to a pointer to member of D,
1843 // where D is derived from B (C++ 4.11p2).
1844 QualType FromClass(FromTypePtr->getClass(), 0);
1845 QualType ToClass(ToTypePtr->getClass(), 0);
1846 // FIXME: What happens when these are dependent? Is this function even called?
1847
1848 if (IsDerivedFrom(ToClass, FromClass)) {
1849 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1850 ToClass.getTypePtr());
1851 return true;
1852 }
1853
1854 return false;
1855}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001856
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001857/// CheckMemberPointerConversion - Check the member pointer conversion from the
1858/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00001859/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001860/// for which IsMemberPointerConversion has already returned true. It returns
1861/// true and produces a diagnostic if there was an error, or returns false
1862/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001863bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00001864 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001865 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001866 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001867 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001868 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001869 if (!FromPtrType) {
1870 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001871 assert(From->isNullPointerConstant(Context,
1872 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001873 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00001874 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001875 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001876 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001877
Ted Kremenek6217b802009-07-29 21:53:49 +00001878 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001879 assert(ToPtrType && "No member pointer cast has a target type "
1880 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001881
Sebastian Redl21593ac2009-01-28 18:33:18 +00001882 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1883 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001884
Sebastian Redl21593ac2009-01-28 18:33:18 +00001885 // FIXME: What about dependent types?
1886 assert(FromClass->isRecordType() && "Pointer into non-class.");
1887 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001888
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001889 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001890 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001891 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1892 assert(DerivationOkay &&
1893 "Should not have been called if derivation isn't OK.");
1894 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001895
Sebastian Redl21593ac2009-01-28 18:33:18 +00001896 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1897 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001898 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1899 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1900 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1901 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001902 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001903
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001904 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001905 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1906 << FromClass << ToClass << QualType(VBase, 0)
1907 << From->getSourceRange();
1908 return true;
1909 }
1910
John McCall6b2accb2010-02-10 09:31:12 +00001911 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00001912 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1913 Paths.front(),
1914 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00001915
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001916 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001917 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001918 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001919 return false;
1920}
1921
Douglas Gregor98cd5992008-10-21 23:43:52 +00001922/// IsQualificationConversion - Determines whether the conversion from
1923/// an rvalue of type FromType to ToType is a qualification conversion
1924/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001925bool
1926Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001927 FromType = Context.getCanonicalType(FromType);
1928 ToType = Context.getCanonicalType(ToType);
1929
1930 // If FromType and ToType are the same type, this is not a
1931 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00001932 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00001933 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001934
Douglas Gregor98cd5992008-10-21 23:43:52 +00001935 // (C++ 4.4p4):
1936 // A conversion can add cv-qualifiers at levels other than the first
1937 // in multi-level pointers, subject to the following rules: [...]
1938 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001939 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001940 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001941 // Within each iteration of the loop, we check the qualifiers to
1942 // determine if this still looks like a qualification
1943 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001944 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001945 // until there are no more pointers or pointers-to-members left to
1946 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001947 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001948
1949 // -- for every j > 0, if const is in cv 1,j then const is in cv
1950 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001951 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001952 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001953
Douglas Gregor98cd5992008-10-21 23:43:52 +00001954 // -- if the cv 1,j and cv 2,j are different, then const is in
1955 // every cv for 0 < k < j.
1956 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001957 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001958 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Douglas Gregor98cd5992008-10-21 23:43:52 +00001960 // Keep track of whether all prior cv-qualifiers in the "to" type
1961 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001962 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001963 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001964 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001965
1966 // We are left with FromType and ToType being the pointee types
1967 // after unwrapping the original FromType and ToType the same number
1968 // of types. If we unwrapped any pointers, and if FromType and
1969 // ToType have the same unqualified type (since we checked
1970 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001971 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001972}
1973
Douglas Gregor734d9862009-01-30 23:27:23 +00001974/// Determines whether there is a user-defined conversion sequence
1975/// (C++ [over.ics.user]) that converts expression From to the type
1976/// ToType. If such a conversion exists, User will contain the
1977/// user-defined conversion sequence that performs such a conversion
1978/// and this routine will return true. Otherwise, this routine returns
1979/// false and User is unspecified.
1980///
Douglas Gregor734d9862009-01-30 23:27:23 +00001981/// \param AllowExplicit true if the conversion should consider C++0x
1982/// "explicit" conversion functions as well as non-explicit conversion
1983/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00001984static OverloadingResult
1985IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1986 UserDefinedConversionSequence& User,
1987 OverloadCandidateSet& CandidateSet,
1988 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001989 // Whether we will only visit constructors.
1990 bool ConstructorsOnly = false;
1991
1992 // If the type we are conversion to is a class type, enumerate its
1993 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00001994 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001995 // C++ [over.match.ctor]p1:
1996 // When objects of class type are direct-initialized (8.5), or
1997 // copy-initialized from an expression of the same or a
1998 // derived class type (8.5), overload resolution selects the
1999 // constructor. [...] For copy-initialization, the candidate
2000 // functions are all the converting constructors (12.3.1) of
2001 // that class. The argument list is the expression-list within
2002 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00002003 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002004 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00002005 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002006 ConstructorsOnly = true;
2007
John McCall120d63c2010-08-24 20:38:10 +00002008 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor393896f2009-11-05 13:06:35 +00002009 // We're not going to find any constructors.
2010 } else if (CXXRecordDecl *ToRecordDecl
2011 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002012 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00002013 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002014 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002015 NamedDecl *D = *Con;
2016 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2017
Douglas Gregordec06662009-08-21 18:42:58 +00002018 // Find the constructor (which may be a template).
2019 CXXConstructorDecl *Constructor = 0;
2020 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002021 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00002022 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00002023 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00002024 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2025 else
John McCall9aa472c2010-03-19 07:35:19 +00002026 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002027
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00002028 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00002029 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00002030 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00002031 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2032 /*ExplicitArgs*/ 0,
2033 &From, 1, CandidateSet,
2034 /*SuppressUserConversions=*/
2035 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002036 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00002037 // Allow one user-defined conversion when user specifies a
2038 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00002039 S.AddOverloadCandidate(Constructor, FoundDecl,
2040 &From, 1, CandidateSet,
2041 /*SuppressUserConversions=*/
2042 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002043 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002044 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002045 }
2046 }
2047
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002048 // Enumerate conversion functions, if we're allowed to.
2049 if (ConstructorsOnly) {
John McCall120d63c2010-08-24 20:38:10 +00002050 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2051 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00002052 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00002053 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002054 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002055 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002056 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2057 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00002058 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002059 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002060 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00002061 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00002062 DeclAccessPair FoundDecl = I.getPair();
2063 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00002064 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2065 if (isa<UsingShadowDecl>(D))
2066 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2067
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002068 CXXConversionDecl *Conv;
2069 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00002070 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2071 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002072 else
John McCall32daa422010-03-31 01:36:47 +00002073 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002074
2075 if (AllowExplicit || !Conv->isExplicit()) {
2076 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00002077 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2078 ActingContext, From, ToType,
2079 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002080 else
John McCall120d63c2010-08-24 20:38:10 +00002081 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2082 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002083 }
2084 }
2085 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002086 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002087
2088 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002089 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00002090 case OR_Success:
2091 // Record the standard conversion we used and the conversion function.
2092 if (CXXConstructorDecl *Constructor
2093 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2094 // C++ [over.ics.user]p1:
2095 // If the user-defined conversion is specified by a
2096 // constructor (12.3.1), the initial standard conversion
2097 // sequence converts the source type to the type required by
2098 // the argument of the constructor.
2099 //
2100 QualType ThisType = Constructor->getThisType(S.Context);
2101 if (Best->Conversions[0].isEllipsis())
2102 User.EllipsisConversion = true;
2103 else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002104 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002105 User.EllipsisConversion = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002106 }
John McCall120d63c2010-08-24 20:38:10 +00002107 User.ConversionFunction = Constructor;
2108 User.After.setAsIdentityConversion();
2109 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2110 User.After.setAllToTypes(ToType);
2111 return OR_Success;
2112 } else if (CXXConversionDecl *Conversion
2113 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2114 // C++ [over.ics.user]p1:
2115 //
2116 // [...] If the user-defined conversion is specified by a
2117 // conversion function (12.3.2), the initial standard
2118 // conversion sequence converts the source type to the
2119 // implicit object parameter of the conversion function.
2120 User.Before = Best->Conversions[0].Standard;
2121 User.ConversionFunction = Conversion;
2122 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002123
John McCall120d63c2010-08-24 20:38:10 +00002124 // C++ [over.ics.user]p2:
2125 // The second standard conversion sequence converts the
2126 // result of the user-defined conversion to the target type
2127 // for the sequence. Since an implicit conversion sequence
2128 // is an initialization, the special rules for
2129 // initialization by user-defined conversion apply when
2130 // selecting the best user-defined conversion for a
2131 // user-defined conversion sequence (see 13.3.3 and
2132 // 13.3.3.1).
2133 User.After = Best->FinalConversion;
2134 return OR_Success;
2135 } else {
2136 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002137 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002138 }
2139
John McCall120d63c2010-08-24 20:38:10 +00002140 case OR_No_Viable_Function:
2141 return OR_No_Viable_Function;
2142 case OR_Deleted:
2143 // No conversion here! We're done.
2144 return OR_Deleted;
2145
2146 case OR_Ambiguous:
2147 return OR_Ambiguous;
2148 }
2149
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002150 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002151}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002152
2153bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002154Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002155 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00002156 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002157 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00002158 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002159 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002160 if (OvResult == OR_Ambiguous)
2161 Diag(From->getSourceRange().getBegin(),
2162 diag::err_typecheck_ambiguous_condition)
2163 << From->getType() << ToType << From->getSourceRange();
2164 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2165 Diag(From->getSourceRange().getBegin(),
2166 diag::err_typecheck_nonviable_condition)
2167 << From->getType() << ToType << From->getSourceRange();
2168 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002169 return false;
John McCall120d63c2010-08-24 20:38:10 +00002170 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002171 return true;
2172}
Douglas Gregor60d62c22008-10-31 16:23:19 +00002173
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002174/// CompareImplicitConversionSequences - Compare two implicit
2175/// conversion sequences to determine whether one is better than the
2176/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00002177static ImplicitConversionSequence::CompareKind
2178CompareImplicitConversionSequences(Sema &S,
2179 const ImplicitConversionSequence& ICS1,
2180 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002181{
2182 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2183 // conversion sequences (as defined in 13.3.3.1)
2184 // -- a standard conversion sequence (13.3.3.1.1) is a better
2185 // conversion sequence than a user-defined conversion sequence or
2186 // an ellipsis conversion sequence, and
2187 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2188 // conversion sequence than an ellipsis conversion sequence
2189 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002190 //
John McCall1d318332010-01-12 00:44:57 +00002191 // C++0x [over.best.ics]p10:
2192 // For the purpose of ranking implicit conversion sequences as
2193 // described in 13.3.3.2, the ambiguous conversion sequence is
2194 // treated as a user-defined sequence that is indistinguishable
2195 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002196 if (ICS1.getKindRank() < ICS2.getKindRank())
2197 return ImplicitConversionSequence::Better;
2198 else if (ICS2.getKindRank() < ICS1.getKindRank())
2199 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002200
Benjamin Kramerb6eee072010-04-18 12:05:54 +00002201 // The following checks require both conversion sequences to be of
2202 // the same kind.
2203 if (ICS1.getKind() != ICS2.getKind())
2204 return ImplicitConversionSequence::Indistinguishable;
2205
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002206 // Two implicit conversion sequences of the same form are
2207 // indistinguishable conversion sequences unless one of the
2208 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00002209 if (ICS1.isStandard())
John McCall120d63c2010-08-24 20:38:10 +00002210 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00002211 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002212 // User-defined conversion sequence U1 is a better conversion
2213 // sequence than another user-defined conversion sequence U2 if
2214 // they contain the same user-defined conversion function or
2215 // constructor and if the second standard conversion sequence of
2216 // U1 is better than the second standard conversion sequence of
2217 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002218 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002219 ICS2.UserDefined.ConversionFunction)
John McCall120d63c2010-08-24 20:38:10 +00002220 return CompareStandardConversionSequences(S,
2221 ICS1.UserDefined.After,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002222 ICS2.UserDefined.After);
2223 }
2224
2225 return ImplicitConversionSequence::Indistinguishable;
2226}
2227
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002228static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2229 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2230 Qualifiers Quals;
2231 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2232 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2233 }
2234
2235 return Context.hasSameUnqualifiedType(T1, T2);
2236}
2237
Douglas Gregorad323a82010-01-27 03:51:04 +00002238// Per 13.3.3.2p3, compare the given standard conversion sequences to
2239// determine if one is a proper subset of the other.
2240static ImplicitConversionSequence::CompareKind
2241compareStandardConversionSubsets(ASTContext &Context,
2242 const StandardConversionSequence& SCS1,
2243 const StandardConversionSequence& SCS2) {
2244 ImplicitConversionSequence::CompareKind Result
2245 = ImplicitConversionSequence::Indistinguishable;
2246
Douglas Gregorae65f4b2010-05-23 22:10:15 +00002247 // the identity conversion sequence is considered to be a subsequence of
2248 // any non-identity conversion sequence
2249 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2250 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2251 return ImplicitConversionSequence::Better;
2252 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2253 return ImplicitConversionSequence::Worse;
2254 }
2255
Douglas Gregorad323a82010-01-27 03:51:04 +00002256 if (SCS1.Second != SCS2.Second) {
2257 if (SCS1.Second == ICK_Identity)
2258 Result = ImplicitConversionSequence::Better;
2259 else if (SCS2.Second == ICK_Identity)
2260 Result = ImplicitConversionSequence::Worse;
2261 else
2262 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002263 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00002264 return ImplicitConversionSequence::Indistinguishable;
2265
2266 if (SCS1.Third == SCS2.Third) {
2267 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2268 : ImplicitConversionSequence::Indistinguishable;
2269 }
2270
2271 if (SCS1.Third == ICK_Identity)
2272 return Result == ImplicitConversionSequence::Worse
2273 ? ImplicitConversionSequence::Indistinguishable
2274 : ImplicitConversionSequence::Better;
2275
2276 if (SCS2.Third == ICK_Identity)
2277 return Result == ImplicitConversionSequence::Better
2278 ? ImplicitConversionSequence::Indistinguishable
2279 : ImplicitConversionSequence::Worse;
2280
2281 return ImplicitConversionSequence::Indistinguishable;
2282}
2283
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002284/// CompareStandardConversionSequences - Compare two standard
2285/// conversion sequences to determine whether one is better than the
2286/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00002287static ImplicitConversionSequence::CompareKind
2288CompareStandardConversionSequences(Sema &S,
2289 const StandardConversionSequence& SCS1,
2290 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002291{
2292 // Standard conversion sequence S1 is a better conversion sequence
2293 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2294
2295 // -- S1 is a proper subsequence of S2 (comparing the conversion
2296 // sequences in the canonical form defined by 13.3.3.1.1,
2297 // excluding any Lvalue Transformation; the identity conversion
2298 // sequence is considered to be a subsequence of any
2299 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00002300 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00002301 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00002302 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002303
2304 // -- the rank of S1 is better than the rank of S2 (by the rules
2305 // defined below), or, if not that,
2306 ImplicitConversionRank Rank1 = SCS1.getRank();
2307 ImplicitConversionRank Rank2 = SCS2.getRank();
2308 if (Rank1 < Rank2)
2309 return ImplicitConversionSequence::Better;
2310 else if (Rank2 < Rank1)
2311 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002312
Douglas Gregor57373262008-10-22 14:17:15 +00002313 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2314 // are indistinguishable unless one of the following rules
2315 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00002316
Douglas Gregor57373262008-10-22 14:17:15 +00002317 // A conversion that is not a conversion of a pointer, or
2318 // pointer to member, to bool is better than another conversion
2319 // that is such a conversion.
2320 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2321 return SCS2.isPointerConversionToBool()
2322 ? ImplicitConversionSequence::Better
2323 : ImplicitConversionSequence::Worse;
2324
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002325 // C++ [over.ics.rank]p4b2:
2326 //
2327 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002328 // conversion of B* to A* is better than conversion of B* to
2329 // void*, and conversion of A* to void* is better than conversion
2330 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00002331 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002332 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002333 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002334 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002335 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2336 // Exactly one of the conversion sequences is a conversion to
2337 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002338 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2339 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002340 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2341 // Neither conversion sequence converts to a void pointer; compare
2342 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002343 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00002344 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002345 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002346 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2347 // Both conversion sequences are conversions to void
2348 // pointers. Compare the source types to determine if there's an
2349 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00002350 QualType FromType1 = SCS1.getFromType();
2351 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002352
2353 // Adjust the types we're converting from via the array-to-pointer
2354 // conversion, if we need to.
2355 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002356 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002357 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002358 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002359
Douglas Gregor01919692009-12-13 21:37:05 +00002360 QualType FromPointee1
2361 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2362 QualType FromPointee2
2363 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002364
John McCall120d63c2010-08-24 20:38:10 +00002365 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00002366 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002367 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00002368 return ImplicitConversionSequence::Worse;
2369
2370 // Objective-C++: If one interface is more specific than the
2371 // other, it is the better one.
John McCallc12c5bb2010-05-15 11:32:37 +00002372 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2373 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor01919692009-12-13 21:37:05 +00002374 if (FromIface1 && FromIface1) {
John McCall120d63c2010-08-24 20:38:10 +00002375 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor01919692009-12-13 21:37:05 +00002376 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002377 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor01919692009-12-13 21:37:05 +00002378 return ImplicitConversionSequence::Worse;
2379 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002380 }
Douglas Gregor57373262008-10-22 14:17:15 +00002381
2382 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2383 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00002384 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00002385 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002386 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00002387
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002388 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002389 // C++0x [over.ics.rank]p3b4:
2390 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2391 // implicit object parameter of a non-static member function declared
2392 // without a ref-qualifier, and S1 binds an rvalue reference to an
2393 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00002394 // FIXME: We don't know if we're dealing with the implicit object parameter,
2395 // or if the member function in this case has a ref qualifier.
2396 // (Of course, we don't have ref qualifiers yet.)
2397 if (SCS1.RRefBinding != SCS2.RRefBinding)
2398 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2399 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002400
2401 // C++ [over.ics.rank]p3b4:
2402 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2403 // which the references refer are the same type except for
2404 // top-level cv-qualifiers, and the type to which the reference
2405 // initialized by S2 refers is more cv-qualified than the type
2406 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00002407 QualType T1 = SCS1.getToType(2);
2408 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002409 T1 = S.Context.getCanonicalType(T1);
2410 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002411 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002412 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2413 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002414 if (UnqualT1 == UnqualT2) {
2415 // If the type is an array type, promote the element qualifiers to the type
2416 // for comparison.
2417 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002418 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002419 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002420 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002421 if (T2.isMoreQualifiedThan(T1))
2422 return ImplicitConversionSequence::Better;
2423 else if (T1.isMoreQualifiedThan(T2))
2424 return ImplicitConversionSequence::Worse;
2425 }
2426 }
Douglas Gregor57373262008-10-22 14:17:15 +00002427
2428 return ImplicitConversionSequence::Indistinguishable;
2429}
2430
2431/// CompareQualificationConversions - Compares two standard conversion
2432/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00002433/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2434ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002435CompareQualificationConversions(Sema &S,
2436 const StandardConversionSequence& SCS1,
2437 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00002438 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00002439 // -- S1 and S2 differ only in their qualification conversion and
2440 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2441 // cv-qualification signature of type T1 is a proper subset of
2442 // the cv-qualification signature of type T2, and S1 is not the
2443 // deprecated string literal array-to-pointer conversion (4.2).
2444 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2445 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2446 return ImplicitConversionSequence::Indistinguishable;
2447
2448 // FIXME: the example in the standard doesn't use a qualification
2449 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00002450 QualType T1 = SCS1.getToType(2);
2451 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002452 T1 = S.Context.getCanonicalType(T1);
2453 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002454 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002455 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2456 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00002457
2458 // If the types are the same, we won't learn anything by unwrapped
2459 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002460 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00002461 return ImplicitConversionSequence::Indistinguishable;
2462
Chandler Carruth28e318c2009-12-29 07:16:59 +00002463 // If the type is an array type, promote the element qualifiers to the type
2464 // for comparison.
2465 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002466 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002467 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002468 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002469
Mike Stump1eb44332009-09-09 15:08:12 +00002470 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00002471 = ImplicitConversionSequence::Indistinguishable;
John McCall120d63c2010-08-24 20:38:10 +00002472 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00002473 // Within each iteration of the loop, we check the qualifiers to
2474 // determine if this still looks like a qualification
2475 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002476 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00002477 // until there are no more pointers or pointers-to-members left
2478 // to unwrap. This essentially mimics what
2479 // IsQualificationConversion does, but here we're checking for a
2480 // strict subset of qualifiers.
2481 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2482 // The qualifiers are the same, so this doesn't tell us anything
2483 // about how the sequences rank.
2484 ;
2485 else if (T2.isMoreQualifiedThan(T1)) {
2486 // T1 has fewer qualifiers, so it could be the better sequence.
2487 if (Result == ImplicitConversionSequence::Worse)
2488 // Neither has qualifiers that are a subset of the other's
2489 // qualifiers.
2490 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002491
Douglas Gregor57373262008-10-22 14:17:15 +00002492 Result = ImplicitConversionSequence::Better;
2493 } else if (T1.isMoreQualifiedThan(T2)) {
2494 // T2 has fewer qualifiers, so it could be the better sequence.
2495 if (Result == ImplicitConversionSequence::Better)
2496 // Neither has qualifiers that are a subset of the other's
2497 // qualifiers.
2498 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002499
Douglas Gregor57373262008-10-22 14:17:15 +00002500 Result = ImplicitConversionSequence::Worse;
2501 } else {
2502 // Qualifiers are disjoint.
2503 return ImplicitConversionSequence::Indistinguishable;
2504 }
2505
2506 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00002507 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00002508 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002509 }
2510
Douglas Gregor57373262008-10-22 14:17:15 +00002511 // Check that the winning standard conversion sequence isn't using
2512 // the deprecated string literal array to pointer conversion.
2513 switch (Result) {
2514 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00002515 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002516 Result = ImplicitConversionSequence::Indistinguishable;
2517 break;
2518
2519 case ImplicitConversionSequence::Indistinguishable:
2520 break;
2521
2522 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00002523 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002524 Result = ImplicitConversionSequence::Indistinguishable;
2525 break;
2526 }
2527
2528 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002529}
2530
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002531/// CompareDerivedToBaseConversions - Compares two standard conversion
2532/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002533/// various kinds of derived-to-base conversions (C++
2534/// [over.ics.rank]p4b3). As part of these checks, we also look at
2535/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002536ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002537CompareDerivedToBaseConversions(Sema &S,
2538 const StandardConversionSequence& SCS1,
2539 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002540 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002541 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002542 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002543 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002544
2545 // Adjust the types we're converting from via the array-to-pointer
2546 // conversion, if we need to.
2547 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002548 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002549 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002550 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002551
2552 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00002553 FromType1 = S.Context.getCanonicalType(FromType1);
2554 ToType1 = S.Context.getCanonicalType(ToType1);
2555 FromType2 = S.Context.getCanonicalType(FromType2);
2556 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002557
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002558 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002559 //
2560 // If class B is derived directly or indirectly from class A and
2561 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002562 //
2563 // For Objective-C, we let A, B, and C also be Objective-C
2564 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002565
2566 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002567 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002568 SCS2.Second == ICK_Pointer_Conversion &&
2569 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2570 FromType1->isPointerType() && FromType2->isPointerType() &&
2571 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002572 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002573 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002574 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002575 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002576 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002577 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002578 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002579 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002580
John McCallc12c5bb2010-05-15 11:32:37 +00002581 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2582 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2583 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2584 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002585
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002586 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002587 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002588 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002589 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002590 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002591 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00002592
2593 if (ToIface1 && ToIface2) {
John McCall120d63c2010-08-24 20:38:10 +00002594 if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002595 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002596 else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002597 return ImplicitConversionSequence::Worse;
2598 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002599 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002600
2601 // -- conversion of B* to A* is better than conversion of C* to A*,
2602 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002603 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002604 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002605 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002606 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00002607
Douglas Gregorcb7de522008-11-26 23:31:11 +00002608 if (FromIface1 && FromIface2) {
John McCall120d63c2010-08-24 20:38:10 +00002609 if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002610 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002611 else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002612 return ImplicitConversionSequence::Worse;
2613 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002614 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002615 }
2616
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002617 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002618 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2619 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2620 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2621 const MemberPointerType * FromMemPointer1 =
2622 FromType1->getAs<MemberPointerType>();
2623 const MemberPointerType * ToMemPointer1 =
2624 ToType1->getAs<MemberPointerType>();
2625 const MemberPointerType * FromMemPointer2 =
2626 FromType2->getAs<MemberPointerType>();
2627 const MemberPointerType * ToMemPointer2 =
2628 ToType2->getAs<MemberPointerType>();
2629 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2630 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2631 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2632 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2633 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2634 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2635 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2636 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002637 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002638 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002639 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002640 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00002641 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002642 return ImplicitConversionSequence::Better;
2643 }
2644 // conversion of B::* to C::* is better than conversion of A::* to C::*
2645 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002646 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002647 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002648 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002649 return ImplicitConversionSequence::Worse;
2650 }
2651 }
2652
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002653 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002654 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00002655 // -- binding of an expression of type C to a reference of type
2656 // B& is better than binding an expression of type C to a
2657 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00002658 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2659 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2660 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002661 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002662 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002663 return ImplicitConversionSequence::Worse;
2664 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002665
Douglas Gregor225c41e2008-11-03 19:09:14 +00002666 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00002667 // -- binding of an expression of type B to a reference of type
2668 // A& is better than binding an expression of type C to a
2669 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00002670 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2671 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2672 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002673 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002674 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002675 return ImplicitConversionSequence::Worse;
2676 }
2677 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002678
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002679 return ImplicitConversionSequence::Indistinguishable;
2680}
2681
Douglas Gregorabe183d2010-04-13 16:31:36 +00002682/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2683/// determine whether they are reference-related,
2684/// reference-compatible, reference-compatible with added
2685/// qualification, or incompatible, for use in C++ initialization by
2686/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2687/// type, and the first type (T1) is the pointee type of the reference
2688/// type being initialized.
2689Sema::ReferenceCompareResult
2690Sema::CompareReferenceRelationship(SourceLocation Loc,
2691 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00002692 bool &DerivedToBase,
2693 bool &ObjCConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002694 assert(!OrigT1->isReferenceType() &&
2695 "T1 must be the pointee type of the reference type");
2696 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2697
2698 QualType T1 = Context.getCanonicalType(OrigT1);
2699 QualType T2 = Context.getCanonicalType(OrigT2);
2700 Qualifiers T1Quals, T2Quals;
2701 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2702 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2703
2704 // C++ [dcl.init.ref]p4:
2705 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2706 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2707 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00002708 DerivedToBase = false;
2709 ObjCConversion = false;
2710 if (UnqualT1 == UnqualT2) {
2711 // Nothing to do.
2712 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00002713 IsDerivedFrom(UnqualT2, UnqualT1))
2714 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00002715 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2716 UnqualT2->isObjCObjectOrInterfaceType() &&
2717 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2718 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002719 else
2720 return Ref_Incompatible;
2721
2722 // At this point, we know that T1 and T2 are reference-related (at
2723 // least).
2724
2725 // If the type is an array type, promote the element qualifiers to the type
2726 // for comparison.
2727 if (isa<ArrayType>(T1) && T1Quals)
2728 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2729 if (isa<ArrayType>(T2) && T2Quals)
2730 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2731
2732 // C++ [dcl.init.ref]p4:
2733 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2734 // reference-related to T2 and cv1 is the same cv-qualification
2735 // as, or greater cv-qualification than, cv2. For purposes of
2736 // overload resolution, cases for which cv1 is greater
2737 // cv-qualification than cv2 are identified as
2738 // reference-compatible with added qualification (see 13.3.3.2).
2739 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2740 return Ref_Compatible;
2741 else if (T1.isMoreQualifiedThan(T2))
2742 return Ref_Compatible_With_Added_Qualification;
2743 else
2744 return Ref_Related;
2745}
2746
Douglas Gregor604eb652010-08-11 02:15:33 +00002747/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00002748/// with DeclType. Return true if something definite is found.
2749static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00002750FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2751 QualType DeclType, SourceLocation DeclLoc,
2752 Expr *Init, QualType T2, bool AllowRvalues,
2753 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00002754 assert(T2->isRecordType() && "Can only find conversions of record types.");
2755 CXXRecordDecl *T2RecordDecl
2756 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2757
Douglas Gregor604eb652010-08-11 02:15:33 +00002758 QualType ToType
2759 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType()
2760 : DeclType;
2761
Sebastian Redl4680bf22010-06-30 18:13:39 +00002762 OverloadCandidateSet CandidateSet(DeclLoc);
2763 const UnresolvedSetImpl *Conversions
2764 = T2RecordDecl->getVisibleConversionFunctions();
2765 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2766 E = Conversions->end(); I != E; ++I) {
2767 NamedDecl *D = *I;
2768 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2769 if (isa<UsingShadowDecl>(D))
2770 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2771
2772 FunctionTemplateDecl *ConvTemplate
2773 = dyn_cast<FunctionTemplateDecl>(D);
2774 CXXConversionDecl *Conv;
2775 if (ConvTemplate)
2776 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2777 else
2778 Conv = cast<CXXConversionDecl>(D);
2779
Douglas Gregor604eb652010-08-11 02:15:33 +00002780 // If this is an explicit conversion, and we're not allowed to consider
2781 // explicit conversions, skip it.
2782 if (!AllowExplicit && Conv->isExplicit())
2783 continue;
2784
2785 if (AllowRvalues) {
2786 bool DerivedToBase = false;
2787 bool ObjCConversion = false;
2788 if (!ConvTemplate &&
2789 S.CompareReferenceRelationship(DeclLoc,
2790 Conv->getConversionType().getNonReferenceType().getUnqualifiedType(),
2791 DeclType.getNonReferenceType().getUnqualifiedType(),
2792 DerivedToBase, ObjCConversion)
2793 == Sema::Ref_Incompatible)
2794 continue;
2795 } else {
2796 // If the conversion function doesn't return a reference type,
2797 // it can't be considered for this conversion. An rvalue reference
2798 // is only acceptable if its referencee is a function type.
2799
2800 const ReferenceType *RefType =
2801 Conv->getConversionType()->getAs<ReferenceType>();
2802 if (!RefType ||
2803 (!RefType->isLValueReferenceType() &&
2804 !RefType->getPointeeType()->isFunctionType()))
2805 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002806 }
Douglas Gregor604eb652010-08-11 02:15:33 +00002807
2808 if (ConvTemplate)
2809 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2810 Init, ToType, CandidateSet);
2811 else
2812 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2813 ToType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002814 }
2815
2816 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002817 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00002818 case OR_Success:
2819 // C++ [over.ics.ref]p1:
2820 //
2821 // [...] If the parameter binds directly to the result of
2822 // applying a conversion function to the argument
2823 // expression, the implicit conversion sequence is a
2824 // user-defined conversion sequence (13.3.3.1.2), with the
2825 // second standard conversion sequence either an identity
2826 // conversion or, if the conversion function returns an
2827 // entity of a type that is a derived class of the parameter
2828 // type, a derived-to-base Conversion.
2829 if (!Best->FinalConversion.DirectBinding)
2830 return false;
2831
2832 ICS.setUserDefined();
2833 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2834 ICS.UserDefined.After = Best->FinalConversion;
2835 ICS.UserDefined.ConversionFunction = Best->Function;
2836 ICS.UserDefined.EllipsisConversion = false;
2837 assert(ICS.UserDefined.After.ReferenceBinding &&
2838 ICS.UserDefined.After.DirectBinding &&
2839 "Expected a direct reference binding!");
2840 return true;
2841
2842 case OR_Ambiguous:
2843 ICS.setAmbiguous();
2844 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2845 Cand != CandidateSet.end(); ++Cand)
2846 if (Cand->Viable)
2847 ICS.Ambiguous.addConversion(Cand->Function);
2848 return true;
2849
2850 case OR_No_Viable_Function:
2851 case OR_Deleted:
2852 // There was no suitable conversion, or we found a deleted
2853 // conversion; continue with other checks.
2854 return false;
2855 }
Eric Christopher1c3d5022010-06-30 18:36:32 +00002856
2857 return false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002858}
2859
Douglas Gregorabe183d2010-04-13 16:31:36 +00002860/// \brief Compute an implicit conversion sequence for reference
2861/// initialization.
2862static ImplicitConversionSequence
2863TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2864 SourceLocation DeclLoc,
2865 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002866 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002867 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2868
2869 // Most paths end in a failed conversion.
2870 ImplicitConversionSequence ICS;
2871 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2872
2873 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2874 QualType T2 = Init->getType();
2875
2876 // If the initializer is the address of an overloaded function, try
2877 // to resolve the overloaded function. If all goes well, T2 is the
2878 // type of the resulting function.
2879 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2880 DeclAccessPair Found;
2881 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2882 false, Found))
2883 T2 = Fn->getType();
2884 }
2885
2886 // Compute some basic properties of the types and the initializer.
2887 bool isRValRef = DeclType->isRValueReferenceType();
2888 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002889 bool ObjCConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002890 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002891 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002892 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2893 ObjCConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002894
Douglas Gregorabe183d2010-04-13 16:31:36 +00002895
Sebastian Redl4680bf22010-06-30 18:13:39 +00002896 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00002897 // A reference to type "cv1 T1" is initialized by an expression
2898 // of type "cv2 T2" as follows:
2899
Sebastian Redl4680bf22010-06-30 18:13:39 +00002900 // -- If reference is an lvalue reference and the initializer expression
2901 // The next bullet point (T1 is a function) is pretty much equivalent to this
2902 // one, so it's handled here.
2903 if (!isRValRef || T1->isFunctionType()) {
2904 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2905 // reference-compatible with "cv2 T2," or
2906 //
2907 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2908 if (InitCategory.isLValue() &&
2909 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002910 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00002911 // When a parameter of reference type binds directly (8.5.3)
2912 // to an argument expression, the implicit conversion sequence
2913 // is the identity conversion, unless the argument expression
2914 // has a type that is a derived class of the parameter type,
2915 // in which case the implicit conversion sequence is a
2916 // derived-to-base Conversion (13.3.3.1).
2917 ICS.setStandard();
2918 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00002919 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2920 : ObjCConversion? ICK_Compatible_Conversion
2921 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002922 ICS.Standard.Third = ICK_Identity;
2923 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2924 ICS.Standard.setToType(0, T2);
2925 ICS.Standard.setToType(1, T1);
2926 ICS.Standard.setToType(2, T1);
2927 ICS.Standard.ReferenceBinding = true;
2928 ICS.Standard.DirectBinding = true;
2929 ICS.Standard.RRefBinding = isRValRef;
2930 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002931
Sebastian Redl4680bf22010-06-30 18:13:39 +00002932 // Nothing more to do: the inaccessibility/ambiguity check for
2933 // derived-to-base conversions is suppressed when we're
2934 // computing the implicit conversion sequence (C++
2935 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00002936 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002937 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00002938
Sebastian Redl4680bf22010-06-30 18:13:39 +00002939 // -- has a class type (i.e., T2 is a class type), where T1 is
2940 // not reference-related to T2, and can be implicitly
2941 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2942 // is reference-compatible with "cv3 T3" 92) (this
2943 // conversion is selected by enumerating the applicable
2944 // conversion functions (13.3.1.6) and choosing the best
2945 // one through overload resolution (13.3)),
2946 if (!SuppressUserConversions && T2->isRecordType() &&
2947 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2948 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00002949 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2950 Init, T2, /*AllowRvalues=*/false,
2951 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00002952 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002953 }
2954 }
2955
Sebastian Redl4680bf22010-06-30 18:13:39 +00002956 // -- Otherwise, the reference shall be an lvalue reference to a
2957 // non-volatile const type (i.e., cv1 shall be const), or the reference
2958 // shall be an rvalue reference and the initializer expression shall be
2959 // an rvalue or have a function type.
Douglas Gregor66821b52010-04-18 09:22:00 +00002960 //
2961 // We actually handle one oddity of C++ [over.ics.ref] at this
2962 // point, which is that, due to p2 (which short-circuits reference
2963 // binding by only attempting a simple conversion for non-direct
2964 // bindings) and p3's strange wording, we allow a const volatile
2965 // reference to bind to an rvalue. Hence the check for the presence
2966 // of "const" rather than checking for "const" being the only
2967 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00002968 // This is also the point where rvalue references and lvalue inits no longer
2969 // go together.
2970 if ((!isRValRef && !T1.isConstQualified()) ||
2971 (isRValRef && InitCategory.isLValue()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00002972 return ICS;
2973
Sebastian Redl4680bf22010-06-30 18:13:39 +00002974 // -- If T1 is a function type, then
2975 // -- if T2 is the same type as T1, the reference is bound to the
2976 // initializer expression lvalue;
2977 // -- if T2 is a class type and the initializer expression can be
2978 // implicitly converted to an lvalue of type T1 [...], the
2979 // reference is bound to the function lvalue that is the result
2980 // of the conversion;
2981 // This is the same as for the lvalue case above, so it was handled there.
2982 // -- otherwise, the program is ill-formed.
2983 // This is the one difference to the lvalue case.
2984 if (T1->isFunctionType())
2985 return ICS;
2986
2987 // -- Otherwise, if T2 is a class type and
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002988 // -- the initializer expression is an rvalue and "cv1 T1"
2989 // is reference-compatible with "cv2 T2," or
Douglas Gregorabe183d2010-04-13 16:31:36 +00002990 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002991 // -- T1 is not reference-related to T2 and the initializer
2992 // expression can be implicitly converted to an rvalue
2993 // of type "cv3 T3" (this conversion is selected by
2994 // enumerating the applicable conversion functions
2995 // (13.3.1.6) and choosing the best one through overload
2996 // resolution (13.3)),
Douglas Gregorabe183d2010-04-13 16:31:36 +00002997 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002998 // then the reference is bound to the initializer
2999 // expression rvalue in the first case and to the object
3000 // that is the result of the conversion in the second case
3001 // (or, in either case, to the appropriate base class
3002 // subobject of the object).
Douglas Gregor604eb652010-08-11 02:15:33 +00003003 if (T2->isRecordType()) {
3004 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a
3005 // direct binding in C++0x but not in C++03.
3006 if (InitCategory.isRValue() &&
3007 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
3008 ICS.setStandard();
3009 ICS.Standard.First = ICK_Identity;
3010 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3011 : ObjCConversion? ICK_Compatible_Conversion
3012 : ICK_Identity;
3013 ICS.Standard.Third = ICK_Identity;
3014 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3015 ICS.Standard.setToType(0, T2);
3016 ICS.Standard.setToType(1, T1);
3017 ICS.Standard.setToType(2, T1);
3018 ICS.Standard.ReferenceBinding = true;
3019 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
3020 ICS.Standard.RRefBinding = isRValRef;
3021 ICS.Standard.CopyConstructor = 0;
3022 return ICS;
3023 }
3024
3025 // Second case: not reference-related.
3026 if (RefRelationship == Sema::Ref_Incompatible &&
3027 !S.RequireCompleteType(DeclLoc, T2, 0) &&
3028 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3029 Init, T2, /*AllowRvalues=*/true,
3030 AllowExplicit))
3031 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003032 }
Douglas Gregor604eb652010-08-11 02:15:33 +00003033
Douglas Gregorabe183d2010-04-13 16:31:36 +00003034 // -- Otherwise, a temporary of type "cv1 T1" is created and
3035 // initialized from the initializer expression using the
3036 // rules for a non-reference copy initialization (8.5). The
3037 // reference is then bound to the temporary. If T1 is
3038 // reference-related to T2, cv1 must be the same
3039 // cv-qualification as, or greater cv-qualification than,
3040 // cv2; otherwise, the program is ill-formed.
3041 if (RefRelationship == Sema::Ref_Related) {
3042 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3043 // we would be reference-compatible or reference-compatible with
3044 // added qualification. But that wasn't the case, so the reference
3045 // initialization fails.
3046 return ICS;
3047 }
3048
3049 // If at least one of the types is a class type, the types are not
3050 // related, and we aren't allowed any user conversions, the
3051 // reference binding fails. This case is important for breaking
3052 // recursion, since TryImplicitConversion below will attempt to
3053 // create a temporary through the use of a copy constructor.
3054 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3055 (T1->isRecordType() || T2->isRecordType()))
3056 return ICS;
3057
3058 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00003059 // When a parameter of reference type is not bound directly to
3060 // an argument expression, the conversion sequence is the one
3061 // required to convert the argument expression to the
3062 // underlying type of the reference according to
3063 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3064 // to copy-initializing a temporary of the underlying type with
3065 // the argument expression. Any difference in top-level
3066 // cv-qualification is subsumed by the initialization itself
3067 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00003068 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3069 /*AllowExplicit=*/false,
3070 /*InOverloadResolution=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003071
3072 // Of course, that's still a reference binding.
3073 if (ICS.isStandard()) {
3074 ICS.Standard.ReferenceBinding = true;
3075 ICS.Standard.RRefBinding = isRValRef;
3076 } else if (ICS.isUserDefined()) {
3077 ICS.UserDefined.After.ReferenceBinding = true;
3078 ICS.UserDefined.After.RRefBinding = isRValRef;
3079 }
3080 return ICS;
3081}
3082
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003083/// TryCopyInitialization - Try to copy-initialize a value of type
3084/// ToType from the expression From. Return the implicit conversion
3085/// sequence required to pass this argument, which may be a bad
3086/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00003087/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00003088/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00003089static ImplicitConversionSequence
3090TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregorb7f9e6a2010-04-16 17:53:55 +00003091 bool SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00003092 bool InOverloadResolution) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003093 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00003094 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00003095 /*FIXME:*/From->getLocStart(),
3096 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003097 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003098
John McCall120d63c2010-08-24 20:38:10 +00003099 return TryImplicitConversion(S, From, ToType,
3100 SuppressUserConversions,
3101 /*AllowExplicit=*/false,
3102 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003103}
3104
Douglas Gregor96176b32008-11-18 23:14:02 +00003105/// TryObjectArgumentInitialization - Try to initialize the object
3106/// parameter of the given member function (@c Method) from the
3107/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00003108static ImplicitConversionSequence
3109TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3110 CXXMethodDecl *Method,
3111 CXXRecordDecl *ActingContext) {
3112 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003113 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3114 // const volatile object.
3115 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3116 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00003117 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00003118
3119 // Set up the conversion sequence as a "bad" conversion, to allow us
3120 // to exit early.
3121 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00003122
3123 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00003124 QualType FromType = OrigFromType;
Ted Kremenek6217b802009-07-29 21:53:49 +00003125 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00003126 FromType = PT->getPointeeType();
3127
3128 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00003129
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003130 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00003131 // where X is the class of which the function is a member
3132 // (C++ [over.match.funcs]p4). However, when finding an implicit
3133 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00003134 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00003135 // (C++ [over.match.funcs]p5). We perform a simplified version of
3136 // reference binding here, that allows class rvalues to bind to
3137 // non-constant references.
3138
3139 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3140 // with the implicit object parameter (C++ [over.match.funcs]p5).
John McCall120d63c2010-08-24 20:38:10 +00003141 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00003142 if (ImplicitParamType.getCVRQualifiers()
3143 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00003144 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00003145 ICS.setBad(BadConversionSequence::bad_qualifiers,
3146 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003147 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003148 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003149
3150 // Check that we have either the same type or a derived type. It
3151 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00003152 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00003153 ImplicitConversionKind SecondKind;
3154 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3155 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00003156 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00003157 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00003158 else {
John McCallb1bdc622010-02-25 01:37:24 +00003159 ICS.setBad(BadConversionSequence::unrelated_class,
3160 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003161 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003162 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003163
3164 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00003165 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00003166 ICS.Standard.setAsIdentityConversion();
3167 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00003168 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003169 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003170 ICS.Standard.ReferenceBinding = true;
3171 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00003172 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003173 return ICS;
3174}
3175
3176/// PerformObjectArgumentInitialization - Perform initialization of
3177/// the implicit object parameter for the given Method with the given
3178/// expression.
3179bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00003180Sema::PerformObjectArgumentInitialization(Expr *&From,
3181 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00003182 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00003183 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003184 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00003185 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00003186 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003187
Ted Kremenek6217b802009-07-29 21:53:49 +00003188 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003189 FromRecordType = PT->getPointeeType();
3190 DestType = Method->getThisType(Context);
3191 } else {
3192 FromRecordType = From->getType();
3193 DestType = ImplicitParamRecordType;
3194 }
3195
John McCall701c89e2009-12-03 04:06:58 +00003196 // Note that we always use the true parent context when performing
3197 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003198 ImplicitConversionSequence ICS
John McCall120d63c2010-08-24 20:38:10 +00003199 = TryObjectArgumentInitialization(*this, From->getType(), Method,
John McCall701c89e2009-12-03 04:06:58 +00003200 Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00003201 if (ICS.isBad()) {
3202 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3203 Qualifiers FromQs = FromRecordType.getQualifiers();
3204 Qualifiers ToQs = DestType.getQualifiers();
3205 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3206 if (CVR) {
3207 Diag(From->getSourceRange().getBegin(),
3208 diag::err_member_function_call_bad_cvr)
3209 << Method->getDeclName() << FromRecordType << (CVR - 1)
3210 << From->getSourceRange();
3211 Diag(Method->getLocation(), diag::note_previous_decl)
3212 << Method->getDeclName();
3213 return true;
3214 }
3215 }
3216
Douglas Gregor96176b32008-11-18 23:14:02 +00003217 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003218 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00003219 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00003220 }
Mike Stump1eb44332009-09-09 15:08:12 +00003221
Douglas Gregor5fccd362010-03-03 23:55:11 +00003222 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall6bb80172010-03-30 21:47:33 +00003223 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor96176b32008-11-18 23:14:02 +00003224
Douglas Gregor5fccd362010-03-03 23:55:11 +00003225 if (!Context.hasSameType(From->getType(), DestType))
John McCall2de56d12010-08-25 11:45:40 +00003226 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall5baba9d2010-08-25 10:28:54 +00003227 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor96176b32008-11-18 23:14:02 +00003228 return false;
3229}
3230
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003231/// TryContextuallyConvertToBool - Attempt to contextually convert the
3232/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00003233static ImplicitConversionSequence
3234TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00003235 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00003236 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003237 // FIXME: Are these flags correct?
3238 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00003239 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00003240 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003241}
3242
3243/// PerformContextuallyConvertToBool - Perform a contextual conversion
3244/// of the expression From to bool (C++0x [conv]p3).
3245bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall120d63c2010-08-24 20:38:10 +00003246 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00003247 if (!ICS.isBad())
3248 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003249
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003250 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003251 return Diag(From->getSourceRange().getBegin(),
3252 diag::err_typecheck_bool_condition)
3253 << From->getType() << From->getSourceRange();
3254 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003255}
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003256
3257/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3258/// expression From to 'id'.
John McCall120d63c2010-08-24 20:38:10 +00003259static ImplicitConversionSequence
3260TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3261 QualType Ty = S.Context.getObjCIdType();
3262 return TryImplicitConversion(S, From, Ty,
3263 // FIXME: Are these flags correct?
3264 /*SuppressUserConversions=*/false,
3265 /*AllowExplicit=*/true,
3266 /*InOverloadResolution=*/false);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003267}
John McCall120d63c2010-08-24 20:38:10 +00003268
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003269/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3270/// of the expression From to 'id'.
3271bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003272 QualType Ty = Context.getObjCIdType();
John McCall120d63c2010-08-24 20:38:10 +00003273 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003274 if (!ICS.isBad())
3275 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3276 return true;
3277}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003278
Douglas Gregorc30614b2010-06-29 23:17:37 +00003279/// \brief Attempt to convert the given expression to an integral or
3280/// enumeration type.
3281///
3282/// This routine will attempt to convert an expression of class type to an
3283/// integral or enumeration type, if that class type only has a single
3284/// conversion to an integral or enumeration type.
3285///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003286/// \param Loc The source location of the construct that requires the
3287/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00003288///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003289/// \param FromE The expression we're converting from.
3290///
3291/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3292/// have integral or enumeration type.
3293///
3294/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3295/// incomplete class type.
3296///
3297/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3298/// explicit conversion function (because no implicit conversion functions
3299/// were available). This is a recovery mode.
3300///
3301/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3302/// showing which conversion was picked.
3303///
3304/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3305/// conversion function that could convert to integral or enumeration type.
3306///
3307/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3308/// usable conversion function.
3309///
3310/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3311/// function, which may be an extension in this case.
3312///
3313/// \returns The expression, converted to an integral or enumeration type if
3314/// successful.
John McCall60d7b3a2010-08-24 06:29:42 +00003315ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003316Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorc30614b2010-06-29 23:17:37 +00003317 const PartialDiagnostic &NotIntDiag,
3318 const PartialDiagnostic &IncompleteDiag,
3319 const PartialDiagnostic &ExplicitConvDiag,
3320 const PartialDiagnostic &ExplicitConvNote,
3321 const PartialDiagnostic &AmbigDiag,
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003322 const PartialDiagnostic &AmbigNote,
3323 const PartialDiagnostic &ConvDiag) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00003324 // We can't perform any more checking for type-dependent expressions.
3325 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00003326 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003327
3328 // If the expression already has integral or enumeration type, we're golden.
3329 QualType T = From->getType();
3330 if (T->isIntegralOrEnumerationType())
John McCall9ae2f072010-08-23 23:25:46 +00003331 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003332
3333 // FIXME: Check for missing '()' if T is a function type?
3334
3335 // If we don't have a class type in C++, there's no way we can get an
3336 // expression of integral or enumeration type.
3337 const RecordType *RecordTy = T->getAs<RecordType>();
3338 if (!RecordTy || !getLangOptions().CPlusPlus) {
3339 Diag(Loc, NotIntDiag)
3340 << T << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00003341 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003342 }
3343
3344 // We must have a complete class type.
3345 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCall9ae2f072010-08-23 23:25:46 +00003346 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003347
3348 // Look for a conversion to an integral or enumeration type.
3349 UnresolvedSet<4> ViableConversions;
3350 UnresolvedSet<4> ExplicitConversions;
3351 const UnresolvedSetImpl *Conversions
3352 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3353
3354 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3355 E = Conversions->end();
3356 I != E;
3357 ++I) {
3358 if (CXXConversionDecl *Conversion
3359 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3360 if (Conversion->getConversionType().getNonReferenceType()
3361 ->isIntegralOrEnumerationType()) {
3362 if (Conversion->isExplicit())
3363 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3364 else
3365 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3366 }
3367 }
3368
3369 switch (ViableConversions.size()) {
3370 case 0:
3371 if (ExplicitConversions.size() == 1) {
3372 DeclAccessPair Found = ExplicitConversions[0];
3373 CXXConversionDecl *Conversion
3374 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3375
3376 // The user probably meant to invoke the given explicit
3377 // conversion; use it.
3378 QualType ConvTy
3379 = Conversion->getConversionType().getNonReferenceType();
3380 std::string TypeStr;
3381 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3382
3383 Diag(Loc, ExplicitConvDiag)
3384 << T << ConvTy
3385 << FixItHint::CreateInsertion(From->getLocStart(),
3386 "static_cast<" + TypeStr + ">(")
3387 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3388 ")");
3389 Diag(Conversion->getLocation(), ExplicitConvNote)
3390 << ConvTy->isEnumeralType() << ConvTy;
3391
3392 // If we aren't in a SFINAE context, build a call to the
3393 // explicit conversion function.
3394 if (isSFINAEContext())
3395 return ExprError();
3396
3397 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
John McCall9ae2f072010-08-23 23:25:46 +00003398 From = BuildCXXMemberCallExpr(From, Found, Conversion);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003399 }
3400
3401 // We'll complain below about a non-integral condition type.
3402 break;
3403
3404 case 1: {
3405 // Apply this conversion.
3406 DeclAccessPair Found = ViableConversions[0];
3407 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003408
3409 CXXConversionDecl *Conversion
3410 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3411 QualType ConvTy
3412 = Conversion->getConversionType().getNonReferenceType();
3413 if (ConvDiag.getDiagID()) {
3414 if (isSFINAEContext())
3415 return ExprError();
3416
3417 Diag(Loc, ConvDiag)
3418 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3419 }
3420
John McCall9ae2f072010-08-23 23:25:46 +00003421 From = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorc30614b2010-06-29 23:17:37 +00003422 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregorc30614b2010-06-29 23:17:37 +00003423 break;
3424 }
3425
3426 default:
3427 Diag(Loc, AmbigDiag)
3428 << T << From->getSourceRange();
3429 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3430 CXXConversionDecl *Conv
3431 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3432 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3433 Diag(Conv->getLocation(), AmbigNote)
3434 << ConvTy->isEnumeralType() << ConvTy;
3435 }
John McCall9ae2f072010-08-23 23:25:46 +00003436 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003437 }
3438
Douglas Gregoracb0bd82010-06-29 23:25:20 +00003439 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorc30614b2010-06-29 23:17:37 +00003440 Diag(Loc, NotIntDiag)
3441 << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00003442
John McCall9ae2f072010-08-23 23:25:46 +00003443 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003444}
3445
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003446/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00003447/// candidate functions, using the given function call arguments. If
3448/// @p SuppressUserConversions, then don't allow user-defined
3449/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003450///
3451/// \para PartialOverloading true if we are performing "partial" overloading
3452/// based on an incomplete set of function arguments. This feature is used by
3453/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00003454void
3455Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00003456 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003457 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00003458 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00003459 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003460 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00003461 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003462 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003463 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00003464 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00003465 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00003466
Douglas Gregor88a35142008-12-22 05:46:06 +00003467 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003468 if (!isa<CXXConstructorDecl>(Method)) {
3469 // If we get here, it's because we're calling a member function
3470 // that is named without a member access expression (e.g.,
3471 // "this->f") that was either written explicitly or created
3472 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00003473 // function, e.g., X::f(). We use an empty type for the implied
3474 // object argument (C++ [over.call.func]p3), and the acting context
3475 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00003476 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall701c89e2009-12-03 04:06:58 +00003477 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003478 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003479 return;
3480 }
3481 // We treat a constructor like a non-member function, since its object
3482 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00003483 }
3484
Douglas Gregorfd476482009-11-13 23:59:09 +00003485 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00003486 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00003487
Douglas Gregor7edfb692009-11-23 12:27:39 +00003488 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003489 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003490
Douglas Gregor66724ea2009-11-14 01:20:54 +00003491 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3492 // C++ [class.copy]p3:
3493 // A member function template is never instantiated to perform the copy
3494 // of a class object to an object of its class type.
3495 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3496 if (NumArgs == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00003497 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00003498 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3499 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00003500 return;
3501 }
3502
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003503 // Add this candidate
3504 CandidateSet.push_back(OverloadCandidate());
3505 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003506 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003507 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00003508 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003509 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003510 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003511
3512 unsigned NumArgsInProto = Proto->getNumArgs();
3513
3514 // (C++ 13.3.2p2): A candidate function having fewer than m
3515 // parameters is viable only if it has an ellipsis in its parameter
3516 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00003517 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3518 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003519 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003520 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003521 return;
3522 }
3523
3524 // (C++ 13.3.2p2): A candidate function having more than m parameters
3525 // is viable only if the (m+1)st parameter has a default argument
3526 // (8.3.6). For the purposes of overload resolution, the
3527 // parameter list is truncated on the right, so that there are
3528 // exactly m parameters.
3529 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003530 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003531 // Not enough arguments.
3532 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003533 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003534 return;
3535 }
3536
3537 // Determine the implicit conversion sequences for each of the
3538 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003539 Candidate.Conversions.resize(NumArgs);
3540 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3541 if (ArgIdx < NumArgsInProto) {
3542 // (C++ 13.3.2p3): for F to be a viable function, there shall
3543 // exist for each argument an implicit conversion sequence
3544 // (13.3.3.1) that converts that argument to the corresponding
3545 // parameter of F.
3546 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003547 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003548 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003549 SuppressUserConversions,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003550 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003551 if (Candidate.Conversions[ArgIdx].isBad()) {
3552 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003553 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00003554 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00003555 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003556 } else {
3557 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3558 // argument for which there is no corresponding parameter is
3559 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003560 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003561 }
3562 }
3563}
3564
Douglas Gregor063daf62009-03-13 18:40:31 +00003565/// \brief Add all of the function declarations in the given function set to
3566/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00003567void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00003568 Expr **Args, unsigned NumArgs,
3569 OverloadCandidateSet& CandidateSet,
3570 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00003571 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00003572 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3573 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003574 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003575 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003576 cast<CXXMethodDecl>(FD)->getParent(),
3577 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003578 CandidateSet, SuppressUserConversions);
3579 else
John McCall9aa472c2010-03-19 07:35:19 +00003580 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00003581 SuppressUserConversions);
3582 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003583 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00003584 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3585 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003586 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003587 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00003588 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00003589 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003590 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00003591 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00003592 else
John McCall9aa472c2010-03-19 07:35:19 +00003593 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00003594 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00003595 Args, NumArgs, CandidateSet,
3596 SuppressUserConversions);
3597 }
Douglas Gregor364e0212009-06-27 21:05:07 +00003598 }
Douglas Gregor063daf62009-03-13 18:40:31 +00003599}
3600
John McCall314be4e2009-11-17 07:50:12 +00003601/// AddMethodCandidate - Adds a named decl (which is some kind of
3602/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00003603void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003604 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00003605 Expr **Args, unsigned NumArgs,
3606 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003607 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00003608 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003609 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00003610
3611 if (isa<UsingShadowDecl>(Decl))
3612 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3613
3614 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3615 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3616 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00003617 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3618 /*ExplicitArgs*/ 0,
John McCall701c89e2009-12-03 04:06:58 +00003619 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00003620 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003621 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003622 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003623 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00003624 ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003625 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003626 }
3627}
3628
Douglas Gregor96176b32008-11-18 23:14:02 +00003629/// AddMethodCandidate - Adds the given C++ member function to the set
3630/// of candidate functions, using the given function call arguments
3631/// and the object argument (@c Object). For example, in a call
3632/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3633/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3634/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00003635/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00003636void
John McCall9aa472c2010-03-19 07:35:19 +00003637Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003638 CXXRecordDecl *ActingContext, QualType ObjectType,
3639 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00003640 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003641 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00003642 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003643 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00003644 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003645 assert(!isa<CXXConstructorDecl>(Method) &&
3646 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00003647
Douglas Gregor3f396022009-09-28 04:47:19 +00003648 if (!CandidateSet.isNewCandidate(Method))
3649 return;
3650
Douglas Gregor7edfb692009-11-23 12:27:39 +00003651 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003652 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003653
Douglas Gregor96176b32008-11-18 23:14:02 +00003654 // Add this candidate
3655 CandidateSet.push_back(OverloadCandidate());
3656 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003657 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00003658 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003659 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003660 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003661
3662 unsigned NumArgsInProto = Proto->getNumArgs();
3663
3664 // (C++ 13.3.2p2): A candidate function having fewer than m
3665 // parameters is viable only if it has an ellipsis in its parameter
3666 // list (8.3.5).
3667 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3668 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003669 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003670 return;
3671 }
3672
3673 // (C++ 13.3.2p2): A candidate function having more than m parameters
3674 // is viable only if the (m+1)st parameter has a default argument
3675 // (8.3.6). For the purposes of overload resolution, the
3676 // parameter list is truncated on the right, so that there are
3677 // exactly m parameters.
3678 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3679 if (NumArgs < MinRequiredArgs) {
3680 // Not enough arguments.
3681 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003682 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003683 return;
3684 }
3685
3686 Candidate.Viable = true;
3687 Candidate.Conversions.resize(NumArgs + 1);
3688
John McCall701c89e2009-12-03 04:06:58 +00003689 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00003690 // The implicit object argument is ignored.
3691 Candidate.IgnoreObjectArgument = true;
3692 else {
3693 // Determine the implicit conversion sequence for the object
3694 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00003695 Candidate.Conversions[0]
John McCall120d63c2010-08-24 20:38:10 +00003696 = TryObjectArgumentInitialization(*this, ObjectType, Method,
3697 ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003698 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003699 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003700 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00003701 return;
3702 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003703 }
3704
3705 // Determine the implicit conversion sequences for each of the
3706 // arguments.
3707 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3708 if (ArgIdx < NumArgsInProto) {
3709 // (C++ 13.3.2p3): for F to be a viable function, there shall
3710 // exist for each argument an implicit conversion sequence
3711 // (13.3.3.1) that converts that argument to the corresponding
3712 // parameter of F.
3713 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003714 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003715 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003716 SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +00003717 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003718 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003719 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003720 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003721 break;
3722 }
3723 } else {
3724 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3725 // argument for which there is no corresponding parameter is
3726 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003727 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00003728 }
3729 }
3730}
Douglas Gregora9333192010-05-08 17:41:32 +00003731
Douglas Gregor6b906862009-08-21 00:16:32 +00003732/// \brief Add a C++ member function template as a candidate to the candidate
3733/// set, using template argument deduction to produce an appropriate member
3734/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003735void
Douglas Gregor6b906862009-08-21 00:16:32 +00003736Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00003737 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003738 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00003739 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00003740 QualType ObjectType,
3741 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003742 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003743 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003744 if (!CandidateSet.isNewCandidate(MethodTmpl))
3745 return;
3746
Douglas Gregor6b906862009-08-21 00:16:32 +00003747 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003748 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00003749 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003750 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00003751 // candidate functions in the usual way.113) A given name can refer to one
3752 // or more function templates and also to a set of overloaded non-template
3753 // functions. In such a case, the candidate functions generated from each
3754 // function template are combined with the set of non-template candidate
3755 // functions.
John McCall5769d612010-02-08 23:07:23 +00003756 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00003757 FunctionDecl *Specialization = 0;
3758 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003759 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003760 Args, NumArgs, Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003761 CandidateSet.push_back(OverloadCandidate());
3762 OverloadCandidate &Candidate = CandidateSet.back();
3763 Candidate.FoundDecl = FoundDecl;
3764 Candidate.Function = MethodTmpl->getTemplatedDecl();
3765 Candidate.Viable = false;
3766 Candidate.FailureKind = ovl_fail_bad_deduction;
3767 Candidate.IsSurrogate = false;
3768 Candidate.IgnoreObjectArgument = false;
3769 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3770 Info);
3771 return;
3772 }
Mike Stump1eb44332009-09-09 15:08:12 +00003773
Douglas Gregor6b906862009-08-21 00:16:32 +00003774 // Add the function template specialization produced by template argument
3775 // deduction as a candidate.
3776 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00003777 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00003778 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00003779 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003780 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003781 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00003782}
3783
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003784/// \brief Add a C++ function template specialization as a candidate
3785/// in the candidate set, using template argument deduction to produce
3786/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003787void
Douglas Gregore53060f2009-06-25 22:08:12 +00003788Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003789 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00003790 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00003791 Expr **Args, unsigned NumArgs,
3792 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003793 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003794 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3795 return;
3796
Douglas Gregore53060f2009-06-25 22:08:12 +00003797 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003798 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00003799 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003800 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00003801 // candidate functions in the usual way.113) A given name can refer to one
3802 // or more function templates and also to a set of overloaded non-template
3803 // functions. In such a case, the candidate functions generated from each
3804 // function template are combined with the set of non-template candidate
3805 // functions.
John McCall5769d612010-02-08 23:07:23 +00003806 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00003807 FunctionDecl *Specialization = 0;
3808 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003809 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003810 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00003811 CandidateSet.push_back(OverloadCandidate());
3812 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003813 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00003814 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3815 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003816 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00003817 Candidate.IsSurrogate = false;
3818 Candidate.IgnoreObjectArgument = false;
Douglas Gregorff5adac2010-05-08 20:18:54 +00003819 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3820 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00003821 return;
3822 }
Mike Stump1eb44332009-09-09 15:08:12 +00003823
Douglas Gregore53060f2009-06-25 22:08:12 +00003824 // Add the function template specialization produced by template argument
3825 // deduction as a candidate.
3826 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003827 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003828 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00003829}
Mike Stump1eb44332009-09-09 15:08:12 +00003830
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003831/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00003832/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003833/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00003834/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003835/// (which may or may not be the same type as the type that the
3836/// conversion function produces).
3837void
3838Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003839 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003840 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003841 Expr *From, QualType ToType,
3842 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003843 assert(!Conversion->getDescribedFunctionTemplate() &&
3844 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003845 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00003846 if (!CandidateSet.isNewCandidate(Conversion))
3847 return;
3848
Douglas Gregor7edfb692009-11-23 12:27:39 +00003849 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003850 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003851
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003852 // Add this candidate
3853 CandidateSet.push_back(OverloadCandidate());
3854 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003855 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003856 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003857 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003858 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003859 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003860 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003861 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003862 Candidate.Viable = true;
3863 Candidate.Conversions.resize(1);
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003864
Douglas Gregorbca39322010-08-19 15:37:02 +00003865 // C++ [over.match.funcs]p4:
3866 // For conversion functions, the function is considered to be a member of
3867 // the class of the implicit implied object argument for the purpose of
3868 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003869 //
3870 // Determine the implicit conversion sequence for the implicit
3871 // object parameter.
3872 QualType ImplicitParamType = From->getType();
3873 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3874 ImplicitParamType = FromPtrType->getPointeeType();
3875 CXXRecordDecl *ConversionContext
3876 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3877
3878 Candidate.Conversions[0]
John McCall120d63c2010-08-24 20:38:10 +00003879 = TryObjectArgumentInitialization(*this, From->getType(), Conversion,
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003880 ConversionContext);
3881
John McCall1d318332010-01-12 00:44:57 +00003882 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003883 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003884 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003885 return;
3886 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003887
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003888 // We won't go through a user-define type conversion function to convert a
3889 // derived to base as such conversions are given Conversion Rank. They only
3890 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3891 QualType FromCanon
3892 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3893 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3894 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3895 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003896 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003897 return;
3898 }
3899
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003900 // To determine what the conversion from the result of calling the
3901 // conversion function to the type we're eventually trying to
3902 // convert to (ToType), we need to synthesize a call to the
3903 // conversion function and attempt copy initialization from it. This
3904 // makes sure that we get the right semantics with respect to
3905 // lvalues/rvalues and the type. Fortunately, we can allocate this
3906 // call on the stack and we don't need its arguments to be
3907 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00003908 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00003909 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00003910 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3911 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00003912 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00003913 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00003914
Douglas Gregor7d14d382010-11-13 19:36:57 +00003915 QualType CallResultType
3916 = Conversion->getConversionType().getNonLValueExprType(Context);
3917 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
3918 Candidate.Viable = false;
3919 Candidate.FailureKind = ovl_fail_bad_final_conversion;
3920 return;
3921 }
3922
John McCallf89e55a2010-11-18 06:31:45 +00003923 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
3924
Mike Stump1eb44332009-09-09 15:08:12 +00003925 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00003926 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3927 // allocator).
John McCallf89e55a2010-11-18 06:31:45 +00003928 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003929 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00003930 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00003931 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003932 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003933 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003934
John McCall1d318332010-01-12 00:44:57 +00003935 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003936 case ImplicitConversionSequence::StandardConversion:
3937 Candidate.FinalConversion = ICS.Standard;
Douglas Gregorc520c842010-04-12 23:42:09 +00003938
3939 // C++ [over.ics.user]p3:
3940 // If the user-defined conversion is specified by a specialization of a
3941 // conversion function template, the second standard conversion sequence
3942 // shall have exact match rank.
3943 if (Conversion->getPrimaryTemplate() &&
3944 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3945 Candidate.Viable = false;
3946 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3947 }
3948
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003949 break;
3950
3951 case ImplicitConversionSequence::BadConversion:
3952 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003953 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003954 break;
3955
3956 default:
Mike Stump1eb44332009-09-09 15:08:12 +00003957 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003958 "Can only end up with a standard conversion sequence or failure");
3959 }
3960}
3961
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003962/// \brief Adds a conversion function template specialization
3963/// candidate to the overload set, using template argument deduction
3964/// to deduce the template arguments of the conversion function
3965/// template from the type that we are converting to (C++
3966/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00003967void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003968Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003969 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003970 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003971 Expr *From, QualType ToType,
3972 OverloadCandidateSet &CandidateSet) {
3973 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3974 "Only conversion function templates permitted here");
3975
Douglas Gregor3f396022009-09-28 04:47:19 +00003976 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3977 return;
3978
John McCall5769d612010-02-08 23:07:23 +00003979 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003980 CXXConversionDecl *Specialization = 0;
3981 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00003982 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003983 Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003984 CandidateSet.push_back(OverloadCandidate());
3985 OverloadCandidate &Candidate = CandidateSet.back();
3986 Candidate.FoundDecl = FoundDecl;
3987 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3988 Candidate.Viable = false;
3989 Candidate.FailureKind = ovl_fail_bad_deduction;
3990 Candidate.IsSurrogate = false;
3991 Candidate.IgnoreObjectArgument = false;
3992 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3993 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003994 return;
3995 }
Mike Stump1eb44332009-09-09 15:08:12 +00003996
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003997 // Add the conversion function template specialization produced by
3998 // template argument deduction as a candidate.
3999 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00004000 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00004001 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004002}
4003
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004004/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4005/// converts the given @c Object to a function pointer via the
4006/// conversion function @c Conversion, and then attempts to call it
4007/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4008/// the type of function that we'll eventually be calling.
4009void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00004010 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004011 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00004012 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00004013 QualType ObjectType,
4014 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004015 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004016 if (!CandidateSet.isNewCandidate(Conversion))
4017 return;
4018
Douglas Gregor7edfb692009-11-23 12:27:39 +00004019 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004020 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004021
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004022 CandidateSet.push_back(OverloadCandidate());
4023 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004024 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004025 Candidate.Function = 0;
4026 Candidate.Surrogate = Conversion;
4027 Candidate.Viable = true;
4028 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004029 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004030 Candidate.Conversions.resize(NumArgs + 1);
4031
4032 // Determine the implicit conversion sequence for the implicit
4033 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004034 ImplicitConversionSequence ObjectInit
John McCall120d63c2010-08-24 20:38:10 +00004035 = TryObjectArgumentInitialization(*this, ObjectType, Conversion,
4036 ActingContext);
John McCall1d318332010-01-12 00:44:57 +00004037 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004038 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004039 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00004040 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004041 return;
4042 }
4043
4044 // The first conversion is actually a user-defined conversion whose
4045 // first conversion is ObjectInit's standard conversion (which is
4046 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00004047 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004048 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004049 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004050 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00004051 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004052 = Candidate.Conversions[0].UserDefined.Before;
4053 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4054
Mike Stump1eb44332009-09-09 15:08:12 +00004055 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004056 unsigned NumArgsInProto = Proto->getNumArgs();
4057
4058 // (C++ 13.3.2p2): A candidate function having fewer than m
4059 // parameters is viable only if it has an ellipsis in its parameter
4060 // list (8.3.5).
4061 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4062 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004063 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004064 return;
4065 }
4066
4067 // Function types don't have any default arguments, so just check if
4068 // we have enough arguments.
4069 if (NumArgs < NumArgsInProto) {
4070 // Not enough arguments.
4071 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004072 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004073 return;
4074 }
4075
4076 // Determine the implicit conversion sequences for each of the
4077 // arguments.
4078 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4079 if (ArgIdx < NumArgsInProto) {
4080 // (C++ 13.3.2p3): for F to be a viable function, there shall
4081 // exist for each argument an implicit conversion sequence
4082 // (13.3.3.1) that converts that argument to the corresponding
4083 // parameter of F.
4084 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004085 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004086 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00004087 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004088 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00004089 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004090 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004091 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004092 break;
4093 }
4094 } else {
4095 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4096 // argument for which there is no corresponding parameter is
4097 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004098 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004099 }
4100 }
4101}
4102
Douglas Gregor063daf62009-03-13 18:40:31 +00004103/// \brief Add overload candidates for overloaded operators that are
4104/// member functions.
4105///
4106/// Add the overloaded operator candidates that are member functions
4107/// for the operator Op that was used in an operator expression such
4108/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4109/// CandidateSet will store the added overload candidates. (C++
4110/// [over.match.oper]).
4111void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4112 SourceLocation OpLoc,
4113 Expr **Args, unsigned NumArgs,
4114 OverloadCandidateSet& CandidateSet,
4115 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00004116 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4117
4118 // C++ [over.match.oper]p3:
4119 // For a unary operator @ with an operand of a type whose
4120 // cv-unqualified version is T1, and for a binary operator @ with
4121 // a left operand of a type whose cv-unqualified version is T1 and
4122 // a right operand of a type whose cv-unqualified version is T2,
4123 // three sets of candidate functions, designated member
4124 // candidates, non-member candidates and built-in candidates, are
4125 // constructed as follows:
4126 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00004127
4128 // -- If T1 is a class type, the set of member candidates is the
4129 // result of the qualified lookup of T1::operator@
4130 // (13.3.1.1.1); otherwise, the set of member candidates is
4131 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00004132 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004133 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004134 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004135 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004136
John McCalla24dc2e2009-11-17 02:14:36 +00004137 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4138 LookupQualifiedName(Operators, T1Rec->getDecl());
4139 Operators.suppressDiagnostics();
4140
Mike Stump1eb44332009-09-09 15:08:12 +00004141 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004142 OperEnd = Operators.end();
4143 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00004144 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00004145 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall701c89e2009-12-03 04:06:58 +00004146 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00004147 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00004148 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004149}
4150
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004151/// AddBuiltinCandidate - Add a candidate for a built-in
4152/// operator. ResultTy and ParamTys are the result and parameter types
4153/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004154/// arguments being passed to the candidate. IsAssignmentOperator
4155/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004156/// operator. NumContextualBoolArguments is the number of arguments
4157/// (at the beginning of the argument list) that will be contextually
4158/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00004159void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004160 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004161 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004162 bool IsAssignmentOperator,
4163 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00004164 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004165 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004166
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004167 // Add this candidate
4168 CandidateSet.push_back(OverloadCandidate());
4169 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004170 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004171 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00004172 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004173 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004174 Candidate.BuiltinTypes.ResultTy = ResultTy;
4175 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4176 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4177
4178 // Determine the implicit conversion sequences for each of the
4179 // arguments.
4180 Candidate.Viable = true;
4181 Candidate.Conversions.resize(NumArgs);
4182 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004183 // C++ [over.match.oper]p4:
4184 // For the built-in assignment operators, conversions of the
4185 // left operand are restricted as follows:
4186 // -- no temporaries are introduced to hold the left operand, and
4187 // -- no user-defined conversions are applied to the left
4188 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00004189 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004190 //
4191 // We block these conversions by turning off user-defined
4192 // conversions, since that is the only way that initialization of
4193 // a reference to a non-class type can occur from something that
4194 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004195 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00004196 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004197 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00004198 Candidate.Conversions[ArgIdx]
4199 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004200 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004201 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004202 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00004203 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004204 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004205 }
John McCall1d318332010-01-12 00:44:57 +00004206 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004207 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004208 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00004209 break;
4210 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004211 }
4212}
4213
4214/// BuiltinCandidateTypeSet - A set of types that will be used for the
4215/// candidate operator functions for built-in operators (C++
4216/// [over.built]). The types are separated into pointer types and
4217/// enumeration types.
4218class BuiltinCandidateTypeSet {
4219 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004220 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004221
4222 /// PointerTypes - The set of pointer types that will be used in the
4223 /// built-in candidates.
4224 TypeSet PointerTypes;
4225
Sebastian Redl78eb8742009-04-19 21:53:20 +00004226 /// MemberPointerTypes - The set of member pointer types that will be
4227 /// used in the built-in candidates.
4228 TypeSet MemberPointerTypes;
4229
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004230 /// EnumerationTypes - The set of enumeration types that will be
4231 /// used in the built-in candidates.
4232 TypeSet EnumerationTypes;
4233
Douglas Gregor26bcf672010-05-19 03:21:00 +00004234 /// \brief The set of vector types that will be used in the built-in
4235 /// candidates.
4236 TypeSet VectorTypes;
4237
Douglas Gregor5842ba92009-08-24 15:23:48 +00004238 /// Sema - The semantic analysis instance where we are building the
4239 /// candidate type set.
4240 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004241
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004242 /// Context - The AST context in which we will build the type sets.
4243 ASTContext &Context;
4244
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004245 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4246 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00004247 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004248
4249public:
4250 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004251 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004252
Mike Stump1eb44332009-09-09 15:08:12 +00004253 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00004254 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004255
Douglas Gregor573d9c32009-10-21 23:19:44 +00004256 void AddTypesConvertedFrom(QualType Ty,
4257 SourceLocation Loc,
4258 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004259 bool AllowExplicitConversions,
4260 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004261
4262 /// pointer_begin - First pointer type found;
4263 iterator pointer_begin() { return PointerTypes.begin(); }
4264
Sebastian Redl78eb8742009-04-19 21:53:20 +00004265 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004266 iterator pointer_end() { return PointerTypes.end(); }
4267
Sebastian Redl78eb8742009-04-19 21:53:20 +00004268 /// member_pointer_begin - First member pointer type found;
4269 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4270
4271 /// member_pointer_end - Past the last member pointer type found;
4272 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4273
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004274 /// enumeration_begin - First enumeration type found;
4275 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4276
Sebastian Redl78eb8742009-04-19 21:53:20 +00004277 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004278 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004279
4280 iterator vector_begin() { return VectorTypes.begin(); }
4281 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004282};
4283
Sebastian Redl78eb8742009-04-19 21:53:20 +00004284/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004285/// the set of pointer types along with any more-qualified variants of
4286/// that type. For example, if @p Ty is "int const *", this routine
4287/// will add "int const *", "int const volatile *", "int const
4288/// restrict *", and "int const volatile restrict *" to the set of
4289/// pointer types. Returns true if the add of @p Ty itself succeeded,
4290/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004291///
4292/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004293bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00004294BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4295 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00004296
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004297 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004298 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004299 return false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004300
4301 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00004302 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004303 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004304 if (!PointerTy) {
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004305 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004306 PointeeTy = PTy->getPointeeType();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004307 buildObjCPtr = true;
4308 }
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004309 else
4310 assert(false && "type was not a pointer type!");
4311 }
4312 else
4313 PointeeTy = PointerTy->getPointeeType();
4314
Sebastian Redla9efada2009-11-18 20:39:26 +00004315 // Don't add qualified variants of arrays. For one, they're not allowed
4316 // (the qualifier would sink to the element type), and for another, the
4317 // only overload situation where it matters is subscript or pointer +- int,
4318 // and those shouldn't have qualifier variants anyway.
4319 if (PointeeTy->isArrayType())
4320 return true;
John McCall0953e762009-09-24 19:53:00 +00004321 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00004322 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00004323 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004324 bool hasVolatile = VisibleQuals.hasVolatile();
4325 bool hasRestrict = VisibleQuals.hasRestrict();
4326
John McCall0953e762009-09-24 19:53:00 +00004327 // Iterate through all strict supersets of BaseCVR.
4328 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4329 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004330 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4331 // in the types.
4332 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4333 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00004334 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004335 if (!buildObjCPtr)
4336 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4337 else
4338 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004339 }
4340
4341 return true;
4342}
4343
Sebastian Redl78eb8742009-04-19 21:53:20 +00004344/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4345/// to the set of pointer types along with any more-qualified variants of
4346/// that type. For example, if @p Ty is "int const *", this routine
4347/// will add "int const *", "int const volatile *", "int const
4348/// restrict *", and "int const volatile restrict *" to the set of
4349/// pointer types. Returns true if the add of @p Ty itself succeeded,
4350/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004351///
4352/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004353bool
4354BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4355 QualType Ty) {
4356 // Insert this type.
4357 if (!MemberPointerTypes.insert(Ty))
4358 return false;
4359
John McCall0953e762009-09-24 19:53:00 +00004360 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4361 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00004362
John McCall0953e762009-09-24 19:53:00 +00004363 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00004364 // Don't add qualified variants of arrays. For one, they're not allowed
4365 // (the qualifier would sink to the element type), and for another, the
4366 // only overload situation where it matters is subscript or pointer +- int,
4367 // and those shouldn't have qualifier variants anyway.
4368 if (PointeeTy->isArrayType())
4369 return true;
John McCall0953e762009-09-24 19:53:00 +00004370 const Type *ClassTy = PointerTy->getClass();
4371
4372 // Iterate through all strict supersets of the pointee type's CVR
4373 // qualifiers.
4374 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4375 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4376 if ((CVR | BaseCVR) != CVR) continue;
4377
4378 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4379 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00004380 }
4381
4382 return true;
4383}
4384
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004385/// AddTypesConvertedFrom - Add each of the types to which the type @p
4386/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00004387/// primarily interested in pointer types and enumeration types. We also
4388/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004389/// AllowUserConversions is true if we should look at the conversion
4390/// functions of a class type, and AllowExplicitConversions if we
4391/// should also include the explicit conversion functions of a class
4392/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00004393void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004394BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004395 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004396 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004397 bool AllowExplicitConversions,
4398 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004399 // Only deal with canonical types.
4400 Ty = Context.getCanonicalType(Ty);
4401
4402 // Look through reference types; they aren't part of the type of an
4403 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004404 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004405 Ty = RefTy->getPointeeType();
4406
4407 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004408 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004409
Sebastian Redla65b5512009-11-05 16:36:20 +00004410 // If we're dealing with an array type, decay to the pointer.
4411 if (Ty->isArrayType())
4412 Ty = SemaRef.Context.getArrayDecayedType(Ty);
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004413 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4414 PointerTypes.insert(Ty);
4415 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004416 // Insert our type, and its more-qualified variants, into the set
4417 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004418 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004419 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00004420 } else if (Ty->isMemberPointerType()) {
4421 // Member pointers are far easier, since the pointee can't be converted.
4422 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4423 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004424 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00004425 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004426 } else if (Ty->isVectorType()) {
4427 VectorTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004428 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004429 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004430 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00004431 // No conversion functions in incomplete types.
4432 return;
4433 }
Mike Stump1eb44332009-09-09 15:08:12 +00004434
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004435 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00004436 const UnresolvedSetImpl *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00004437 = ClassDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00004438 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004439 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004440 NamedDecl *D = I.getDecl();
4441 if (isa<UsingShadowDecl>(D))
4442 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004443
Mike Stump1eb44332009-09-09 15:08:12 +00004444 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004445 // about which builtin types we can convert to.
John McCall32daa422010-03-31 01:36:47 +00004446 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004447 continue;
4448
John McCall32daa422010-03-31 01:36:47 +00004449 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004450 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004451 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004452 VisibleQuals);
4453 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004454 }
4455 }
4456 }
4457}
4458
Douglas Gregor19b7b152009-08-24 13:43:27 +00004459/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4460/// the volatile- and non-volatile-qualified assignment operators for the
4461/// given type to the candidate set.
4462static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4463 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00004464 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004465 unsigned NumArgs,
4466 OverloadCandidateSet &CandidateSet) {
4467 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00004468
Douglas Gregor19b7b152009-08-24 13:43:27 +00004469 // T& operator=(T&, T)
4470 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4471 ParamTypes[1] = T;
4472 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4473 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004474
Douglas Gregor19b7b152009-08-24 13:43:27 +00004475 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4476 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00004477 ParamTypes[0]
4478 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00004479 ParamTypes[1] = T;
4480 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00004481 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004482 }
4483}
Mike Stump1eb44332009-09-09 15:08:12 +00004484
Sebastian Redl9994a342009-10-25 17:03:50 +00004485/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4486/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004487static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4488 Qualifiers VRQuals;
4489 const RecordType *TyRec;
4490 if (const MemberPointerType *RHSMPType =
4491 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004492 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004493 else
4494 TyRec = ArgExpr->getType()->getAs<RecordType>();
4495 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004496 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004497 VRQuals.addVolatile();
4498 VRQuals.addRestrict();
4499 return VRQuals;
4500 }
4501
4502 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00004503 if (!ClassDecl->hasDefinition())
4504 return VRQuals;
4505
John McCalleec51cf2010-01-20 00:46:10 +00004506 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00004507 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004508
John McCalleec51cf2010-01-20 00:46:10 +00004509 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004510 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004511 NamedDecl *D = I.getDecl();
4512 if (isa<UsingShadowDecl>(D))
4513 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4514 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004515 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4516 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4517 CanTy = ResTypeRef->getPointeeType();
4518 // Need to go down the pointer/mempointer chain and add qualifiers
4519 // as see them.
4520 bool done = false;
4521 while (!done) {
4522 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4523 CanTy = ResTypePtr->getPointeeType();
4524 else if (const MemberPointerType *ResTypeMPtr =
4525 CanTy->getAs<MemberPointerType>())
4526 CanTy = ResTypeMPtr->getPointeeType();
4527 else
4528 done = true;
4529 if (CanTy.isVolatileQualified())
4530 VRQuals.addVolatile();
4531 if (CanTy.isRestrictQualified())
4532 VRQuals.addRestrict();
4533 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4534 return VRQuals;
4535 }
4536 }
4537 }
4538 return VRQuals;
4539}
John McCall00071ec2010-11-13 05:51:15 +00004540
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004541
Douglas Gregor74253732008-11-19 15:42:04 +00004542/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4543/// operator overloads to the candidate set (C++ [over.built]), based
4544/// on the operator @p Op and the arguments given. For example, if the
4545/// operator is a binary '+', this routine might add "int
4546/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004547void
Mike Stump1eb44332009-09-09 15:08:12 +00004548Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004549 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00004550 Expr **Args, unsigned NumArgs,
4551 OverloadCandidateSet& CandidateSet) {
John McCall00071ec2010-11-13 05:51:15 +00004552 // Information about arithmetic types useful to builtin-type
4553 // calculations.
4554
4555 // The "promoted arithmetic types" are the arithmetic
4556 // types are that preserved by promotion (C++ [over.built]p2).
4557
4558 static const unsigned FirstIntegralType = 3;
4559 static const unsigned LastIntegralType = 18;
4560 static const unsigned FirstPromotedIntegralType = 3,
4561 LastPromotedIntegralType = 9;
4562 static const unsigned FirstPromotedArithmeticType = 0,
4563 LastPromotedArithmeticType = 9;
4564 static const unsigned NumArithmeticTypes = 18;
4565
John McCall72a01412010-11-13 02:01:09 +00004566 static CanQualType ASTContext::* const ArithmeticTypes[NumArithmeticTypes] = {
John McCall00071ec2010-11-13 05:51:15 +00004567 // Start of promoted types.
4568 &ASTContext::FloatTy,
4569 &ASTContext::DoubleTy,
4570 &ASTContext::LongDoubleTy,
4571
4572 // Start of integral types.
4573 &ASTContext::IntTy,
4574 &ASTContext::LongTy,
4575 &ASTContext::LongLongTy,
4576 &ASTContext::UnsignedIntTy,
4577 &ASTContext::UnsignedLongTy,
4578 &ASTContext::UnsignedLongLongTy,
4579 // End of promoted types.
4580
John McCall72a01412010-11-13 02:01:09 +00004581 &ASTContext::BoolTy,
4582 &ASTContext::CharTy,
4583 &ASTContext::WCharTy,
4584 &ASTContext::Char16Ty,
4585 &ASTContext::Char32Ty,
4586 &ASTContext::SignedCharTy,
4587 &ASTContext::ShortTy,
4588 &ASTContext::UnsignedCharTy,
John McCall00071ec2010-11-13 05:51:15 +00004589 &ASTContext::UnsignedShortTy
4590 // End of integral types.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004591 };
John McCall00071ec2010-11-13 05:51:15 +00004592 // FIXME: What about complex?
John McCall72a01412010-11-13 02:01:09 +00004593 assert(ArithmeticTypes[FirstPromotedIntegralType] == &ASTContext::IntTy &&
Douglas Gregor652371a2009-10-21 22:01:30 +00004594 "Invalid first promoted integral type");
4595 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
John McCall72a01412010-11-13 02:01:09 +00004596 == &ASTContext::UnsignedLongLongTy &&
Douglas Gregor652371a2009-10-21 22:01:30 +00004597 "Invalid last promoted integral type");
John McCall00071ec2010-11-13 05:51:15 +00004598 assert(ArithmeticTypes[FirstPromotedArithmeticType] == &ASTContext::FloatTy &&
Douglas Gregor652371a2009-10-21 22:01:30 +00004599 "Invalid first promoted arithmetic type");
4600 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
John McCall00071ec2010-11-13 05:51:15 +00004601 == &ASTContext::UnsignedLongLongTy &&
Douglas Gregor652371a2009-10-21 22:01:30 +00004602 "Invalid last promoted arithmetic type");
John McCall00071ec2010-11-13 05:51:15 +00004603
4604 // Accelerator table for performing the usual arithmetic conversions.
4605 // The rules are basically:
4606 // - if either is floating-point, use the wider floating-point
4607 // - if same signedness, use the higher rank
4608 // - if same size, use unsigned of the higher rank
4609 // - use the larger type
4610 // These rules, together with the axiom that higher ranks are
4611 // never smaller, are sufficient to precompute all of these results
4612 // *except* when dealing with signed types of higher rank.
4613 // (we could precompute SLL x UI for all known platforms, but it's
4614 // better not to make any assumptions).
4615 enum PromT { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1 };
4616 static PromT UsualArithmeticConversionsTypes
4617 [LastPromotedArithmeticType][LastPromotedArithmeticType] = {
4618 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
4619 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
4620 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
4621 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
4622 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
4623 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
4624 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
4625 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
4626 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL }
4627 };
4628 struct UsualArithmeticConversionsType {
4629 static CanQualType find(ASTContext &C, unsigned L, unsigned R) {
4630 assert(L < LastPromotedArithmeticType);
4631 assert(R < LastPromotedArithmeticType);
4632 signed char Idx = UsualArithmeticConversionsTypes[L][R];
4633
4634 // Fast path: the table gives us a concrete answer.
4635 if (Idx != Dep) return C.*ArithmeticTypes[Idx];
4636
4637 // Slow path: we need to compare widths.
4638 // An invariant is that the signed type has higher rank.
4639 CanQualType LT = C.*ArithmeticTypes[L], RT = C.*ArithmeticTypes[R];
4640 unsigned LW = C.getIntWidth(LT), RW = C.getIntWidth(RT);
4641
4642 // If they're different widths, use the signed type.
4643 if (LW > RW) return LT;
4644 else if (LW > RW) return RT;
4645
4646 // Otherwise, use the unsigned type of the signed type's rank.
4647 if (L == SL || R == SL) return C.UnsignedLongTy;
4648 assert(L == SLL || R == SLL);
4649 return C.UnsignedLongLongTy;
4650 }
4651 };
Douglas Gregor652371a2009-10-21 22:01:30 +00004652
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004653 // Find all of the types that the arguments can convert to, but only
4654 // if the operator we're looking at has built-in operator candidates
4655 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004656 Qualifiers VisibleTypeConversionsQuals;
4657 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004658 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4659 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4660
Douglas Gregorfec56e72010-11-03 17:00:07 +00004661 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
4662 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4663 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
4664 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4665 OpLoc,
4666 true,
4667 (Op == OO_Exclaim ||
4668 Op == OO_AmpAmp ||
4669 Op == OO_PipePipe),
4670 VisibleTypeConversionsQuals);
4671 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004672
Douglas Gregor661b4932010-09-12 04:28:07 +00004673 // C++ [over.built]p1:
4674 // If there is a user-written candidate with the same name and parameter
4675 // types as a built-in candidate operator function, the built-in operator
4676 // function is hidden and is not included in the set of candidate functions.
4677 //
4678 // The text is actually in a note, but if we don't implement it then we end
4679 // up with ambiguities when the user provides an overloaded operator for
4680 // an enumeration type. Note that only enumeration types have this problem,
4681 // so we track which enumeration types we've seen operators for.
4682 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
4683 UserDefinedBinaryOperators;
4684
Douglas Gregorfec56e72010-11-03 17:00:07 +00004685 /// Set of (canonical) types that we've already handled.
4686 llvm::SmallPtrSet<QualType, 8> AddedTypes;
4687
4688 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4689 if (CandidateTypes[ArgIdx].enumeration_begin()
4690 != CandidateTypes[ArgIdx].enumeration_end()) {
4691 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
4692 CEnd = CandidateSet.end();
4693 C != CEnd; ++C) {
4694 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
4695 continue;
4696
4697 // Check if the first parameter is of enumeration type.
4698 QualType FirstParamType
4699 = C->Function->getParamDecl(0)->getType().getUnqualifiedType();
4700 if (!FirstParamType->isEnumeralType())
4701 continue;
4702
4703 // Check if the second parameter is of enumeration type.
4704 QualType SecondParamType
4705 = C->Function->getParamDecl(1)->getType().getUnqualifiedType();
4706 if (!SecondParamType->isEnumeralType())
4707 continue;
Douglas Gregor661b4932010-09-12 04:28:07 +00004708
Douglas Gregorfec56e72010-11-03 17:00:07 +00004709 // Add this operator to the set of known user-defined operators.
4710 UserDefinedBinaryOperators.insert(
4711 std::make_pair(Context.getCanonicalType(FirstParamType),
4712 Context.getCanonicalType(SecondParamType)));
4713 }
Douglas Gregor661b4932010-09-12 04:28:07 +00004714 }
4715 }
4716
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004717 bool isComparison = false;
4718 switch (Op) {
4719 case OO_None:
4720 case NUM_OVERLOADED_OPERATORS:
4721 assert(false && "Expected an overloaded operator");
4722 break;
4723
Douglas Gregor74253732008-11-19 15:42:04 +00004724 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00004725 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00004726 goto UnaryStar;
4727 else
4728 goto BinaryStar;
4729 break;
4730
4731 case OO_Plus: // '+' is either unary or binary
4732 if (NumArgs == 1)
4733 goto UnaryPlus;
4734 else
4735 goto BinaryPlus;
4736 break;
4737
4738 case OO_Minus: // '-' is either unary or binary
4739 if (NumArgs == 1)
4740 goto UnaryMinus;
4741 else
4742 goto BinaryMinus;
4743 break;
4744
4745 case OO_Amp: // '&' is either unary or binary
4746 if (NumArgs == 1)
4747 goto UnaryAmp;
4748 else
4749 goto BinaryAmp;
4750
4751 case OO_PlusPlus:
4752 case OO_MinusMinus:
4753 // C++ [over.built]p3:
4754 //
4755 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4756 // is either volatile or empty, there exist candidate operator
4757 // functions of the form
4758 //
4759 // VQ T& operator++(VQ T&);
4760 // T operator++(VQ T&, int);
4761 //
4762 // C++ [over.built]p4:
4763 //
4764 // For every pair (T, VQ), where T is an arithmetic type other
4765 // than bool, and VQ is either volatile or empty, there exist
4766 // candidate operator functions of the form
4767 //
4768 // VQ T& operator--(VQ T&);
4769 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00004770 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00004771 Arith < NumArithmeticTypes; ++Arith) {
John McCall72a01412010-11-13 02:01:09 +00004772 QualType ArithTy = Context.*ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00004773 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004774 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00004775
4776 // Non-volatile version.
4777 if (NumArgs == 1)
4778 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4779 else
4780 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004781 // heuristic to reduce number of builtin candidates in the set.
4782 // Add volatile version only if there are conversions to a volatile type.
4783 if (VisibleTypeConversionsQuals.hasVolatile()) {
4784 // Volatile version
4785 ParamTypes[0]
4786 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4787 if (NumArgs == 1)
4788 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4789 else
4790 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4791 }
Douglas Gregor74253732008-11-19 15:42:04 +00004792 }
4793
4794 // C++ [over.built]p5:
4795 //
4796 // For every pair (T, VQ), where T is a cv-qualified or
4797 // cv-unqualified object type, and VQ is either volatile or
4798 // empty, there exist candidate operator functions of the form
4799 //
4800 // T*VQ& operator++(T*VQ&);
4801 // T*VQ& operator--(T*VQ&);
4802 // T* operator++(T*VQ&, int);
4803 // T* operator--(T*VQ&, int);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004804 for (BuiltinCandidateTypeSet::iterator
4805 Ptr = CandidateTypes[0].pointer_begin(),
4806 PtrEnd = CandidateTypes[0].pointer_end();
4807 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor74253732008-11-19 15:42:04 +00004808 // Skip pointer types that aren't pointers to object types.
Eli Friedman13578692010-08-05 02:49:48 +00004809 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00004810 continue;
4811
Mike Stump1eb44332009-09-09 15:08:12 +00004812 QualType ParamTypes[2] = {
4813 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00004814 };
Mike Stump1eb44332009-09-09 15:08:12 +00004815
Douglas Gregor74253732008-11-19 15:42:04 +00004816 // Without volatile
4817 if (NumArgs == 1)
4818 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4819 else
4820 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4821
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004822 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4823 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00004824 // With volatile
John McCall0953e762009-09-24 19:53:00 +00004825 ParamTypes[0]
4826 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00004827 if (NumArgs == 1)
4828 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4829 else
4830 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4831 }
4832 }
4833 break;
4834
4835 UnaryStar:
4836 // C++ [over.built]p6:
4837 // For every cv-qualified or cv-unqualified object type T, there
4838 // exist candidate operator functions of the form
4839 //
4840 // T& operator*(T*);
4841 //
4842 // C++ [over.built]p7:
4843 // For every function type T, there exist candidate operator
4844 // functions of the form
4845 // T& operator*(T*);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004846 for (BuiltinCandidateTypeSet::iterator
4847 Ptr = CandidateTypes[0].pointer_begin(),
4848 PtrEnd = CandidateTypes[0].pointer_end();
4849 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor74253732008-11-19 15:42:04 +00004850 QualType ParamTy = *Ptr;
Argyrios Kyrtzidis42d0f2a2010-08-23 07:12:16 +00004851 QualType PointeeTy = ParamTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004852 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00004853 &ParamTy, Args, 1, CandidateSet);
4854 }
4855 break;
4856
4857 UnaryPlus:
4858 // C++ [over.built]p8:
4859 // For every type T, there exist candidate operator functions of
4860 // the form
4861 //
4862 // T* operator+(T*);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004863 for (BuiltinCandidateTypeSet::iterator
4864 Ptr = CandidateTypes[0].pointer_begin(),
4865 PtrEnd = CandidateTypes[0].pointer_end();
4866 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor74253732008-11-19 15:42:04 +00004867 QualType ParamTy = *Ptr;
4868 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4869 }
Mike Stump1eb44332009-09-09 15:08:12 +00004870
Douglas Gregor74253732008-11-19 15:42:04 +00004871 // Fall through
4872
4873 UnaryMinus:
4874 // C++ [over.built]p9:
4875 // For every promoted arithmetic type T, there exist candidate
4876 // operator functions of the form
4877 //
4878 // T operator+(T);
4879 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004880 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00004881 Arith < LastPromotedArithmeticType; ++Arith) {
John McCall72a01412010-11-13 02:01:09 +00004882 QualType ArithTy = Context.*ArithmeticTypes[Arith];
Douglas Gregor74253732008-11-19 15:42:04 +00004883 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4884 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004885
4886 // Extension: We also add these operators for vector types.
Douglas Gregorfec56e72010-11-03 17:00:07 +00004887 for (BuiltinCandidateTypeSet::iterator
4888 Vec = CandidateTypes[0].vector_begin(),
4889 VecEnd = CandidateTypes[0].vector_end();
Douglas Gregor26bcf672010-05-19 03:21:00 +00004890 Vec != VecEnd; ++Vec) {
4891 QualType VecTy = *Vec;
4892 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4893 }
Douglas Gregor74253732008-11-19 15:42:04 +00004894 break;
4895
4896 case OO_Tilde:
4897 // C++ [over.built]p10:
4898 // For every promoted integral type T, there exist candidate
4899 // operator functions of the form
4900 //
4901 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004902 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00004903 Int < LastPromotedIntegralType; ++Int) {
John McCall72a01412010-11-13 02:01:09 +00004904 QualType IntTy = Context.*ArithmeticTypes[Int];
Douglas Gregor74253732008-11-19 15:42:04 +00004905 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4906 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004907
4908 // Extension: We also add this operator for vector types.
Douglas Gregorfec56e72010-11-03 17:00:07 +00004909 for (BuiltinCandidateTypeSet::iterator
4910 Vec = CandidateTypes[0].vector_begin(),
4911 VecEnd = CandidateTypes[0].vector_end();
Douglas Gregor26bcf672010-05-19 03:21:00 +00004912 Vec != VecEnd; ++Vec) {
4913 QualType VecTy = *Vec;
4914 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4915 }
Douglas Gregor74253732008-11-19 15:42:04 +00004916 break;
4917
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004918 case OO_New:
4919 case OO_Delete:
4920 case OO_Array_New:
4921 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004922 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00004923 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004924 break;
4925
4926 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00004927 UnaryAmp:
4928 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004929 // C++ [over.match.oper]p3:
4930 // -- For the operator ',', the unary operator '&', or the
4931 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004932 break;
4933
Douglas Gregor19b7b152009-08-24 13:43:27 +00004934 case OO_EqualEqual:
4935 case OO_ExclaimEqual:
4936 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00004937 // For every pointer to member type T, there exist candidate operator
4938 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00004939 //
4940 // bool operator==(T,T);
4941 // bool operator!=(T,T);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004942 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4943 for (BuiltinCandidateTypeSet::iterator
4944 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
4945 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
4946 MemPtr != MemPtrEnd;
4947 ++MemPtr) {
4948 // Don't add the same builtin candidate twice.
4949 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
4950 continue;
4951
4952 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4953 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4954 }
Douglas Gregor19b7b152009-08-24 13:43:27 +00004955 }
Douglas Gregorfec56e72010-11-03 17:00:07 +00004956 AddedTypes.clear();
4957
Douglas Gregor19b7b152009-08-24 13:43:27 +00004958 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00004959
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004960 case OO_Less:
4961 case OO_Greater:
4962 case OO_LessEqual:
4963 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004964 // C++ [over.built]p15:
4965 //
4966 // For every pointer or enumeration type T, there exist
4967 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004968 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004969 // bool operator<(T, T);
4970 // bool operator>(T, T);
4971 // bool operator<=(T, T);
4972 // bool operator>=(T, T);
4973 // bool operator==(T, T);
4974 // bool operator!=(T, T);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004975 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4976 for (BuiltinCandidateTypeSet::iterator
4977 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
4978 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
4979 Ptr != PtrEnd; ++Ptr) {
4980 // Don't add the same builtin candidate twice.
4981 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
4982 continue;
4983
4984 QualType ParamTypes[2] = { *Ptr, *Ptr };
Douglas Gregor661b4932010-09-12 04:28:07 +00004985 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004986 }
4987 for (BuiltinCandidateTypeSet::iterator
4988 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
4989 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
4990 Enum != EnumEnd; ++Enum) {
4991 // Don't add the same builtin candidate twice.
4992 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
4993 continue;
4994
4995 QualType ParamTypes[2] = { *Enum, *Enum };
4996 CanQualType CanonType = Context.getCanonicalType(*Enum);
4997 if (!UserDefinedBinaryOperators.count(
4998 std::make_pair(CanonType, CanonType)))
4999 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
5000 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005001 }
Douglas Gregorfec56e72010-11-03 17:00:07 +00005002 AddedTypes.clear();
5003
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005004 // Fall through.
5005 isComparison = true;
5006
Douglas Gregor74253732008-11-19 15:42:04 +00005007 BinaryPlus:
5008 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005009 if (!isComparison) {
5010 // We didn't fall through, so we must have OO_Plus or OO_Minus.
5011
5012 // C++ [over.built]p13:
5013 //
5014 // For every cv-qualified or cv-unqualified object type T
5015 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00005016 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005017 // T* operator+(T*, ptrdiff_t);
5018 // T& operator[](T*, ptrdiff_t); [BELOW]
5019 // T* operator-(T*, ptrdiff_t);
5020 // T* operator+(ptrdiff_t, T*);
5021 // T& operator[](ptrdiff_t, T*); [BELOW]
5022 //
5023 // C++ [over.built]p14:
5024 //
5025 // For every T, where T is a pointer to object type, there
5026 // exist candidate operator functions of the form
5027 //
5028 // ptrdiff_t operator-(T, T);
Douglas Gregorfec56e72010-11-03 17:00:07 +00005029 for (BuiltinCandidateTypeSet::iterator
5030 Ptr = CandidateTypes[0].pointer_begin(),
5031 PtrEnd = CandidateTypes[0].pointer_end();
5032 Ptr != PtrEnd; ++Ptr) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005033 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
5034
5035 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5036 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5037
Douglas Gregorfec56e72010-11-03 17:00:07 +00005038 if (Op == OO_Minus) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005039 // ptrdiff_t operator-(T, T);
Douglas Gregorfec56e72010-11-03 17:00:07 +00005040 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5041 continue;
5042
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005043 ParamTypes[1] = *Ptr;
5044 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
5045 Args, 2, CandidateSet);
5046 }
5047 }
Douglas Gregorfec56e72010-11-03 17:00:07 +00005048
5049 for (BuiltinCandidateTypeSet::iterator
5050 Ptr = CandidateTypes[1].pointer_begin(),
5051 PtrEnd = CandidateTypes[1].pointer_end();
5052 Ptr != PtrEnd; ++Ptr) {
5053 if (Op == OO_Plus) {
5054 // T* operator+(ptrdiff_t, T*);
5055 QualType ParamTypes[2] = { Context.getPointerDiffType(), *Ptr };
5056 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5057 } else {
5058 // ptrdiff_t operator-(T, T);
5059 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5060 continue;
5061
5062 QualType ParamTypes[2] = { *Ptr, *Ptr };
5063 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
5064 Args, 2, CandidateSet);
5065 }
5066 }
5067
5068 AddedTypes.clear();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005069 }
5070 // Fall through
5071
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005072 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00005073 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005074 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005075 // C++ [over.built]p12:
5076 //
5077 // For every pair of promoted arithmetic types L and R, there
5078 // exist candidate operator functions of the form
5079 //
5080 // LR operator*(L, R);
5081 // LR operator/(L, R);
5082 // LR operator+(L, R);
5083 // LR operator-(L, R);
5084 // bool operator<(L, R);
5085 // bool operator>(L, R);
5086 // bool operator<=(L, R);
5087 // bool operator>=(L, R);
5088 // bool operator==(L, R);
5089 // bool operator!=(L, R);
5090 //
5091 // where LR is the result of the usual arithmetic conversions
5092 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005093 //
5094 // C++ [over.built]p24:
5095 //
5096 // For every pair of promoted arithmetic types L and R, there exist
5097 // candidate operator functions of the form
5098 //
5099 // LR operator?(bool, L, R);
5100 //
5101 // where LR is the result of the usual arithmetic conversions
5102 // between types L and R.
5103 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005104 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005105 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00005106 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005107 Right < LastPromotedArithmeticType; ++Right) {
John McCall72a01412010-11-13 02:01:09 +00005108 QualType LandR[2] = { Context.*ArithmeticTypes[Left],
5109 Context.*ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00005110 QualType Result
5111 = isComparison
5112 ? Context.BoolTy
John McCall00071ec2010-11-13 05:51:15 +00005113 : UsualArithmeticConversionsType::find(Context, Left, Right);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005114 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5115 }
5116 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00005117
5118 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5119 // conditional operator for vector types.
Douglas Gregorfec56e72010-11-03 17:00:07 +00005120 for (BuiltinCandidateTypeSet::iterator
5121 Vec1 = CandidateTypes[0].vector_begin(),
5122 Vec1End = CandidateTypes[0].vector_end();
Douglas Gregor26bcf672010-05-19 03:21:00 +00005123 Vec1 != Vec1End; ++Vec1)
5124 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorfec56e72010-11-03 17:00:07 +00005125 Vec2 = CandidateTypes[1].vector_begin(),
5126 Vec2End = CandidateTypes[1].vector_end();
Douglas Gregor26bcf672010-05-19 03:21:00 +00005127 Vec2 != Vec2End; ++Vec2) {
5128 QualType LandR[2] = { *Vec1, *Vec2 };
5129 QualType Result;
5130 if (isComparison)
5131 Result = Context.BoolTy;
5132 else {
5133 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5134 Result = *Vec1;
5135 else
5136 Result = *Vec2;
5137 }
5138
5139 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5140 }
5141
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005142 break;
5143
5144 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00005145 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005146 case OO_Caret:
5147 case OO_Pipe:
5148 case OO_LessLess:
5149 case OO_GreaterGreater:
5150 // C++ [over.built]p17:
5151 //
5152 // For every pair of promoted integral types L and R, there
5153 // exist candidate operator functions of the form
5154 //
5155 // LR operator%(L, R);
5156 // LR operator&(L, R);
5157 // LR operator^(L, R);
5158 // LR operator|(L, R);
5159 // L operator<<(L, R);
5160 // L operator>>(L, R);
5161 //
5162 // where LR is the result of the usual arithmetic conversions
5163 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00005164 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005165 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00005166 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005167 Right < LastPromotedIntegralType; ++Right) {
John McCall72a01412010-11-13 02:01:09 +00005168 QualType LandR[2] = { Context.*ArithmeticTypes[Left],
5169 Context.*ArithmeticTypes[Right] };
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005170 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5171 ? LandR[0]
John McCall00071ec2010-11-13 05:51:15 +00005172 : UsualArithmeticConversionsType::find(Context, Left, Right);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005173 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5174 }
5175 }
5176 break;
5177
5178 case OO_Equal:
5179 // C++ [over.built]p20:
5180 //
5181 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00005182 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005183 // empty, there exist candidate operator functions of the form
5184 //
5185 // VQ T& operator=(VQ T&, T);
Douglas Gregorfec56e72010-11-03 17:00:07 +00005186 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5187 for (BuiltinCandidateTypeSet::iterator
5188 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5189 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5190 Enum != EnumEnd; ++Enum) {
5191 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
5192 continue;
5193
5194 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
5195 CandidateSet);
5196 }
5197
5198 for (BuiltinCandidateTypeSet::iterator
5199 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5200 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5201 MemPtr != MemPtrEnd; ++MemPtr) {
5202 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
5203 continue;
5204
5205 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
5206 CandidateSet);
5207 }
5208 }
5209 AddedTypes.clear();
Douglas Gregor26bcf672010-05-19 03:21:00 +00005210
5211 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005212
5213 case OO_PlusEqual:
5214 case OO_MinusEqual:
5215 // C++ [over.built]p19:
5216 //
5217 // For every pair (T, VQ), where T is any type and VQ is either
5218 // volatile or empty, there exist candidate operator functions
5219 // of the form
5220 //
5221 // T*VQ& operator=(T*VQ&, T*);
5222 //
5223 // C++ [over.built]p21:
5224 //
5225 // For every pair (T, VQ), where T is a cv-qualified or
5226 // cv-unqualified object type and VQ is either volatile or
5227 // empty, there exist candidate operator functions of the form
5228 //
5229 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5230 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
Douglas Gregorfec56e72010-11-03 17:00:07 +00005231 for (BuiltinCandidateTypeSet::iterator
5232 Ptr = CandidateTypes[0].pointer_begin(),
5233 PtrEnd = CandidateTypes[0].pointer_end();
5234 Ptr != PtrEnd; ++Ptr) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005235 QualType ParamTypes[2];
5236 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
5237
Douglas Gregorfec56e72010-11-03 17:00:07 +00005238 // If this is operator=, keep track of the builtin candidates we added.
5239 if (Op == OO_Equal)
5240 AddedTypes.insert(Context.getCanonicalType(*Ptr));
5241
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005242 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005243 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005244 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5245 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005246
Fariborz Jahanian8621d012009-10-19 21:30:45 +00005247 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5248 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00005249 // volatile version
John McCall0953e762009-09-24 19:53:00 +00005250 ParamTypes[0]
5251 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005252 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5253 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00005254 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005255 }
Douglas Gregorfec56e72010-11-03 17:00:07 +00005256
5257 if (Op == OO_Equal) {
5258 for (BuiltinCandidateTypeSet::iterator
5259 Ptr = CandidateTypes[1].pointer_begin(),
5260 PtrEnd = CandidateTypes[1].pointer_end();
5261 Ptr != PtrEnd; ++Ptr) {
5262 // Make sure we don't add the same candidate twice.
5263 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5264 continue;
5265
5266 QualType ParamTypes[2] = { Context.getLValueReferenceType(*Ptr), *Ptr };
5267
5268 // non-volatile version
5269 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5270 /*IsAssigmentOperator=*/true);
5271
5272 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5273 VisibleTypeConversionsQuals.hasVolatile()) {
5274 // volatile version
5275 ParamTypes[0]
5276 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
5277 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5278 /*IsAssigmentOperator=*/true);
5279 }
5280 }
5281 AddedTypes.clear();
5282 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005283 // Fall through.
5284
5285 case OO_StarEqual:
5286 case OO_SlashEqual:
5287 // C++ [over.built]p18:
5288 //
5289 // For every triple (L, VQ, R), where L is an arithmetic type,
5290 // VQ is either volatile or empty, and R is a promoted
5291 // arithmetic type, there exist candidate operator functions of
5292 // the form
5293 //
5294 // VQ L& operator=(VQ L&, R);
5295 // VQ L& operator*=(VQ L&, R);
5296 // VQ L& operator/=(VQ L&, R);
5297 // VQ L& operator+=(VQ L&, R);
5298 // VQ L& operator-=(VQ L&, R);
5299 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00005300 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005301 Right < LastPromotedArithmeticType; ++Right) {
5302 QualType ParamTypes[2];
John McCall72a01412010-11-13 02:01:09 +00005303 ParamTypes[1] = Context.*ArithmeticTypes[Right];
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005304
5305 // Add this built-in operator as a candidate (VQ is empty).
John McCall72a01412010-11-13 02:01:09 +00005306 ParamTypes[0] =
5307 Context.getLValueReferenceType(Context.*ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005308 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5309 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005310
5311 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00005312 if (VisibleTypeConversionsQuals.hasVolatile()) {
John McCall72a01412010-11-13 02:01:09 +00005313 ParamTypes[0] =
5314 Context.getVolatileType(Context.*ArithmeticTypes[Left]);
Fariborz Jahanian8621d012009-10-19 21:30:45 +00005315 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5316 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5317 /*IsAssigmentOperator=*/Op == OO_Equal);
5318 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005319 }
5320 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00005321
5322 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
Douglas Gregorfec56e72010-11-03 17:00:07 +00005323 for (BuiltinCandidateTypeSet::iterator
5324 Vec1 = CandidateTypes[0].vector_begin(),
5325 Vec1End = CandidateTypes[0].vector_end();
Douglas Gregor26bcf672010-05-19 03:21:00 +00005326 Vec1 != Vec1End; ++Vec1)
5327 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorfec56e72010-11-03 17:00:07 +00005328 Vec2 = CandidateTypes[1].vector_begin(),
5329 Vec2End = CandidateTypes[1].vector_end();
Douglas Gregor26bcf672010-05-19 03:21:00 +00005330 Vec2 != Vec2End; ++Vec2) {
5331 QualType ParamTypes[2];
5332 ParamTypes[1] = *Vec2;
5333 // Add this built-in operator as a candidate (VQ is empty).
5334 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
5335 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5336 /*IsAssigmentOperator=*/Op == OO_Equal);
5337
5338 // Add this built-in operator as a candidate (VQ is 'volatile').
5339 if (VisibleTypeConversionsQuals.hasVolatile()) {
5340 ParamTypes[0] = Context.getVolatileType(*Vec1);
5341 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5342 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5343 /*IsAssigmentOperator=*/Op == OO_Equal);
5344 }
5345 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005346 break;
5347
5348 case OO_PercentEqual:
5349 case OO_LessLessEqual:
5350 case OO_GreaterGreaterEqual:
5351 case OO_AmpEqual:
5352 case OO_CaretEqual:
5353 case OO_PipeEqual:
5354 // C++ [over.built]p22:
5355 //
5356 // For every triple (L, VQ, R), where L is an integral type, VQ
5357 // is either volatile or empty, and R is a promoted integral
5358 // type, there exist candidate operator functions of the form
5359 //
5360 // VQ L& operator%=(VQ L&, R);
5361 // VQ L& operator<<=(VQ L&, R);
5362 // VQ L& operator>>=(VQ L&, R);
5363 // VQ L& operator&=(VQ L&, R);
5364 // VQ L& operator^=(VQ L&, R);
5365 // VQ L& operator|=(VQ L&, R);
5366 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00005367 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005368 Right < LastPromotedIntegralType; ++Right) {
5369 QualType ParamTypes[2];
John McCall72a01412010-11-13 02:01:09 +00005370 ParamTypes[1] = Context.*ArithmeticTypes[Right];
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005371
5372 // Add this built-in operator as a candidate (VQ is empty).
John McCall72a01412010-11-13 02:01:09 +00005373 ParamTypes[0] =
5374 Context.getLValueReferenceType(Context.*ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005375 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00005376 if (VisibleTypeConversionsQuals.hasVolatile()) {
5377 // Add this built-in operator as a candidate (VQ is 'volatile').
John McCall72a01412010-11-13 02:01:09 +00005378 ParamTypes[0] = Context.*ArithmeticTypes[Left];
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00005379 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
5380 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5381 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5382 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005383 }
5384 }
5385 break;
5386
Douglas Gregor74253732008-11-19 15:42:04 +00005387 case OO_Exclaim: {
5388 // C++ [over.operator]p23:
5389 //
5390 // There also exist candidate operator functions of the form
5391 //
Mike Stump1eb44332009-09-09 15:08:12 +00005392 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00005393 // bool operator&&(bool, bool); [BELOW]
5394 // bool operator||(bool, bool); [BELOW]
5395 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005396 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5397 /*IsAssignmentOperator=*/false,
5398 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00005399 break;
5400 }
5401
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005402 case OO_AmpAmp:
5403 case OO_PipePipe: {
5404 // C++ [over.operator]p23:
5405 //
5406 // There also exist candidate operator functions of the form
5407 //
Douglas Gregor74253732008-11-19 15:42:04 +00005408 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005409 // bool operator&&(bool, bool);
5410 // bool operator||(bool, bool);
5411 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005412 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5413 /*IsAssignmentOperator=*/false,
5414 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005415 break;
5416 }
5417
5418 case OO_Subscript:
5419 // C++ [over.built]p13:
5420 //
5421 // For every cv-qualified or cv-unqualified object type T there
5422 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00005423 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005424 // T* operator+(T*, ptrdiff_t); [ABOVE]
5425 // T& operator[](T*, ptrdiff_t);
5426 // T* operator-(T*, ptrdiff_t); [ABOVE]
5427 // T* operator+(ptrdiff_t, T*); [ABOVE]
5428 // T& operator[](ptrdiff_t, T*);
Douglas Gregorfec56e72010-11-03 17:00:07 +00005429 for (BuiltinCandidateTypeSet::iterator
5430 Ptr = CandidateTypes[0].pointer_begin(),
5431 PtrEnd = CandidateTypes[0].pointer_end();
5432 Ptr != PtrEnd; ++Ptr) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005433 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Argyrios Kyrtzidis42d0f2a2010-08-23 07:12:16 +00005434 QualType PointeeType = (*Ptr)->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005435 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005436
5437 // T& operator[](T*, ptrdiff_t)
5438 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorfec56e72010-11-03 17:00:07 +00005439 }
5440
5441 for (BuiltinCandidateTypeSet::iterator
5442 Ptr = CandidateTypes[1].pointer_begin(),
5443 PtrEnd = CandidateTypes[1].pointer_end();
5444 Ptr != PtrEnd; ++Ptr) {
5445 QualType ParamTypes[2] = { Context.getPointerDiffType(), *Ptr };
5446 QualType PointeeType = (*Ptr)->getPointeeType();
5447 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
5448
5449 // T& operator[](ptrdiff_t, T*)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005450 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorfec56e72010-11-03 17:00:07 +00005451 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005452 break;
5453
5454 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005455 // C++ [over.built]p11:
5456 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5457 // C1 is the same type as C2 or is a derived class of C2, T is an object
5458 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5459 // there exist candidate operator functions of the form
Douglas Gregorfec56e72010-11-03 17:00:07 +00005460 //
5461 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5462 //
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005463 // where CV12 is the union of CV1 and CV2.
5464 {
Douglas Gregorfec56e72010-11-03 17:00:07 +00005465 for (BuiltinCandidateTypeSet::iterator
5466 Ptr = CandidateTypes[0].pointer_begin(),
5467 PtrEnd = CandidateTypes[0].pointer_end();
5468 Ptr != PtrEnd; ++Ptr) {
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005469 QualType C1Ty = (*Ptr);
5470 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005471 QualifierCollector Q1;
Argyrios Kyrtzidis42d0f2a2010-08-23 07:12:16 +00005472 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5473 if (!isa<RecordType>(C1))
5474 continue;
5475 // heuristic to reduce number of builtin candidates in the set.
5476 // Add volatile/restrict version only if there are conversions to a
5477 // volatile/restrict type.
5478 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5479 continue;
5480 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5481 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005482 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorfec56e72010-11-03 17:00:07 +00005483 MemPtr = CandidateTypes[1].member_pointer_begin(),
5484 MemPtrEnd = CandidateTypes[1].member_pointer_end();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005485 MemPtr != MemPtrEnd; ++MemPtr) {
5486 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5487 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00005488 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005489 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5490 break;
5491 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5492 // build CV12 T&
5493 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005494 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5495 T.isVolatileQualified())
5496 continue;
5497 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5498 T.isRestrictQualified())
5499 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005500 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005501 QualType ResultTy = Context.getLValueReferenceType(T);
5502 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5503 }
5504 }
5505 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005506 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005507
5508 case OO_Conditional:
5509 // Note that we don't consider the first argument, since it has been
5510 // contextually converted to bool long ago. The candidates below are
5511 // therefore added as binary.
5512 //
Douglas Gregor5a1f97e2010-10-15 00:50:56 +00005513 // C++ [over.built]p25:
5514 // For every type T, where T is a pointer, pointer-to-member, or scoped
5515 // enumeration type, there exist candidate operator functions of the form
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005516 //
5517 // T operator?(bool, T, T);
5518 //
Douglas Gregorfec56e72010-11-03 17:00:07 +00005519 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5520 for (BuiltinCandidateTypeSet::iterator
5521 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5522 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5523 Ptr != PtrEnd; ++Ptr) {
5524 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5525 continue;
5526
5527 QualType ParamTypes[2] = { *Ptr, *Ptr };
5528 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5529 }
5530
5531 for (BuiltinCandidateTypeSet::iterator
5532 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5533 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5534 MemPtr != MemPtrEnd; ++MemPtr) {
5535 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
5536 continue;
5537
5538 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5539 AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5540 }
5541
5542 if (getLangOptions().CPlusPlus0x) {
5543 for (BuiltinCandidateTypeSet::iterator
5544 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5545 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5546 Enum != EnumEnd; ++Enum) {
5547 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5548 continue;
5549
5550 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
5551 continue;
5552
5553 QualType ParamTypes[2] = { *Enum, *Enum };
5554 AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5555 }
5556 }
Douglas Gregor5a1f97e2010-10-15 00:50:56 +00005557 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005558 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005559 }
5560}
5561
Douglas Gregorfa047642009-02-04 00:32:51 +00005562/// \brief Add function candidates found via argument-dependent lookup
5563/// to the set of overloading candidates.
5564///
5565/// This routine performs argument-dependent name lookup based on the
5566/// given function name (which may also be an operator name) and adds
5567/// all of the overload candidates found by ADL to the overload
5568/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00005569void
Douglas Gregorfa047642009-02-04 00:32:51 +00005570Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00005571 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00005572 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00005573 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005574 OverloadCandidateSet& CandidateSet,
5575 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00005576 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00005577
John McCalla113e722010-01-26 06:04:06 +00005578 // FIXME: This approach for uniquing ADL results (and removing
5579 // redundant candidates from the set) relies on pointer-equality,
5580 // which means we need to key off the canonical decl. However,
5581 // always going back to the canonical decl might not get us the
5582 // right set of default arguments. What default arguments are
5583 // we supposed to consider on ADL candidates, anyway?
5584
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005585 // FIXME: Pass in the explicit template arguments?
John McCall7edb5fd2010-01-26 07:16:45 +00005586 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00005587
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005588 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005589 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5590 CandEnd = CandidateSet.end();
5591 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00005592 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00005593 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00005594 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00005595 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00005596 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005597
5598 // For each of the ADL candidates we found, add it to the overload
5599 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00005600 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00005601 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00005602 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00005603 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005604 continue;
5605
John McCall9aa472c2010-03-19 07:35:19 +00005606 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00005607 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005608 } else
John McCall6e266892010-01-26 03:27:55 +00005609 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00005610 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00005611 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00005612 }
Douglas Gregorfa047642009-02-04 00:32:51 +00005613}
5614
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005615/// isBetterOverloadCandidate - Determines whether the first overload
5616/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00005617bool
John McCall120d63c2010-08-24 20:38:10 +00005618isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00005619 const OverloadCandidate &Cand1,
5620 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005621 SourceLocation Loc,
5622 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005623 // Define viable functions to be better candidates than non-viable
5624 // functions.
5625 if (!Cand2.Viable)
5626 return Cand1.Viable;
5627 else if (!Cand1.Viable)
5628 return false;
5629
Douglas Gregor88a35142008-12-22 05:46:06 +00005630 // C++ [over.match.best]p1:
5631 //
5632 // -- if F is a static member function, ICS1(F) is defined such
5633 // that ICS1(F) is neither better nor worse than ICS1(G) for
5634 // any function G, and, symmetrically, ICS1(G) is neither
5635 // better nor worse than ICS1(F).
5636 unsigned StartArg = 0;
5637 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5638 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005639
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005640 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00005641 // A viable function F1 is defined to be a better function than another
5642 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005643 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005644 unsigned NumArgs = Cand1.Conversions.size();
5645 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5646 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005647 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00005648 switch (CompareImplicitConversionSequences(S,
5649 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005650 Cand2.Conversions[ArgIdx])) {
5651 case ImplicitConversionSequence::Better:
5652 // Cand1 has a better conversion sequence.
5653 HasBetterConversion = true;
5654 break;
5655
5656 case ImplicitConversionSequence::Worse:
5657 // Cand1 can't be better than Cand2.
5658 return false;
5659
5660 case ImplicitConversionSequence::Indistinguishable:
5661 // Do nothing.
5662 break;
5663 }
5664 }
5665
Mike Stump1eb44332009-09-09 15:08:12 +00005666 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005667 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005668 if (HasBetterConversion)
5669 return true;
5670
Mike Stump1eb44332009-09-09 15:08:12 +00005671 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005672 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00005673 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005674 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5675 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005676
5677 // -- F1 and F2 are function template specializations, and the function
5678 // template for F1 is more specialized than the template for F2
5679 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005680 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00005681 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5682 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005683 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00005684 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5685 Cand2.Function->getPrimaryTemplate(),
5686 Loc,
Douglas Gregor5d7d3752009-09-14 23:02:14 +00005687 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5688 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005689 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005690
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005691 // -- the context is an initialization by user-defined conversion
5692 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5693 // from the return type of F1 to the destination type (i.e.,
5694 // the type of the entity being initialized) is a better
5695 // conversion sequence than the standard conversion sequence
5696 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005697 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00005698 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005699 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall120d63c2010-08-24 20:38:10 +00005700 switch (CompareStandardConversionSequences(S,
5701 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005702 Cand2.FinalConversion)) {
5703 case ImplicitConversionSequence::Better:
5704 // Cand1 has a better conversion sequence.
5705 return true;
5706
5707 case ImplicitConversionSequence::Worse:
5708 // Cand1 can't be better than Cand2.
5709 return false;
5710
5711 case ImplicitConversionSequence::Indistinguishable:
5712 // Do nothing
5713 break;
5714 }
5715 }
5716
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005717 return false;
5718}
5719
Mike Stump1eb44332009-09-09 15:08:12 +00005720/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00005721/// within an overload candidate set.
5722///
5723/// \param CandidateSet the set of candidate functions.
5724///
5725/// \param Loc the location of the function name (or operator symbol) for
5726/// which overload resolution occurs.
5727///
Mike Stump1eb44332009-09-09 15:08:12 +00005728/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00005729/// function, Best points to the candidate function found.
5730///
5731/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00005732OverloadingResult
5733OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00005734 iterator &Best,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005735 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005736 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00005737 Best = end();
5738 for (iterator Cand = begin(); Cand != end(); ++Cand) {
5739 if (Cand->Viable)
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005740 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
5741 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005742 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005743 }
5744
5745 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00005746 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005747 return OR_No_Viable_Function;
5748
5749 // Make sure that this function is better than every other viable
5750 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00005751 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00005752 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005753 Cand != Best &&
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005754 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
5755 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00005756 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005757 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005758 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005759 }
Mike Stump1eb44332009-09-09 15:08:12 +00005760
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005761 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005762 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00005763 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005764 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005765 return OR_Deleted;
5766
Douglas Gregore0762c92009-06-19 23:52:42 +00005767 // C++ [basic.def.odr]p2:
5768 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00005769 // when referred to from a potentially-evaluated expression. [Note: this
5770 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00005771 // (clause 13), user-defined conversions (12.3.2), allocation function for
5772 // placement new (5.3.4), as well as non-default initialization (8.5).
5773 if (Best->Function)
John McCall120d63c2010-08-24 20:38:10 +00005774 S.MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor9b623632010-10-12 23:32:35 +00005775
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005776 return OR_Success;
5777}
5778
John McCall3c80f572010-01-12 02:15:36 +00005779namespace {
5780
5781enum OverloadCandidateKind {
5782 oc_function,
5783 oc_method,
5784 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005785 oc_function_template,
5786 oc_method_template,
5787 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00005788 oc_implicit_default_constructor,
5789 oc_implicit_copy_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005790 oc_implicit_copy_assignment
John McCall3c80f572010-01-12 02:15:36 +00005791};
5792
John McCall220ccbf2010-01-13 00:25:19 +00005793OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5794 FunctionDecl *Fn,
5795 std::string &Description) {
5796 bool isTemplate = false;
5797
5798 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5799 isTemplate = true;
5800 Description = S.getTemplateArgumentBindingsText(
5801 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5802 }
John McCallb1622a12010-01-06 09:43:14 +00005803
5804 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00005805 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005806 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005807
John McCall3c80f572010-01-12 02:15:36 +00005808 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5809 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005810 }
5811
5812 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5813 // This actually gets spelled 'candidate function' for now, but
5814 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00005815 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005816 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00005817
Douglas Gregor3e9438b2010-09-27 22:37:28 +00005818 assert(Meth->isCopyAssignmentOperator()
John McCallb1622a12010-01-06 09:43:14 +00005819 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00005820 return oc_implicit_copy_assignment;
5821 }
5822
John McCall220ccbf2010-01-13 00:25:19 +00005823 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00005824}
5825
5826} // end anonymous namespace
5827
5828// Notes the location of an overload candidate.
5829void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00005830 std::string FnDesc;
5831 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5832 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5833 << (unsigned) K << FnDesc;
John McCallb1622a12010-01-06 09:43:14 +00005834}
5835
John McCall1d318332010-01-12 00:44:57 +00005836/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5837/// "lead" diagnostic; it will be given two arguments, the source and
5838/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00005839void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
5840 Sema &S,
5841 SourceLocation CaretLoc,
5842 const PartialDiagnostic &PDiag) const {
5843 S.Diag(CaretLoc, PDiag)
5844 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00005845 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00005846 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
5847 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00005848 }
John McCall81201622010-01-08 04:41:39 +00005849}
5850
John McCall1d318332010-01-12 00:44:57 +00005851namespace {
5852
John McCalladbb8f82010-01-13 09:16:55 +00005853void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5854 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5855 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00005856 assert(Cand->Function && "for now, candidate must be a function");
5857 FunctionDecl *Fn = Cand->Function;
5858
5859 // There's a conversion slot for the object argument if this is a
5860 // non-constructor method. Note that 'I' corresponds the
5861 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00005862 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00005863 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00005864 if (I == 0)
5865 isObjectArgument = true;
5866 else
5867 I--;
John McCall220ccbf2010-01-13 00:25:19 +00005868 }
5869
John McCall220ccbf2010-01-13 00:25:19 +00005870 std::string FnDesc;
5871 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5872
John McCalladbb8f82010-01-13 09:16:55 +00005873 Expr *FromExpr = Conv.Bad.FromExpr;
5874 QualType FromTy = Conv.Bad.getFromType();
5875 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00005876
John McCall5920dbb2010-02-02 02:42:52 +00005877 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00005878 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00005879 Expr *E = FromExpr->IgnoreParens();
5880 if (isa<UnaryOperator>(E))
5881 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00005882 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00005883
5884 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5885 << (unsigned) FnKind << FnDesc
5886 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5887 << ToTy << Name << I+1;
5888 return;
5889 }
5890
John McCall258b2032010-01-23 08:10:49 +00005891 // Do some hand-waving analysis to see if the non-viability is due
5892 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00005893 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5894 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5895 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5896 CToTy = RT->getPointeeType();
5897 else {
5898 // TODO: detect and diagnose the full richness of const mismatches.
5899 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5900 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5901 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5902 }
5903
5904 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5905 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5906 // It is dumb that we have to do this here.
5907 while (isa<ArrayType>(CFromTy))
5908 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5909 while (isa<ArrayType>(CToTy))
5910 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5911
5912 Qualifiers FromQs = CFromTy.getQualifiers();
5913 Qualifiers ToQs = CToTy.getQualifiers();
5914
5915 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5916 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5917 << (unsigned) FnKind << FnDesc
5918 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5919 << FromTy
5920 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5921 << (unsigned) isObjectArgument << I+1;
5922 return;
5923 }
5924
5925 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5926 assert(CVR && "unexpected qualifiers mismatch");
5927
5928 if (isObjectArgument) {
5929 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5930 << (unsigned) FnKind << FnDesc
5931 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5932 << FromTy << (CVR - 1);
5933 } else {
5934 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5935 << (unsigned) FnKind << FnDesc
5936 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5937 << FromTy << (CVR - 1) << I+1;
5938 }
5939 return;
5940 }
5941
John McCall258b2032010-01-23 08:10:49 +00005942 // Diagnose references or pointers to incomplete types differently,
5943 // since it's far from impossible that the incompleteness triggered
5944 // the failure.
5945 QualType TempFromTy = FromTy.getNonReferenceType();
5946 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5947 TempFromTy = PTy->getPointeeType();
5948 if (TempFromTy->isIncompleteType()) {
5949 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5950 << (unsigned) FnKind << FnDesc
5951 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5952 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5953 return;
5954 }
5955
Douglas Gregor85789812010-06-30 23:01:39 +00005956 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005957 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00005958 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5959 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5960 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5961 FromPtrTy->getPointeeType()) &&
5962 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5963 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5964 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5965 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005966 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00005967 }
5968 } else if (const ObjCObjectPointerType *FromPtrTy
5969 = FromTy->getAs<ObjCObjectPointerType>()) {
5970 if (const ObjCObjectPointerType *ToPtrTy
5971 = ToTy->getAs<ObjCObjectPointerType>())
5972 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5973 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5974 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5975 FromPtrTy->getPointeeType()) &&
5976 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005977 BaseToDerivedConversion = 2;
5978 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5979 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5980 !FromTy->isIncompleteType() &&
5981 !ToRefTy->getPointeeType()->isIncompleteType() &&
5982 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5983 BaseToDerivedConversion = 3;
5984 }
5985
5986 if (BaseToDerivedConversion) {
Douglas Gregor85789812010-06-30 23:01:39 +00005987 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005988 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00005989 << (unsigned) FnKind << FnDesc
5990 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005991 << (BaseToDerivedConversion - 1)
Douglas Gregor85789812010-06-30 23:01:39 +00005992 << FromTy << ToTy << I+1;
5993 return;
5994 }
5995
John McCall651f3ee2010-01-14 03:28:57 +00005996 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00005997 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5998 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00005999 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00006000 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCalladbb8f82010-01-13 09:16:55 +00006001}
6002
6003void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6004 unsigned NumFormalArgs) {
6005 // TODO: treat calls to a missing default constructor as a special case
6006
6007 FunctionDecl *Fn = Cand->Function;
6008 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6009
6010 unsigned MinParams = Fn->getMinRequiredArguments();
6011
6012 // at least / at most / exactly
Douglas Gregora18592e2010-05-08 18:13:28 +00006013 // FIXME: variadic templates "at most" should account for parameter packs
John McCalladbb8f82010-01-13 09:16:55 +00006014 unsigned mode, modeCount;
6015 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00006016 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6017 (Cand->FailureKind == ovl_fail_bad_deduction &&
6018 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCalladbb8f82010-01-13 09:16:55 +00006019 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
6020 mode = 0; // "at least"
6021 else
6022 mode = 2; // "exactly"
6023 modeCount = MinParams;
6024 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00006025 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6026 (Cand->FailureKind == ovl_fail_bad_deduction &&
6027 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00006028 if (MinParams != FnTy->getNumArgs())
6029 mode = 1; // "at most"
6030 else
6031 mode = 2; // "exactly"
6032 modeCount = FnTy->getNumArgs();
6033 }
6034
6035 std::string Description;
6036 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6037
6038 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregora18592e2010-05-08 18:13:28 +00006039 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
6040 << modeCount << NumFormalArgs;
John McCall220ccbf2010-01-13 00:25:19 +00006041}
6042
John McCall342fec42010-02-01 18:53:26 +00006043/// Diagnose a failed template-argument deduction.
6044void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6045 Expr **Args, unsigned NumArgs) {
6046 FunctionDecl *Fn = Cand->Function; // pattern
6047
Douglas Gregora9333192010-05-08 17:41:32 +00006048 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00006049 NamedDecl *ParamD;
6050 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6051 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6052 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00006053 switch (Cand->DeductionFailure.Result) {
6054 case Sema::TDK_Success:
6055 llvm_unreachable("TDK_success while diagnosing bad deduction");
6056
6057 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00006058 assert(ParamD && "no parameter found for incomplete deduction result");
6059 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6060 << ParamD->getDeclName();
6061 return;
6062 }
6063
John McCall57e97782010-08-05 09:05:08 +00006064 case Sema::TDK_Underqualified: {
6065 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6066 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6067
6068 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6069
6070 // Param will have been canonicalized, but it should just be a
6071 // qualified version of ParamD, so move the qualifiers to that.
6072 QualifierCollector Qs(S.Context);
6073 Qs.strip(Param);
6074 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
6075 assert(S.Context.hasSameType(Param, NonCanonParam));
6076
6077 // Arg has also been canonicalized, but there's nothing we can do
6078 // about that. It also doesn't matter as much, because it won't
6079 // have any template parameters in it (because deduction isn't
6080 // done on dependent types).
6081 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6082
6083 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6084 << ParamD->getDeclName() << Arg << NonCanonParam;
6085 return;
6086 }
6087
6088 case Sema::TDK_Inconsistent: {
Douglas Gregorf1a84452010-05-08 19:15:54 +00006089 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00006090 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00006091 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00006092 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00006093 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00006094 which = 1;
6095 else {
Douglas Gregora9333192010-05-08 17:41:32 +00006096 which = 2;
6097 }
6098
6099 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
6100 << which << ParamD->getDeclName()
6101 << *Cand->DeductionFailure.getFirstArg()
6102 << *Cand->DeductionFailure.getSecondArg();
6103 return;
6104 }
Douglas Gregora18592e2010-05-08 18:13:28 +00006105
Douglas Gregorf1a84452010-05-08 19:15:54 +00006106 case Sema::TDK_InvalidExplicitArguments:
6107 assert(ParamD && "no parameter found for invalid explicit arguments");
6108 if (ParamD->getDeclName())
6109 S.Diag(Fn->getLocation(),
6110 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6111 << ParamD->getDeclName();
6112 else {
6113 int index = 0;
6114 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6115 index = TTP->getIndex();
6116 else if (NonTypeTemplateParmDecl *NTTP
6117 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6118 index = NTTP->getIndex();
6119 else
6120 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
6121 S.Diag(Fn->getLocation(),
6122 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6123 << (index + 1);
6124 }
6125 return;
6126
Douglas Gregora18592e2010-05-08 18:13:28 +00006127 case Sema::TDK_TooManyArguments:
6128 case Sema::TDK_TooFewArguments:
6129 DiagnoseArityMismatch(S, Cand, NumArgs);
6130 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00006131
6132 case Sema::TDK_InstantiationDepth:
6133 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
6134 return;
6135
6136 case Sema::TDK_SubstitutionFailure: {
6137 std::string ArgString;
6138 if (TemplateArgumentList *Args
6139 = Cand->DeductionFailure.getTemplateArgumentList())
6140 ArgString = S.getTemplateArgumentBindingsText(
6141 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6142 *Args);
6143 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6144 << ArgString;
6145 return;
6146 }
Douglas Gregora9333192010-05-08 17:41:32 +00006147
John McCall342fec42010-02-01 18:53:26 +00006148 // TODO: diagnose these individually, then kill off
6149 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00006150 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00006151 case Sema::TDK_FailedOverloadResolution:
6152 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
6153 return;
6154 }
6155}
6156
6157/// Generates a 'note' diagnostic for an overload candidate. We've
6158/// already generated a primary error at the call site.
6159///
6160/// It really does need to be a single diagnostic with its caret
6161/// pointed at the candidate declaration. Yes, this creates some
6162/// major challenges of technical writing. Yes, this makes pointing
6163/// out problems with specific arguments quite awkward. It's still
6164/// better than generating twenty screens of text for every failed
6165/// overload.
6166///
6167/// It would be great to be able to express per-candidate problems
6168/// more richly for those diagnostic clients that cared, but we'd
6169/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00006170void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6171 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00006172 FunctionDecl *Fn = Cand->Function;
6173
John McCall81201622010-01-08 04:41:39 +00006174 // Note deleted candidates, but only if they're viable.
John McCall3c80f572010-01-12 02:15:36 +00006175 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCall220ccbf2010-01-13 00:25:19 +00006176 std::string FnDesc;
6177 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00006178
6179 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00006180 << FnKind << FnDesc << Fn->isDeleted();
John McCalla1d7d622010-01-08 00:58:21 +00006181 return;
John McCall81201622010-01-08 04:41:39 +00006182 }
6183
John McCall220ccbf2010-01-13 00:25:19 +00006184 // We don't really have anything else to say about viable candidates.
6185 if (Cand->Viable) {
6186 S.NoteOverloadCandidate(Fn);
6187 return;
6188 }
John McCall1d318332010-01-12 00:44:57 +00006189
John McCalladbb8f82010-01-13 09:16:55 +00006190 switch (Cand->FailureKind) {
6191 case ovl_fail_too_many_arguments:
6192 case ovl_fail_too_few_arguments:
6193 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00006194
John McCalladbb8f82010-01-13 09:16:55 +00006195 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00006196 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6197
John McCall717e8912010-01-23 05:17:32 +00006198 case ovl_fail_trivial_conversion:
6199 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00006200 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00006201 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00006202
John McCallb1bdc622010-02-25 01:37:24 +00006203 case ovl_fail_bad_conversion: {
6204 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6205 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00006206 if (Cand->Conversions[I].isBad())
6207 return DiagnoseBadConversion(S, Cand, I);
6208
6209 // FIXME: this currently happens when we're called from SemaInit
6210 // when user-conversion overload fails. Figure out how to handle
6211 // those conditions and diagnose them well.
6212 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00006213 }
John McCallb1bdc622010-02-25 01:37:24 +00006214 }
John McCalla1d7d622010-01-08 00:58:21 +00006215}
6216
6217void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6218 // Desugar the type of the surrogate down to a function type,
6219 // retaining as many typedefs as possible while still showing
6220 // the function type (and, therefore, its parameter types).
6221 QualType FnType = Cand->Surrogate->getConversionType();
6222 bool isLValueReference = false;
6223 bool isRValueReference = false;
6224 bool isPointer = false;
6225 if (const LValueReferenceType *FnTypeRef =
6226 FnType->getAs<LValueReferenceType>()) {
6227 FnType = FnTypeRef->getPointeeType();
6228 isLValueReference = true;
6229 } else if (const RValueReferenceType *FnTypeRef =
6230 FnType->getAs<RValueReferenceType>()) {
6231 FnType = FnTypeRef->getPointeeType();
6232 isRValueReference = true;
6233 }
6234 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6235 FnType = FnTypePtr->getPointeeType();
6236 isPointer = true;
6237 }
6238 // Desugar down to a function type.
6239 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6240 // Reconstruct the pointer/reference as appropriate.
6241 if (isPointer) FnType = S.Context.getPointerType(FnType);
6242 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6243 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6244
6245 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6246 << FnType;
6247}
6248
6249void NoteBuiltinOperatorCandidate(Sema &S,
6250 const char *Opc,
6251 SourceLocation OpLoc,
6252 OverloadCandidate *Cand) {
6253 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6254 std::string TypeStr("operator");
6255 TypeStr += Opc;
6256 TypeStr += "(";
6257 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6258 if (Cand->Conversions.size() == 1) {
6259 TypeStr += ")";
6260 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6261 } else {
6262 TypeStr += ", ";
6263 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6264 TypeStr += ")";
6265 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6266 }
6267}
6268
6269void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6270 OverloadCandidate *Cand) {
6271 unsigned NoOperands = Cand->Conversions.size();
6272 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6273 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00006274 if (ICS.isBad()) break; // all meaningless after first invalid
6275 if (!ICS.isAmbiguous()) continue;
6276
John McCall120d63c2010-08-24 20:38:10 +00006277 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006278 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00006279 }
6280}
6281
John McCall1b77e732010-01-15 23:32:50 +00006282SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6283 if (Cand->Function)
6284 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00006285 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00006286 return Cand->Surrogate->getLocation();
6287 return SourceLocation();
6288}
6289
John McCallbf65c0b2010-01-12 00:48:53 +00006290struct CompareOverloadCandidatesForDisplay {
6291 Sema &S;
6292 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00006293
6294 bool operator()(const OverloadCandidate *L,
6295 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00006296 // Fast-path this check.
6297 if (L == R) return false;
6298
John McCall81201622010-01-08 04:41:39 +00006299 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00006300 if (L->Viable) {
6301 if (!R->Viable) return true;
6302
6303 // TODO: introduce a tri-valued comparison for overload
6304 // candidates. Would be more worthwhile if we had a sort
6305 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00006306 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6307 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00006308 } else if (R->Viable)
6309 return false;
John McCall81201622010-01-08 04:41:39 +00006310
John McCall1b77e732010-01-15 23:32:50 +00006311 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00006312
John McCall1b77e732010-01-15 23:32:50 +00006313 // Criteria by which we can sort non-viable candidates:
6314 if (!L->Viable) {
6315 // 1. Arity mismatches come after other candidates.
6316 if (L->FailureKind == ovl_fail_too_many_arguments ||
6317 L->FailureKind == ovl_fail_too_few_arguments)
6318 return false;
6319 if (R->FailureKind == ovl_fail_too_many_arguments ||
6320 R->FailureKind == ovl_fail_too_few_arguments)
6321 return true;
John McCall81201622010-01-08 04:41:39 +00006322
John McCall717e8912010-01-23 05:17:32 +00006323 // 2. Bad conversions come first and are ordered by the number
6324 // of bad conversions and quality of good conversions.
6325 if (L->FailureKind == ovl_fail_bad_conversion) {
6326 if (R->FailureKind != ovl_fail_bad_conversion)
6327 return true;
6328
6329 // If there's any ordering between the defined conversions...
6330 // FIXME: this might not be transitive.
6331 assert(L->Conversions.size() == R->Conversions.size());
6332
6333 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00006334 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6335 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00006336 switch (CompareImplicitConversionSequences(S,
6337 L->Conversions[I],
6338 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00006339 case ImplicitConversionSequence::Better:
6340 leftBetter++;
6341 break;
6342
6343 case ImplicitConversionSequence::Worse:
6344 leftBetter--;
6345 break;
6346
6347 case ImplicitConversionSequence::Indistinguishable:
6348 break;
6349 }
6350 }
6351 if (leftBetter > 0) return true;
6352 if (leftBetter < 0) return false;
6353
6354 } else if (R->FailureKind == ovl_fail_bad_conversion)
6355 return false;
6356
John McCall1b77e732010-01-15 23:32:50 +00006357 // TODO: others?
6358 }
6359
6360 // Sort everything else by location.
6361 SourceLocation LLoc = GetLocationForCandidate(L);
6362 SourceLocation RLoc = GetLocationForCandidate(R);
6363
6364 // Put candidates without locations (e.g. builtins) at the end.
6365 if (LLoc.isInvalid()) return false;
6366 if (RLoc.isInvalid()) return true;
6367
6368 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00006369 }
6370};
6371
John McCall717e8912010-01-23 05:17:32 +00006372/// CompleteNonViableCandidate - Normally, overload resolution only
6373/// computes up to the first
6374void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6375 Expr **Args, unsigned NumArgs) {
6376 assert(!Cand->Viable);
6377
6378 // Don't do anything on failures other than bad conversion.
6379 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6380
6381 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00006382 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00006383 unsigned ConvCount = Cand->Conversions.size();
6384 while (true) {
6385 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6386 ConvIdx++;
6387 if (Cand->Conversions[ConvIdx - 1].isBad())
6388 break;
6389 }
6390
6391 if (ConvIdx == ConvCount)
6392 return;
6393
John McCallb1bdc622010-02-25 01:37:24 +00006394 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6395 "remaining conversion is initialized?");
6396
Douglas Gregor23ef6c02010-04-16 17:45:54 +00006397 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00006398 // operation somehow.
6399 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00006400
6401 const FunctionProtoType* Proto;
6402 unsigned ArgIdx = ConvIdx;
6403
6404 if (Cand->IsSurrogate) {
6405 QualType ConvType
6406 = Cand->Surrogate->getConversionType().getNonReferenceType();
6407 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6408 ConvType = ConvPtrType->getPointeeType();
6409 Proto = ConvType->getAs<FunctionProtoType>();
6410 ArgIdx--;
6411 } else if (Cand->Function) {
6412 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6413 if (isa<CXXMethodDecl>(Cand->Function) &&
6414 !isa<CXXConstructorDecl>(Cand->Function))
6415 ArgIdx--;
6416 } else {
6417 // Builtin binary operator with a bad first conversion.
6418 assert(ConvCount <= 3);
6419 for (; ConvIdx != ConvCount; ++ConvIdx)
6420 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006421 = TryCopyInitialization(S, Args[ConvIdx],
6422 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6423 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00006424 /*InOverloadResolution*/ true);
John McCall717e8912010-01-23 05:17:32 +00006425 return;
6426 }
6427
6428 // Fill in the rest of the conversions.
6429 unsigned NumArgsInProto = Proto->getNumArgs();
6430 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6431 if (ArgIdx < NumArgsInProto)
6432 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006433 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6434 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00006435 /*InOverloadResolution=*/true);
John McCall717e8912010-01-23 05:17:32 +00006436 else
6437 Cand->Conversions[ConvIdx].setEllipsis();
6438 }
6439}
6440
John McCalla1d7d622010-01-08 00:58:21 +00006441} // end anonymous namespace
6442
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006443/// PrintOverloadCandidates - When overload resolution fails, prints
6444/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00006445/// set.
John McCall120d63c2010-08-24 20:38:10 +00006446void OverloadCandidateSet::NoteCandidates(Sema &S,
6447 OverloadCandidateDisplayKind OCD,
6448 Expr **Args, unsigned NumArgs,
6449 const char *Opc,
6450 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00006451 // Sort the candidates by viability and position. Sorting directly would
6452 // be prohibitive, so we make a set of pointers and sort those.
6453 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00006454 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6455 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00006456 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00006457 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00006458 else if (OCD == OCD_AllCandidates) {
John McCall120d63c2010-08-24 20:38:10 +00006459 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006460 if (Cand->Function || Cand->IsSurrogate)
6461 Cands.push_back(Cand);
6462 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6463 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00006464 }
6465 }
6466
John McCallbf65c0b2010-01-12 00:48:53 +00006467 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00006468 CompareOverloadCandidatesForDisplay(S));
John McCall81201622010-01-08 04:41:39 +00006469
John McCall1d318332010-01-12 00:44:57 +00006470 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00006471
John McCall81201622010-01-08 04:41:39 +00006472 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall120d63c2010-08-24 20:38:10 +00006473 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006474 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00006475 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6476 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00006477
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006478 // Set an arbitrary limit on the number of candidate functions we'll spam
6479 // the user with. FIXME: This limit should depend on details of the
6480 // candidate list.
6481 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6482 break;
6483 }
6484 ++CandsShown;
6485
John McCalla1d7d622010-01-08 00:58:21 +00006486 if (Cand->Function)
John McCall120d63c2010-08-24 20:38:10 +00006487 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00006488 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00006489 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006490 else {
6491 assert(Cand->Viable &&
6492 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00006493 // Generally we only see ambiguities including viable builtin
6494 // operators if overload resolution got screwed up by an
6495 // ambiguous user-defined conversion.
6496 //
6497 // FIXME: It's quite possible for different conversions to see
6498 // different ambiguities, though.
6499 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00006500 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00006501 ReportedAmbiguousConversions = true;
6502 }
John McCalla1d7d622010-01-08 00:58:21 +00006503
John McCall1d318332010-01-12 00:44:57 +00006504 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00006505 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006506 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006507 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006508
6509 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00006510 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006511}
6512
John McCall9aa472c2010-03-19 07:35:19 +00006513static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCallc373d482010-01-27 01:50:18 +00006514 if (isa<UnresolvedLookupExpr>(E))
John McCall9aa472c2010-03-19 07:35:19 +00006515 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006516
John McCall9aa472c2010-03-19 07:35:19 +00006517 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006518}
6519
Douglas Gregor904eed32008-11-10 20:40:00 +00006520/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6521/// an overloaded function (C++ [over.over]), where @p From is an
6522/// expression with overloaded function type and @p ToType is the type
6523/// we're trying to resolve to. For example:
6524///
6525/// @code
6526/// int f(double);
6527/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00006528///
Douglas Gregor904eed32008-11-10 20:40:00 +00006529/// int (*pfd)(double) = f; // selects f(double)
6530/// @endcode
6531///
6532/// This routine returns the resulting FunctionDecl if it could be
6533/// resolved, and NULL otherwise. When @p Complain is true, this
6534/// routine will emit diagnostics if there is an error.
6535FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00006536Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall6bb80172010-03-30 21:47:33 +00006537 bool Complain,
6538 DeclAccessPair &FoundResult) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006539 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00006540 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00006541 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00006542 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00006543 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00006544 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00006545 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00006546 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006547 FunctionType = MemTypePtr->getPointeeType();
6548 IsMember = true;
6549 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006550
Douglas Gregor904eed32008-11-10 20:40:00 +00006551 // C++ [over.over]p1:
6552 // [...] [Note: any redundant set of parentheses surrounding the
6553 // overloaded function name is ignored (5.1). ]
Douglas Gregor904eed32008-11-10 20:40:00 +00006554 // C++ [over.over]p1:
6555 // [...] The overloaded function name can be preceded by the &
6556 // operator.
John McCallc988fab2010-08-24 23:26:21 +00006557 // However, remember whether the expression has member-pointer form:
6558 // C++ [expr.unary.op]p4:
6559 // A pointer to member is only formed when an explicit & is used
6560 // and its operand is a qualified-id not enclosed in
6561 // parentheses.
John McCall9c72c602010-08-27 09:08:28 +00006562 OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6563 OverloadExpr *OvlExpr = Ovl.Expression;
John McCallc988fab2010-08-24 23:26:21 +00006564
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006565 // We expect a pointer or reference to function, or a function pointer.
6566 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6567 if (!FunctionType->isFunctionType()) {
6568 if (Complain)
6569 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6570 << OvlExpr->getName() << ToType;
6571
6572 return 0;
6573 }
6574
John McCallfb97e752010-08-24 22:52:39 +00006575 // If the overload expression doesn't have the form of a pointer to
John McCallc988fab2010-08-24 23:26:21 +00006576 // member, don't try to convert it to a pointer-to-member type.
John McCall9c72c602010-08-27 09:08:28 +00006577 if (IsMember && !Ovl.HasFormOfMemberPointer) {
John McCallfb97e752010-08-24 22:52:39 +00006578 if (!Complain) return 0;
6579
6580 // TODO: Should we condition this on whether any functions might
6581 // have matched, or is it more appropriate to do that in callers?
6582 // TODO: a fixit wouldn't hurt.
6583 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6584 << ToType << OvlExpr->getSourceRange();
6585 return 0;
6586 }
6587
6588 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6589 if (OvlExpr->hasExplicitTemplateArgs()) {
6590 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6591 ExplicitTemplateArgs = &ETABuffer;
6592 }
6593
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006594 assert(From->getType() == Context.OverloadTy);
Douglas Gregor904eed32008-11-10 20:40:00 +00006595
Douglas Gregor904eed32008-11-10 20:40:00 +00006596 // Look through all of the overloaded functions, searching for one
6597 // whose type matches exactly.
John McCall9aa472c2010-03-19 07:35:19 +00006598 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb7a09262010-04-01 18:32:35 +00006599 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
Douglas Gregor9b623632010-10-12 23:32:35 +00006600
Douglas Gregor00aeb522009-07-08 23:33:52 +00006601 bool FoundNonTemplateFunction = false;
John McCall7bb12da2010-02-02 06:20:04 +00006602 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6603 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00006604 // Look through any using declarations to find the underlying function.
6605 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6606
Douglas Gregor904eed32008-11-10 20:40:00 +00006607 // C++ [over.over]p3:
6608 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00006609 // targets of type "pointer-to-function" or "reference-to-function."
6610 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00006611 // type "pointer-to-member-function."
6612 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00006613
Mike Stump1eb44332009-09-09 15:08:12 +00006614 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00006615 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006616 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00006617 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00006618 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00006619 // static when converting to member pointer.
6620 if (Method->isStatic() == IsMember)
6621 continue;
6622 } else if (IsMember)
6623 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00006624
Douglas Gregor00aeb522009-07-08 23:33:52 +00006625 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00006626 // If the name is a function template, template argument deduction is
6627 // done (14.8.2.2), and if the argument deduction succeeds, the
6628 // resulting template argument list is used to generate a single
6629 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00006630 // overloaded functions considered.
Douglas Gregor83314aa2009-07-08 20:55:45 +00006631 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006632 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor83314aa2009-07-08 20:55:45 +00006633 if (TemplateDeductionResult Result
John McCall7bb12da2010-02-02 06:20:04 +00006634 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00006635 FunctionType, Specialization, Info)) {
6636 // FIXME: make a note of the failed deduction for diagnostics.
6637 (void)Result;
6638 } else {
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00006639 // Template argument deduction ensures that we have an exact match.
6640 // This function template specicalization works.
Douglas Gregor9b623632010-10-12 23:32:35 +00006641 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006642 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00006643 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor9b623632010-10-12 23:32:35 +00006644 Matches.push_back(std::make_pair(I.getPair(), Specialization));
Douglas Gregor83314aa2009-07-08 20:55:45 +00006645 }
John McCallba135432009-11-21 08:51:07 +00006646
6647 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00006648 }
Mike Stump1eb44332009-09-09 15:08:12 +00006649
Chandler Carruthbd647292009-12-29 06:17:27 +00006650 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006651 // Skip non-static functions when converting to pointer, and static
6652 // when converting to member pointer.
6653 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00006654 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006655
6656 // If we have explicit template arguments, skip non-templates.
John McCall7bb12da2010-02-02 06:20:04 +00006657 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006658 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00006659 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00006660 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00006661
Chandler Carruthbd647292009-12-29 06:17:27 +00006662 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00006663 QualType ResultTy;
6664 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6665 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6666 ResultTy)) {
John McCall9aa472c2010-03-19 07:35:19 +00006667 Matches.push_back(std::make_pair(I.getPair(),
6668 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00006669 FoundNonTemplateFunction = true;
6670 }
Mike Stump1eb44332009-09-09 15:08:12 +00006671 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006672 }
6673
Douglas Gregor00aeb522009-07-08 23:33:52 +00006674 // If there were 0 or 1 matches, we're done.
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006675 if (Matches.empty()) {
6676 if (Complain) {
6677 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6678 << OvlExpr->getName() << FunctionType;
6679 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6680 E = OvlExpr->decls_end();
6681 I != E; ++I)
6682 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6683 NoteOverloadCandidate(F);
6684 }
6685
Douglas Gregor00aeb522009-07-08 23:33:52 +00006686 return 0;
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006687 } else if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006688 FunctionDecl *Result = Matches[0].second;
Douglas Gregor9b623632010-10-12 23:32:35 +00006689 FoundResult = Matches[0].first;
Sebastian Redl07ab2022009-10-17 21:12:09 +00006690 MarkDeclarationReferenced(From->getLocStart(), Result);
Douglas Gregor9b623632010-10-12 23:32:35 +00006691 if (Complain) {
John McCall6bb80172010-03-30 21:47:33 +00006692 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Douglas Gregor9b623632010-10-12 23:32:35 +00006693 }
Sebastian Redl07ab2022009-10-17 21:12:09 +00006694 return Result;
6695 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00006696
6697 // C++ [over.over]p4:
6698 // If more than one function is selected, [...]
Douglas Gregor312a2022009-09-26 03:56:17 +00006699 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006700 // [...] and any given function template specialization F1 is
6701 // eliminated if the set contains a second function template
6702 // specialization whose function template is more specialized
6703 // than the function template of F1 according to the partial
6704 // ordering rules of 14.5.5.2.
6705
6706 // The algorithm specified above is quadratic. We instead use a
6707 // two-pass algorithm (similar to the one used to identify the
6708 // best viable function in an overload set) that identifies the
6709 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00006710
6711 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6712 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6713 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCallc373d482010-01-27 01:50:18 +00006714
6715 UnresolvedSetIterator Result =
John McCall9aa472c2010-03-19 07:35:19 +00006716 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redl07ab2022009-10-17 21:12:09 +00006717 TPOC_Other, From->getLocStart(),
6718 PDiag(),
6719 PDiag(diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00006720 << Matches[0].second->getDeclName(),
John McCall220ccbf2010-01-13 00:25:19 +00006721 PDiag(diag::note_ovl_candidate)
6722 << (unsigned) oc_function_template);
Douglas Gregor78c057e2010-09-12 08:16:09 +00006723 if (Result == MatchesCopy.end())
6724 return 0;
6725
John McCallc373d482010-01-27 01:50:18 +00006726 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall6bb80172010-03-30 21:47:33 +00006727 FoundResult = Matches[Result - MatchesCopy.begin()].first;
Douglas Gregor9b623632010-10-12 23:32:35 +00006728 if (Complain)
John McCall6bb80172010-03-30 21:47:33 +00006729 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCallc373d482010-01-27 01:50:18 +00006730 return cast<FunctionDecl>(*Result);
Douglas Gregor00aeb522009-07-08 23:33:52 +00006731 }
Mike Stump1eb44332009-09-09 15:08:12 +00006732
Douglas Gregor312a2022009-09-26 03:56:17 +00006733 // [...] any function template specializations in the set are
6734 // eliminated if the set also contains a non-template function, [...]
John McCallc373d482010-01-27 01:50:18 +00006735 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCall9aa472c2010-03-19 07:35:19 +00006736 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCallc373d482010-01-27 01:50:18 +00006737 ++I;
6738 else {
John McCall9aa472c2010-03-19 07:35:19 +00006739 Matches[I] = Matches[--N];
6740 Matches.set_size(N);
John McCallc373d482010-01-27 01:50:18 +00006741 }
6742 }
Douglas Gregor312a2022009-09-26 03:56:17 +00006743
Mike Stump1eb44332009-09-09 15:08:12 +00006744 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00006745 // selected function.
John McCallc373d482010-01-27 01:50:18 +00006746 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006747 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall6bb80172010-03-30 21:47:33 +00006748 FoundResult = Matches[0].first;
Douglas Gregor9b623632010-10-12 23:32:35 +00006749 if (Complain)
John McCall9aa472c2010-03-19 07:35:19 +00006750 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
6751 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redl07ab2022009-10-17 21:12:09 +00006752 }
Mike Stump1eb44332009-09-09 15:08:12 +00006753
Douglas Gregor00aeb522009-07-08 23:33:52 +00006754 // FIXME: We should probably return the same thing that BestViableFunction
6755 // returns (even if we issue the diagnostics here).
Douglas Gregor8e960432010-11-08 03:40:48 +00006756 if (Complain) {
6757 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
6758 << Matches[0].second->getDeclName();
6759 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6760 NoteOverloadCandidate(Matches[I].second);
6761 }
6762
Douglas Gregor904eed32008-11-10 20:40:00 +00006763 return 0;
6764}
6765
Douglas Gregor4b52e252009-12-21 23:17:24 +00006766/// \brief Given an expression that refers to an overloaded function, try to
6767/// resolve that overloaded function expression down to a single function.
6768///
6769/// This routine can only resolve template-ids that refer to a single function
6770/// template, where that template-id refers to a single template whose template
6771/// arguments are either provided by the template-id or have defaults,
6772/// as described in C++0x [temp.arg.explicit]p3.
6773FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6774 // C++ [over.over]p1:
6775 // [...] [Note: any redundant set of parentheses surrounding the
6776 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00006777 // C++ [over.over]p1:
6778 // [...] The overloaded function name can be preceded by the &
6779 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00006780
6781 if (From->getType() != Context.OverloadTy)
6782 return 0;
6783
John McCall9c72c602010-08-27 09:08:28 +00006784 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
Douglas Gregor4b52e252009-12-21 23:17:24 +00006785
6786 // If we didn't actually find any template-ids, we're done.
John McCall7bb12da2010-02-02 06:20:04 +00006787 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00006788 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00006789
6790 TemplateArgumentListInfo ExplicitTemplateArgs;
6791 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor4b52e252009-12-21 23:17:24 +00006792
6793 // Look through all of the overloaded functions, searching for one
6794 // whose type matches exactly.
6795 FunctionDecl *Matched = 0;
John McCall7bb12da2010-02-02 06:20:04 +00006796 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6797 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00006798 // C++0x [temp.arg.explicit]p3:
6799 // [...] In contexts where deduction is done and fails, or in contexts
6800 // where deduction is not done, if a template argument list is
6801 // specified and it, along with any default template arguments,
6802 // identifies a single function template specialization, then the
6803 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00006804 FunctionTemplateDecl *FunctionTemplate
6805 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006806
6807 // C++ [over.over]p2:
6808 // If the name is a function template, template argument deduction is
6809 // done (14.8.2.2), and if the argument deduction succeeds, the
6810 // resulting template argument list is used to generate a single
6811 // function template specialization, which is added to the set of
6812 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00006813 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006814 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006815 if (TemplateDeductionResult Result
6816 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6817 Specialization, Info)) {
6818 // FIXME: make a note of the failed deduction for diagnostics.
6819 (void)Result;
6820 continue;
6821 }
6822
6823 // Multiple matches; we can't resolve to a single declaration.
6824 if (Matched)
6825 return 0;
6826
6827 Matched = Specialization;
6828 }
Douglas Gregor9b623632010-10-12 23:32:35 +00006829
Douglas Gregor4b52e252009-12-21 23:17:24 +00006830 return Matched;
6831}
6832
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006833/// \brief Add a single candidate to the overload set.
6834static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00006835 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00006836 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006837 Expr **Args, unsigned NumArgs,
6838 OverloadCandidateSet &CandidateSet,
6839 bool PartialOverloading) {
John McCall9aa472c2010-03-19 07:35:19 +00006840 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00006841 if (isa<UsingShadowDecl>(Callee))
6842 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6843
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006844 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00006845 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall9aa472c2010-03-19 07:35:19 +00006846 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00006847 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006848 return;
John McCallba135432009-11-21 08:51:07 +00006849 }
6850
6851 if (FunctionTemplateDecl *FuncTemplate
6852 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00006853 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6854 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006855 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00006856 return;
6857 }
6858
6859 assert(false && "unhandled case in overloaded call candidate");
6860
6861 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006862}
6863
6864/// \brief Add the overload candidates named by callee and/or found by argument
6865/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00006866void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006867 Expr **Args, unsigned NumArgs,
6868 OverloadCandidateSet &CandidateSet,
6869 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00006870
6871#ifndef NDEBUG
6872 // Verify that ArgumentDependentLookup is consistent with the rules
6873 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006874 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006875 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6876 // and let Y be the lookup set produced by argument dependent
6877 // lookup (defined as follows). If X contains
6878 //
6879 // -- a declaration of a class member, or
6880 //
6881 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00006882 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006883 //
6884 // -- a declaration that is neither a function or a function
6885 // template
6886 //
6887 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00006888
John McCall3b4294e2009-12-16 12:17:52 +00006889 if (ULE->requiresADL()) {
6890 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6891 E = ULE->decls_end(); I != E; ++I) {
6892 assert(!(*I)->getDeclContext()->isRecord());
6893 assert(isa<UsingShadowDecl>(*I) ||
6894 !(*I)->getDeclContext()->isFunctionOrMethod());
6895 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00006896 }
6897 }
6898#endif
6899
John McCall3b4294e2009-12-16 12:17:52 +00006900 // It would be nice to avoid this copy.
6901 TemplateArgumentListInfo TABuffer;
6902 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6903 if (ULE->hasExplicitTemplateArgs()) {
6904 ULE->copyTemplateArgumentsInto(TABuffer);
6905 ExplicitTemplateArgs = &TABuffer;
6906 }
6907
6908 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6909 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00006910 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006911 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006912 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00006913
John McCall3b4294e2009-12-16 12:17:52 +00006914 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00006915 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6916 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006917 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006918 CandidateSet,
6919 PartialOverloading);
6920}
John McCall578b69b2009-12-16 08:11:27 +00006921
6922/// Attempts to recover from a call where no functions were found.
6923///
6924/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00006925static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006926BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00006927 UnresolvedLookupExpr *ULE,
6928 SourceLocation LParenLoc,
6929 Expr **Args, unsigned NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00006930 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00006931
6932 CXXScopeSpec SS;
6933 if (ULE->getQualifier()) {
6934 SS.setScopeRep(ULE->getQualifier());
6935 SS.setRange(ULE->getQualifierRange());
6936 }
6937
John McCall3b4294e2009-12-16 12:17:52 +00006938 TemplateArgumentListInfo TABuffer;
6939 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6940 if (ULE->hasExplicitTemplateArgs()) {
6941 ULE->copyTemplateArgumentsInto(TABuffer);
6942 ExplicitTemplateArgs = &TABuffer;
6943 }
6944
John McCall578b69b2009-12-16 08:11:27 +00006945 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6946 Sema::LookupOrdinaryName);
Douglas Gregor91f7ac72010-05-18 16:14:23 +00006947 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallf312b1e2010-08-26 23:41:50 +00006948 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00006949
John McCall3b4294e2009-12-16 12:17:52 +00006950 assert(!R.empty() && "lookup results empty despite recovery");
6951
6952 // Build an implicit member call if appropriate. Just drop the
6953 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00006954 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00006955 if ((*R.begin())->isCXXClassMember())
6956 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6957 else if (ExplicitTemplateArgs)
6958 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6959 else
6960 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6961
6962 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006963 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00006964
6965 // This shouldn't cause an infinite loop because we're giving it
6966 // an expression with non-empty lookup results, which should never
6967 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00006968 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +00006969 MultiExprArg(Args, NumArgs), RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006970}
Douglas Gregord7a95972010-06-08 17:35:15 +00006971
Douglas Gregorf6b89692008-11-26 05:54:23 +00006972/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00006973/// (which eventually refers to the declaration Func) and the call
6974/// arguments Args/NumArgs, attempt to resolve the function call down
6975/// to a specific function. If overload resolution succeeds, returns
6976/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00006977/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00006978/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00006979ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006980Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00006981 SourceLocation LParenLoc,
6982 Expr **Args, unsigned NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00006983 SourceLocation RParenLoc) {
6984#ifndef NDEBUG
6985 if (ULE->requiresADL()) {
6986 // To do ADL, we must have found an unqualified name.
6987 assert(!ULE->getQualifier() && "qualified name with ADL");
6988
6989 // We don't perform ADL for implicit declarations of builtins.
6990 // Verify that this was correctly set up.
6991 FunctionDecl *F;
6992 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6993 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6994 F->getBuiltinID() && F->isImplicit())
6995 assert(0 && "performing ADL for builtin");
6996
6997 // We don't perform ADL in C.
6998 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6999 }
7000#endif
7001
John McCall5769d612010-02-08 23:07:23 +00007002 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00007003
John McCall3b4294e2009-12-16 12:17:52 +00007004 // Add the functions denoted by the callee to the set of candidate
7005 // functions, including those from argument-dependent lookup.
7006 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00007007
7008 // If we found nothing, try to recover.
7009 // AddRecoveryCallCandidates diagnoses the error itself, so we just
7010 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00007011 if (CandidateSet.empty())
Douglas Gregor1aae80b2010-04-14 20:27:54 +00007012 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00007013 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00007014
Douglas Gregorf6b89692008-11-26 05:54:23 +00007015 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007016 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00007017 case OR_Success: {
7018 FunctionDecl *FDecl = Best->Function;
John McCall9aa472c2010-03-19 07:35:19 +00007019 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00007020 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(), ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00007021 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall3b4294e2009-12-16 12:17:52 +00007022 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
7023 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00007024
7025 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00007026 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00007027 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00007028 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007029 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00007030 break;
7031
7032 case OR_Ambiguous:
7033 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00007034 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007035 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00007036 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007037
7038 case OR_Deleted:
7039 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7040 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00007041 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007042 << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007043 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007044 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00007045 }
7046
Douglas Gregorff331c12010-07-25 18:17:45 +00007047 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00007048 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00007049}
7050
John McCall6e266892010-01-26 03:27:55 +00007051static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00007052 return Functions.size() > 1 ||
7053 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7054}
7055
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007056/// \brief Create a unary operation that may resolve to an overloaded
7057/// operator.
7058///
7059/// \param OpLoc The location of the operator itself (e.g., '*').
7060///
7061/// \param OpcIn The UnaryOperator::Opcode that describes this
7062/// operator.
7063///
7064/// \param Functions The set of non-member functions that will be
7065/// considered by overload resolution. The caller needs to build this
7066/// set based on the context using, e.g.,
7067/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7068/// set should not contain any member functions; those will be added
7069/// by CreateOverloadedUnaryOp().
7070///
7071/// \param input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00007072ExprResult
John McCall6e266892010-01-26 03:27:55 +00007073Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7074 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00007075 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007076 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007077
7078 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7079 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7080 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00007081 // TODO: provide better source location info.
7082 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007083
7084 Expr *Args[2] = { Input, 0 };
7085 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00007086
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007087 // For post-increment and post-decrement, add the implicit '0' as
7088 // the second argument, so that we know this is a post-increment or
7089 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00007090 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007091 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007092 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7093 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007094 NumArgs = 2;
7095 }
7096
7097 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00007098 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00007099 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00007100 Opc,
7101 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00007102 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00007103 OpLoc));
7104
John McCallc373d482010-01-27 01:50:18 +00007105 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00007106 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00007107 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00007108 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007109 /*ADL*/ true, IsOverloaded(Fns),
7110 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007111 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
7112 &Args[0], NumArgs,
7113 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00007114 VK_RValue,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007115 OpLoc));
7116 }
7117
7118 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007119 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007120
7121 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00007122 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007123
7124 // Add operator candidates that are member functions.
7125 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7126
John McCall6e266892010-01-26 03:27:55 +00007127 // Add candidates from ADL.
7128 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00007129 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00007130 /*ExplicitTemplateArgs*/ 0,
7131 CandidateSet);
7132
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007133 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00007134 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007135
7136 // Perform overload resolution.
7137 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007138 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007139 case OR_Success: {
7140 // We found a built-in operator or an overloaded operator.
7141 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00007142
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007143 if (FnDecl) {
7144 // We matched an overloaded operator. Build a call to that
7145 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00007146
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007147 // Convert the arguments.
7148 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00007149 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00007150
John McCall6bb80172010-03-30 21:47:33 +00007151 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7152 Best->FoundDecl, Method))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007153 return ExprError();
7154 } else {
7155 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00007156 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00007157 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007158 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +00007159 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00007160 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00007161 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00007162 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007163 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00007164 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007165 }
7166
John McCallb697e082010-05-06 18:15:07 +00007167 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7168
John McCallf89e55a2010-11-18 06:31:45 +00007169 // Determine the result type.
7170 QualType ResultTy = FnDecl->getResultType();
7171 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7172 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00007173
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007174 // Build the actual expression node.
John McCallf89e55a2010-11-18 06:31:45 +00007175 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00007176
Eli Friedman4c3b8962009-11-18 03:58:17 +00007177 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00007178 CallExpr *TheCall =
Anders Carlsson26a2a072009-10-13 21:19:37 +00007179 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCallf89e55a2010-11-18 06:31:45 +00007180 Args, NumArgs, ResultTy, VK, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00007181
John McCall9ae2f072010-08-23 23:25:46 +00007182 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00007183 FnDecl))
7184 return ExprError();
7185
John McCall9ae2f072010-08-23 23:25:46 +00007186 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007187 } else {
7188 // We matched a built-in operator. Convert the arguments, then
7189 // break out so that we will build the appropriate built-in
7190 // operator node.
7191 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007192 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007193 return ExprError();
7194
7195 break;
7196 }
7197 }
7198
7199 case OR_No_Viable_Function:
7200 // No viable function; fall through to handling this as a
7201 // built-in operator, which will produce an error message for us.
7202 break;
7203
7204 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00007205 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007206 << UnaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +00007207 << Input->getType()
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007208 << Input->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007209 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7210 Args, NumArgs,
7211 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007212 return ExprError();
7213
7214 case OR_Deleted:
7215 Diag(OpLoc, diag::err_ovl_deleted_oper)
7216 << Best->Function->isDeleted()
7217 << UnaryOperator::getOpcodeStr(Opc)
7218 << Input->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007219 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007220 return ExprError();
7221 }
7222
7223 // Either we found no viable overloaded operator or we matched a
7224 // built-in operator. In either case, fall through to trying to
7225 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +00007226 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007227}
7228
Douglas Gregor063daf62009-03-13 18:40:31 +00007229/// \brief Create a binary operation that may resolve to an overloaded
7230/// operator.
7231///
7232/// \param OpLoc The location of the operator itself (e.g., '+').
7233///
7234/// \param OpcIn The BinaryOperator::Opcode that describes this
7235/// operator.
7236///
7237/// \param Functions The set of non-member functions that will be
7238/// considered by overload resolution. The caller needs to build this
7239/// set based on the context using, e.g.,
7240/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7241/// set should not contain any member functions; those will be added
7242/// by CreateOverloadedBinOp().
7243///
7244/// \param LHS Left-hand argument.
7245/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +00007246ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00007247Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00007248 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00007249 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00007250 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00007251 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007252 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00007253
7254 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
7255 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
7256 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7257
7258 // If either side is type-dependent, create an appropriate dependent
7259 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007260 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00007261 if (Fns.empty()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007262 // If there are no functions to store, just build a dependent
7263 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +00007264 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007265 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +00007266 Context.DependentTy,
7267 VK_RValue, OK_Ordinary,
7268 OpLoc));
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007269
7270 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
7271 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00007272 VK_LValue,
7273 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007274 Context.DependentTy,
7275 Context.DependentTy,
7276 OpLoc));
7277 }
John McCall6e266892010-01-26 03:27:55 +00007278
7279 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00007280 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00007281 // TODO: provide better source location info in DNLoc component.
7282 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +00007283 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00007284 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00007285 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007286 /*ADL*/ true, IsOverloaded(Fns),
7287 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00007288 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00007289 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00007290 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00007291 VK_RValue,
Douglas Gregor063daf62009-03-13 18:40:31 +00007292 OpLoc));
7293 }
7294
7295 // If this is the .* operator, which is not overloadable, just
7296 // create a built-in binary operator.
John McCall2de56d12010-08-25 11:45:40 +00007297 if (Opc == BO_PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007298 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007299
Sebastian Redl275c2b42009-11-18 23:10:33 +00007300 // If this is the assignment operator, we only perform overload resolution
7301 // if the left-hand side is a class or enumeration type. This is actually
7302 // a hack. The standard requires that we do overload resolution between the
7303 // various built-in candidates, but as DR507 points out, this can lead to
7304 // problems. So we do it this way, which pretty much follows what GCC does.
7305 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +00007306 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007307 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007308
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007309 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007310 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007311
7312 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00007313 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00007314
7315 // Add operator candidates that are member functions.
7316 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7317
John McCall6e266892010-01-26 03:27:55 +00007318 // Add candidates from ADL.
7319 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7320 Args, 2,
7321 /*ExplicitTemplateArgs*/ 0,
7322 CandidateSet);
7323
Douglas Gregor063daf62009-03-13 18:40:31 +00007324 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00007325 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00007326
7327 // Perform overload resolution.
7328 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007329 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007330 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00007331 // We found a built-in operator or an overloaded operator.
7332 FunctionDecl *FnDecl = Best->Function;
7333
7334 if (FnDecl) {
7335 // We matched an overloaded operator. Build a call to that
7336 // operator.
7337
7338 // Convert the arguments.
7339 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00007340 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00007341 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00007342
John McCall60d7b3a2010-08-24 06:29:42 +00007343 ExprResult Arg1
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007344 = PerformCopyInitialization(
7345 InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007346 Context,
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007347 FnDecl->getParamDecl(0)),
7348 SourceLocation(),
7349 Owned(Args[1]));
7350 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00007351 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007352
Douglas Gregor5fccd362010-03-03 23:55:11 +00007353 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007354 Best->FoundDecl, Method))
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007355 return ExprError();
7356
7357 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00007358 } else {
7359 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00007360 ExprResult Arg0
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007361 = PerformCopyInitialization(
7362 InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007363 Context,
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007364 FnDecl->getParamDecl(0)),
7365 SourceLocation(),
7366 Owned(Args[0]));
7367 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00007368 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007369
John McCall60d7b3a2010-08-24 06:29:42 +00007370 ExprResult Arg1
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007371 = PerformCopyInitialization(
7372 InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007373 Context,
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007374 FnDecl->getParamDecl(1)),
7375 SourceLocation(),
7376 Owned(Args[1]));
7377 if (Arg1.isInvalid())
7378 return ExprError();
7379 Args[0] = LHS = Arg0.takeAs<Expr>();
7380 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00007381 }
7382
John McCallb697e082010-05-06 18:15:07 +00007383 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7384
John McCallf89e55a2010-11-18 06:31:45 +00007385 // Determine the result type.
7386 QualType ResultTy = FnDecl->getResultType();
7387 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7388 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +00007389
7390 // Build the actual expression node.
John McCallf89e55a2010-11-18 06:31:45 +00007391 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007392
John McCall9ae2f072010-08-23 23:25:46 +00007393 CXXOperatorCallExpr *TheCall =
7394 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCallf89e55a2010-11-18 06:31:45 +00007395 Args, 2, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007396
John McCall9ae2f072010-08-23 23:25:46 +00007397 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00007398 FnDecl))
7399 return ExprError();
7400
John McCall9ae2f072010-08-23 23:25:46 +00007401 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +00007402 } else {
7403 // We matched a built-in operator. Convert the arguments, then
7404 // break out so that we will build the appropriate built-in
7405 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007406 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007407 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007408 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00007409 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00007410 return ExprError();
7411
7412 break;
7413 }
7414 }
7415
Douglas Gregor33074752009-09-30 21:46:01 +00007416 case OR_No_Viable_Function: {
7417 // C++ [over.match.oper]p9:
7418 // If the operator is the operator , [...] and there are no
7419 // viable functions, then the operator is assumed to be the
7420 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +00007421 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +00007422 break;
7423
Sebastian Redl8593c782009-05-21 11:50:50 +00007424 // For class as left operand for assignment or compound assigment operator
7425 // do not fall through to handling in built-in, but report that no overloaded
7426 // assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +00007427 ExprResult Result = ExprError();
Douglas Gregor33074752009-09-30 21:46:01 +00007428 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +00007429 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00007430 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7431 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007432 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00007433 } else {
7434 // No viable function; try to create a built-in operation, which will
7435 // produce an error. Then, show the non-viable candidates.
7436 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00007437 }
Douglas Gregor33074752009-09-30 21:46:01 +00007438 assert(Result.isInvalid() &&
7439 "C++ binary operator overloading is missing candidates!");
7440 if (Result.isInvalid())
John McCall120d63c2010-08-24 20:38:10 +00007441 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7442 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00007443 return move(Result);
7444 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007445
7446 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00007447 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +00007448 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +00007449 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007450 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007451 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7452 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007453 return ExprError();
7454
7455 case OR_Deleted:
7456 Diag(OpLoc, diag::err_ovl_deleted_oper)
7457 << Best->Function->isDeleted()
7458 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007459 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007460 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00007461 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00007462 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007463
Douglas Gregor33074752009-09-30 21:46:01 +00007464 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007465 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007466}
7467
John McCall60d7b3a2010-08-24 06:29:42 +00007468ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +00007469Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7470 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +00007471 Expr *Base, Expr *Idx) {
7472 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +00007473 DeclarationName OpName =
7474 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7475
7476 // If either side is type-dependent, create an appropriate dependent
7477 // expression.
7478 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7479
John McCallc373d482010-01-27 01:50:18 +00007480 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00007481 // CHECKME: no 'operator' keyword?
7482 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7483 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +00007484 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00007485 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00007486 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007487 /*ADL*/ true, /*Overloaded*/ false,
7488 UnresolvedSetIterator(),
7489 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +00007490 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00007491
Sebastian Redlf322ed62009-10-29 20:17:01 +00007492 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7493 Args, 2,
7494 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00007495 VK_RValue,
Sebastian Redlf322ed62009-10-29 20:17:01 +00007496 RLoc));
7497 }
7498
7499 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007500 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007501
7502 // Subscript can only be overloaded as a member function.
7503
7504 // Add operator candidates that are member functions.
7505 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7506
7507 // Add builtin operator candidates.
7508 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7509
7510 // Perform overload resolution.
7511 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007512 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00007513 case OR_Success: {
7514 // We found a built-in operator or an overloaded operator.
7515 FunctionDecl *FnDecl = Best->Function;
7516
7517 if (FnDecl) {
7518 // We matched an overloaded operator. Build a call to that
7519 // operator.
7520
John McCall9aa472c2010-03-19 07:35:19 +00007521 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007522 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +00007523
Sebastian Redlf322ed62009-10-29 20:17:01 +00007524 // Convert the arguments.
7525 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007526 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007527 Best->FoundDecl, Method))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007528 return ExprError();
7529
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007530 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00007531 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007532 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007533 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007534 FnDecl->getParamDecl(0)),
7535 SourceLocation(),
7536 Owned(Args[1]));
7537 if (InputInit.isInvalid())
7538 return ExprError();
7539
7540 Args[1] = InputInit.takeAs<Expr>();
7541
Sebastian Redlf322ed62009-10-29 20:17:01 +00007542 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +00007543 QualType ResultTy = FnDecl->getResultType();
7544 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7545 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007546
7547 // Build the actual expression node.
John McCallf89e55a2010-11-18 06:31:45 +00007548 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007549
John McCall9ae2f072010-08-23 23:25:46 +00007550 CXXOperatorCallExpr *TheCall =
7551 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7552 FnExpr, Args, 2,
John McCallf89e55a2010-11-18 06:31:45 +00007553 ResultTy, VK, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007554
John McCall9ae2f072010-08-23 23:25:46 +00007555 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +00007556 FnDecl))
7557 return ExprError();
7558
John McCall9ae2f072010-08-23 23:25:46 +00007559 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007560 } else {
7561 // We matched a built-in operator. Convert the arguments, then
7562 // break out so that we will build the appropriate built-in
7563 // operator node.
7564 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007565 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00007566 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00007567 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007568 return ExprError();
7569
7570 break;
7571 }
7572 }
7573
7574 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00007575 if (CandidateSet.empty())
7576 Diag(LLoc, diag::err_ovl_no_oper)
7577 << Args[0]->getType() << /*subscript*/ 0
7578 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7579 else
7580 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7581 << Args[0]->getType()
7582 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007583 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7584 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +00007585 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00007586 }
7587
7588 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00007589 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
7590 << "[]"
7591 << Args[0]->getType() << Args[1]->getType()
7592 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007593 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7594 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007595 return ExprError();
7596
7597 case OR_Deleted:
7598 Diag(LLoc, diag::err_ovl_deleted_oper)
7599 << Best->Function->isDeleted() << "[]"
7600 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007601 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7602 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007603 return ExprError();
7604 }
7605
7606 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +00007607 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007608}
7609
Douglas Gregor88a35142008-12-22 05:46:06 +00007610/// BuildCallToMemberFunction - Build a call to a member
7611/// function. MemExpr is the expression that refers to the member
7612/// function (and includes the object parameter), Args/NumArgs are the
7613/// arguments to the function call (not including the object
7614/// parameter). The caller needs to validate that the member
7615/// expression refers to a member function or an overloaded member
7616/// function.
John McCall60d7b3a2010-08-24 06:29:42 +00007617ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00007618Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7619 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +00007620 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor88a35142008-12-22 05:46:06 +00007621 // Dig out the member expression. This holds both the object
7622 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00007623 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7624
John McCall129e2df2009-11-30 22:42:35 +00007625 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00007626 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00007627 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007628 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00007629 if (isa<MemberExpr>(NakedMemExpr)) {
7630 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00007631 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00007632 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00007633 Qualifier = MemExpr->getQualifier();
John McCall129e2df2009-11-30 22:42:35 +00007634 } else {
7635 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007636 Qualifier = UnresExpr->getQualifier();
7637
John McCall701c89e2009-12-03 04:06:58 +00007638 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00007639
Douglas Gregor88a35142008-12-22 05:46:06 +00007640 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00007641 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00007642
John McCallaa81e162009-12-01 22:10:20 +00007643 // FIXME: avoid copy.
7644 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7645 if (UnresExpr->hasExplicitTemplateArgs()) {
7646 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7647 TemplateArgs = &TemplateArgsBuffer;
7648 }
7649
John McCall129e2df2009-11-30 22:42:35 +00007650 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7651 E = UnresExpr->decls_end(); I != E; ++I) {
7652
John McCall701c89e2009-12-03 04:06:58 +00007653 NamedDecl *Func = *I;
7654 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7655 if (isa<UsingShadowDecl>(Func))
7656 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7657
John McCall129e2df2009-11-30 22:42:35 +00007658 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007659 // If explicit template arguments were provided, we can't call a
7660 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00007661 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007662 continue;
7663
John McCall9aa472c2010-03-19 07:35:19 +00007664 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCall86820f52010-01-26 01:37:31 +00007665 Args, NumArgs,
John McCall701c89e2009-12-03 04:06:58 +00007666 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007667 } else {
John McCall129e2df2009-11-30 22:42:35 +00007668 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00007669 I.getPair(), ActingDC, TemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00007670 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00007671 CandidateSet,
7672 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007673 }
Douglas Gregordec06662009-08-21 18:42:58 +00007674 }
Mike Stump1eb44332009-09-09 15:08:12 +00007675
John McCall129e2df2009-11-30 22:42:35 +00007676 DeclarationName DeclName = UnresExpr->getMemberName();
7677
Douglas Gregor88a35142008-12-22 05:46:06 +00007678 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007679 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +00007680 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00007681 case OR_Success:
7682 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007683 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00007684 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007685 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +00007686 break;
7687
7688 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00007689 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00007690 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007691 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007692 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007693 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007694 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007695
7696 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00007697 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007698 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007699 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007700 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007701 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007702
7703 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00007704 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007705 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00007706 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007707 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007708 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007709 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007710 }
7711
John McCall6bb80172010-03-30 21:47:33 +00007712 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00007713
John McCallaa81e162009-12-01 22:10:20 +00007714 // If overload resolution picked a static member, build a
7715 // non-member call based on that function.
7716 if (Method->isStatic()) {
7717 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7718 Args, NumArgs, RParenLoc);
7719 }
7720
John McCall129e2df2009-11-30 22:42:35 +00007721 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00007722 }
7723
John McCallf89e55a2010-11-18 06:31:45 +00007724 QualType ResultType = Method->getResultType();
7725 ExprValueKind VK = Expr::getValueKindForType(ResultType);
7726 ResultType = ResultType.getNonLValueExprType(Context);
7727
Douglas Gregor88a35142008-12-22 05:46:06 +00007728 assert(Method && "Member call to something that isn't a method?");
John McCall9ae2f072010-08-23 23:25:46 +00007729 CXXMemberCallExpr *TheCall =
7730 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCallf89e55a2010-11-18 06:31:45 +00007731 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +00007732
Anders Carlssoneed3e692009-10-10 00:06:20 +00007733 // Check for a valid return type.
7734 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +00007735 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +00007736 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00007737
Douglas Gregor88a35142008-12-22 05:46:06 +00007738 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00007739 // We only need to do this if there was actually an overload; otherwise
7740 // it was done at lookup.
John McCallaa81e162009-12-01 22:10:20 +00007741 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00007742 if (!Method->isStatic() &&
John McCall6bb80172010-03-30 21:47:33 +00007743 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7744 FoundDecl, Method))
John McCallaa81e162009-12-01 22:10:20 +00007745 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007746 MemExpr->setBase(ObjectArg);
7747
7748 // Convert the rest of the arguments
Douglas Gregor5f970ee2010-05-04 18:18:31 +00007749 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +00007750 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00007751 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00007752 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007753
John McCall9ae2f072010-08-23 23:25:46 +00007754 if (CheckFunctionCall(Method, TheCall))
John McCallaa81e162009-12-01 22:10:20 +00007755 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00007756
John McCall9ae2f072010-08-23 23:25:46 +00007757 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +00007758}
7759
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007760/// BuildCallToObjectOfClassType - Build a call to an object of class
7761/// type (C++ [over.call.object]), which can end up invoking an
7762/// overloaded function call operator (@c operator()) or performing a
7763/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +00007764ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00007765Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00007766 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007767 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007768 SourceLocation RParenLoc) {
7769 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00007770 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00007771
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007772 // C++ [over.call.object]p1:
7773 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00007774 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007775 // candidate functions includes at least the function call
7776 // operators of T. The function call operators of T are obtained by
7777 // ordinary lookup of the name operator() in the context of
7778 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00007779 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00007780 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00007781
7782 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007783 PDiag(diag::err_incomplete_object_call)
Douglas Gregor593564b2009-11-15 07:48:03 +00007784 << Object->getSourceRange()))
7785 return true;
7786
John McCalla24dc2e2009-11-17 02:14:36 +00007787 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7788 LookupQualifiedName(R, Record->getDecl());
7789 R.suppressDiagnostics();
7790
Douglas Gregor593564b2009-11-15 07:48:03 +00007791 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00007792 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007793 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCall86820f52010-01-26 01:37:31 +00007794 Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00007795 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00007796 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00007797
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007798 // C++ [over.call.object]p2:
7799 // In addition, for each conversion function declared in T of the
7800 // form
7801 //
7802 // operator conversion-type-id () cv-qualifier;
7803 //
7804 // where cv-qualifier is the same cv-qualification as, or a
7805 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00007806 // denotes the type "pointer to function of (P1,...,Pn) returning
7807 // R", or the type "reference to pointer to function of
7808 // (P1,...,Pn) returning R", or the type "reference to function
7809 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007810 // is also considered as a candidate function. Similarly,
7811 // surrogate call functions are added to the set of candidate
7812 // functions for each conversion function declared in an
7813 // accessible base class provided the function is not hidden
7814 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00007815 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00007816 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00007817 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00007818 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00007819 NamedDecl *D = *I;
7820 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7821 if (isa<UsingShadowDecl>(D))
7822 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7823
Douglas Gregor4a27d702009-10-21 06:18:39 +00007824 // Skip over templated conversion functions; they aren't
7825 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00007826 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00007827 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007828
John McCall701c89e2009-12-03 04:06:58 +00007829 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00007830
Douglas Gregor4a27d702009-10-21 06:18:39 +00007831 // Strip the reference type (if any) and then the pointer type (if
7832 // any) to get down to what might be a function type.
7833 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7834 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7835 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007836
Douglas Gregor4a27d702009-10-21 06:18:39 +00007837 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall9aa472c2010-03-19 07:35:19 +00007838 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall701c89e2009-12-03 04:06:58 +00007839 Object->getType(), Args, NumArgs,
7840 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007841 }
Mike Stump1eb44332009-09-09 15:08:12 +00007842
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007843 // Perform overload resolution.
7844 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007845 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
7846 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007847 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007848 // Overload resolution succeeded; we'll build the appropriate call
7849 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007850 break;
7851
7852 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00007853 if (CandidateSet.empty())
7854 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7855 << Object->getType() << /*call*/ 1
7856 << Object->getSourceRange();
7857 else
7858 Diag(Object->getSourceRange().getBegin(),
7859 diag::err_ovl_no_viable_object_call)
7860 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007861 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007862 break;
7863
7864 case OR_Ambiguous:
7865 Diag(Object->getSourceRange().getBegin(),
7866 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00007867 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007868 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007869 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007870
7871 case OR_Deleted:
7872 Diag(Object->getSourceRange().getBegin(),
7873 diag::err_ovl_deleted_object_call)
7874 << Best->Function->isDeleted()
7875 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007876 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007877 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007878 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007879
Douglas Gregorff331c12010-07-25 18:17:45 +00007880 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007881 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007882
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007883 if (Best->Function == 0) {
7884 // Since there is no function declaration, this is one of the
7885 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00007886 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007887 = cast<CXXConversionDecl>(
7888 Best->Conversions[0].UserDefined.ConversionFunction);
7889
John McCall9aa472c2010-03-19 07:35:19 +00007890 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007891 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007892
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007893 // We selected one of the surrogate functions that converts the
7894 // object parameter to a function pointer. Perform the conversion
7895 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00007896
7897 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007898 // and then call it.
John McCall6bb80172010-03-30 21:47:33 +00007899 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7900 Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007901
John McCallf312b1e2010-08-26 23:41:50 +00007902 return ActOnCallExpr(S, CE, LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007903 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007904 }
7905
John McCall9aa472c2010-03-19 07:35:19 +00007906 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007907 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007908
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007909 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7910 // that calls this method, using Object for the implicit object
7911 // parameter and passing along the remaining arguments.
7912 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00007913 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007914
7915 unsigned NumArgsInProto = Proto->getNumArgs();
7916 unsigned NumArgsToCheck = NumArgs;
7917
7918 // Build the full argument list for the method call (the
7919 // implicit object parameter is placed at the beginning of the
7920 // list).
7921 Expr **MethodArgs;
7922 if (NumArgs < NumArgsInProto) {
7923 NumArgsToCheck = NumArgsInProto;
7924 MethodArgs = new Expr*[NumArgsInProto + 1];
7925 } else {
7926 MethodArgs = new Expr*[NumArgs + 1];
7927 }
7928 MethodArgs[0] = Object;
7929 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7930 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00007931
John McCallf89e55a2010-11-18 06:31:45 +00007932 Expr *NewFn = CreateFunctionRefExpr(*this, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007933
7934 // Once we've built TheCall, all of the expressions are properly
7935 // owned.
John McCallf89e55a2010-11-18 06:31:45 +00007936 QualType ResultTy = Method->getResultType();
7937 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7938 ResultTy = ResultTy.getNonLValueExprType(Context);
7939
John McCall9ae2f072010-08-23 23:25:46 +00007940 CXXOperatorCallExpr *TheCall =
7941 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
7942 MethodArgs, NumArgs + 1,
John McCallf89e55a2010-11-18 06:31:45 +00007943 ResultTy, VK, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007944 delete [] MethodArgs;
7945
John McCall9ae2f072010-08-23 23:25:46 +00007946 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +00007947 Method))
7948 return true;
7949
Douglas Gregor518fda12009-01-13 05:10:00 +00007950 // We may have default arguments. If so, we need to allocate more
7951 // slots in the call for them.
7952 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00007953 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00007954 else if (NumArgs > NumArgsInProto)
7955 NumArgsToCheck = NumArgsInProto;
7956
Chris Lattner312531a2009-04-12 08:11:20 +00007957 bool IsError = false;
7958
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007959 // Initialize the implicit object parameter.
Douglas Gregor5fccd362010-03-03 23:55:11 +00007960 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007961 Best->FoundDecl, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007962 TheCall->setArg(0, Object);
7963
Chris Lattner312531a2009-04-12 08:11:20 +00007964
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007965 // Check the argument types.
7966 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007967 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00007968 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007969 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00007970
Douglas Gregor518fda12009-01-13 05:10:00 +00007971 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00007972
John McCall60d7b3a2010-08-24 06:29:42 +00007973 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +00007974 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007975 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +00007976 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +00007977 SourceLocation(), Arg);
Anders Carlsson3faa4862010-01-29 18:43:53 +00007978
7979 IsError |= InputInit.isInvalid();
7980 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007981 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00007982 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +00007983 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7984 if (DefArg.isInvalid()) {
7985 IsError = true;
7986 break;
7987 }
7988
7989 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007990 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007991
7992 TheCall->setArg(i + 1, Arg);
7993 }
7994
7995 // If this is a variadic call, handle args passed through "...".
7996 if (Proto->isVariadic()) {
7997 // Promote the arguments (C99 6.5.2.2p7).
7998 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7999 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00008000 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008001 TheCall->setArg(i + 1, Arg);
8002 }
8003 }
8004
Chris Lattner312531a2009-04-12 08:11:20 +00008005 if (IsError) return true;
8006
John McCall9ae2f072010-08-23 23:25:46 +00008007 if (CheckFunctionCall(Method, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00008008 return true;
8009
John McCall182f7092010-08-24 06:09:16 +00008010 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008011}
8012
Douglas Gregor8ba10742008-11-20 16:27:02 +00008013/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00008014/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00008015/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +00008016ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008017Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00008018 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00008019
John McCall5769d612010-02-08 23:07:23 +00008020 SourceLocation Loc = Base->getExprLoc();
8021
Douglas Gregor8ba10742008-11-20 16:27:02 +00008022 // C++ [over.ref]p1:
8023 //
8024 // [...] An expression x->m is interpreted as (x.operator->())->m
8025 // for a class object x of type T if T::operator->() exists and if
8026 // the operator is selected as the best match function by the
8027 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00008028 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00008029 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00008030 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008031
John McCall5769d612010-02-08 23:07:23 +00008032 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00008033 PDiag(diag::err_typecheck_incomplete_tag)
8034 << Base->getSourceRange()))
8035 return ExprError();
8036
John McCalla24dc2e2009-11-17 02:14:36 +00008037 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
8038 LookupQualifiedName(R, BaseRecord->getDecl());
8039 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00008040
8041 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00008042 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00008043 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00008044 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00008045 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00008046
8047 // Perform overload resolution.
8048 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008049 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00008050 case OR_Success:
8051 // Overload resolution succeeded; we'll build the call below.
8052 break;
8053
8054 case OR_No_Viable_Function:
8055 if (CandidateSet.empty())
8056 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008057 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00008058 else
8059 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008060 << "operator->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008061 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008062 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00008063
8064 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00008065 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8066 << "->" << Base->getType() << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008067 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008068 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008069
8070 case OR_Deleted:
8071 Diag(OpLoc, diag::err_ovl_deleted_oper)
8072 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00008073 << "->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008074 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008075 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00008076 }
8077
John McCall9aa472c2010-03-19 07:35:19 +00008078 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00008079 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +00008080
Douglas Gregor8ba10742008-11-20 16:27:02 +00008081 // Convert the object parameter.
8082 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00008083 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
8084 Best->FoundDecl, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008085 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00008086
Douglas Gregor8ba10742008-11-20 16:27:02 +00008087 // Build the operator call.
John McCallf89e55a2010-11-18 06:31:45 +00008088 Expr *FnExpr = CreateFunctionRefExpr(*this, Method);
Anders Carlsson15ea3782009-10-13 22:43:21 +00008089
John McCallf89e55a2010-11-18 06:31:45 +00008090 QualType ResultTy = Method->getResultType();
8091 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8092 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +00008093 CXXOperatorCallExpr *TheCall =
8094 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
John McCallf89e55a2010-11-18 06:31:45 +00008095 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +00008096
John McCall9ae2f072010-08-23 23:25:46 +00008097 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00008098 Method))
8099 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00008100 return Owned(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00008101}
8102
Douglas Gregor904eed32008-11-10 20:40:00 +00008103/// FixOverloadedFunctionReference - E is an expression that refers to
8104/// a C++ overloaded function (possibly with some parentheses and
8105/// perhaps a '&' around it). We have resolved the overloaded function
8106/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00008107/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +00008108Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +00008109 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00008110 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00008111 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
8112 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00008113 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00008114 return PE;
Douglas Gregor699ee522009-11-20 19:42:02 +00008115
8116 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
8117 }
8118
8119 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00008120 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
8121 Found, Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00008122 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00008123 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00008124 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +00008125 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +00008126 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00008127 return ICE;
Douglas Gregor699ee522009-11-20 19:42:02 +00008128
John McCallf871d0c2010-08-07 06:22:56 +00008129 return ImplicitCastExpr::Create(Context, ICE->getType(),
8130 ICE->getCastKind(),
8131 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +00008132 ICE->getValueKind());
Douglas Gregor699ee522009-11-20 19:42:02 +00008133 }
8134
8135 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00008136 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00008137 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00008138 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8139 if (Method->isStatic()) {
8140 // Do nothing: static member functions aren't any different
8141 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00008142 } else {
John McCallf7a1a742009-11-24 19:00:30 +00008143 // Fix the sub expression, which really has to be an
8144 // UnresolvedLookupExpr holding an overloaded member function
8145 // or template.
John McCall6bb80172010-03-30 21:47:33 +00008146 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8147 Found, Fn);
John McCallba135432009-11-21 08:51:07 +00008148 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00008149 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +00008150
John McCallba135432009-11-21 08:51:07 +00008151 assert(isa<DeclRefExpr>(SubExpr)
8152 && "fixed to something other than a decl ref");
8153 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8154 && "fixed to a member ref with no nested name qualifier");
8155
8156 // We have taken the address of a pointer to member
8157 // function. Perform the computation here so that we get the
8158 // appropriate pointer to member type.
8159 QualType ClassType
8160 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8161 QualType MemPtrType
8162 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
8163
John McCallf89e55a2010-11-18 06:31:45 +00008164 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
8165 VK_RValue, OK_Ordinary,
8166 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00008167 }
8168 }
John McCall6bb80172010-03-30 21:47:33 +00008169 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8170 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00008171 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00008172 return UnOp;
Anders Carlsson96ad5332009-10-21 17:16:23 +00008173
John McCall2de56d12010-08-25 11:45:40 +00008174 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +00008175 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00008176 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +00008177 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00008178 }
John McCallba135432009-11-21 08:51:07 +00008179
8180 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00008181 // FIXME: avoid copy.
8182 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00008183 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00008184 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
8185 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00008186 }
8187
John McCallba135432009-11-21 08:51:07 +00008188 return DeclRefExpr::Create(Context,
8189 ULE->getQualifier(),
8190 ULE->getQualifierRange(),
8191 Fn,
8192 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00008193 Fn->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008194 VK_LValue,
John McCallaa81e162009-12-01 22:10:20 +00008195 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00008196 }
8197
John McCall129e2df2009-11-30 22:42:35 +00008198 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00008199 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00008200 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8201 if (MemExpr->hasExplicitTemplateArgs()) {
8202 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8203 TemplateArgs = &TemplateArgsBuffer;
8204 }
John McCalld5532b62009-11-23 01:53:49 +00008205
John McCallaa81e162009-12-01 22:10:20 +00008206 Expr *Base;
8207
John McCallf89e55a2010-11-18 06:31:45 +00008208 // If we're filling in a static method where we used to have an
8209 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +00008210 if (MemExpr->isImplicitAccess()) {
8211 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
8212 return DeclRefExpr::Create(Context,
8213 MemExpr->getQualifier(),
8214 MemExpr->getQualifierRange(),
8215 Fn,
8216 MemExpr->getMemberLoc(),
8217 Fn->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008218 VK_LValue,
John McCallaa81e162009-12-01 22:10:20 +00008219 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00008220 } else {
8221 SourceLocation Loc = MemExpr->getMemberLoc();
8222 if (MemExpr->getQualifier())
8223 Loc = MemExpr->getQualifierRange().getBegin();
8224 Base = new (Context) CXXThisExpr(Loc,
8225 MemExpr->getBaseType(),
8226 /*isImplicit=*/true);
8227 }
John McCallaa81e162009-12-01 22:10:20 +00008228 } else
John McCall3fa5cae2010-10-26 07:05:15 +00008229 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +00008230
8231 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00008232 MemExpr->isArrow(),
8233 MemExpr->getQualifier(),
8234 MemExpr->getQualifierRange(),
8235 Fn,
John McCall6bb80172010-03-30 21:47:33 +00008236 Found,
Abramo Bagnara25777432010-08-11 22:01:17 +00008237 MemExpr->getMemberNameInfo(),
John McCallaa81e162009-12-01 22:10:20 +00008238 TemplateArgs,
John McCallf89e55a2010-11-18 06:31:45 +00008239 Fn->getType(),
8240 cast<CXXMethodDecl>(Fn)->isStatic()
8241 ? VK_LValue : VK_RValue,
8242 OK_Ordinary);
Douglas Gregor699ee522009-11-20 19:42:02 +00008243 }
8244
John McCall3fa5cae2010-10-26 07:05:15 +00008245 llvm_unreachable("Invalid reference to overloaded function");
8246 return E;
Douglas Gregor904eed32008-11-10 20:40:00 +00008247}
8248
John McCall60d7b3a2010-08-24 06:29:42 +00008249ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
8250 DeclAccessPair Found,
8251 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +00008252 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +00008253}
8254
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008255} // end namespace clang