File: | tools/clang/lib/Sema/SemaOverload.cpp |
Warning: | line 9872, column 50 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// | |||
2 | // | |||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
4 | // See https://llvm.org/LICENSE.txt for license information. | |||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
6 | // | |||
7 | //===----------------------------------------------------------------------===// | |||
8 | // | |||
9 | // This file provides Sema routines for C++ overloading. | |||
10 | // | |||
11 | //===----------------------------------------------------------------------===// | |||
12 | ||||
13 | #include "clang/Sema/Overload.h" | |||
14 | #include "clang/AST/ASTContext.h" | |||
15 | #include "clang/AST/CXXInheritance.h" | |||
16 | #include "clang/AST/DeclObjC.h" | |||
17 | #include "clang/AST/Expr.h" | |||
18 | #include "clang/AST/ExprCXX.h" | |||
19 | #include "clang/AST/ExprObjC.h" | |||
20 | #include "clang/AST/TypeOrdering.h" | |||
21 | #include "clang/Basic/Diagnostic.h" | |||
22 | #include "clang/Basic/DiagnosticOptions.h" | |||
23 | #include "clang/Basic/PartialDiagnostic.h" | |||
24 | #include "clang/Basic/TargetInfo.h" | |||
25 | #include "clang/Sema/Initialization.h" | |||
26 | #include "clang/Sema/Lookup.h" | |||
27 | #include "clang/Sema/SemaInternal.h" | |||
28 | #include "clang/Sema/Template.h" | |||
29 | #include "clang/Sema/TemplateDeduction.h" | |||
30 | #include "llvm/ADT/DenseSet.h" | |||
31 | #include "llvm/ADT/Optional.h" | |||
32 | #include "llvm/ADT/STLExtras.h" | |||
33 | #include "llvm/ADT/SmallPtrSet.h" | |||
34 | #include "llvm/ADT/SmallString.h" | |||
35 | #include <algorithm> | |||
36 | #include <cstdlib> | |||
37 | ||||
38 | using namespace clang; | |||
39 | using namespace sema; | |||
40 | ||||
41 | static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { | |||
42 | return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { | |||
43 | return P->hasAttr<PassObjectSizeAttr>(); | |||
44 | }); | |||
45 | } | |||
46 | ||||
47 | /// A convenience routine for creating a decayed reference to a function. | |||
48 | static ExprResult | |||
49 | CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, | |||
50 | const Expr *Base, bool HadMultipleCandidates, | |||
51 | SourceLocation Loc = SourceLocation(), | |||
52 | const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ | |||
53 | if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) | |||
54 | return ExprError(); | |||
55 | // If FoundDecl is different from Fn (such as if one is a template | |||
56 | // and the other a specialization), make sure DiagnoseUseOfDecl is | |||
57 | // called on both. | |||
58 | // FIXME: This would be more comprehensively addressed by modifying | |||
59 | // DiagnoseUseOfDecl to accept both the FoundDecl and the decl | |||
60 | // being used. | |||
61 | if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) | |||
62 | return ExprError(); | |||
63 | if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) | |||
64 | S.ResolveExceptionSpec(Loc, FPT); | |||
65 | DeclRefExpr *DRE = new (S.Context) | |||
66 | DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); | |||
67 | if (HadMultipleCandidates) | |||
68 | DRE->setHadMultipleCandidates(true); | |||
69 | ||||
70 | S.MarkDeclRefReferenced(DRE, Base); | |||
71 | return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), | |||
72 | CK_FunctionToPointerDecay); | |||
73 | } | |||
74 | ||||
75 | static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, | |||
76 | bool InOverloadResolution, | |||
77 | StandardConversionSequence &SCS, | |||
78 | bool CStyle, | |||
79 | bool AllowObjCWritebackConversion); | |||
80 | ||||
81 | static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, | |||
82 | QualType &ToType, | |||
83 | bool InOverloadResolution, | |||
84 | StandardConversionSequence &SCS, | |||
85 | bool CStyle); | |||
86 | static OverloadingResult | |||
87 | IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, | |||
88 | UserDefinedConversionSequence& User, | |||
89 | OverloadCandidateSet& Conversions, | |||
90 | bool AllowExplicit, | |||
91 | bool AllowObjCConversionOnExplicit); | |||
92 | ||||
93 | ||||
94 | static ImplicitConversionSequence::CompareKind | |||
95 | CompareStandardConversionSequences(Sema &S, SourceLocation Loc, | |||
96 | const StandardConversionSequence& SCS1, | |||
97 | const StandardConversionSequence& SCS2); | |||
98 | ||||
99 | static ImplicitConversionSequence::CompareKind | |||
100 | CompareQualificationConversions(Sema &S, | |||
101 | const StandardConversionSequence& SCS1, | |||
102 | const StandardConversionSequence& SCS2); | |||
103 | ||||
104 | static ImplicitConversionSequence::CompareKind | |||
105 | CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, | |||
106 | const StandardConversionSequence& SCS1, | |||
107 | const StandardConversionSequence& SCS2); | |||
108 | ||||
109 | /// GetConversionRank - Retrieve the implicit conversion rank | |||
110 | /// corresponding to the given implicit conversion kind. | |||
111 | ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { | |||
112 | static const ImplicitConversionRank | |||
113 | Rank[(int)ICK_Num_Conversion_Kinds] = { | |||
114 | ICR_Exact_Match, | |||
115 | ICR_Exact_Match, | |||
116 | ICR_Exact_Match, | |||
117 | ICR_Exact_Match, | |||
118 | ICR_Exact_Match, | |||
119 | ICR_Exact_Match, | |||
120 | ICR_Promotion, | |||
121 | ICR_Promotion, | |||
122 | ICR_Promotion, | |||
123 | ICR_Conversion, | |||
124 | ICR_Conversion, | |||
125 | ICR_Conversion, | |||
126 | ICR_Conversion, | |||
127 | ICR_Conversion, | |||
128 | ICR_Conversion, | |||
129 | ICR_Conversion, | |||
130 | ICR_Conversion, | |||
131 | ICR_Conversion, | |||
132 | ICR_Conversion, | |||
133 | ICR_OCL_Scalar_Widening, | |||
134 | ICR_Complex_Real_Conversion, | |||
135 | ICR_Conversion, | |||
136 | ICR_Conversion, | |||
137 | ICR_Writeback_Conversion, | |||
138 | ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- | |||
139 | // it was omitted by the patch that added | |||
140 | // ICK_Zero_Event_Conversion | |||
141 | ICR_C_Conversion, | |||
142 | ICR_C_Conversion_Extension | |||
143 | }; | |||
144 | return Rank[(int)Kind]; | |||
145 | } | |||
146 | ||||
147 | /// GetImplicitConversionName - Return the name of this kind of | |||
148 | /// implicit conversion. | |||
149 | static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { | |||
150 | static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { | |||
151 | "No conversion", | |||
152 | "Lvalue-to-rvalue", | |||
153 | "Array-to-pointer", | |||
154 | "Function-to-pointer", | |||
155 | "Function pointer conversion", | |||
156 | "Qualification", | |||
157 | "Integral promotion", | |||
158 | "Floating point promotion", | |||
159 | "Complex promotion", | |||
160 | "Integral conversion", | |||
161 | "Floating conversion", | |||
162 | "Complex conversion", | |||
163 | "Floating-integral conversion", | |||
164 | "Pointer conversion", | |||
165 | "Pointer-to-member conversion", | |||
166 | "Boolean conversion", | |||
167 | "Compatible-types conversion", | |||
168 | "Derived-to-base conversion", | |||
169 | "Vector conversion", | |||
170 | "Vector splat", | |||
171 | "Complex-real conversion", | |||
172 | "Block Pointer conversion", | |||
173 | "Transparent Union Conversion", | |||
174 | "Writeback conversion", | |||
175 | "OpenCL Zero Event Conversion", | |||
176 | "C specific type conversion", | |||
177 | "Incompatible pointer conversion" | |||
178 | }; | |||
179 | return Name[Kind]; | |||
180 | } | |||
181 | ||||
182 | /// StandardConversionSequence - Set the standard conversion | |||
183 | /// sequence to the identity conversion. | |||
184 | void StandardConversionSequence::setAsIdentityConversion() { | |||
185 | First = ICK_Identity; | |||
186 | Second = ICK_Identity; | |||
187 | Third = ICK_Identity; | |||
188 | DeprecatedStringLiteralToCharPtr = false; | |||
189 | QualificationIncludesObjCLifetime = false; | |||
190 | ReferenceBinding = false; | |||
191 | DirectBinding = false; | |||
192 | IsLvalueReference = true; | |||
193 | BindsToFunctionLvalue = false; | |||
194 | BindsToRvalue = false; | |||
195 | BindsImplicitObjectArgumentWithoutRefQualifier = false; | |||
196 | ObjCLifetimeConversionBinding = false; | |||
197 | CopyConstructor = nullptr; | |||
198 | } | |||
199 | ||||
200 | /// getRank - Retrieve the rank of this standard conversion sequence | |||
201 | /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the | |||
202 | /// implicit conversions. | |||
203 | ImplicitConversionRank StandardConversionSequence::getRank() const { | |||
204 | ImplicitConversionRank Rank = ICR_Exact_Match; | |||
205 | if (GetConversionRank(First) > Rank) | |||
206 | Rank = GetConversionRank(First); | |||
207 | if (GetConversionRank(Second) > Rank) | |||
208 | Rank = GetConversionRank(Second); | |||
209 | if (GetConversionRank(Third) > Rank) | |||
210 | Rank = GetConversionRank(Third); | |||
211 | return Rank; | |||
212 | } | |||
213 | ||||
214 | /// isPointerConversionToBool - Determines whether this conversion is | |||
215 | /// a conversion of a pointer or pointer-to-member to bool. This is | |||
216 | /// used as part of the ranking of standard conversion sequences | |||
217 | /// (C++ 13.3.3.2p4). | |||
218 | bool StandardConversionSequence::isPointerConversionToBool() const { | |||
219 | // Note that FromType has not necessarily been transformed by the | |||
220 | // array-to-pointer or function-to-pointer implicit conversions, so | |||
221 | // check for their presence as well as checking whether FromType is | |||
222 | // a pointer. | |||
223 | if (getToType(1)->isBooleanType() && | |||
224 | (getFromType()->isPointerType() || | |||
225 | getFromType()->isMemberPointerType() || | |||
226 | getFromType()->isObjCObjectPointerType() || | |||
227 | getFromType()->isBlockPointerType() || | |||
228 | getFromType()->isNullPtrType() || | |||
229 | First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) | |||
230 | return true; | |||
231 | ||||
232 | return false; | |||
233 | } | |||
234 | ||||
235 | /// isPointerConversionToVoidPointer - Determines whether this | |||
236 | /// conversion is a conversion of a pointer to a void pointer. This is | |||
237 | /// used as part of the ranking of standard conversion sequences (C++ | |||
238 | /// 13.3.3.2p4). | |||
239 | bool | |||
240 | StandardConversionSequence:: | |||
241 | isPointerConversionToVoidPointer(ASTContext& Context) const { | |||
242 | QualType FromType = getFromType(); | |||
243 | QualType ToType = getToType(1); | |||
244 | ||||
245 | // Note that FromType has not necessarily been transformed by the | |||
246 | // array-to-pointer implicit conversion, so check for its presence | |||
247 | // and redo the conversion to get a pointer. | |||
248 | if (First == ICK_Array_To_Pointer) | |||
249 | FromType = Context.getArrayDecayedType(FromType); | |||
250 | ||||
251 | if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) | |||
252 | if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) | |||
253 | return ToPtrType->getPointeeType()->isVoidType(); | |||
254 | ||||
255 | return false; | |||
256 | } | |||
257 | ||||
258 | /// Skip any implicit casts which could be either part of a narrowing conversion | |||
259 | /// or after one in an implicit conversion. | |||
260 | static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { | |||
261 | while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { | |||
262 | switch (ICE->getCastKind()) { | |||
263 | case CK_NoOp: | |||
264 | case CK_IntegralCast: | |||
265 | case CK_IntegralToBoolean: | |||
266 | case CK_IntegralToFloating: | |||
267 | case CK_BooleanToSignedIntegral: | |||
268 | case CK_FloatingToIntegral: | |||
269 | case CK_FloatingToBoolean: | |||
270 | case CK_FloatingCast: | |||
271 | Converted = ICE->getSubExpr(); | |||
272 | continue; | |||
273 | ||||
274 | default: | |||
275 | return Converted; | |||
276 | } | |||
277 | } | |||
278 | ||||
279 | return Converted; | |||
280 | } | |||
281 | ||||
282 | /// Check if this standard conversion sequence represents a narrowing | |||
283 | /// conversion, according to C++11 [dcl.init.list]p7. | |||
284 | /// | |||
285 | /// \param Ctx The AST context. | |||
286 | /// \param Converted The result of applying this standard conversion sequence. | |||
287 | /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the | |||
288 | /// value of the expression prior to the narrowing conversion. | |||
289 | /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the | |||
290 | /// type of the expression prior to the narrowing conversion. | |||
291 | /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions | |||
292 | /// from floating point types to integral types should be ignored. | |||
293 | NarrowingKind StandardConversionSequence::getNarrowingKind( | |||
294 | ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, | |||
295 | QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { | |||
296 | assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++")((Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++" ) ? static_cast<void> (0) : __assert_fail ("Ctx.getLangOpts().CPlusPlus && \"narrowing check outside C++\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 296, __PRETTY_FUNCTION__)); | |||
297 | ||||
298 | // C++11 [dcl.init.list]p7: | |||
299 | // A narrowing conversion is an implicit conversion ... | |||
300 | QualType FromType = getToType(0); | |||
301 | QualType ToType = getToType(1); | |||
302 | ||||
303 | // A conversion to an enumeration type is narrowing if the conversion to | |||
304 | // the underlying type is narrowing. This only arises for expressions of | |||
305 | // the form 'Enum{init}'. | |||
306 | if (auto *ET = ToType->getAs<EnumType>()) | |||
307 | ToType = ET->getDecl()->getIntegerType(); | |||
308 | ||||
309 | switch (Second) { | |||
310 | // 'bool' is an integral type; dispatch to the right place to handle it. | |||
311 | case ICK_Boolean_Conversion: | |||
312 | if (FromType->isRealFloatingType()) | |||
313 | goto FloatingIntegralConversion; | |||
314 | if (FromType->isIntegralOrUnscopedEnumerationType()) | |||
315 | goto IntegralConversion; | |||
316 | // Boolean conversions can be from pointers and pointers to members | |||
317 | // [conv.bool], and those aren't considered narrowing conversions. | |||
318 | return NK_Not_Narrowing; | |||
319 | ||||
320 | // -- from a floating-point type to an integer type, or | |||
321 | // | |||
322 | // -- from an integer type or unscoped enumeration type to a floating-point | |||
323 | // type, except where the source is a constant expression and the actual | |||
324 | // value after conversion will fit into the target type and will produce | |||
325 | // the original value when converted back to the original type, or | |||
326 | case ICK_Floating_Integral: | |||
327 | FloatingIntegralConversion: | |||
328 | if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { | |||
329 | return NK_Type_Narrowing; | |||
330 | } else if (FromType->isIntegralOrUnscopedEnumerationType() && | |||
331 | ToType->isRealFloatingType()) { | |||
332 | if (IgnoreFloatToIntegralConversion) | |||
333 | return NK_Not_Narrowing; | |||
334 | llvm::APSInt IntConstantValue; | |||
335 | const Expr *Initializer = IgnoreNarrowingConversion(Converted); | |||
336 | assert(Initializer && "Unknown conversion expression")((Initializer && "Unknown conversion expression") ? static_cast <void> (0) : __assert_fail ("Initializer && \"Unknown conversion expression\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 336, __PRETTY_FUNCTION__)); | |||
337 | ||||
338 | // If it's value-dependent, we can't tell whether it's narrowing. | |||
339 | if (Initializer->isValueDependent()) | |||
340 | return NK_Dependent_Narrowing; | |||
341 | ||||
342 | if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { | |||
343 | // Convert the integer to the floating type. | |||
344 | llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); | |||
345 | Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), | |||
346 | llvm::APFloat::rmNearestTiesToEven); | |||
347 | // And back. | |||
348 | llvm::APSInt ConvertedValue = IntConstantValue; | |||
349 | bool ignored; | |||
350 | Result.convertToInteger(ConvertedValue, | |||
351 | llvm::APFloat::rmTowardZero, &ignored); | |||
352 | // If the resulting value is different, this was a narrowing conversion. | |||
353 | if (IntConstantValue != ConvertedValue) { | |||
354 | ConstantValue = APValue(IntConstantValue); | |||
355 | ConstantType = Initializer->getType(); | |||
356 | return NK_Constant_Narrowing; | |||
357 | } | |||
358 | } else { | |||
359 | // Variables are always narrowings. | |||
360 | return NK_Variable_Narrowing; | |||
361 | } | |||
362 | } | |||
363 | return NK_Not_Narrowing; | |||
364 | ||||
365 | // -- from long double to double or float, or from double to float, except | |||
366 | // where the source is a constant expression and the actual value after | |||
367 | // conversion is within the range of values that can be represented (even | |||
368 | // if it cannot be represented exactly), or | |||
369 | case ICK_Floating_Conversion: | |||
370 | if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && | |||
371 | Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { | |||
372 | // FromType is larger than ToType. | |||
373 | const Expr *Initializer = IgnoreNarrowingConversion(Converted); | |||
374 | ||||
375 | // If it's value-dependent, we can't tell whether it's narrowing. | |||
376 | if (Initializer->isValueDependent()) | |||
377 | return NK_Dependent_Narrowing; | |||
378 | ||||
379 | if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { | |||
380 | // Constant! | |||
381 | assert(ConstantValue.isFloat())((ConstantValue.isFloat()) ? static_cast<void> (0) : __assert_fail ("ConstantValue.isFloat()", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 381, __PRETTY_FUNCTION__)); | |||
382 | llvm::APFloat FloatVal = ConstantValue.getFloat(); | |||
383 | // Convert the source value into the target type. | |||
384 | bool ignored; | |||
385 | llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( | |||
386 | Ctx.getFloatTypeSemantics(ToType), | |||
387 | llvm::APFloat::rmNearestTiesToEven, &ignored); | |||
388 | // If there was no overflow, the source value is within the range of | |||
389 | // values that can be represented. | |||
390 | if (ConvertStatus & llvm::APFloat::opOverflow) { | |||
391 | ConstantType = Initializer->getType(); | |||
392 | return NK_Constant_Narrowing; | |||
393 | } | |||
394 | } else { | |||
395 | return NK_Variable_Narrowing; | |||
396 | } | |||
397 | } | |||
398 | return NK_Not_Narrowing; | |||
399 | ||||
400 | // -- from an integer type or unscoped enumeration type to an integer type | |||
401 | // that cannot represent all the values of the original type, except where | |||
402 | // the source is a constant expression and the actual value after | |||
403 | // conversion will fit into the target type and will produce the original | |||
404 | // value when converted back to the original type. | |||
405 | case ICK_Integral_Conversion: | |||
406 | IntegralConversion: { | |||
407 | assert(FromType->isIntegralOrUnscopedEnumerationType())((FromType->isIntegralOrUnscopedEnumerationType()) ? static_cast <void> (0) : __assert_fail ("FromType->isIntegralOrUnscopedEnumerationType()" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 407, __PRETTY_FUNCTION__)); | |||
408 | assert(ToType->isIntegralOrUnscopedEnumerationType())((ToType->isIntegralOrUnscopedEnumerationType()) ? static_cast <void> (0) : __assert_fail ("ToType->isIntegralOrUnscopedEnumerationType()" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 408, __PRETTY_FUNCTION__)); | |||
409 | const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); | |||
410 | const unsigned FromWidth = Ctx.getIntWidth(FromType); | |||
411 | const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); | |||
412 | const unsigned ToWidth = Ctx.getIntWidth(ToType); | |||
413 | ||||
414 | if (FromWidth > ToWidth || | |||
415 | (FromWidth == ToWidth && FromSigned != ToSigned) || | |||
416 | (FromSigned && !ToSigned)) { | |||
417 | // Not all values of FromType can be represented in ToType. | |||
418 | llvm::APSInt InitializerValue; | |||
419 | const Expr *Initializer = IgnoreNarrowingConversion(Converted); | |||
420 | ||||
421 | // If it's value-dependent, we can't tell whether it's narrowing. | |||
422 | if (Initializer->isValueDependent()) | |||
423 | return NK_Dependent_Narrowing; | |||
424 | ||||
425 | if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { | |||
426 | // Such conversions on variables are always narrowing. | |||
427 | return NK_Variable_Narrowing; | |||
428 | } | |||
429 | bool Narrowing = false; | |||
430 | if (FromWidth < ToWidth) { | |||
431 | // Negative -> unsigned is narrowing. Otherwise, more bits is never | |||
432 | // narrowing. | |||
433 | if (InitializerValue.isSigned() && InitializerValue.isNegative()) | |||
434 | Narrowing = true; | |||
435 | } else { | |||
436 | // Add a bit to the InitializerValue so we don't have to worry about | |||
437 | // signed vs. unsigned comparisons. | |||
438 | InitializerValue = InitializerValue.extend( | |||
439 | InitializerValue.getBitWidth() + 1); | |||
440 | // Convert the initializer to and from the target width and signed-ness. | |||
441 | llvm::APSInt ConvertedValue = InitializerValue; | |||
442 | ConvertedValue = ConvertedValue.trunc(ToWidth); | |||
443 | ConvertedValue.setIsSigned(ToSigned); | |||
444 | ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); | |||
445 | ConvertedValue.setIsSigned(InitializerValue.isSigned()); | |||
446 | // If the result is different, this was a narrowing conversion. | |||
447 | if (ConvertedValue != InitializerValue) | |||
448 | Narrowing = true; | |||
449 | } | |||
450 | if (Narrowing) { | |||
451 | ConstantType = Initializer->getType(); | |||
452 | ConstantValue = APValue(InitializerValue); | |||
453 | return NK_Constant_Narrowing; | |||
454 | } | |||
455 | } | |||
456 | return NK_Not_Narrowing; | |||
457 | } | |||
458 | ||||
459 | default: | |||
460 | // Other kinds of conversions are not narrowings. | |||
461 | return NK_Not_Narrowing; | |||
462 | } | |||
463 | } | |||
464 | ||||
465 | /// dump - Print this standard conversion sequence to standard | |||
466 | /// error. Useful for debugging overloading issues. | |||
467 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void StandardConversionSequence::dump() const { | |||
468 | raw_ostream &OS = llvm::errs(); | |||
469 | bool PrintedSomething = false; | |||
470 | if (First != ICK_Identity) { | |||
471 | OS << GetImplicitConversionName(First); | |||
472 | PrintedSomething = true; | |||
473 | } | |||
474 | ||||
475 | if (Second != ICK_Identity) { | |||
476 | if (PrintedSomething) { | |||
477 | OS << " -> "; | |||
478 | } | |||
479 | OS << GetImplicitConversionName(Second); | |||
480 | ||||
481 | if (CopyConstructor) { | |||
482 | OS << " (by copy constructor)"; | |||
483 | } else if (DirectBinding) { | |||
484 | OS << " (direct reference binding)"; | |||
485 | } else if (ReferenceBinding) { | |||
486 | OS << " (reference binding)"; | |||
487 | } | |||
488 | PrintedSomething = true; | |||
489 | } | |||
490 | ||||
491 | if (Third != ICK_Identity) { | |||
492 | if (PrintedSomething) { | |||
493 | OS << " -> "; | |||
494 | } | |||
495 | OS << GetImplicitConversionName(Third); | |||
496 | PrintedSomething = true; | |||
497 | } | |||
498 | ||||
499 | if (!PrintedSomething) { | |||
500 | OS << "No conversions required"; | |||
501 | } | |||
502 | } | |||
503 | ||||
504 | /// dump - Print this user-defined conversion sequence to standard | |||
505 | /// error. Useful for debugging overloading issues. | |||
506 | void UserDefinedConversionSequence::dump() const { | |||
507 | raw_ostream &OS = llvm::errs(); | |||
508 | if (Before.First || Before.Second || Before.Third) { | |||
509 | Before.dump(); | |||
510 | OS << " -> "; | |||
511 | } | |||
512 | if (ConversionFunction) | |||
513 | OS << '\'' << *ConversionFunction << '\''; | |||
514 | else | |||
515 | OS << "aggregate initialization"; | |||
516 | if (After.First || After.Second || After.Third) { | |||
517 | OS << " -> "; | |||
518 | After.dump(); | |||
519 | } | |||
520 | } | |||
521 | ||||
522 | /// dump - Print this implicit conversion sequence to standard | |||
523 | /// error. Useful for debugging overloading issues. | |||
524 | void ImplicitConversionSequence::dump() const { | |||
525 | raw_ostream &OS = llvm::errs(); | |||
526 | if (isStdInitializerListElement()) | |||
527 | OS << "Worst std::initializer_list element conversion: "; | |||
528 | switch (ConversionKind) { | |||
529 | case StandardConversion: | |||
530 | OS << "Standard conversion: "; | |||
531 | Standard.dump(); | |||
532 | break; | |||
533 | case UserDefinedConversion: | |||
534 | OS << "User-defined conversion: "; | |||
535 | UserDefined.dump(); | |||
536 | break; | |||
537 | case EllipsisConversion: | |||
538 | OS << "Ellipsis conversion"; | |||
539 | break; | |||
540 | case AmbiguousConversion: | |||
541 | OS << "Ambiguous conversion"; | |||
542 | break; | |||
543 | case BadConversion: | |||
544 | OS << "Bad conversion"; | |||
545 | break; | |||
546 | } | |||
547 | ||||
548 | OS << "\n"; | |||
549 | } | |||
550 | ||||
551 | void AmbiguousConversionSequence::construct() { | |||
552 | new (&conversions()) ConversionSet(); | |||
553 | } | |||
554 | ||||
555 | void AmbiguousConversionSequence::destruct() { | |||
556 | conversions().~ConversionSet(); | |||
557 | } | |||
558 | ||||
559 | void | |||
560 | AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { | |||
561 | FromTypePtr = O.FromTypePtr; | |||
562 | ToTypePtr = O.ToTypePtr; | |||
563 | new (&conversions()) ConversionSet(O.conversions()); | |||
564 | } | |||
565 | ||||
566 | namespace { | |||
567 | // Structure used by DeductionFailureInfo to store | |||
568 | // template argument information. | |||
569 | struct DFIArguments { | |||
570 | TemplateArgument FirstArg; | |||
571 | TemplateArgument SecondArg; | |||
572 | }; | |||
573 | // Structure used by DeductionFailureInfo to store | |||
574 | // template parameter and template argument information. | |||
575 | struct DFIParamWithArguments : DFIArguments { | |||
576 | TemplateParameter Param; | |||
577 | }; | |||
578 | // Structure used by DeductionFailureInfo to store template argument | |||
579 | // information and the index of the problematic call argument. | |||
580 | struct DFIDeducedMismatchArgs : DFIArguments { | |||
581 | TemplateArgumentList *TemplateArgs; | |||
582 | unsigned CallArgIndex; | |||
583 | }; | |||
584 | } | |||
585 | ||||
586 | /// Convert from Sema's representation of template deduction information | |||
587 | /// to the form used in overload-candidate information. | |||
588 | DeductionFailureInfo | |||
589 | clang::MakeDeductionFailureInfo(ASTContext &Context, | |||
590 | Sema::TemplateDeductionResult TDK, | |||
591 | TemplateDeductionInfo &Info) { | |||
592 | DeductionFailureInfo Result; | |||
593 | Result.Result = static_cast<unsigned>(TDK); | |||
594 | Result.HasDiagnostic = false; | |||
595 | switch (TDK) { | |||
596 | case Sema::TDK_Invalid: | |||
597 | case Sema::TDK_InstantiationDepth: | |||
598 | case Sema::TDK_TooManyArguments: | |||
599 | case Sema::TDK_TooFewArguments: | |||
600 | case Sema::TDK_MiscellaneousDeductionFailure: | |||
601 | case Sema::TDK_CUDATargetMismatch: | |||
602 | Result.Data = nullptr; | |||
603 | break; | |||
604 | ||||
605 | case Sema::TDK_Incomplete: | |||
606 | case Sema::TDK_InvalidExplicitArguments: | |||
607 | Result.Data = Info.Param.getOpaqueValue(); | |||
608 | break; | |||
609 | ||||
610 | case Sema::TDK_DeducedMismatch: | |||
611 | case Sema::TDK_DeducedMismatchNested: { | |||
612 | // FIXME: Should allocate from normal heap so that we can free this later. | |||
613 | auto *Saved = new (Context) DFIDeducedMismatchArgs; | |||
614 | Saved->FirstArg = Info.FirstArg; | |||
615 | Saved->SecondArg = Info.SecondArg; | |||
616 | Saved->TemplateArgs = Info.take(); | |||
617 | Saved->CallArgIndex = Info.CallArgIndex; | |||
618 | Result.Data = Saved; | |||
619 | break; | |||
620 | } | |||
621 | ||||
622 | case Sema::TDK_NonDeducedMismatch: { | |||
623 | // FIXME: Should allocate from normal heap so that we can free this later. | |||
624 | DFIArguments *Saved = new (Context) DFIArguments; | |||
625 | Saved->FirstArg = Info.FirstArg; | |||
626 | Saved->SecondArg = Info.SecondArg; | |||
627 | Result.Data = Saved; | |||
628 | break; | |||
629 | } | |||
630 | ||||
631 | case Sema::TDK_IncompletePack: | |||
632 | // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. | |||
633 | case Sema::TDK_Inconsistent: | |||
634 | case Sema::TDK_Underqualified: { | |||
635 | // FIXME: Should allocate from normal heap so that we can free this later. | |||
636 | DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; | |||
637 | Saved->Param = Info.Param; | |||
638 | Saved->FirstArg = Info.FirstArg; | |||
639 | Saved->SecondArg = Info.SecondArg; | |||
640 | Result.Data = Saved; | |||
641 | break; | |||
642 | } | |||
643 | ||||
644 | case Sema::TDK_SubstitutionFailure: | |||
645 | Result.Data = Info.take(); | |||
646 | if (Info.hasSFINAEDiagnostic()) { | |||
647 | PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( | |||
648 | SourceLocation(), PartialDiagnostic::NullDiagnostic()); | |||
649 | Info.takeSFINAEDiagnostic(*Diag); | |||
650 | Result.HasDiagnostic = true; | |||
651 | } | |||
652 | break; | |||
653 | ||||
654 | case Sema::TDK_Success: | |||
655 | case Sema::TDK_NonDependentConversionFailure: | |||
656 | llvm_unreachable("not a deduction failure")::llvm::llvm_unreachable_internal("not a deduction failure", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 656); | |||
657 | } | |||
658 | ||||
659 | return Result; | |||
660 | } | |||
661 | ||||
662 | void DeductionFailureInfo::Destroy() { | |||
663 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { | |||
664 | case Sema::TDK_Success: | |||
665 | case Sema::TDK_Invalid: | |||
666 | case Sema::TDK_InstantiationDepth: | |||
667 | case Sema::TDK_Incomplete: | |||
668 | case Sema::TDK_TooManyArguments: | |||
669 | case Sema::TDK_TooFewArguments: | |||
670 | case Sema::TDK_InvalidExplicitArguments: | |||
671 | case Sema::TDK_CUDATargetMismatch: | |||
672 | case Sema::TDK_NonDependentConversionFailure: | |||
673 | break; | |||
674 | ||||
675 | case Sema::TDK_IncompletePack: | |||
676 | case Sema::TDK_Inconsistent: | |||
677 | case Sema::TDK_Underqualified: | |||
678 | case Sema::TDK_DeducedMismatch: | |||
679 | case Sema::TDK_DeducedMismatchNested: | |||
680 | case Sema::TDK_NonDeducedMismatch: | |||
681 | // FIXME: Destroy the data? | |||
682 | Data = nullptr; | |||
683 | break; | |||
684 | ||||
685 | case Sema::TDK_SubstitutionFailure: | |||
686 | // FIXME: Destroy the template argument list? | |||
687 | Data = nullptr; | |||
688 | if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { | |||
689 | Diag->~PartialDiagnosticAt(); | |||
690 | HasDiagnostic = false; | |||
691 | } | |||
692 | break; | |||
693 | ||||
694 | // Unhandled | |||
695 | case Sema::TDK_MiscellaneousDeductionFailure: | |||
696 | break; | |||
697 | } | |||
698 | } | |||
699 | ||||
700 | PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { | |||
701 | if (HasDiagnostic) | |||
702 | return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); | |||
703 | return nullptr; | |||
704 | } | |||
705 | ||||
706 | TemplateParameter DeductionFailureInfo::getTemplateParameter() { | |||
707 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { | |||
708 | case Sema::TDK_Success: | |||
709 | case Sema::TDK_Invalid: | |||
710 | case Sema::TDK_InstantiationDepth: | |||
711 | case Sema::TDK_TooManyArguments: | |||
712 | case Sema::TDK_TooFewArguments: | |||
713 | case Sema::TDK_SubstitutionFailure: | |||
714 | case Sema::TDK_DeducedMismatch: | |||
715 | case Sema::TDK_DeducedMismatchNested: | |||
716 | case Sema::TDK_NonDeducedMismatch: | |||
717 | case Sema::TDK_CUDATargetMismatch: | |||
718 | case Sema::TDK_NonDependentConversionFailure: | |||
719 | return TemplateParameter(); | |||
720 | ||||
721 | case Sema::TDK_Incomplete: | |||
722 | case Sema::TDK_InvalidExplicitArguments: | |||
723 | return TemplateParameter::getFromOpaqueValue(Data); | |||
724 | ||||
725 | case Sema::TDK_IncompletePack: | |||
726 | case Sema::TDK_Inconsistent: | |||
727 | case Sema::TDK_Underqualified: | |||
728 | return static_cast<DFIParamWithArguments*>(Data)->Param; | |||
729 | ||||
730 | // Unhandled | |||
731 | case Sema::TDK_MiscellaneousDeductionFailure: | |||
732 | break; | |||
733 | } | |||
734 | ||||
735 | return TemplateParameter(); | |||
736 | } | |||
737 | ||||
738 | TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { | |||
739 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { | |||
740 | case Sema::TDK_Success: | |||
741 | case Sema::TDK_Invalid: | |||
742 | case Sema::TDK_InstantiationDepth: | |||
743 | case Sema::TDK_TooManyArguments: | |||
744 | case Sema::TDK_TooFewArguments: | |||
745 | case Sema::TDK_Incomplete: | |||
746 | case Sema::TDK_IncompletePack: | |||
747 | case Sema::TDK_InvalidExplicitArguments: | |||
748 | case Sema::TDK_Inconsistent: | |||
749 | case Sema::TDK_Underqualified: | |||
750 | case Sema::TDK_NonDeducedMismatch: | |||
751 | case Sema::TDK_CUDATargetMismatch: | |||
752 | case Sema::TDK_NonDependentConversionFailure: | |||
753 | return nullptr; | |||
754 | ||||
755 | case Sema::TDK_DeducedMismatch: | |||
756 | case Sema::TDK_DeducedMismatchNested: | |||
757 | return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; | |||
758 | ||||
759 | case Sema::TDK_SubstitutionFailure: | |||
760 | return static_cast<TemplateArgumentList*>(Data); | |||
761 | ||||
762 | // Unhandled | |||
763 | case Sema::TDK_MiscellaneousDeductionFailure: | |||
764 | break; | |||
765 | } | |||
766 | ||||
767 | return nullptr; | |||
768 | } | |||
769 | ||||
770 | const TemplateArgument *DeductionFailureInfo::getFirstArg() { | |||
771 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { | |||
772 | case Sema::TDK_Success: | |||
773 | case Sema::TDK_Invalid: | |||
774 | case Sema::TDK_InstantiationDepth: | |||
775 | case Sema::TDK_Incomplete: | |||
776 | case Sema::TDK_TooManyArguments: | |||
777 | case Sema::TDK_TooFewArguments: | |||
778 | case Sema::TDK_InvalidExplicitArguments: | |||
779 | case Sema::TDK_SubstitutionFailure: | |||
780 | case Sema::TDK_CUDATargetMismatch: | |||
781 | case Sema::TDK_NonDependentConversionFailure: | |||
782 | return nullptr; | |||
783 | ||||
784 | case Sema::TDK_IncompletePack: | |||
785 | case Sema::TDK_Inconsistent: | |||
786 | case Sema::TDK_Underqualified: | |||
787 | case Sema::TDK_DeducedMismatch: | |||
788 | case Sema::TDK_DeducedMismatchNested: | |||
789 | case Sema::TDK_NonDeducedMismatch: | |||
790 | return &static_cast<DFIArguments*>(Data)->FirstArg; | |||
791 | ||||
792 | // Unhandled | |||
793 | case Sema::TDK_MiscellaneousDeductionFailure: | |||
794 | break; | |||
795 | } | |||
796 | ||||
797 | return nullptr; | |||
798 | } | |||
799 | ||||
800 | const TemplateArgument *DeductionFailureInfo::getSecondArg() { | |||
801 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { | |||
802 | case Sema::TDK_Success: | |||
803 | case Sema::TDK_Invalid: | |||
804 | case Sema::TDK_InstantiationDepth: | |||
805 | case Sema::TDK_Incomplete: | |||
806 | case Sema::TDK_IncompletePack: | |||
807 | case Sema::TDK_TooManyArguments: | |||
808 | case Sema::TDK_TooFewArguments: | |||
809 | case Sema::TDK_InvalidExplicitArguments: | |||
810 | case Sema::TDK_SubstitutionFailure: | |||
811 | case Sema::TDK_CUDATargetMismatch: | |||
812 | case Sema::TDK_NonDependentConversionFailure: | |||
813 | return nullptr; | |||
814 | ||||
815 | case Sema::TDK_Inconsistent: | |||
816 | case Sema::TDK_Underqualified: | |||
817 | case Sema::TDK_DeducedMismatch: | |||
818 | case Sema::TDK_DeducedMismatchNested: | |||
819 | case Sema::TDK_NonDeducedMismatch: | |||
820 | return &static_cast<DFIArguments*>(Data)->SecondArg; | |||
821 | ||||
822 | // Unhandled | |||
823 | case Sema::TDK_MiscellaneousDeductionFailure: | |||
824 | break; | |||
825 | } | |||
826 | ||||
827 | return nullptr; | |||
828 | } | |||
829 | ||||
830 | llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { | |||
831 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { | |||
832 | case Sema::TDK_DeducedMismatch: | |||
833 | case Sema::TDK_DeducedMismatchNested: | |||
834 | return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; | |||
835 | ||||
836 | default: | |||
837 | return llvm::None; | |||
838 | } | |||
839 | } | |||
840 | ||||
841 | void OverloadCandidateSet::destroyCandidates() { | |||
842 | for (iterator i = begin(), e = end(); i != e; ++i) { | |||
843 | for (auto &C : i->Conversions) | |||
844 | C.~ImplicitConversionSequence(); | |||
845 | if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) | |||
846 | i->DeductionFailure.Destroy(); | |||
847 | } | |||
848 | } | |||
849 | ||||
850 | void OverloadCandidateSet::clear(CandidateSetKind CSK) { | |||
851 | destroyCandidates(); | |||
852 | SlabAllocator.Reset(); | |||
853 | NumInlineBytesUsed = 0; | |||
854 | Candidates.clear(); | |||
855 | Functions.clear(); | |||
856 | Kind = CSK; | |||
857 | } | |||
858 | ||||
859 | namespace { | |||
860 | class UnbridgedCastsSet { | |||
861 | struct Entry { | |||
862 | Expr **Addr; | |||
863 | Expr *Saved; | |||
864 | }; | |||
865 | SmallVector<Entry, 2> Entries; | |||
866 | ||||
867 | public: | |||
868 | void save(Sema &S, Expr *&E) { | |||
869 | assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast))((E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)) ? static_cast <void> (0) : __assert_fail ("E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 869, __PRETTY_FUNCTION__)); | |||
870 | Entry entry = { &E, E }; | |||
871 | Entries.push_back(entry); | |||
872 | E = S.stripARCUnbridgedCast(E); | |||
873 | } | |||
874 | ||||
875 | void restore() { | |||
876 | for (SmallVectorImpl<Entry>::iterator | |||
877 | i = Entries.begin(), e = Entries.end(); i != e; ++i) | |||
878 | *i->Addr = i->Saved; | |||
879 | } | |||
880 | }; | |||
881 | } | |||
882 | ||||
883 | /// checkPlaceholderForOverload - Do any interesting placeholder-like | |||
884 | /// preprocessing on the given expression. | |||
885 | /// | |||
886 | /// \param unbridgedCasts a collection to which to add unbridged casts; | |||
887 | /// without this, they will be immediately diagnosed as errors | |||
888 | /// | |||
889 | /// Return true on unrecoverable error. | |||
890 | static bool | |||
891 | checkPlaceholderForOverload(Sema &S, Expr *&E, | |||
892 | UnbridgedCastsSet *unbridgedCasts = nullptr) { | |||
893 | if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { | |||
894 | // We can't handle overloaded expressions here because overload | |||
895 | // resolution might reasonably tweak them. | |||
896 | if (placeholder->getKind() == BuiltinType::Overload) return false; | |||
897 | ||||
898 | // If the context potentially accepts unbridged ARC casts, strip | |||
899 | // the unbridged cast and add it to the collection for later restoration. | |||
900 | if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && | |||
901 | unbridgedCasts) { | |||
902 | unbridgedCasts->save(S, E); | |||
903 | return false; | |||
904 | } | |||
905 | ||||
906 | // Go ahead and check everything else. | |||
907 | ExprResult result = S.CheckPlaceholderExpr(E); | |||
908 | if (result.isInvalid()) | |||
909 | return true; | |||
910 | ||||
911 | E = result.get(); | |||
912 | return false; | |||
913 | } | |||
914 | ||||
915 | // Nothing to do. | |||
916 | return false; | |||
917 | } | |||
918 | ||||
919 | /// checkArgPlaceholdersForOverload - Check a set of call operands for | |||
920 | /// placeholders. | |||
921 | static bool checkArgPlaceholdersForOverload(Sema &S, | |||
922 | MultiExprArg Args, | |||
923 | UnbridgedCastsSet &unbridged) { | |||
924 | for (unsigned i = 0, e = Args.size(); i != e; ++i) | |||
925 | if (checkPlaceholderForOverload(S, Args[i], &unbridged)) | |||
926 | return true; | |||
927 | ||||
928 | return false; | |||
929 | } | |||
930 | ||||
931 | /// Determine whether the given New declaration is an overload of the | |||
932 | /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if | |||
933 | /// New and Old cannot be overloaded, e.g., if New has the same signature as | |||
934 | /// some function in Old (C++ 1.3.10) or if the Old declarations aren't | |||
935 | /// functions (or function templates) at all. When it does return Ovl_Match or | |||
936 | /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be | |||
937 | /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying | |||
938 | /// declaration. | |||
939 | /// | |||
940 | /// Example: Given the following input: | |||
941 | /// | |||
942 | /// void f(int, float); // #1 | |||
943 | /// void f(int, int); // #2 | |||
944 | /// int f(int, int); // #3 | |||
945 | /// | |||
946 | /// When we process #1, there is no previous declaration of "f", so IsOverload | |||
947 | /// will not be used. | |||
948 | /// | |||
949 | /// When we process #2, Old contains only the FunctionDecl for #1. By comparing | |||
950 | /// the parameter types, we see that #1 and #2 are overloaded (since they have | |||
951 | /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is | |||
952 | /// unchanged. | |||
953 | /// | |||
954 | /// When we process #3, Old is an overload set containing #1 and #2. We compare | |||
955 | /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then | |||
956 | /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of | |||
957 | /// functions are not part of the signature), IsOverload returns Ovl_Match and | |||
958 | /// MatchedDecl will be set to point to the FunctionDecl for #2. | |||
959 | /// | |||
960 | /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class | |||
961 | /// by a using declaration. The rules for whether to hide shadow declarations | |||
962 | /// ignore some properties which otherwise figure into a function template's | |||
963 | /// signature. | |||
964 | Sema::OverloadKind | |||
965 | Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, | |||
966 | NamedDecl *&Match, bool NewIsUsingDecl) { | |||
967 | for (LookupResult::iterator I = Old.begin(), E = Old.end(); | |||
968 | I != E; ++I) { | |||
969 | NamedDecl *OldD = *I; | |||
970 | ||||
971 | bool OldIsUsingDecl = false; | |||
972 | if (isa<UsingShadowDecl>(OldD)) { | |||
973 | OldIsUsingDecl = true; | |||
974 | ||||
975 | // We can always introduce two using declarations into the same | |||
976 | // context, even if they have identical signatures. | |||
977 | if (NewIsUsingDecl) continue; | |||
978 | ||||
979 | OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); | |||
980 | } | |||
981 | ||||
982 | // A using-declaration does not conflict with another declaration | |||
983 | // if one of them is hidden. | |||
984 | if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) | |||
985 | continue; | |||
986 | ||||
987 | // If either declaration was introduced by a using declaration, | |||
988 | // we'll need to use slightly different rules for matching. | |||
989 | // Essentially, these rules are the normal rules, except that | |||
990 | // function templates hide function templates with different | |||
991 | // return types or template parameter lists. | |||
992 | bool UseMemberUsingDeclRules = | |||
993 | (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && | |||
994 | !New->getFriendObjectKind(); | |||
995 | ||||
996 | if (FunctionDecl *OldF = OldD->getAsFunction()) { | |||
997 | if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { | |||
998 | if (UseMemberUsingDeclRules && OldIsUsingDecl) { | |||
999 | HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); | |||
1000 | continue; | |||
1001 | } | |||
1002 | ||||
1003 | if (!isa<FunctionTemplateDecl>(OldD) && | |||
1004 | !shouldLinkPossiblyHiddenDecl(*I, New)) | |||
1005 | continue; | |||
1006 | ||||
1007 | Match = *I; | |||
1008 | return Ovl_Match; | |||
1009 | } | |||
1010 | ||||
1011 | // Builtins that have custom typechecking or have a reference should | |||
1012 | // not be overloadable or redeclarable. | |||
1013 | if (!getASTContext().canBuiltinBeRedeclared(OldF)) { | |||
1014 | Match = *I; | |||
1015 | return Ovl_NonFunction; | |||
1016 | } | |||
1017 | } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { | |||
1018 | // We can overload with these, which can show up when doing | |||
1019 | // redeclaration checks for UsingDecls. | |||
1020 | assert(Old.getLookupKind() == LookupUsingDeclName)((Old.getLookupKind() == LookupUsingDeclName) ? static_cast< void> (0) : __assert_fail ("Old.getLookupKind() == LookupUsingDeclName" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 1020, __PRETTY_FUNCTION__)); | |||
1021 | } else if (isa<TagDecl>(OldD)) { | |||
1022 | // We can always overload with tags by hiding them. | |||
1023 | } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { | |||
1024 | // Optimistically assume that an unresolved using decl will | |||
1025 | // overload; if it doesn't, we'll have to diagnose during | |||
1026 | // template instantiation. | |||
1027 | // | |||
1028 | // Exception: if the scope is dependent and this is not a class | |||
1029 | // member, the using declaration can only introduce an enumerator. | |||
1030 | if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { | |||
1031 | Match = *I; | |||
1032 | return Ovl_NonFunction; | |||
1033 | } | |||
1034 | } else { | |||
1035 | // (C++ 13p1): | |||
1036 | // Only function declarations can be overloaded; object and type | |||
1037 | // declarations cannot be overloaded. | |||
1038 | Match = *I; | |||
1039 | return Ovl_NonFunction; | |||
1040 | } | |||
1041 | } | |||
1042 | ||||
1043 | // C++ [temp.friend]p1: | |||
1044 | // For a friend function declaration that is not a template declaration: | |||
1045 | // -- if the name of the friend is a qualified or unqualified template-id, | |||
1046 | // [...], otherwise | |||
1047 | // -- if the name of the friend is a qualified-id and a matching | |||
1048 | // non-template function is found in the specified class or namespace, | |||
1049 | // the friend declaration refers to that function, otherwise, | |||
1050 | // -- if the name of the friend is a qualified-id and a matching function | |||
1051 | // template is found in the specified class or namespace, the friend | |||
1052 | // declaration refers to the deduced specialization of that function | |||
1053 | // template, otherwise | |||
1054 | // -- the name shall be an unqualified-id [...] | |||
1055 | // If we get here for a qualified friend declaration, we've just reached the | |||
1056 | // third bullet. If the type of the friend is dependent, skip this lookup | |||
1057 | // until instantiation. | |||
1058 | if (New->getFriendObjectKind() && New->getQualifier() && | |||
1059 | !New->getDescribedFunctionTemplate() && | |||
1060 | !New->getDependentSpecializationInfo() && | |||
1061 | !New->getType()->isDependentType()) { | |||
1062 | LookupResult TemplateSpecResult(LookupResult::Temporary, Old); | |||
1063 | TemplateSpecResult.addAllDecls(Old); | |||
1064 | if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, | |||
1065 | /*QualifiedFriend*/true)) { | |||
1066 | New->setInvalidDecl(); | |||
1067 | return Ovl_Overload; | |||
1068 | } | |||
1069 | ||||
1070 | Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); | |||
1071 | return Ovl_Match; | |||
1072 | } | |||
1073 | ||||
1074 | return Ovl_Overload; | |||
1075 | } | |||
1076 | ||||
1077 | bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, | |||
1078 | bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { | |||
1079 | // C++ [basic.start.main]p2: This function shall not be overloaded. | |||
1080 | if (New->isMain()) | |||
1081 | return false; | |||
1082 | ||||
1083 | // MSVCRT user defined entry points cannot be overloaded. | |||
1084 | if (New->isMSVCRTEntryPoint()) | |||
1085 | return false; | |||
1086 | ||||
1087 | FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); | |||
1088 | FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); | |||
1089 | ||||
1090 | // C++ [temp.fct]p2: | |||
1091 | // A function template can be overloaded with other function templates | |||
1092 | // and with normal (non-template) functions. | |||
1093 | if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) | |||
1094 | return true; | |||
1095 | ||||
1096 | // Is the function New an overload of the function Old? | |||
1097 | QualType OldQType = Context.getCanonicalType(Old->getType()); | |||
1098 | QualType NewQType = Context.getCanonicalType(New->getType()); | |||
1099 | ||||
1100 | // Compare the signatures (C++ 1.3.10) of the two functions to | |||
1101 | // determine whether they are overloads. If we find any mismatch | |||
1102 | // in the signature, they are overloads. | |||
1103 | ||||
1104 | // If either of these functions is a K&R-style function (no | |||
1105 | // prototype), then we consider them to have matching signatures. | |||
1106 | if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || | |||
1107 | isa<FunctionNoProtoType>(NewQType.getTypePtr())) | |||
1108 | return false; | |||
1109 | ||||
1110 | const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); | |||
1111 | const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); | |||
1112 | ||||
1113 | // The signature of a function includes the types of its | |||
1114 | // parameters (C++ 1.3.10), which includes the presence or absence | |||
1115 | // of the ellipsis; see C++ DR 357). | |||
1116 | if (OldQType != NewQType && | |||
1117 | (OldType->getNumParams() != NewType->getNumParams() || | |||
1118 | OldType->isVariadic() != NewType->isVariadic() || | |||
1119 | !FunctionParamTypesAreEqual(OldType, NewType))) | |||
1120 | return true; | |||
1121 | ||||
1122 | // C++ [temp.over.link]p4: | |||
1123 | // The signature of a function template consists of its function | |||
1124 | // signature, its return type and its template parameter list. The names | |||
1125 | // of the template parameters are significant only for establishing the | |||
1126 | // relationship between the template parameters and the rest of the | |||
1127 | // signature. | |||
1128 | // | |||
1129 | // We check the return type and template parameter lists for function | |||
1130 | // templates first; the remaining checks follow. | |||
1131 | // | |||
1132 | // However, we don't consider either of these when deciding whether | |||
1133 | // a member introduced by a shadow declaration is hidden. | |||
1134 | if (!UseMemberUsingDeclRules && NewTemplate && | |||
1135 | (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), | |||
1136 | OldTemplate->getTemplateParameters(), | |||
1137 | false, TPL_TemplateMatch) || | |||
1138 | !Context.hasSameType(Old->getDeclaredReturnType(), | |||
1139 | New->getDeclaredReturnType()))) | |||
1140 | return true; | |||
1141 | ||||
1142 | // If the function is a class member, its signature includes the | |||
1143 | // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. | |||
1144 | // | |||
1145 | // As part of this, also check whether one of the member functions | |||
1146 | // is static, in which case they are not overloads (C++ | |||
1147 | // 13.1p2). While not part of the definition of the signature, | |||
1148 | // this check is important to determine whether these functions | |||
1149 | // can be overloaded. | |||
1150 | CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); | |||
1151 | CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); | |||
1152 | if (OldMethod && NewMethod && | |||
1153 | !OldMethod->isStatic() && !NewMethod->isStatic()) { | |||
1154 | if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { | |||
1155 | if (!UseMemberUsingDeclRules && | |||
1156 | (OldMethod->getRefQualifier() == RQ_None || | |||
1157 | NewMethod->getRefQualifier() == RQ_None)) { | |||
1158 | // C++0x [over.load]p2: | |||
1159 | // - Member function declarations with the same name and the same | |||
1160 | // parameter-type-list as well as member function template | |||
1161 | // declarations with the same name, the same parameter-type-list, and | |||
1162 | // the same template parameter lists cannot be overloaded if any of | |||
1163 | // them, but not all, have a ref-qualifier (8.3.5). | |||
1164 | Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) | |||
1165 | << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); | |||
1166 | Diag(OldMethod->getLocation(), diag::note_previous_declaration); | |||
1167 | } | |||
1168 | return true; | |||
1169 | } | |||
1170 | ||||
1171 | // We may not have applied the implicit const for a constexpr member | |||
1172 | // function yet (because we haven't yet resolved whether this is a static | |||
1173 | // or non-static member function). Add it now, on the assumption that this | |||
1174 | // is a redeclaration of OldMethod. | |||
1175 | auto OldQuals = OldMethod->getMethodQualifiers(); | |||
1176 | auto NewQuals = NewMethod->getMethodQualifiers(); | |||
1177 | if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && | |||
1178 | !isa<CXXConstructorDecl>(NewMethod)) | |||
1179 | NewQuals.addConst(); | |||
1180 | // We do not allow overloading based off of '__restrict'. | |||
1181 | OldQuals.removeRestrict(); | |||
1182 | NewQuals.removeRestrict(); | |||
1183 | if (OldQuals != NewQuals) | |||
1184 | return true; | |||
1185 | } | |||
1186 | ||||
1187 | // Though pass_object_size is placed on parameters and takes an argument, we | |||
1188 | // consider it to be a function-level modifier for the sake of function | |||
1189 | // identity. Either the function has one or more parameters with | |||
1190 | // pass_object_size or it doesn't. | |||
1191 | if (functionHasPassObjectSizeParams(New) != | |||
1192 | functionHasPassObjectSizeParams(Old)) | |||
1193 | return true; | |||
1194 | ||||
1195 | // enable_if attributes are an order-sensitive part of the signature. | |||
1196 | for (specific_attr_iterator<EnableIfAttr> | |||
1197 | NewI = New->specific_attr_begin<EnableIfAttr>(), | |||
1198 | NewE = New->specific_attr_end<EnableIfAttr>(), | |||
1199 | OldI = Old->specific_attr_begin<EnableIfAttr>(), | |||
1200 | OldE = Old->specific_attr_end<EnableIfAttr>(); | |||
1201 | NewI != NewE || OldI != OldE; ++NewI, ++OldI) { | |||
1202 | if (NewI == NewE || OldI == OldE) | |||
1203 | return true; | |||
1204 | llvm::FoldingSetNodeID NewID, OldID; | |||
1205 | NewI->getCond()->Profile(NewID, Context, true); | |||
1206 | OldI->getCond()->Profile(OldID, Context, true); | |||
1207 | if (NewID != OldID) | |||
1208 | return true; | |||
1209 | } | |||
1210 | ||||
1211 | if (getLangOpts().CUDA && ConsiderCudaAttrs) { | |||
1212 | // Don't allow overloading of destructors. (In theory we could, but it | |||
1213 | // would be a giant change to clang.) | |||
1214 | if (isa<CXXDestructorDecl>(New)) | |||
1215 | return false; | |||
1216 | ||||
1217 | CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), | |||
1218 | OldTarget = IdentifyCUDATarget(Old); | |||
1219 | if (NewTarget == CFT_InvalidTarget) | |||
1220 | return false; | |||
1221 | ||||
1222 | assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.")(((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target." ) ? static_cast<void> (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 1222, __PRETTY_FUNCTION__)); | |||
1223 | ||||
1224 | // Allow overloading of functions with same signature and different CUDA | |||
1225 | // target attributes. | |||
1226 | return NewTarget != OldTarget; | |||
1227 | } | |||
1228 | ||||
1229 | // The signatures match; this is not an overload. | |||
1230 | return false; | |||
1231 | } | |||
1232 | ||||
1233 | /// Tries a user-defined conversion from From to ToType. | |||
1234 | /// | |||
1235 | /// Produces an implicit conversion sequence for when a standard conversion | |||
1236 | /// is not an option. See TryImplicitConversion for more information. | |||
1237 | static ImplicitConversionSequence | |||
1238 | TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, | |||
1239 | bool SuppressUserConversions, | |||
1240 | bool AllowExplicit, | |||
1241 | bool InOverloadResolution, | |||
1242 | bool CStyle, | |||
1243 | bool AllowObjCWritebackConversion, | |||
1244 | bool AllowObjCConversionOnExplicit) { | |||
1245 | ImplicitConversionSequence ICS; | |||
1246 | ||||
1247 | if (SuppressUserConversions) { | |||
1248 | // We're not in the case above, so there is no conversion that | |||
1249 | // we can perform. | |||
1250 | ICS.setBad(BadConversionSequence::no_conversion, From, ToType); | |||
1251 | return ICS; | |||
1252 | } | |||
1253 | ||||
1254 | // Attempt user-defined conversion. | |||
1255 | OverloadCandidateSet Conversions(From->getExprLoc(), | |||
1256 | OverloadCandidateSet::CSK_Normal); | |||
1257 | switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, | |||
1258 | Conversions, AllowExplicit, | |||
1259 | AllowObjCConversionOnExplicit)) { | |||
1260 | case OR_Success: | |||
1261 | case OR_Deleted: | |||
1262 | ICS.setUserDefined(); | |||
1263 | // C++ [over.ics.user]p4: | |||
1264 | // A conversion of an expression of class type to the same class | |||
1265 | // type is given Exact Match rank, and a conversion of an | |||
1266 | // expression of class type to a base class of that type is | |||
1267 | // given Conversion rank, in spite of the fact that a copy | |||
1268 | // constructor (i.e., a user-defined conversion function) is | |||
1269 | // called for those cases. | |||
1270 | if (CXXConstructorDecl *Constructor | |||
1271 | = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { | |||
1272 | QualType FromCanon | |||
1273 | = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); | |||
1274 | QualType ToCanon | |||
1275 | = S.Context.getCanonicalType(ToType).getUnqualifiedType(); | |||
1276 | if (Constructor->isCopyConstructor() && | |||
1277 | (FromCanon == ToCanon || | |||
1278 | S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { | |||
1279 | // Turn this into a "standard" conversion sequence, so that it | |||
1280 | // gets ranked with standard conversion sequences. | |||
1281 | DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; | |||
1282 | ICS.setStandard(); | |||
1283 | ICS.Standard.setAsIdentityConversion(); | |||
1284 | ICS.Standard.setFromType(From->getType()); | |||
1285 | ICS.Standard.setAllToTypes(ToType); | |||
1286 | ICS.Standard.CopyConstructor = Constructor; | |||
1287 | ICS.Standard.FoundCopyConstructor = Found; | |||
1288 | if (ToCanon != FromCanon) | |||
1289 | ICS.Standard.Second = ICK_Derived_To_Base; | |||
1290 | } | |||
1291 | } | |||
1292 | break; | |||
1293 | ||||
1294 | case OR_Ambiguous: | |||
1295 | ICS.setAmbiguous(); | |||
1296 | ICS.Ambiguous.setFromType(From->getType()); | |||
1297 | ICS.Ambiguous.setToType(ToType); | |||
1298 | for (OverloadCandidateSet::iterator Cand = Conversions.begin(); | |||
1299 | Cand != Conversions.end(); ++Cand) | |||
1300 | if (Cand->Viable) | |||
1301 | ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); | |||
1302 | break; | |||
1303 | ||||
1304 | // Fall through. | |||
1305 | case OR_No_Viable_Function: | |||
1306 | ICS.setBad(BadConversionSequence::no_conversion, From, ToType); | |||
1307 | break; | |||
1308 | } | |||
1309 | ||||
1310 | return ICS; | |||
1311 | } | |||
1312 | ||||
1313 | /// TryImplicitConversion - Attempt to perform an implicit conversion | |||
1314 | /// from the given expression (Expr) to the given type (ToType). This | |||
1315 | /// function returns an implicit conversion sequence that can be used | |||
1316 | /// to perform the initialization. Given | |||
1317 | /// | |||
1318 | /// void f(float f); | |||
1319 | /// void g(int i) { f(i); } | |||
1320 | /// | |||
1321 | /// this routine would produce an implicit conversion sequence to | |||
1322 | /// describe the initialization of f from i, which will be a standard | |||
1323 | /// conversion sequence containing an lvalue-to-rvalue conversion (C++ | |||
1324 | /// 4.1) followed by a floating-integral conversion (C++ 4.9). | |||
1325 | // | |||
1326 | /// Note that this routine only determines how the conversion can be | |||
1327 | /// performed; it does not actually perform the conversion. As such, | |||
1328 | /// it will not produce any diagnostics if no conversion is available, | |||
1329 | /// but will instead return an implicit conversion sequence of kind | |||
1330 | /// "BadConversion". | |||
1331 | /// | |||
1332 | /// If @p SuppressUserConversions, then user-defined conversions are | |||
1333 | /// not permitted. | |||
1334 | /// If @p AllowExplicit, then explicit user-defined conversions are | |||
1335 | /// permitted. | |||
1336 | /// | |||
1337 | /// \param AllowObjCWritebackConversion Whether we allow the Objective-C | |||
1338 | /// writeback conversion, which allows __autoreleasing id* parameters to | |||
1339 | /// be initialized with __strong id* or __weak id* arguments. | |||
1340 | static ImplicitConversionSequence | |||
1341 | TryImplicitConversion(Sema &S, Expr *From, QualType ToType, | |||
1342 | bool SuppressUserConversions, | |||
1343 | bool AllowExplicit, | |||
1344 | bool InOverloadResolution, | |||
1345 | bool CStyle, | |||
1346 | bool AllowObjCWritebackConversion, | |||
1347 | bool AllowObjCConversionOnExplicit) { | |||
1348 | ImplicitConversionSequence ICS; | |||
1349 | if (IsStandardConversion(S, From, ToType, InOverloadResolution, | |||
1350 | ICS.Standard, CStyle, AllowObjCWritebackConversion)){ | |||
1351 | ICS.setStandard(); | |||
1352 | return ICS; | |||
1353 | } | |||
1354 | ||||
1355 | if (!S.getLangOpts().CPlusPlus) { | |||
1356 | ICS.setBad(BadConversionSequence::no_conversion, From, ToType); | |||
1357 | return ICS; | |||
1358 | } | |||
1359 | ||||
1360 | // C++ [over.ics.user]p4: | |||
1361 | // A conversion of an expression of class type to the same class | |||
1362 | // type is given Exact Match rank, and a conversion of an | |||
1363 | // expression of class type to a base class of that type is | |||
1364 | // given Conversion rank, in spite of the fact that a copy/move | |||
1365 | // constructor (i.e., a user-defined conversion function) is | |||
1366 | // called for those cases. | |||
1367 | QualType FromType = From->getType(); | |||
1368 | if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && | |||
1369 | (S.Context.hasSameUnqualifiedType(FromType, ToType) || | |||
1370 | S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { | |||
1371 | ICS.setStandard(); | |||
1372 | ICS.Standard.setAsIdentityConversion(); | |||
1373 | ICS.Standard.setFromType(FromType); | |||
1374 | ICS.Standard.setAllToTypes(ToType); | |||
1375 | ||||
1376 | // We don't actually check at this point whether there is a valid | |||
1377 | // copy/move constructor, since overloading just assumes that it | |||
1378 | // exists. When we actually perform initialization, we'll find the | |||
1379 | // appropriate constructor to copy the returned object, if needed. | |||
1380 | ICS.Standard.CopyConstructor = nullptr; | |||
1381 | ||||
1382 | // Determine whether this is considered a derived-to-base conversion. | |||
1383 | if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) | |||
1384 | ICS.Standard.Second = ICK_Derived_To_Base; | |||
1385 | ||||
1386 | return ICS; | |||
1387 | } | |||
1388 | ||||
1389 | return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, | |||
1390 | AllowExplicit, InOverloadResolution, CStyle, | |||
1391 | AllowObjCWritebackConversion, | |||
1392 | AllowObjCConversionOnExplicit); | |||
1393 | } | |||
1394 | ||||
1395 | ImplicitConversionSequence | |||
1396 | Sema::TryImplicitConversion(Expr *From, QualType ToType, | |||
1397 | bool SuppressUserConversions, | |||
1398 | bool AllowExplicit, | |||
1399 | bool InOverloadResolution, | |||
1400 | bool CStyle, | |||
1401 | bool AllowObjCWritebackConversion) { | |||
1402 | return ::TryImplicitConversion(*this, From, ToType, | |||
1403 | SuppressUserConversions, AllowExplicit, | |||
1404 | InOverloadResolution, CStyle, | |||
1405 | AllowObjCWritebackConversion, | |||
1406 | /*AllowObjCConversionOnExplicit=*/false); | |||
1407 | } | |||
1408 | ||||
1409 | /// PerformImplicitConversion - Perform an implicit conversion of the | |||
1410 | /// expression From to the type ToType. Returns the | |||
1411 | /// converted expression. Flavor is the kind of conversion we're | |||
1412 | /// performing, used in the error message. If @p AllowExplicit, | |||
1413 | /// explicit user-defined conversions are permitted. | |||
1414 | ExprResult | |||
1415 | Sema::PerformImplicitConversion(Expr *From, QualType ToType, | |||
1416 | AssignmentAction Action, bool AllowExplicit) { | |||
1417 | ImplicitConversionSequence ICS; | |||
1418 | return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); | |||
1419 | } | |||
1420 | ||||
1421 | ExprResult | |||
1422 | Sema::PerformImplicitConversion(Expr *From, QualType ToType, | |||
1423 | AssignmentAction Action, bool AllowExplicit, | |||
1424 | ImplicitConversionSequence& ICS) { | |||
1425 | if (checkPlaceholderForOverload(*this, From)) | |||
1426 | return ExprError(); | |||
1427 | ||||
1428 | // Objective-C ARC: Determine whether we will allow the writeback conversion. | |||
1429 | bool AllowObjCWritebackConversion | |||
1430 | = getLangOpts().ObjCAutoRefCount && | |||
1431 | (Action == AA_Passing || Action == AA_Sending); | |||
1432 | if (getLangOpts().ObjC) | |||
1433 | CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, | |||
1434 | From->getType(), From); | |||
1435 | ICS = ::TryImplicitConversion(*this, From, ToType, | |||
1436 | /*SuppressUserConversions=*/false, | |||
1437 | AllowExplicit, | |||
1438 | /*InOverloadResolution=*/false, | |||
1439 | /*CStyle=*/false, | |||
1440 | AllowObjCWritebackConversion, | |||
1441 | /*AllowObjCConversionOnExplicit=*/false); | |||
1442 | return PerformImplicitConversion(From, ToType, ICS, Action); | |||
1443 | } | |||
1444 | ||||
1445 | /// Determine whether the conversion from FromType to ToType is a valid | |||
1446 | /// conversion that strips "noexcept" or "noreturn" off the nested function | |||
1447 | /// type. | |||
1448 | bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, | |||
1449 | QualType &ResultTy) { | |||
1450 | if (Context.hasSameUnqualifiedType(FromType, ToType)) | |||
1451 | return false; | |||
1452 | ||||
1453 | // Permit the conversion F(t __attribute__((noreturn))) -> F(t) | |||
1454 | // or F(t noexcept) -> F(t) | |||
1455 | // where F adds one of the following at most once: | |||
1456 | // - a pointer | |||
1457 | // - a member pointer | |||
1458 | // - a block pointer | |||
1459 | // Changes here need matching changes in FindCompositePointerType. | |||
1460 | CanQualType CanTo = Context.getCanonicalType(ToType); | |||
1461 | CanQualType CanFrom = Context.getCanonicalType(FromType); | |||
1462 | Type::TypeClass TyClass = CanTo->getTypeClass(); | |||
1463 | if (TyClass != CanFrom->getTypeClass()) return false; | |||
1464 | if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { | |||
1465 | if (TyClass == Type::Pointer) { | |||
1466 | CanTo = CanTo.getAs<PointerType>()->getPointeeType(); | |||
1467 | CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); | |||
1468 | } else if (TyClass == Type::BlockPointer) { | |||
1469 | CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); | |||
1470 | CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); | |||
1471 | } else if (TyClass == Type::MemberPointer) { | |||
1472 | auto ToMPT = CanTo.getAs<MemberPointerType>(); | |||
1473 | auto FromMPT = CanFrom.getAs<MemberPointerType>(); | |||
1474 | // A function pointer conversion cannot change the class of the function. | |||
1475 | if (ToMPT->getClass() != FromMPT->getClass()) | |||
1476 | return false; | |||
1477 | CanTo = ToMPT->getPointeeType(); | |||
1478 | CanFrom = FromMPT->getPointeeType(); | |||
1479 | } else { | |||
1480 | return false; | |||
1481 | } | |||
1482 | ||||
1483 | TyClass = CanTo->getTypeClass(); | |||
1484 | if (TyClass != CanFrom->getTypeClass()) return false; | |||
1485 | if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) | |||
1486 | return false; | |||
1487 | } | |||
1488 | ||||
1489 | const auto *FromFn = cast<FunctionType>(CanFrom); | |||
1490 | FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); | |||
1491 | ||||
1492 | const auto *ToFn = cast<FunctionType>(CanTo); | |||
1493 | FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); | |||
1494 | ||||
1495 | bool Changed = false; | |||
1496 | ||||
1497 | // Drop 'noreturn' if not present in target type. | |||
1498 | if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { | |||
1499 | FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); | |||
1500 | Changed = true; | |||
1501 | } | |||
1502 | ||||
1503 | // Drop 'noexcept' if not present in target type. | |||
1504 | if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { | |||
1505 | const auto *ToFPT = cast<FunctionProtoType>(ToFn); | |||
1506 | if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { | |||
1507 | FromFn = cast<FunctionType>( | |||
1508 | Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), | |||
1509 | EST_None) | |||
1510 | .getTypePtr()); | |||
1511 | Changed = true; | |||
1512 | } | |||
1513 | ||||
1514 | // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid | |||
1515 | // only if the ExtParameterInfo lists of the two function prototypes can be | |||
1516 | // merged and the merged list is identical to ToFPT's ExtParameterInfo list. | |||
1517 | SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; | |||
1518 | bool CanUseToFPT, CanUseFromFPT; | |||
1519 | if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, | |||
1520 | CanUseFromFPT, NewParamInfos) && | |||
1521 | CanUseToFPT && !CanUseFromFPT) { | |||
1522 | FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); | |||
1523 | ExtInfo.ExtParameterInfos = | |||
1524 | NewParamInfos.empty() ? nullptr : NewParamInfos.data(); | |||
1525 | QualType QT = Context.getFunctionType(FromFPT->getReturnType(), | |||
1526 | FromFPT->getParamTypes(), ExtInfo); | |||
1527 | FromFn = QT->getAs<FunctionType>(); | |||
1528 | Changed = true; | |||
1529 | } | |||
1530 | } | |||
1531 | ||||
1532 | if (!Changed) | |||
1533 | return false; | |||
1534 | ||||
1535 | assert(QualType(FromFn, 0).isCanonical())((QualType(FromFn, 0).isCanonical()) ? static_cast<void> (0) : __assert_fail ("QualType(FromFn, 0).isCanonical()", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 1535, __PRETTY_FUNCTION__)); | |||
1536 | if (QualType(FromFn, 0) != CanTo) return false; | |||
1537 | ||||
1538 | ResultTy = ToType; | |||
1539 | return true; | |||
1540 | } | |||
1541 | ||||
1542 | /// Determine whether the conversion from FromType to ToType is a valid | |||
1543 | /// vector conversion. | |||
1544 | /// | |||
1545 | /// \param ICK Will be set to the vector conversion kind, if this is a vector | |||
1546 | /// conversion. | |||
1547 | static bool IsVectorConversion(Sema &S, QualType FromType, | |||
1548 | QualType ToType, ImplicitConversionKind &ICK) { | |||
1549 | // We need at least one of these types to be a vector type to have a vector | |||
1550 | // conversion. | |||
1551 | if (!ToType->isVectorType() && !FromType->isVectorType()) | |||
1552 | return false; | |||
1553 | ||||
1554 | // Identical types require no conversions. | |||
1555 | if (S.Context.hasSameUnqualifiedType(FromType, ToType)) | |||
1556 | return false; | |||
1557 | ||||
1558 | // There are no conversions between extended vector types, only identity. | |||
1559 | if (ToType->isExtVectorType()) { | |||
1560 | // There are no conversions between extended vector types other than the | |||
1561 | // identity conversion. | |||
1562 | if (FromType->isExtVectorType()) | |||
1563 | return false; | |||
1564 | ||||
1565 | // Vector splat from any arithmetic type to a vector. | |||
1566 | if (FromType->isArithmeticType()) { | |||
1567 | ICK = ICK_Vector_Splat; | |||
1568 | return true; | |||
1569 | } | |||
1570 | } | |||
1571 | ||||
1572 | // We can perform the conversion between vector types in the following cases: | |||
1573 | // 1)vector types are equivalent AltiVec and GCC vector types | |||
1574 | // 2)lax vector conversions are permitted and the vector types are of the | |||
1575 | // same size | |||
1576 | if (ToType->isVectorType() && FromType->isVectorType()) { | |||
1577 | if (S.Context.areCompatibleVectorTypes(FromType, ToType) || | |||
1578 | S.isLaxVectorConversion(FromType, ToType)) { | |||
1579 | ICK = ICK_Vector_Conversion; | |||
1580 | return true; | |||
1581 | } | |||
1582 | } | |||
1583 | ||||
1584 | return false; | |||
1585 | } | |||
1586 | ||||
1587 | static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, | |||
1588 | bool InOverloadResolution, | |||
1589 | StandardConversionSequence &SCS, | |||
1590 | bool CStyle); | |||
1591 | ||||
1592 | /// IsStandardConversion - Determines whether there is a standard | |||
1593 | /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the | |||
1594 | /// expression From to the type ToType. Standard conversion sequences | |||
1595 | /// only consider non-class types; for conversions that involve class | |||
1596 | /// types, use TryImplicitConversion. If a conversion exists, SCS will | |||
1597 | /// contain the standard conversion sequence required to perform this | |||
1598 | /// conversion and this routine will return true. Otherwise, this | |||
1599 | /// routine will return false and the value of SCS is unspecified. | |||
1600 | static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, | |||
1601 | bool InOverloadResolution, | |||
1602 | StandardConversionSequence &SCS, | |||
1603 | bool CStyle, | |||
1604 | bool AllowObjCWritebackConversion) { | |||
1605 | QualType FromType = From->getType(); | |||
1606 | ||||
1607 | // Standard conversions (C++ [conv]) | |||
1608 | SCS.setAsIdentityConversion(); | |||
1609 | SCS.IncompatibleObjC = false; | |||
1610 | SCS.setFromType(FromType); | |||
1611 | SCS.CopyConstructor = nullptr; | |||
1612 | ||||
1613 | // There are no standard conversions for class types in C++, so | |||
1614 | // abort early. When overloading in C, however, we do permit them. | |||
1615 | if (S.getLangOpts().CPlusPlus && | |||
1616 | (FromType->isRecordType() || ToType->isRecordType())) | |||
1617 | return false; | |||
1618 | ||||
1619 | // The first conversion can be an lvalue-to-rvalue conversion, | |||
1620 | // array-to-pointer conversion, or function-to-pointer conversion | |||
1621 | // (C++ 4p1). | |||
1622 | ||||
1623 | if (FromType == S.Context.OverloadTy) { | |||
1624 | DeclAccessPair AccessPair; | |||
1625 | if (FunctionDecl *Fn | |||
1626 | = S.ResolveAddressOfOverloadedFunction(From, ToType, false, | |||
1627 | AccessPair)) { | |||
1628 | // We were able to resolve the address of the overloaded function, | |||
1629 | // so we can convert to the type of that function. | |||
1630 | FromType = Fn->getType(); | |||
1631 | SCS.setFromType(FromType); | |||
1632 | ||||
1633 | // we can sometimes resolve &foo<int> regardless of ToType, so check | |||
1634 | // if the type matches (identity) or we are converting to bool | |||
1635 | if (!S.Context.hasSameUnqualifiedType( | |||
1636 | S.ExtractUnqualifiedFunctionType(ToType), FromType)) { | |||
1637 | QualType resultTy; | |||
1638 | // if the function type matches except for [[noreturn]], it's ok | |||
1639 | if (!S.IsFunctionConversion(FromType, | |||
1640 | S.ExtractUnqualifiedFunctionType(ToType), resultTy)) | |||
1641 | // otherwise, only a boolean conversion is standard | |||
1642 | if (!ToType->isBooleanType()) | |||
1643 | return false; | |||
1644 | } | |||
1645 | ||||
1646 | // Check if the "from" expression is taking the address of an overloaded | |||
1647 | // function and recompute the FromType accordingly. Take advantage of the | |||
1648 | // fact that non-static member functions *must* have such an address-of | |||
1649 | // expression. | |||
1650 | CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); | |||
1651 | if (Method && !Method->isStatic()) { | |||
1652 | assert(isa<UnaryOperator>(From->IgnoreParens()) &&((isa<UnaryOperator>(From->IgnoreParens()) && "Non-unary operator on non-static member address") ? static_cast <void> (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 1653, __PRETTY_FUNCTION__)) | |||
1653 | "Non-unary operator on non-static member address")((isa<UnaryOperator>(From->IgnoreParens()) && "Non-unary operator on non-static member address") ? static_cast <void> (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 1653, __PRETTY_FUNCTION__)); | |||
1654 | assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()((cast<UnaryOperator>(From->IgnoreParens())->getOpcode () == UO_AddrOf && "Non-address-of operator on non-static member address" ) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 1656, __PRETTY_FUNCTION__)) | |||
1655 | == UO_AddrOf &&((cast<UnaryOperator>(From->IgnoreParens())->getOpcode () == UO_AddrOf && "Non-address-of operator on non-static member address" ) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 1656, __PRETTY_FUNCTION__)) | |||
1656 | "Non-address-of operator on non-static member address")((cast<UnaryOperator>(From->IgnoreParens())->getOpcode () == UO_AddrOf && "Non-address-of operator on non-static member address" ) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 1656, __PRETTY_FUNCTION__)); | |||
1657 | const Type *ClassType | |||
1658 | = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); | |||
1659 | FromType = S.Context.getMemberPointerType(FromType, ClassType); | |||
1660 | } else if (isa<UnaryOperator>(From->IgnoreParens())) { | |||
1661 | assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==((cast<UnaryOperator>(From->IgnoreParens())->getOpcode () == UO_AddrOf && "Non-address-of operator for overloaded function expression" ) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 1663, __PRETTY_FUNCTION__)) | |||
1662 | UO_AddrOf &&((cast<UnaryOperator>(From->IgnoreParens())->getOpcode () == UO_AddrOf && "Non-address-of operator for overloaded function expression" ) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 1663, __PRETTY_FUNCTION__)) | |||
1663 | "Non-address-of operator for overloaded function expression")((cast<UnaryOperator>(From->IgnoreParens())->getOpcode () == UO_AddrOf && "Non-address-of operator for overloaded function expression" ) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 1663, __PRETTY_FUNCTION__)); | |||
1664 | FromType = S.Context.getPointerType(FromType); | |||
1665 | } | |||
1666 | ||||
1667 | // Check that we've computed the proper type after overload resolution. | |||
1668 | // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't | |||
1669 | // be calling it from within an NDEBUG block. | |||
1670 | assert(S.Context.hasSameType(((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference (From, AccessPair, Fn)->getType())) ? static_cast<void> (0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 1672, __PRETTY_FUNCTION__)) | |||
1671 | FromType,((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference (From, AccessPair, Fn)->getType())) ? static_cast<void> (0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 1672, __PRETTY_FUNCTION__)) | |||
1672 | S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()))((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference (From, AccessPair, Fn)->getType())) ? static_cast<void> (0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 1672, __PRETTY_FUNCTION__)); | |||
1673 | } else { | |||
1674 | return false; | |||
1675 | } | |||
1676 | } | |||
1677 | // Lvalue-to-rvalue conversion (C++11 4.1): | |||
1678 | // A glvalue (3.10) of a non-function, non-array type T can | |||
1679 | // be converted to a prvalue. | |||
1680 | bool argIsLValue = From->isGLValue(); | |||
1681 | if (argIsLValue && | |||
1682 | !FromType->isFunctionType() && !FromType->isArrayType() && | |||
1683 | S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { | |||
1684 | SCS.First = ICK_Lvalue_To_Rvalue; | |||
1685 | ||||
1686 | // C11 6.3.2.1p2: | |||
1687 | // ... if the lvalue has atomic type, the value has the non-atomic version | |||
1688 | // of the type of the lvalue ... | |||
1689 | if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) | |||
1690 | FromType = Atomic->getValueType(); | |||
1691 | ||||
1692 | // If T is a non-class type, the type of the rvalue is the | |||
1693 | // cv-unqualified version of T. Otherwise, the type of the rvalue | |||
1694 | // is T (C++ 4.1p1). C++ can't get here with class types; in C, we | |||
1695 | // just strip the qualifiers because they don't matter. | |||
1696 | FromType = FromType.getUnqualifiedType(); | |||
1697 | } else if (FromType->isArrayType()) { | |||
1698 | // Array-to-pointer conversion (C++ 4.2) | |||
1699 | SCS.First = ICK_Array_To_Pointer; | |||
1700 | ||||
1701 | // An lvalue or rvalue of type "array of N T" or "array of unknown | |||
1702 | // bound of T" can be converted to an rvalue of type "pointer to | |||
1703 | // T" (C++ 4.2p1). | |||
1704 | FromType = S.Context.getArrayDecayedType(FromType); | |||
1705 | ||||
1706 | if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { | |||
1707 | // This conversion is deprecated in C++03 (D.4) | |||
1708 | SCS.DeprecatedStringLiteralToCharPtr = true; | |||
1709 | ||||
1710 | // For the purpose of ranking in overload resolution | |||
1711 | // (13.3.3.1.1), this conversion is considered an | |||
1712 | // array-to-pointer conversion followed by a qualification | |||
1713 | // conversion (4.4). (C++ 4.2p2) | |||
1714 | SCS.Second = ICK_Identity; | |||
1715 | SCS.Third = ICK_Qualification; | |||
1716 | SCS.QualificationIncludesObjCLifetime = false; | |||
1717 | SCS.setAllToTypes(FromType); | |||
1718 | return true; | |||
1719 | } | |||
1720 | } else if (FromType->isFunctionType() && argIsLValue) { | |||
1721 | // Function-to-pointer conversion (C++ 4.3). | |||
1722 | SCS.First = ICK_Function_To_Pointer; | |||
1723 | ||||
1724 | if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) | |||
1725 | if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) | |||
1726 | if (!S.checkAddressOfFunctionIsAvailable(FD)) | |||
1727 | return false; | |||
1728 | ||||
1729 | // An lvalue of function type T can be converted to an rvalue of | |||
1730 | // type "pointer to T." The result is a pointer to the | |||
1731 | // function. (C++ 4.3p1). | |||
1732 | FromType = S.Context.getPointerType(FromType); | |||
1733 | } else { | |||
1734 | // We don't require any conversions for the first step. | |||
1735 | SCS.First = ICK_Identity; | |||
1736 | } | |||
1737 | SCS.setToType(0, FromType); | |||
1738 | ||||
1739 | // The second conversion can be an integral promotion, floating | |||
1740 | // point promotion, integral conversion, floating point conversion, | |||
1741 | // floating-integral conversion, pointer conversion, | |||
1742 | // pointer-to-member conversion, or boolean conversion (C++ 4p1). | |||
1743 | // For overloading in C, this can also be a "compatible-type" | |||
1744 | // conversion. | |||
1745 | bool IncompatibleObjC = false; | |||
1746 | ImplicitConversionKind SecondICK = ICK_Identity; | |||
1747 | if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { | |||
1748 | // The unqualified versions of the types are the same: there's no | |||
1749 | // conversion to do. | |||
1750 | SCS.Second = ICK_Identity; | |||
1751 | } else if (S.IsIntegralPromotion(From, FromType, ToType)) { | |||
1752 | // Integral promotion (C++ 4.5). | |||
1753 | SCS.Second = ICK_Integral_Promotion; | |||
1754 | FromType = ToType.getUnqualifiedType(); | |||
1755 | } else if (S.IsFloatingPointPromotion(FromType, ToType)) { | |||
1756 | // Floating point promotion (C++ 4.6). | |||
1757 | SCS.Second = ICK_Floating_Promotion; | |||
1758 | FromType = ToType.getUnqualifiedType(); | |||
1759 | } else if (S.IsComplexPromotion(FromType, ToType)) { | |||
1760 | // Complex promotion (Clang extension) | |||
1761 | SCS.Second = ICK_Complex_Promotion; | |||
1762 | FromType = ToType.getUnqualifiedType(); | |||
1763 | } else if (ToType->isBooleanType() && | |||
1764 | (FromType->isArithmeticType() || | |||
1765 | FromType->isAnyPointerType() || | |||
1766 | FromType->isBlockPointerType() || | |||
1767 | FromType->isMemberPointerType() || | |||
1768 | FromType->isNullPtrType())) { | |||
1769 | // Boolean conversions (C++ 4.12). | |||
1770 | SCS.Second = ICK_Boolean_Conversion; | |||
1771 | FromType = S.Context.BoolTy; | |||
1772 | } else if (FromType->isIntegralOrUnscopedEnumerationType() && | |||
1773 | ToType->isIntegralType(S.Context)) { | |||
1774 | // Integral conversions (C++ 4.7). | |||
1775 | SCS.Second = ICK_Integral_Conversion; | |||
1776 | FromType = ToType.getUnqualifiedType(); | |||
1777 | } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { | |||
1778 | // Complex conversions (C99 6.3.1.6) | |||
1779 | SCS.Second = ICK_Complex_Conversion; | |||
1780 | FromType = ToType.getUnqualifiedType(); | |||
1781 | } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || | |||
1782 | (ToType->isAnyComplexType() && FromType->isArithmeticType())) { | |||
1783 | // Complex-real conversions (C99 6.3.1.7) | |||
1784 | SCS.Second = ICK_Complex_Real; | |||
1785 | FromType = ToType.getUnqualifiedType(); | |||
1786 | } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { | |||
1787 | // FIXME: disable conversions between long double and __float128 if | |||
1788 | // their representation is different until there is back end support | |||
1789 | // We of course allow this conversion if long double is really double. | |||
1790 | if (&S.Context.getFloatTypeSemantics(FromType) != | |||
1791 | &S.Context.getFloatTypeSemantics(ToType)) { | |||
1792 | bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && | |||
1793 | ToType == S.Context.LongDoubleTy) || | |||
1794 | (FromType == S.Context.LongDoubleTy && | |||
1795 | ToType == S.Context.Float128Ty)); | |||
1796 | if (Float128AndLongDouble && | |||
1797 | (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == | |||
1798 | &llvm::APFloat::PPCDoubleDouble())) | |||
1799 | return false; | |||
1800 | } | |||
1801 | // Floating point conversions (C++ 4.8). | |||
1802 | SCS.Second = ICK_Floating_Conversion; | |||
1803 | FromType = ToType.getUnqualifiedType(); | |||
1804 | } else if ((FromType->isRealFloatingType() && | |||
1805 | ToType->isIntegralType(S.Context)) || | |||
1806 | (FromType->isIntegralOrUnscopedEnumerationType() && | |||
1807 | ToType->isRealFloatingType())) { | |||
1808 | // Floating-integral conversions (C++ 4.9). | |||
1809 | SCS.Second = ICK_Floating_Integral; | |||
1810 | FromType = ToType.getUnqualifiedType(); | |||
1811 | } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { | |||
1812 | SCS.Second = ICK_Block_Pointer_Conversion; | |||
1813 | } else if (AllowObjCWritebackConversion && | |||
1814 | S.isObjCWritebackConversion(FromType, ToType, FromType)) { | |||
1815 | SCS.Second = ICK_Writeback_Conversion; | |||
1816 | } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, | |||
1817 | FromType, IncompatibleObjC)) { | |||
1818 | // Pointer conversions (C++ 4.10). | |||
1819 | SCS.Second = ICK_Pointer_Conversion; | |||
1820 | SCS.IncompatibleObjC = IncompatibleObjC; | |||
1821 | FromType = FromType.getUnqualifiedType(); | |||
1822 | } else if (S.IsMemberPointerConversion(From, FromType, ToType, | |||
1823 | InOverloadResolution, FromType)) { | |||
1824 | // Pointer to member conversions (4.11). | |||
1825 | SCS.Second = ICK_Pointer_Member; | |||
1826 | } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { | |||
1827 | SCS.Second = SecondICK; | |||
1828 | FromType = ToType.getUnqualifiedType(); | |||
1829 | } else if (!S.getLangOpts().CPlusPlus && | |||
1830 | S.Context.typesAreCompatible(ToType, FromType)) { | |||
1831 | // Compatible conversions (Clang extension for C function overloading) | |||
1832 | SCS.Second = ICK_Compatible_Conversion; | |||
1833 | FromType = ToType.getUnqualifiedType(); | |||
1834 | } else if (IsTransparentUnionStandardConversion(S, From, ToType, | |||
1835 | InOverloadResolution, | |||
1836 | SCS, CStyle)) { | |||
1837 | SCS.Second = ICK_TransparentUnionConversion; | |||
1838 | FromType = ToType; | |||
1839 | } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, | |||
1840 | CStyle)) { | |||
1841 | // tryAtomicConversion has updated the standard conversion sequence | |||
1842 | // appropriately. | |||
1843 | return true; | |||
1844 | } else if (ToType->isEventT() && | |||
1845 | From->isIntegerConstantExpr(S.getASTContext()) && | |||
1846 | From->EvaluateKnownConstInt(S.getASTContext()) == 0) { | |||
1847 | SCS.Second = ICK_Zero_Event_Conversion; | |||
1848 | FromType = ToType; | |||
1849 | } else if (ToType->isQueueT() && | |||
1850 | From->isIntegerConstantExpr(S.getASTContext()) && | |||
1851 | (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { | |||
1852 | SCS.Second = ICK_Zero_Queue_Conversion; | |||
1853 | FromType = ToType; | |||
1854 | } else { | |||
1855 | // No second conversion required. | |||
1856 | SCS.Second = ICK_Identity; | |||
1857 | } | |||
1858 | SCS.setToType(1, FromType); | |||
1859 | ||||
1860 | // The third conversion can be a function pointer conversion or a | |||
1861 | // qualification conversion (C++ [conv.fctptr], [conv.qual]). | |||
1862 | bool ObjCLifetimeConversion; | |||
1863 | if (S.IsFunctionConversion(FromType, ToType, FromType)) { | |||
1864 | // Function pointer conversions (removing 'noexcept') including removal of | |||
1865 | // 'noreturn' (Clang extension). | |||
1866 | SCS.Third = ICK_Function_Conversion; | |||
1867 | } else if (S.IsQualificationConversion(FromType, ToType, CStyle, | |||
1868 | ObjCLifetimeConversion)) { | |||
1869 | SCS.Third = ICK_Qualification; | |||
1870 | SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; | |||
1871 | FromType = ToType; | |||
1872 | } else { | |||
1873 | // No conversion required | |||
1874 | SCS.Third = ICK_Identity; | |||
1875 | } | |||
1876 | ||||
1877 | // C++ [over.best.ics]p6: | |||
1878 | // [...] Any difference in top-level cv-qualification is | |||
1879 | // subsumed by the initialization itself and does not constitute | |||
1880 | // a conversion. [...] | |||
1881 | QualType CanonFrom = S.Context.getCanonicalType(FromType); | |||
1882 | QualType CanonTo = S.Context.getCanonicalType(ToType); | |||
1883 | if (CanonFrom.getLocalUnqualifiedType() | |||
1884 | == CanonTo.getLocalUnqualifiedType() && | |||
1885 | CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { | |||
1886 | FromType = ToType; | |||
1887 | CanonFrom = CanonTo; | |||
1888 | } | |||
1889 | ||||
1890 | SCS.setToType(2, FromType); | |||
1891 | ||||
1892 | if (CanonFrom == CanonTo) | |||
1893 | return true; | |||
1894 | ||||
1895 | // If we have not converted the argument type to the parameter type, | |||
1896 | // this is a bad conversion sequence, unless we're resolving an overload in C. | |||
1897 | if (S.getLangOpts().CPlusPlus || !InOverloadResolution) | |||
1898 | return false; | |||
1899 | ||||
1900 | ExprResult ER = ExprResult{From}; | |||
1901 | Sema::AssignConvertType Conv = | |||
1902 | S.CheckSingleAssignmentConstraints(ToType, ER, | |||
1903 | /*Diagnose=*/false, | |||
1904 | /*DiagnoseCFAudited=*/false, | |||
1905 | /*ConvertRHS=*/false); | |||
1906 | ImplicitConversionKind SecondConv; | |||
1907 | switch (Conv) { | |||
1908 | case Sema::Compatible: | |||
1909 | SecondConv = ICK_C_Only_Conversion; | |||
1910 | break; | |||
1911 | // For our purposes, discarding qualifiers is just as bad as using an | |||
1912 | // incompatible pointer. Note that an IncompatiblePointer conversion can drop | |||
1913 | // qualifiers, as well. | |||
1914 | case Sema::CompatiblePointerDiscardsQualifiers: | |||
1915 | case Sema::IncompatiblePointer: | |||
1916 | case Sema::IncompatiblePointerSign: | |||
1917 | SecondConv = ICK_Incompatible_Pointer_Conversion; | |||
1918 | break; | |||
1919 | default: | |||
1920 | return false; | |||
1921 | } | |||
1922 | ||||
1923 | // First can only be an lvalue conversion, so we pretend that this was the | |||
1924 | // second conversion. First should already be valid from earlier in the | |||
1925 | // function. | |||
1926 | SCS.Second = SecondConv; | |||
1927 | SCS.setToType(1, ToType); | |||
1928 | ||||
1929 | // Third is Identity, because Second should rank us worse than any other | |||
1930 | // conversion. This could also be ICK_Qualification, but it's simpler to just | |||
1931 | // lump everything in with the second conversion, and we don't gain anything | |||
1932 | // from making this ICK_Qualification. | |||
1933 | SCS.Third = ICK_Identity; | |||
1934 | SCS.setToType(2, ToType); | |||
1935 | return true; | |||
1936 | } | |||
1937 | ||||
1938 | static bool | |||
1939 | IsTransparentUnionStandardConversion(Sema &S, Expr* From, | |||
1940 | QualType &ToType, | |||
1941 | bool InOverloadResolution, | |||
1942 | StandardConversionSequence &SCS, | |||
1943 | bool CStyle) { | |||
1944 | ||||
1945 | const RecordType *UT = ToType->getAsUnionType(); | |||
1946 | if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) | |||
1947 | return false; | |||
1948 | // The field to initialize within the transparent union. | |||
1949 | RecordDecl *UD = UT->getDecl(); | |||
1950 | // It's compatible if the expression matches any of the fields. | |||
1951 | for (const auto *it : UD->fields()) { | |||
1952 | if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, | |||
1953 | CStyle, /*ObjCWritebackConversion=*/false)) { | |||
1954 | ToType = it->getType(); | |||
1955 | return true; | |||
1956 | } | |||
1957 | } | |||
1958 | return false; | |||
1959 | } | |||
1960 | ||||
1961 | /// IsIntegralPromotion - Determines whether the conversion from the | |||
1962 | /// expression From (whose potentially-adjusted type is FromType) to | |||
1963 | /// ToType is an integral promotion (C++ 4.5). If so, returns true and | |||
1964 | /// sets PromotedType to the promoted type. | |||
1965 | bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { | |||
1966 | const BuiltinType *To = ToType->getAs<BuiltinType>(); | |||
1967 | // All integers are built-in. | |||
1968 | if (!To) { | |||
1969 | return false; | |||
1970 | } | |||
1971 | ||||
1972 | // An rvalue of type char, signed char, unsigned char, short int, or | |||
1973 | // unsigned short int can be converted to an rvalue of type int if | |||
1974 | // int can represent all the values of the source type; otherwise, | |||
1975 | // the source rvalue can be converted to an rvalue of type unsigned | |||
1976 | // int (C++ 4.5p1). | |||
1977 | if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && | |||
1978 | !FromType->isEnumeralType()) { | |||
1979 | if (// We can promote any signed, promotable integer type to an int | |||
1980 | (FromType->isSignedIntegerType() || | |||
1981 | // We can promote any unsigned integer type whose size is | |||
1982 | // less than int to an int. | |||
1983 | Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { | |||
1984 | return To->getKind() == BuiltinType::Int; | |||
1985 | } | |||
1986 | ||||
1987 | return To->getKind() == BuiltinType::UInt; | |||
1988 | } | |||
1989 | ||||
1990 | // C++11 [conv.prom]p3: | |||
1991 | // A prvalue of an unscoped enumeration type whose underlying type is not | |||
1992 | // fixed (7.2) can be converted to an rvalue a prvalue of the first of the | |||
1993 | // following types that can represent all the values of the enumeration | |||
1994 | // (i.e., the values in the range bmin to bmax as described in 7.2): int, | |||
1995 | // unsigned int, long int, unsigned long int, long long int, or unsigned | |||
1996 | // long long int. If none of the types in that list can represent all the | |||
1997 | // values of the enumeration, an rvalue a prvalue of an unscoped enumeration | |||
1998 | // type can be converted to an rvalue a prvalue of the extended integer type | |||
1999 | // with lowest integer conversion rank (4.13) greater than the rank of long | |||
2000 | // long in which all the values of the enumeration can be represented. If | |||
2001 | // there are two such extended types, the signed one is chosen. | |||
2002 | // C++11 [conv.prom]p4: | |||
2003 | // A prvalue of an unscoped enumeration type whose underlying type is fixed | |||
2004 | // can be converted to a prvalue of its underlying type. Moreover, if | |||
2005 | // integral promotion can be applied to its underlying type, a prvalue of an | |||
2006 | // unscoped enumeration type whose underlying type is fixed can also be | |||
2007 | // converted to a prvalue of the promoted underlying type. | |||
2008 | if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { | |||
2009 | // C++0x 7.2p9: Note that this implicit enum to int conversion is not | |||
2010 | // provided for a scoped enumeration. | |||
2011 | if (FromEnumType->getDecl()->isScoped()) | |||
2012 | return false; | |||
2013 | ||||
2014 | // We can perform an integral promotion to the underlying type of the enum, | |||
2015 | // even if that's not the promoted type. Note that the check for promoting | |||
2016 | // the underlying type is based on the type alone, and does not consider | |||
2017 | // the bitfield-ness of the actual source expression. | |||
2018 | if (FromEnumType->getDecl()->isFixed()) { | |||
2019 | QualType Underlying = FromEnumType->getDecl()->getIntegerType(); | |||
2020 | return Context.hasSameUnqualifiedType(Underlying, ToType) || | |||
2021 | IsIntegralPromotion(nullptr, Underlying, ToType); | |||
2022 | } | |||
2023 | ||||
2024 | // We have already pre-calculated the promotion type, so this is trivial. | |||
2025 | if (ToType->isIntegerType() && | |||
2026 | isCompleteType(From->getBeginLoc(), FromType)) | |||
2027 | return Context.hasSameUnqualifiedType( | |||
2028 | ToType, FromEnumType->getDecl()->getPromotionType()); | |||
2029 | ||||
2030 | // C++ [conv.prom]p5: | |||
2031 | // If the bit-field has an enumerated type, it is treated as any other | |||
2032 | // value of that type for promotion purposes. | |||
2033 | // | |||
2034 | // ... so do not fall through into the bit-field checks below in C++. | |||
2035 | if (getLangOpts().CPlusPlus) | |||
2036 | return false; | |||
2037 | } | |||
2038 | ||||
2039 | // C++0x [conv.prom]p2: | |||
2040 | // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted | |||
2041 | // to an rvalue a prvalue of the first of the following types that can | |||
2042 | // represent all the values of its underlying type: int, unsigned int, | |||
2043 | // long int, unsigned long int, long long int, or unsigned long long int. | |||
2044 | // If none of the types in that list can represent all the values of its | |||
2045 | // underlying type, an rvalue a prvalue of type char16_t, char32_t, | |||
2046 | // or wchar_t can be converted to an rvalue a prvalue of its underlying | |||
2047 | // type. | |||
2048 | if (FromType->isAnyCharacterType() && !FromType->isCharType() && | |||
2049 | ToType->isIntegerType()) { | |||
2050 | // Determine whether the type we're converting from is signed or | |||
2051 | // unsigned. | |||
2052 | bool FromIsSigned = FromType->isSignedIntegerType(); | |||
2053 | uint64_t FromSize = Context.getTypeSize(FromType); | |||
2054 | ||||
2055 | // The types we'll try to promote to, in the appropriate | |||
2056 | // order. Try each of these types. | |||
2057 | QualType PromoteTypes[6] = { | |||
2058 | Context.IntTy, Context.UnsignedIntTy, | |||
2059 | Context.LongTy, Context.UnsignedLongTy , | |||
2060 | Context.LongLongTy, Context.UnsignedLongLongTy | |||
2061 | }; | |||
2062 | for (int Idx = 0; Idx < 6; ++Idx) { | |||
2063 | uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); | |||
2064 | if (FromSize < ToSize || | |||
2065 | (FromSize == ToSize && | |||
2066 | FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { | |||
2067 | // We found the type that we can promote to. If this is the | |||
2068 | // type we wanted, we have a promotion. Otherwise, no | |||
2069 | // promotion. | |||
2070 | return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); | |||
2071 | } | |||
2072 | } | |||
2073 | } | |||
2074 | ||||
2075 | // An rvalue for an integral bit-field (9.6) can be converted to an | |||
2076 | // rvalue of type int if int can represent all the values of the | |||
2077 | // bit-field; otherwise, it can be converted to unsigned int if | |||
2078 | // unsigned int can represent all the values of the bit-field. If | |||
2079 | // the bit-field is larger yet, no integral promotion applies to | |||
2080 | // it. If the bit-field has an enumerated type, it is treated as any | |||
2081 | // other value of that type for promotion purposes (C++ 4.5p3). | |||
2082 | // FIXME: We should delay checking of bit-fields until we actually perform the | |||
2083 | // conversion. | |||
2084 | // | |||
2085 | // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be | |||
2086 | // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum | |||
2087 | // bit-fields and those whose underlying type is larger than int) for GCC | |||
2088 | // compatibility. | |||
2089 | if (From) { | |||
2090 | if (FieldDecl *MemberDecl = From->getSourceBitField()) { | |||
2091 | llvm::APSInt BitWidth; | |||
2092 | if (FromType->isIntegralType(Context) && | |||
2093 | MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { | |||
2094 | llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); | |||
2095 | ToSize = Context.getTypeSize(ToType); | |||
2096 | ||||
2097 | // Are we promoting to an int from a bitfield that fits in an int? | |||
2098 | if (BitWidth < ToSize || | |||
2099 | (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { | |||
2100 | return To->getKind() == BuiltinType::Int; | |||
2101 | } | |||
2102 | ||||
2103 | // Are we promoting to an unsigned int from an unsigned bitfield | |||
2104 | // that fits into an unsigned int? | |||
2105 | if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { | |||
2106 | return To->getKind() == BuiltinType::UInt; | |||
2107 | } | |||
2108 | ||||
2109 | return false; | |||
2110 | } | |||
2111 | } | |||
2112 | } | |||
2113 | ||||
2114 | // An rvalue of type bool can be converted to an rvalue of type int, | |||
2115 | // with false becoming zero and true becoming one (C++ 4.5p4). | |||
2116 | if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { | |||
2117 | return true; | |||
2118 | } | |||
2119 | ||||
2120 | return false; | |||
2121 | } | |||
2122 | ||||
2123 | /// IsFloatingPointPromotion - Determines whether the conversion from | |||
2124 | /// FromType to ToType is a floating point promotion (C++ 4.6). If so, | |||
2125 | /// returns true and sets PromotedType to the promoted type. | |||
2126 | bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { | |||
2127 | if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) | |||
2128 | if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { | |||
2129 | /// An rvalue of type float can be converted to an rvalue of type | |||
2130 | /// double. (C++ 4.6p1). | |||
2131 | if (FromBuiltin->getKind() == BuiltinType::Float && | |||
2132 | ToBuiltin->getKind() == BuiltinType::Double) | |||
2133 | return true; | |||
2134 | ||||
2135 | // C99 6.3.1.5p1: | |||
2136 | // When a float is promoted to double or long double, or a | |||
2137 | // double is promoted to long double [...]. | |||
2138 | if (!getLangOpts().CPlusPlus && | |||
2139 | (FromBuiltin->getKind() == BuiltinType::Float || | |||
2140 | FromBuiltin->getKind() == BuiltinType::Double) && | |||
2141 | (ToBuiltin->getKind() == BuiltinType::LongDouble || | |||
2142 | ToBuiltin->getKind() == BuiltinType::Float128)) | |||
2143 | return true; | |||
2144 | ||||
2145 | // Half can be promoted to float. | |||
2146 | if (!getLangOpts().NativeHalfType && | |||
2147 | FromBuiltin->getKind() == BuiltinType::Half && | |||
2148 | ToBuiltin->getKind() == BuiltinType::Float) | |||
2149 | return true; | |||
2150 | } | |||
2151 | ||||
2152 | return false; | |||
2153 | } | |||
2154 | ||||
2155 | /// Determine if a conversion is a complex promotion. | |||
2156 | /// | |||
2157 | /// A complex promotion is defined as a complex -> complex conversion | |||
2158 | /// where the conversion between the underlying real types is a | |||
2159 | /// floating-point or integral promotion. | |||
2160 | bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { | |||
2161 | const ComplexType *FromComplex = FromType->getAs<ComplexType>(); | |||
2162 | if (!FromComplex) | |||
2163 | return false; | |||
2164 | ||||
2165 | const ComplexType *ToComplex = ToType->getAs<ComplexType>(); | |||
2166 | if (!ToComplex) | |||
2167 | return false; | |||
2168 | ||||
2169 | return IsFloatingPointPromotion(FromComplex->getElementType(), | |||
2170 | ToComplex->getElementType()) || | |||
2171 | IsIntegralPromotion(nullptr, FromComplex->getElementType(), | |||
2172 | ToComplex->getElementType()); | |||
2173 | } | |||
2174 | ||||
2175 | /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from | |||
2176 | /// the pointer type FromPtr to a pointer to type ToPointee, with the | |||
2177 | /// same type qualifiers as FromPtr has on its pointee type. ToType, | |||
2178 | /// if non-empty, will be a pointer to ToType that may or may not have | |||
2179 | /// the right set of qualifiers on its pointee. | |||
2180 | /// | |||
2181 | static QualType | |||
2182 | BuildSimilarlyQualifiedPointerType(const Type *FromPtr, | |||
2183 | QualType ToPointee, QualType ToType, | |||
2184 | ASTContext &Context, | |||
2185 | bool StripObjCLifetime = false) { | |||
2186 | assert((FromPtr->getTypeClass() == Type::Pointer ||(((FromPtr->getTypeClass() == Type::Pointer || FromPtr-> getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type" ) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 2188, __PRETTY_FUNCTION__)) | |||
2187 | FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&(((FromPtr->getTypeClass() == Type::Pointer || FromPtr-> getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type" ) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 2188, __PRETTY_FUNCTION__)) | |||
2188 | "Invalid similarly-qualified pointer type")(((FromPtr->getTypeClass() == Type::Pointer || FromPtr-> getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type" ) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 2188, __PRETTY_FUNCTION__)); | |||
2189 | ||||
2190 | /// Conversions to 'id' subsume cv-qualifier conversions. | |||
2191 | if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) | |||
2192 | return ToType.getUnqualifiedType(); | |||
2193 | ||||
2194 | QualType CanonFromPointee | |||
2195 | = Context.getCanonicalType(FromPtr->getPointeeType()); | |||
2196 | QualType CanonToPointee = Context.getCanonicalType(ToPointee); | |||
2197 | Qualifiers Quals = CanonFromPointee.getQualifiers(); | |||
2198 | ||||
2199 | if (StripObjCLifetime) | |||
2200 | Quals.removeObjCLifetime(); | |||
2201 | ||||
2202 | // Exact qualifier match -> return the pointer type we're converting to. | |||
2203 | if (CanonToPointee.getLocalQualifiers() == Quals) { | |||
2204 | // ToType is exactly what we need. Return it. | |||
2205 | if (!ToType.isNull()) | |||
2206 | return ToType.getUnqualifiedType(); | |||
2207 | ||||
2208 | // Build a pointer to ToPointee. It has the right qualifiers | |||
2209 | // already. | |||
2210 | if (isa<ObjCObjectPointerType>(ToType)) | |||
2211 | return Context.getObjCObjectPointerType(ToPointee); | |||
2212 | return Context.getPointerType(ToPointee); | |||
2213 | } | |||
2214 | ||||
2215 | // Just build a canonical type that has the right qualifiers. | |||
2216 | QualType QualifiedCanonToPointee | |||
2217 | = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); | |||
2218 | ||||
2219 | if (isa<ObjCObjectPointerType>(ToType)) | |||
2220 | return Context.getObjCObjectPointerType(QualifiedCanonToPointee); | |||
2221 | return Context.getPointerType(QualifiedCanonToPointee); | |||
2222 | } | |||
2223 | ||||
2224 | static bool isNullPointerConstantForConversion(Expr *Expr, | |||
2225 | bool InOverloadResolution, | |||
2226 | ASTContext &Context) { | |||
2227 | // Handle value-dependent integral null pointer constants correctly. | |||
2228 | // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 | |||
2229 | if (Expr->isValueDependent() && !Expr->isTypeDependent() && | |||
2230 | Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) | |||
2231 | return !InOverloadResolution; | |||
2232 | ||||
2233 | return Expr->isNullPointerConstant(Context, | |||
2234 | InOverloadResolution? Expr::NPC_ValueDependentIsNotNull | |||
2235 | : Expr::NPC_ValueDependentIsNull); | |||
2236 | } | |||
2237 | ||||
2238 | /// IsPointerConversion - Determines whether the conversion of the | |||
2239 | /// expression From, which has the (possibly adjusted) type FromType, | |||
2240 | /// can be converted to the type ToType via a pointer conversion (C++ | |||
2241 | /// 4.10). If so, returns true and places the converted type (that | |||
2242 | /// might differ from ToType in its cv-qualifiers at some level) into | |||
2243 | /// ConvertedType. | |||
2244 | /// | |||
2245 | /// This routine also supports conversions to and from block pointers | |||
2246 | /// and conversions with Objective-C's 'id', 'id<protocols...>', and | |||
2247 | /// pointers to interfaces. FIXME: Once we've determined the | |||
2248 | /// appropriate overloading rules for Objective-C, we may want to | |||
2249 | /// split the Objective-C checks into a different routine; however, | |||
2250 | /// GCC seems to consider all of these conversions to be pointer | |||
2251 | /// conversions, so for now they live here. IncompatibleObjC will be | |||
2252 | /// set if the conversion is an allowed Objective-C conversion that | |||
2253 | /// should result in a warning. | |||
2254 | bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, | |||
2255 | bool InOverloadResolution, | |||
2256 | QualType& ConvertedType, | |||
2257 | bool &IncompatibleObjC) { | |||
2258 | IncompatibleObjC = false; | |||
2259 | if (isObjCPointerConversion(FromType, ToType, ConvertedType, | |||
2260 | IncompatibleObjC)) | |||
2261 | return true; | |||
2262 | ||||
2263 | // Conversion from a null pointer constant to any Objective-C pointer type. | |||
2264 | if (ToType->isObjCObjectPointerType() && | |||
2265 | isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { | |||
2266 | ConvertedType = ToType; | |||
2267 | return true; | |||
2268 | } | |||
2269 | ||||
2270 | // Blocks: Block pointers can be converted to void*. | |||
2271 | if (FromType->isBlockPointerType() && ToType->isPointerType() && | |||
2272 | ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { | |||
2273 | ConvertedType = ToType; | |||
2274 | return true; | |||
2275 | } | |||
2276 | // Blocks: A null pointer constant can be converted to a block | |||
2277 | // pointer type. | |||
2278 | if (ToType->isBlockPointerType() && | |||
2279 | isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { | |||
2280 | ConvertedType = ToType; | |||
2281 | return true; | |||
2282 | } | |||
2283 | ||||
2284 | // If the left-hand-side is nullptr_t, the right side can be a null | |||
2285 | // pointer constant. | |||
2286 | if (ToType->isNullPtrType() && | |||
2287 | isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { | |||
2288 | ConvertedType = ToType; | |||
2289 | return true; | |||
2290 | } | |||
2291 | ||||
2292 | const PointerType* ToTypePtr = ToType->getAs<PointerType>(); | |||
2293 | if (!ToTypePtr) | |||
2294 | return false; | |||
2295 | ||||
2296 | // A null pointer constant can be converted to a pointer type (C++ 4.10p1). | |||
2297 | if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { | |||
2298 | ConvertedType = ToType; | |||
2299 | return true; | |||
2300 | } | |||
2301 | ||||
2302 | // Beyond this point, both types need to be pointers | |||
2303 | // , including objective-c pointers. | |||
2304 | QualType ToPointeeType = ToTypePtr->getPointeeType(); | |||
2305 | if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && | |||
2306 | !getLangOpts().ObjCAutoRefCount) { | |||
2307 | ConvertedType = BuildSimilarlyQualifiedPointerType( | |||
2308 | FromType->getAs<ObjCObjectPointerType>(), | |||
2309 | ToPointeeType, | |||
2310 | ToType, Context); | |||
2311 | return true; | |||
2312 | } | |||
2313 | const PointerType *FromTypePtr = FromType->getAs<PointerType>(); | |||
2314 | if (!FromTypePtr) | |||
2315 | return false; | |||
2316 | ||||
2317 | QualType FromPointeeType = FromTypePtr->getPointeeType(); | |||
2318 | ||||
2319 | // If the unqualified pointee types are the same, this can't be a | |||
2320 | // pointer conversion, so don't do all of the work below. | |||
2321 | if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) | |||
2322 | return false; | |||
2323 | ||||
2324 | // An rvalue of type "pointer to cv T," where T is an object type, | |||
2325 | // can be converted to an rvalue of type "pointer to cv void" (C++ | |||
2326 | // 4.10p2). | |||
2327 | if (FromPointeeType->isIncompleteOrObjectType() && | |||
2328 | ToPointeeType->isVoidType()) { | |||
2329 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, | |||
2330 | ToPointeeType, | |||
2331 | ToType, Context, | |||
2332 | /*StripObjCLifetime=*/true); | |||
2333 | return true; | |||
2334 | } | |||
2335 | ||||
2336 | // MSVC allows implicit function to void* type conversion. | |||
2337 | if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && | |||
2338 | ToPointeeType->isVoidType()) { | |||
2339 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, | |||
2340 | ToPointeeType, | |||
2341 | ToType, Context); | |||
2342 | return true; | |||
2343 | } | |||
2344 | ||||
2345 | // When we're overloading in C, we allow a special kind of pointer | |||
2346 | // conversion for compatible-but-not-identical pointee types. | |||
2347 | if (!getLangOpts().CPlusPlus && | |||
2348 | Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { | |||
2349 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, | |||
2350 | ToPointeeType, | |||
2351 | ToType, Context); | |||
2352 | return true; | |||
2353 | } | |||
2354 | ||||
2355 | // C++ [conv.ptr]p3: | |||
2356 | // | |||
2357 | // An rvalue of type "pointer to cv D," where D is a class type, | |||
2358 | // can be converted to an rvalue of type "pointer to cv B," where | |||
2359 | // B is a base class (clause 10) of D. If B is an inaccessible | |||
2360 | // (clause 11) or ambiguous (10.2) base class of D, a program that | |||
2361 | // necessitates this conversion is ill-formed. The result of the | |||
2362 | // conversion is a pointer to the base class sub-object of the | |||
2363 | // derived class object. The null pointer value is converted to | |||
2364 | // the null pointer value of the destination type. | |||
2365 | // | |||
2366 | // Note that we do not check for ambiguity or inaccessibility | |||
2367 | // here. That is handled by CheckPointerConversion. | |||
2368 | if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && | |||
2369 | ToPointeeType->isRecordType() && | |||
2370 | !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && | |||
2371 | IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { | |||
2372 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, | |||
2373 | ToPointeeType, | |||
2374 | ToType, Context); | |||
2375 | return true; | |||
2376 | } | |||
2377 | ||||
2378 | if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && | |||
2379 | Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { | |||
2380 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, | |||
2381 | ToPointeeType, | |||
2382 | ToType, Context); | |||
2383 | return true; | |||
2384 | } | |||
2385 | ||||
2386 | return false; | |||
2387 | } | |||
2388 | ||||
2389 | /// Adopt the given qualifiers for the given type. | |||
2390 | static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ | |||
2391 | Qualifiers TQs = T.getQualifiers(); | |||
2392 | ||||
2393 | // Check whether qualifiers already match. | |||
2394 | if (TQs == Qs) | |||
2395 | return T; | |||
2396 | ||||
2397 | if (Qs.compatiblyIncludes(TQs)) | |||
2398 | return Context.getQualifiedType(T, Qs); | |||
2399 | ||||
2400 | return Context.getQualifiedType(T.getUnqualifiedType(), Qs); | |||
2401 | } | |||
2402 | ||||
2403 | /// isObjCPointerConversion - Determines whether this is an | |||
2404 | /// Objective-C pointer conversion. Subroutine of IsPointerConversion, | |||
2405 | /// with the same arguments and return values. | |||
2406 | bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, | |||
2407 | QualType& ConvertedType, | |||
2408 | bool &IncompatibleObjC) { | |||
2409 | if (!getLangOpts().ObjC) | |||
2410 | return false; | |||
2411 | ||||
2412 | // The set of qualifiers on the type we're converting from. | |||
2413 | Qualifiers FromQualifiers = FromType.getQualifiers(); | |||
2414 | ||||
2415 | // First, we handle all conversions on ObjC object pointer types. | |||
2416 | const ObjCObjectPointerType* ToObjCPtr = | |||
2417 | ToType->getAs<ObjCObjectPointerType>(); | |||
2418 | const ObjCObjectPointerType *FromObjCPtr = | |||
2419 | FromType->getAs<ObjCObjectPointerType>(); | |||
2420 | ||||
2421 | if (ToObjCPtr && FromObjCPtr) { | |||
2422 | // If the pointee types are the same (ignoring qualifications), | |||
2423 | // then this is not a pointer conversion. | |||
2424 | if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), | |||
2425 | FromObjCPtr->getPointeeType())) | |||
2426 | return false; | |||
2427 | ||||
2428 | // Conversion between Objective-C pointers. | |||
2429 | if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { | |||
2430 | const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); | |||
2431 | const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); | |||
2432 | if (getLangOpts().CPlusPlus && LHS && RHS && | |||
2433 | !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( | |||
2434 | FromObjCPtr->getPointeeType())) | |||
2435 | return false; | |||
2436 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, | |||
2437 | ToObjCPtr->getPointeeType(), | |||
2438 | ToType, Context); | |||
2439 | ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); | |||
2440 | return true; | |||
2441 | } | |||
2442 | ||||
2443 | if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { | |||
2444 | // Okay: this is some kind of implicit downcast of Objective-C | |||
2445 | // interfaces, which is permitted. However, we're going to | |||
2446 | // complain about it. | |||
2447 | IncompatibleObjC = true; | |||
2448 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, | |||
2449 | ToObjCPtr->getPointeeType(), | |||
2450 | ToType, Context); | |||
2451 | ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); | |||
2452 | return true; | |||
2453 | } | |||
2454 | } | |||
2455 | // Beyond this point, both types need to be C pointers or block pointers. | |||
2456 | QualType ToPointeeType; | |||
2457 | if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) | |||
2458 | ToPointeeType = ToCPtr->getPointeeType(); | |||
2459 | else if (const BlockPointerType *ToBlockPtr = | |||
2460 | ToType->getAs<BlockPointerType>()) { | |||
2461 | // Objective C++: We're able to convert from a pointer to any object | |||
2462 | // to a block pointer type. | |||
2463 | if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { | |||
2464 | ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); | |||
2465 | return true; | |||
2466 | } | |||
2467 | ToPointeeType = ToBlockPtr->getPointeeType(); | |||
2468 | } | |||
2469 | else if (FromType->getAs<BlockPointerType>() && | |||
2470 | ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { | |||
2471 | // Objective C++: We're able to convert from a block pointer type to a | |||
2472 | // pointer to any object. | |||
2473 | ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); | |||
2474 | return true; | |||
2475 | } | |||
2476 | else | |||
2477 | return false; | |||
2478 | ||||
2479 | QualType FromPointeeType; | |||
2480 | if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) | |||
2481 | FromPointeeType = FromCPtr->getPointeeType(); | |||
2482 | else if (const BlockPointerType *FromBlockPtr = | |||
2483 | FromType->getAs<BlockPointerType>()) | |||
2484 | FromPointeeType = FromBlockPtr->getPointeeType(); | |||
2485 | else | |||
2486 | return false; | |||
2487 | ||||
2488 | // If we have pointers to pointers, recursively check whether this | |||
2489 | // is an Objective-C conversion. | |||
2490 | if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && | |||
2491 | isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, | |||
2492 | IncompatibleObjC)) { | |||
2493 | // We always complain about this conversion. | |||
2494 | IncompatibleObjC = true; | |||
2495 | ConvertedType = Context.getPointerType(ConvertedType); | |||
2496 | ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); | |||
2497 | return true; | |||
2498 | } | |||
2499 | // Allow conversion of pointee being objective-c pointer to another one; | |||
2500 | // as in I* to id. | |||
2501 | if (FromPointeeType->getAs<ObjCObjectPointerType>() && | |||
2502 | ToPointeeType->getAs<ObjCObjectPointerType>() && | |||
2503 | isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, | |||
2504 | IncompatibleObjC)) { | |||
2505 | ||||
2506 | ConvertedType = Context.getPointerType(ConvertedType); | |||
2507 | ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); | |||
2508 | return true; | |||
2509 | } | |||
2510 | ||||
2511 | // If we have pointers to functions or blocks, check whether the only | |||
2512 | // differences in the argument and result types are in Objective-C | |||
2513 | // pointer conversions. If so, we permit the conversion (but | |||
2514 | // complain about it). | |||
2515 | const FunctionProtoType *FromFunctionType | |||
2516 | = FromPointeeType->getAs<FunctionProtoType>(); | |||
2517 | const FunctionProtoType *ToFunctionType | |||
2518 | = ToPointeeType->getAs<FunctionProtoType>(); | |||
2519 | if (FromFunctionType && ToFunctionType) { | |||
2520 | // If the function types are exactly the same, this isn't an | |||
2521 | // Objective-C pointer conversion. | |||
2522 | if (Context.getCanonicalType(FromPointeeType) | |||
2523 | == Context.getCanonicalType(ToPointeeType)) | |||
2524 | return false; | |||
2525 | ||||
2526 | // Perform the quick checks that will tell us whether these | |||
2527 | // function types are obviously different. | |||
2528 | if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || | |||
2529 | FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || | |||
2530 | FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) | |||
2531 | return false; | |||
2532 | ||||
2533 | bool HasObjCConversion = false; | |||
2534 | if (Context.getCanonicalType(FromFunctionType->getReturnType()) == | |||
2535 | Context.getCanonicalType(ToFunctionType->getReturnType())) { | |||
2536 | // Okay, the types match exactly. Nothing to do. | |||
2537 | } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), | |||
2538 | ToFunctionType->getReturnType(), | |||
2539 | ConvertedType, IncompatibleObjC)) { | |||
2540 | // Okay, we have an Objective-C pointer conversion. | |||
2541 | HasObjCConversion = true; | |||
2542 | } else { | |||
2543 | // Function types are too different. Abort. | |||
2544 | return false; | |||
2545 | } | |||
2546 | ||||
2547 | // Check argument types. | |||
2548 | for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); | |||
2549 | ArgIdx != NumArgs; ++ArgIdx) { | |||
2550 | QualType FromArgType = FromFunctionType->getParamType(ArgIdx); | |||
2551 | QualType ToArgType = ToFunctionType->getParamType(ArgIdx); | |||
2552 | if (Context.getCanonicalType(FromArgType) | |||
2553 | == Context.getCanonicalType(ToArgType)) { | |||
2554 | // Okay, the types match exactly. Nothing to do. | |||
2555 | } else if (isObjCPointerConversion(FromArgType, ToArgType, | |||
2556 | ConvertedType, IncompatibleObjC)) { | |||
2557 | // Okay, we have an Objective-C pointer conversion. | |||
2558 | HasObjCConversion = true; | |||
2559 | } else { | |||
2560 | // Argument types are too different. Abort. | |||
2561 | return false; | |||
2562 | } | |||
2563 | } | |||
2564 | ||||
2565 | if (HasObjCConversion) { | |||
2566 | // We had an Objective-C conversion. Allow this pointer | |||
2567 | // conversion, but complain about it. | |||
2568 | ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); | |||
2569 | IncompatibleObjC = true; | |||
2570 | return true; | |||
2571 | } | |||
2572 | } | |||
2573 | ||||
2574 | return false; | |||
2575 | } | |||
2576 | ||||
2577 | /// Determine whether this is an Objective-C writeback conversion, | |||
2578 | /// used for parameter passing when performing automatic reference counting. | |||
2579 | /// | |||
2580 | /// \param FromType The type we're converting form. | |||
2581 | /// | |||
2582 | /// \param ToType The type we're converting to. | |||
2583 | /// | |||
2584 | /// \param ConvertedType The type that will be produced after applying | |||
2585 | /// this conversion. | |||
2586 | bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, | |||
2587 | QualType &ConvertedType) { | |||
2588 | if (!getLangOpts().ObjCAutoRefCount || | |||
2589 | Context.hasSameUnqualifiedType(FromType, ToType)) | |||
2590 | return false; | |||
2591 | ||||
2592 | // Parameter must be a pointer to __autoreleasing (with no other qualifiers). | |||
2593 | QualType ToPointee; | |||
2594 | if (const PointerType *ToPointer = ToType->getAs<PointerType>()) | |||
2595 | ToPointee = ToPointer->getPointeeType(); | |||
2596 | else | |||
2597 | return false; | |||
2598 | ||||
2599 | Qualifiers ToQuals = ToPointee.getQualifiers(); | |||
2600 | if (!ToPointee->isObjCLifetimeType() || | |||
2601 | ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || | |||
2602 | !ToQuals.withoutObjCLifetime().empty()) | |||
2603 | return false; | |||
2604 | ||||
2605 | // Argument must be a pointer to __strong to __weak. | |||
2606 | QualType FromPointee; | |||
2607 | if (const PointerType *FromPointer = FromType->getAs<PointerType>()) | |||
2608 | FromPointee = FromPointer->getPointeeType(); | |||
2609 | else | |||
2610 | return false; | |||
2611 | ||||
2612 | Qualifiers FromQuals = FromPointee.getQualifiers(); | |||
2613 | if (!FromPointee->isObjCLifetimeType() || | |||
2614 | (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && | |||
2615 | FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) | |||
2616 | return false; | |||
2617 | ||||
2618 | // Make sure that we have compatible qualifiers. | |||
2619 | FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); | |||
2620 | if (!ToQuals.compatiblyIncludes(FromQuals)) | |||
2621 | return false; | |||
2622 | ||||
2623 | // Remove qualifiers from the pointee type we're converting from; they | |||
2624 | // aren't used in the compatibility check belong, and we'll be adding back | |||
2625 | // qualifiers (with __autoreleasing) if the compatibility check succeeds. | |||
2626 | FromPointee = FromPointee.getUnqualifiedType(); | |||
2627 | ||||
2628 | // The unqualified form of the pointee types must be compatible. | |||
2629 | ToPointee = ToPointee.getUnqualifiedType(); | |||
2630 | bool IncompatibleObjC; | |||
2631 | if (Context.typesAreCompatible(FromPointee, ToPointee)) | |||
2632 | FromPointee = ToPointee; | |||
2633 | else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, | |||
2634 | IncompatibleObjC)) | |||
2635 | return false; | |||
2636 | ||||
2637 | /// Construct the type we're converting to, which is a pointer to | |||
2638 | /// __autoreleasing pointee. | |||
2639 | FromPointee = Context.getQualifiedType(FromPointee, FromQuals); | |||
2640 | ConvertedType = Context.getPointerType(FromPointee); | |||
2641 | return true; | |||
2642 | } | |||
2643 | ||||
2644 | bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, | |||
2645 | QualType& ConvertedType) { | |||
2646 | QualType ToPointeeType; | |||
2647 | if (const BlockPointerType *ToBlockPtr = | |||
2648 | ToType->getAs<BlockPointerType>()) | |||
2649 | ToPointeeType = ToBlockPtr->getPointeeType(); | |||
2650 | else | |||
2651 | return false; | |||
2652 | ||||
2653 | QualType FromPointeeType; | |||
2654 | if (const BlockPointerType *FromBlockPtr = | |||
2655 | FromType->getAs<BlockPointerType>()) | |||
2656 | FromPointeeType = FromBlockPtr->getPointeeType(); | |||
2657 | else | |||
2658 | return false; | |||
2659 | // We have pointer to blocks, check whether the only | |||
2660 | // differences in the argument and result types are in Objective-C | |||
2661 | // pointer conversions. If so, we permit the conversion. | |||
2662 | ||||
2663 | const FunctionProtoType *FromFunctionType | |||
2664 | = FromPointeeType->getAs<FunctionProtoType>(); | |||
2665 | const FunctionProtoType *ToFunctionType | |||
2666 | = ToPointeeType->getAs<FunctionProtoType>(); | |||
2667 | ||||
2668 | if (!FromFunctionType || !ToFunctionType) | |||
2669 | return false; | |||
2670 | ||||
2671 | if (Context.hasSameType(FromPointeeType, ToPointeeType)) | |||
2672 | return true; | |||
2673 | ||||
2674 | // Perform the quick checks that will tell us whether these | |||
2675 | // function types are obviously different. | |||
2676 | if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || | |||
2677 | FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) | |||
2678 | return false; | |||
2679 | ||||
2680 | FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); | |||
2681 | FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); | |||
2682 | if (FromEInfo != ToEInfo) | |||
2683 | return false; | |||
2684 | ||||
2685 | bool IncompatibleObjC = false; | |||
2686 | if (Context.hasSameType(FromFunctionType->getReturnType(), | |||
2687 | ToFunctionType->getReturnType())) { | |||
2688 | // Okay, the types match exactly. Nothing to do. | |||
2689 | } else { | |||
2690 | QualType RHS = FromFunctionType->getReturnType(); | |||
2691 | QualType LHS = ToFunctionType->getReturnType(); | |||
2692 | if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && | |||
2693 | !RHS.hasQualifiers() && LHS.hasQualifiers()) | |||
2694 | LHS = LHS.getUnqualifiedType(); | |||
2695 | ||||
2696 | if (Context.hasSameType(RHS,LHS)) { | |||
2697 | // OK exact match. | |||
2698 | } else if (isObjCPointerConversion(RHS, LHS, | |||
2699 | ConvertedType, IncompatibleObjC)) { | |||
2700 | if (IncompatibleObjC) | |||
2701 | return false; | |||
2702 | // Okay, we have an Objective-C pointer conversion. | |||
2703 | } | |||
2704 | else | |||
2705 | return false; | |||
2706 | } | |||
2707 | ||||
2708 | // Check argument types. | |||
2709 | for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); | |||
2710 | ArgIdx != NumArgs; ++ArgIdx) { | |||
2711 | IncompatibleObjC = false; | |||
2712 | QualType FromArgType = FromFunctionType->getParamType(ArgIdx); | |||
2713 | QualType ToArgType = ToFunctionType->getParamType(ArgIdx); | |||
2714 | if (Context.hasSameType(FromArgType, ToArgType)) { | |||
2715 | // Okay, the types match exactly. Nothing to do. | |||
2716 | } else if (isObjCPointerConversion(ToArgType, FromArgType, | |||
2717 | ConvertedType, IncompatibleObjC)) { | |||
2718 | if (IncompatibleObjC) | |||
2719 | return false; | |||
2720 | // Okay, we have an Objective-C pointer conversion. | |||
2721 | } else | |||
2722 | // Argument types are too different. Abort. | |||
2723 | return false; | |||
2724 | } | |||
2725 | ||||
2726 | SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; | |||
2727 | bool CanUseToFPT, CanUseFromFPT; | |||
2728 | if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, | |||
2729 | CanUseToFPT, CanUseFromFPT, | |||
2730 | NewParamInfos)) | |||
2731 | return false; | |||
2732 | ||||
2733 | ConvertedType = ToType; | |||
2734 | return true; | |||
2735 | } | |||
2736 | ||||
2737 | enum { | |||
2738 | ft_default, | |||
2739 | ft_different_class, | |||
2740 | ft_parameter_arity, | |||
2741 | ft_parameter_mismatch, | |||
2742 | ft_return_type, | |||
2743 | ft_qualifer_mismatch, | |||
2744 | ft_noexcept | |||
2745 | }; | |||
2746 | ||||
2747 | /// Attempts to get the FunctionProtoType from a Type. Handles | |||
2748 | /// MemberFunctionPointers properly. | |||
2749 | static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { | |||
2750 | if (auto *FPT = FromType->getAs<FunctionProtoType>()) | |||
2751 | return FPT; | |||
2752 | ||||
2753 | if (auto *MPT = FromType->getAs<MemberPointerType>()) | |||
2754 | return MPT->getPointeeType()->getAs<FunctionProtoType>(); | |||
2755 | ||||
2756 | return nullptr; | |||
2757 | } | |||
2758 | ||||
2759 | /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing | |||
2760 | /// function types. Catches different number of parameter, mismatch in | |||
2761 | /// parameter types, and different return types. | |||
2762 | void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, | |||
2763 | QualType FromType, QualType ToType) { | |||
2764 | // If either type is not valid, include no extra info. | |||
2765 | if (FromType.isNull() || ToType.isNull()) { | |||
2766 | PDiag << ft_default; | |||
2767 | return; | |||
2768 | } | |||
2769 | ||||
2770 | // Get the function type from the pointers. | |||
2771 | if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { | |||
2772 | const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), | |||
2773 | *ToMember = ToType->getAs<MemberPointerType>(); | |||
2774 | if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { | |||
2775 | PDiag << ft_different_class << QualType(ToMember->getClass(), 0) | |||
2776 | << QualType(FromMember->getClass(), 0); | |||
2777 | return; | |||
2778 | } | |||
2779 | FromType = FromMember->getPointeeType(); | |||
2780 | ToType = ToMember->getPointeeType(); | |||
2781 | } | |||
2782 | ||||
2783 | if (FromType->isPointerType()) | |||
2784 | FromType = FromType->getPointeeType(); | |||
2785 | if (ToType->isPointerType()) | |||
2786 | ToType = ToType->getPointeeType(); | |||
2787 | ||||
2788 | // Remove references. | |||
2789 | FromType = FromType.getNonReferenceType(); | |||
2790 | ToType = ToType.getNonReferenceType(); | |||
2791 | ||||
2792 | // Don't print extra info for non-specialized template functions. | |||
2793 | if (FromType->isInstantiationDependentType() && | |||
2794 | !FromType->getAs<TemplateSpecializationType>()) { | |||
2795 | PDiag << ft_default; | |||
2796 | return; | |||
2797 | } | |||
2798 | ||||
2799 | // No extra info for same types. | |||
2800 | if (Context.hasSameType(FromType, ToType)) { | |||
2801 | PDiag << ft_default; | |||
2802 | return; | |||
2803 | } | |||
2804 | ||||
2805 | const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), | |||
2806 | *ToFunction = tryGetFunctionProtoType(ToType); | |||
2807 | ||||
2808 | // Both types need to be function types. | |||
2809 | if (!FromFunction || !ToFunction) { | |||
2810 | PDiag << ft_default; | |||
2811 | return; | |||
2812 | } | |||
2813 | ||||
2814 | if (FromFunction->getNumParams() != ToFunction->getNumParams()) { | |||
2815 | PDiag << ft_parameter_arity << ToFunction->getNumParams() | |||
2816 | << FromFunction->getNumParams(); | |||
2817 | return; | |||
2818 | } | |||
2819 | ||||
2820 | // Handle different parameter types. | |||
2821 | unsigned ArgPos; | |||
2822 | if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { | |||
2823 | PDiag << ft_parameter_mismatch << ArgPos + 1 | |||
2824 | << ToFunction->getParamType(ArgPos) | |||
2825 | << FromFunction->getParamType(ArgPos); | |||
2826 | return; | |||
2827 | } | |||
2828 | ||||
2829 | // Handle different return type. | |||
2830 | if (!Context.hasSameType(FromFunction->getReturnType(), | |||
2831 | ToFunction->getReturnType())) { | |||
2832 | PDiag << ft_return_type << ToFunction->getReturnType() | |||
2833 | << FromFunction->getReturnType(); | |||
2834 | return; | |||
2835 | } | |||
2836 | ||||
2837 | if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { | |||
2838 | PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() | |||
2839 | << FromFunction->getMethodQuals(); | |||
2840 | return; | |||
2841 | } | |||
2842 | ||||
2843 | // Handle exception specification differences on canonical type (in C++17 | |||
2844 | // onwards). | |||
2845 | if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) | |||
2846 | ->isNothrow() != | |||
2847 | cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) | |||
2848 | ->isNothrow()) { | |||
2849 | PDiag << ft_noexcept; | |||
2850 | return; | |||
2851 | } | |||
2852 | ||||
2853 | // Unable to find a difference, so add no extra info. | |||
2854 | PDiag << ft_default; | |||
2855 | } | |||
2856 | ||||
2857 | /// FunctionParamTypesAreEqual - This routine checks two function proto types | |||
2858 | /// for equality of their argument types. Caller has already checked that | |||
2859 | /// they have same number of arguments. If the parameters are different, | |||
2860 | /// ArgPos will have the parameter index of the first different parameter. | |||
2861 | bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, | |||
2862 | const FunctionProtoType *NewType, | |||
2863 | unsigned *ArgPos) { | |||
2864 | for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), | |||
2865 | N = NewType->param_type_begin(), | |||
2866 | E = OldType->param_type_end(); | |||
2867 | O && (O != E); ++O, ++N) { | |||
2868 | if (!Context.hasSameType(O->getUnqualifiedType(), | |||
2869 | N->getUnqualifiedType())) { | |||
2870 | if (ArgPos) | |||
2871 | *ArgPos = O - OldType->param_type_begin(); | |||
2872 | return false; | |||
2873 | } | |||
2874 | } | |||
2875 | return true; | |||
2876 | } | |||
2877 | ||||
2878 | /// CheckPointerConversion - Check the pointer conversion from the | |||
2879 | /// expression From to the type ToType. This routine checks for | |||
2880 | /// ambiguous or inaccessible derived-to-base pointer | |||
2881 | /// conversions for which IsPointerConversion has already returned | |||
2882 | /// true. It returns true and produces a diagnostic if there was an | |||
2883 | /// error, or returns false otherwise. | |||
2884 | bool Sema::CheckPointerConversion(Expr *From, QualType ToType, | |||
2885 | CastKind &Kind, | |||
2886 | CXXCastPath& BasePath, | |||
2887 | bool IgnoreBaseAccess, | |||
2888 | bool Diagnose) { | |||
2889 | QualType FromType = From->getType(); | |||
2890 | bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; | |||
2891 | ||||
2892 | Kind = CK_BitCast; | |||
2893 | ||||
2894 | if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && | |||
2895 | From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == | |||
2896 | Expr::NPCK_ZeroExpression) { | |||
2897 | if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) | |||
2898 | DiagRuntimeBehavior(From->getExprLoc(), From, | |||
2899 | PDiag(diag::warn_impcast_bool_to_null_pointer) | |||
2900 | << ToType << From->getSourceRange()); | |||
2901 | else if (!isUnevaluatedContext()) | |||
2902 | Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) | |||
2903 | << ToType << From->getSourceRange(); | |||
2904 | } | |||
2905 | if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { | |||
2906 | if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { | |||
2907 | QualType FromPointeeType = FromPtrType->getPointeeType(), | |||
2908 | ToPointeeType = ToPtrType->getPointeeType(); | |||
2909 | ||||
2910 | if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && | |||
2911 | !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { | |||
2912 | // We must have a derived-to-base conversion. Check an | |||
2913 | // ambiguous or inaccessible conversion. | |||
2914 | unsigned InaccessibleID = 0; | |||
2915 | unsigned AmbigiousID = 0; | |||
2916 | if (Diagnose) { | |||
2917 | InaccessibleID = diag::err_upcast_to_inaccessible_base; | |||
2918 | AmbigiousID = diag::err_ambiguous_derived_to_base_conv; | |||
2919 | } | |||
2920 | if (CheckDerivedToBaseConversion( | |||
2921 | FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, | |||
2922 | From->getExprLoc(), From->getSourceRange(), DeclarationName(), | |||
2923 | &BasePath, IgnoreBaseAccess)) | |||
2924 | return true; | |||
2925 | ||||
2926 | // The conversion was successful. | |||
2927 | Kind = CK_DerivedToBase; | |||
2928 | } | |||
2929 | ||||
2930 | if (Diagnose && !IsCStyleOrFunctionalCast && | |||
2931 | FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { | |||
2932 | assert(getLangOpts().MSVCCompat &&((getLangOpts().MSVCCompat && "this should only be possible with MSVCCompat!" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 2933, __PRETTY_FUNCTION__)) | |||
2933 | "this should only be possible with MSVCCompat!")((getLangOpts().MSVCCompat && "this should only be possible with MSVCCompat!" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 2933, __PRETTY_FUNCTION__)); | |||
2934 | Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) | |||
2935 | << From->getSourceRange(); | |||
2936 | } | |||
2937 | } | |||
2938 | } else if (const ObjCObjectPointerType *ToPtrType = | |||
2939 | ToType->getAs<ObjCObjectPointerType>()) { | |||
2940 | if (const ObjCObjectPointerType *FromPtrType = | |||
2941 | FromType->getAs<ObjCObjectPointerType>()) { | |||
2942 | // Objective-C++ conversions are always okay. | |||
2943 | // FIXME: We should have a different class of conversions for the | |||
2944 | // Objective-C++ implicit conversions. | |||
2945 | if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) | |||
2946 | return false; | |||
2947 | } else if (FromType->isBlockPointerType()) { | |||
2948 | Kind = CK_BlockPointerToObjCPointerCast; | |||
2949 | } else { | |||
2950 | Kind = CK_CPointerToObjCPointerCast; | |||
2951 | } | |||
2952 | } else if (ToType->isBlockPointerType()) { | |||
2953 | if (!FromType->isBlockPointerType()) | |||
2954 | Kind = CK_AnyPointerToBlockPointerCast; | |||
2955 | } | |||
2956 | ||||
2957 | // We shouldn't fall into this case unless it's valid for other | |||
2958 | // reasons. | |||
2959 | if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) | |||
2960 | Kind = CK_NullToPointer; | |||
2961 | ||||
2962 | return false; | |||
2963 | } | |||
2964 | ||||
2965 | /// IsMemberPointerConversion - Determines whether the conversion of the | |||
2966 | /// expression From, which has the (possibly adjusted) type FromType, can be | |||
2967 | /// converted to the type ToType via a member pointer conversion (C++ 4.11). | |||
2968 | /// If so, returns true and places the converted type (that might differ from | |||
2969 | /// ToType in its cv-qualifiers at some level) into ConvertedType. | |||
2970 | bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, | |||
2971 | QualType ToType, | |||
2972 | bool InOverloadResolution, | |||
2973 | QualType &ConvertedType) { | |||
2974 | const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); | |||
2975 | if (!ToTypePtr) | |||
2976 | return false; | |||
2977 | ||||
2978 | // A null pointer constant can be converted to a member pointer (C++ 4.11p1) | |||
2979 | if (From->isNullPointerConstant(Context, | |||
2980 | InOverloadResolution? Expr::NPC_ValueDependentIsNotNull | |||
2981 | : Expr::NPC_ValueDependentIsNull)) { | |||
2982 | ConvertedType = ToType; | |||
2983 | return true; | |||
2984 | } | |||
2985 | ||||
2986 | // Otherwise, both types have to be member pointers. | |||
2987 | const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); | |||
2988 | if (!FromTypePtr) | |||
2989 | return false; | |||
2990 | ||||
2991 | // A pointer to member of B can be converted to a pointer to member of D, | |||
2992 | // where D is derived from B (C++ 4.11p2). | |||
2993 | QualType FromClass(FromTypePtr->getClass(), 0); | |||
2994 | QualType ToClass(ToTypePtr->getClass(), 0); | |||
2995 | ||||
2996 | if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && | |||
2997 | IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { | |||
2998 | ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), | |||
2999 | ToClass.getTypePtr()); | |||
3000 | return true; | |||
3001 | } | |||
3002 | ||||
3003 | return false; | |||
3004 | } | |||
3005 | ||||
3006 | /// CheckMemberPointerConversion - Check the member pointer conversion from the | |||
3007 | /// expression From to the type ToType. This routine checks for ambiguous or | |||
3008 | /// virtual or inaccessible base-to-derived member pointer conversions | |||
3009 | /// for which IsMemberPointerConversion has already returned true. It returns | |||
3010 | /// true and produces a diagnostic if there was an error, or returns false | |||
3011 | /// otherwise. | |||
3012 | bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, | |||
3013 | CastKind &Kind, | |||
3014 | CXXCastPath &BasePath, | |||
3015 | bool IgnoreBaseAccess) { | |||
3016 | QualType FromType = From->getType(); | |||
3017 | const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); | |||
3018 | if (!FromPtrType) { | |||
3019 | // This must be a null pointer to member pointer conversion | |||
3020 | assert(From->isNullPointerConstant(Context,((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull ) && "Expr must be null pointer constant!") ? static_cast <void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 3022, __PRETTY_FUNCTION__)) | |||
3021 | Expr::NPC_ValueDependentIsNull) &&((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull ) && "Expr must be null pointer constant!") ? static_cast <void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 3022, __PRETTY_FUNCTION__)) | |||
3022 | "Expr must be null pointer constant!")((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull ) && "Expr must be null pointer constant!") ? static_cast <void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 3022, __PRETTY_FUNCTION__)); | |||
3023 | Kind = CK_NullToMemberPointer; | |||
3024 | return false; | |||
3025 | } | |||
3026 | ||||
3027 | const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); | |||
3028 | assert(ToPtrType && "No member pointer cast has a target type "((ToPtrType && "No member pointer cast has a target type " "that is not a member pointer.") ? static_cast<void> ( 0) : __assert_fail ("ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 3029, __PRETTY_FUNCTION__)) | |||
3029 | "that is not a member pointer.")((ToPtrType && "No member pointer cast has a target type " "that is not a member pointer.") ? static_cast<void> ( 0) : __assert_fail ("ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 3029, __PRETTY_FUNCTION__)); | |||
3030 | ||||
3031 | QualType FromClass = QualType(FromPtrType->getClass(), 0); | |||
3032 | QualType ToClass = QualType(ToPtrType->getClass(), 0); | |||
3033 | ||||
3034 | // FIXME: What about dependent types? | |||
3035 | assert(FromClass->isRecordType() && "Pointer into non-class.")((FromClass->isRecordType() && "Pointer into non-class." ) ? static_cast<void> (0) : __assert_fail ("FromClass->isRecordType() && \"Pointer into non-class.\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 3035, __PRETTY_FUNCTION__)); | |||
3036 | assert(ToClass->isRecordType() && "Pointer into non-class.")((ToClass->isRecordType() && "Pointer into non-class." ) ? static_cast<void> (0) : __assert_fail ("ToClass->isRecordType() && \"Pointer into non-class.\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 3036, __PRETTY_FUNCTION__)); | |||
3037 | ||||
3038 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, | |||
3039 | /*DetectVirtual=*/true); | |||
3040 | bool DerivationOkay = | |||
3041 | IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); | |||
3042 | assert(DerivationOkay &&((DerivationOkay && "Should not have been called if derivation isn't OK." ) ? static_cast<void> (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 3043, __PRETTY_FUNCTION__)) | |||
3043 | "Should not have been called if derivation isn't OK.")((DerivationOkay && "Should not have been called if derivation isn't OK." ) ? static_cast<void> (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 3043, __PRETTY_FUNCTION__)); | |||
3044 | (void)DerivationOkay; | |||
3045 | ||||
3046 | if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). | |||
3047 | getUnqualifiedType())) { | |||
3048 | std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); | |||
3049 | Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) | |||
3050 | << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); | |||
3051 | return true; | |||
3052 | } | |||
3053 | ||||
3054 | if (const RecordType *VBase = Paths.getDetectedVirtual()) { | |||
3055 | Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) | |||
3056 | << FromClass << ToClass << QualType(VBase, 0) | |||
3057 | << From->getSourceRange(); | |||
3058 | return true; | |||
3059 | } | |||
3060 | ||||
3061 | if (!IgnoreBaseAccess) | |||
3062 | CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, | |||
3063 | Paths.front(), | |||
3064 | diag::err_downcast_from_inaccessible_base); | |||
3065 | ||||
3066 | // Must be a base to derived member conversion. | |||
3067 | BuildBasePathArray(Paths, BasePath); | |||
3068 | Kind = CK_BaseToDerivedMemberPointer; | |||
3069 | return false; | |||
3070 | } | |||
3071 | ||||
3072 | /// Determine whether the lifetime conversion between the two given | |||
3073 | /// qualifiers sets is nontrivial. | |||
3074 | static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, | |||
3075 | Qualifiers ToQuals) { | |||
3076 | // Converting anything to const __unsafe_unretained is trivial. | |||
3077 | if (ToQuals.hasConst() && | |||
3078 | ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) | |||
3079 | return false; | |||
3080 | ||||
3081 | return true; | |||
3082 | } | |||
3083 | ||||
3084 | /// IsQualificationConversion - Determines whether the conversion from | |||
3085 | /// an rvalue of type FromType to ToType is a qualification conversion | |||
3086 | /// (C++ 4.4). | |||
3087 | /// | |||
3088 | /// \param ObjCLifetimeConversion Output parameter that will be set to indicate | |||
3089 | /// when the qualification conversion involves a change in the Objective-C | |||
3090 | /// object lifetime. | |||
3091 | bool | |||
3092 | Sema::IsQualificationConversion(QualType FromType, QualType ToType, | |||
3093 | bool CStyle, bool &ObjCLifetimeConversion) { | |||
3094 | FromType = Context.getCanonicalType(FromType); | |||
3095 | ToType = Context.getCanonicalType(ToType); | |||
3096 | ObjCLifetimeConversion = false; | |||
3097 | ||||
3098 | // If FromType and ToType are the same type, this is not a | |||
3099 | // qualification conversion. | |||
3100 | if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) | |||
3101 | return false; | |||
3102 | ||||
3103 | // (C++ 4.4p4): | |||
3104 | // A conversion can add cv-qualifiers at levels other than the first | |||
3105 | // in multi-level pointers, subject to the following rules: [...] | |||
3106 | bool PreviousToQualsIncludeConst = true; | |||
3107 | bool UnwrappedAnyPointer = false; | |||
3108 | while (Context.UnwrapSimilarTypes(FromType, ToType)) { | |||
3109 | // Within each iteration of the loop, we check the qualifiers to | |||
3110 | // determine if this still looks like a qualification | |||
3111 | // conversion. Then, if all is well, we unwrap one more level of | |||
3112 | // pointers or pointers-to-members and do it all again | |||
3113 | // until there are no more pointers or pointers-to-members left to | |||
3114 | // unwrap. | |||
3115 | UnwrappedAnyPointer = true; | |||
3116 | ||||
3117 | Qualifiers FromQuals = FromType.getQualifiers(); | |||
3118 | Qualifiers ToQuals = ToType.getQualifiers(); | |||
3119 | ||||
3120 | // Ignore __unaligned qualifier if this type is void. | |||
3121 | if (ToType.getUnqualifiedType()->isVoidType()) | |||
3122 | FromQuals.removeUnaligned(); | |||
3123 | ||||
3124 | // Objective-C ARC: | |||
3125 | // Check Objective-C lifetime conversions. | |||
3126 | if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && | |||
3127 | UnwrappedAnyPointer) { | |||
3128 | if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { | |||
3129 | if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) | |||
3130 | ObjCLifetimeConversion = true; | |||
3131 | FromQuals.removeObjCLifetime(); | |||
3132 | ToQuals.removeObjCLifetime(); | |||
3133 | } else { | |||
3134 | // Qualification conversions cannot cast between different | |||
3135 | // Objective-C lifetime qualifiers. | |||
3136 | return false; | |||
3137 | } | |||
3138 | } | |||
3139 | ||||
3140 | // Allow addition/removal of GC attributes but not changing GC attributes. | |||
3141 | if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && | |||
3142 | (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { | |||
3143 | FromQuals.removeObjCGCAttr(); | |||
3144 | ToQuals.removeObjCGCAttr(); | |||
3145 | } | |||
3146 | ||||
3147 | // -- for every j > 0, if const is in cv 1,j then const is in cv | |||
3148 | // 2,j, and similarly for volatile. | |||
3149 | if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) | |||
3150 | return false; | |||
3151 | ||||
3152 | // -- if the cv 1,j and cv 2,j are different, then const is in | |||
3153 | // every cv for 0 < k < j. | |||
3154 | if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() | |||
3155 | && !PreviousToQualsIncludeConst) | |||
3156 | return false; | |||
3157 | ||||
3158 | // Keep track of whether all prior cv-qualifiers in the "to" type | |||
3159 | // include const. | |||
3160 | PreviousToQualsIncludeConst | |||
3161 | = PreviousToQualsIncludeConst && ToQuals.hasConst(); | |||
3162 | } | |||
3163 | ||||
3164 | // Allows address space promotion by language rules implemented in | |||
3165 | // Type::Qualifiers::isAddressSpaceSupersetOf. | |||
3166 | Qualifiers FromQuals = FromType.getQualifiers(); | |||
3167 | Qualifiers ToQuals = ToType.getQualifiers(); | |||
3168 | if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) && | |||
3169 | !FromQuals.isAddressSpaceSupersetOf(ToQuals)) { | |||
3170 | return false; | |||
3171 | } | |||
3172 | ||||
3173 | // We are left with FromType and ToType being the pointee types | |||
3174 | // after unwrapping the original FromType and ToType the same number | |||
3175 | // of types. If we unwrapped any pointers, and if FromType and | |||
3176 | // ToType have the same unqualified type (since we checked | |||
3177 | // qualifiers above), then this is a qualification conversion. | |||
3178 | return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); | |||
3179 | } | |||
3180 | ||||
3181 | /// - Determine whether this is a conversion from a scalar type to an | |||
3182 | /// atomic type. | |||
3183 | /// | |||
3184 | /// If successful, updates \c SCS's second and third steps in the conversion | |||
3185 | /// sequence to finish the conversion. | |||
3186 | static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, | |||
3187 | bool InOverloadResolution, | |||
3188 | StandardConversionSequence &SCS, | |||
3189 | bool CStyle) { | |||
3190 | const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); | |||
3191 | if (!ToAtomic) | |||
3192 | return false; | |||
3193 | ||||
3194 | StandardConversionSequence InnerSCS; | |||
3195 | if (!IsStandardConversion(S, From, ToAtomic->getValueType(), | |||
3196 | InOverloadResolution, InnerSCS, | |||
3197 | CStyle, /*AllowObjCWritebackConversion=*/false)) | |||
3198 | return false; | |||
3199 | ||||
3200 | SCS.Second = InnerSCS.Second; | |||
3201 | SCS.setToType(1, InnerSCS.getToType(1)); | |||
3202 | SCS.Third = InnerSCS.Third; | |||
3203 | SCS.QualificationIncludesObjCLifetime | |||
3204 | = InnerSCS.QualificationIncludesObjCLifetime; | |||
3205 | SCS.setToType(2, InnerSCS.getToType(2)); | |||
3206 | return true; | |||
3207 | } | |||
3208 | ||||
3209 | static bool isFirstArgumentCompatibleWithType(ASTContext &Context, | |||
3210 | CXXConstructorDecl *Constructor, | |||
3211 | QualType Type) { | |||
3212 | const FunctionProtoType *CtorType = | |||
3213 | Constructor->getType()->getAs<FunctionProtoType>(); | |||
3214 | if (CtorType->getNumParams() > 0) { | |||
3215 | QualType FirstArg = CtorType->getParamType(0); | |||
3216 | if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) | |||
3217 | return true; | |||
3218 | } | |||
3219 | return false; | |||
3220 | } | |||
3221 | ||||
3222 | static OverloadingResult | |||
3223 | IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, | |||
3224 | CXXRecordDecl *To, | |||
3225 | UserDefinedConversionSequence &User, | |||
3226 | OverloadCandidateSet &CandidateSet, | |||
3227 | bool AllowExplicit) { | |||
3228 | CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); | |||
3229 | for (auto *D : S.LookupConstructors(To)) { | |||
3230 | auto Info = getConstructorInfo(D); | |||
3231 | if (!Info) | |||
3232 | continue; | |||
3233 | ||||
3234 | bool Usable = !Info.Constructor->isInvalidDecl() && | |||
3235 | S.isInitListConstructor(Info.Constructor) && | |||
3236 | (AllowExplicit || !Info.Constructor->isExplicit()); | |||
3237 | if (Usable) { | |||
3238 | // If the first argument is (a reference to) the target type, | |||
3239 | // suppress conversions. | |||
3240 | bool SuppressUserConversions = isFirstArgumentCompatibleWithType( | |||
3241 | S.Context, Info.Constructor, ToType); | |||
3242 | if (Info.ConstructorTmpl) | |||
3243 | S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, | |||
3244 | /*ExplicitArgs*/ nullptr, From, | |||
3245 | CandidateSet, SuppressUserConversions, | |||
3246 | /*PartialOverloading*/ false, | |||
3247 | AllowExplicit); | |||
3248 | else | |||
3249 | S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, | |||
3250 | CandidateSet, SuppressUserConversions, | |||
3251 | /*PartialOverloading*/ false, AllowExplicit); | |||
3252 | } | |||
3253 | } | |||
3254 | ||||
3255 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | |||
3256 | ||||
3257 | OverloadCandidateSet::iterator Best; | |||
3258 | switch (auto Result = | |||
3259 | CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { | |||
3260 | case OR_Deleted: | |||
3261 | case OR_Success: { | |||
3262 | // Record the standard conversion we used and the conversion function. | |||
3263 | CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); | |||
3264 | QualType ThisType = Constructor->getThisType(); | |||
3265 | // Initializer lists don't have conversions as such. | |||
3266 | User.Before.setAsIdentityConversion(); | |||
3267 | User.HadMultipleCandidates = HadMultipleCandidates; | |||
3268 | User.ConversionFunction = Constructor; | |||
3269 | User.FoundConversionFunction = Best->FoundDecl; | |||
3270 | User.After.setAsIdentityConversion(); | |||
3271 | User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); | |||
3272 | User.After.setAllToTypes(ToType); | |||
3273 | return Result; | |||
3274 | } | |||
3275 | ||||
3276 | case OR_No_Viable_Function: | |||
3277 | return OR_No_Viable_Function; | |||
3278 | case OR_Ambiguous: | |||
3279 | return OR_Ambiguous; | |||
3280 | } | |||
3281 | ||||
3282 | llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 3282); | |||
3283 | } | |||
3284 | ||||
3285 | /// Determines whether there is a user-defined conversion sequence | |||
3286 | /// (C++ [over.ics.user]) that converts expression From to the type | |||
3287 | /// ToType. If such a conversion exists, User will contain the | |||
3288 | /// user-defined conversion sequence that performs such a conversion | |||
3289 | /// and this routine will return true. Otherwise, this routine returns | |||
3290 | /// false and User is unspecified. | |||
3291 | /// | |||
3292 | /// \param AllowExplicit true if the conversion should consider C++0x | |||
3293 | /// "explicit" conversion functions as well as non-explicit conversion | |||
3294 | /// functions (C++0x [class.conv.fct]p2). | |||
3295 | /// | |||
3296 | /// \param AllowObjCConversionOnExplicit true if the conversion should | |||
3297 | /// allow an extra Objective-C pointer conversion on uses of explicit | |||
3298 | /// constructors. Requires \c AllowExplicit to also be set. | |||
3299 | static OverloadingResult | |||
3300 | IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, | |||
3301 | UserDefinedConversionSequence &User, | |||
3302 | OverloadCandidateSet &CandidateSet, | |||
3303 | bool AllowExplicit, | |||
3304 | bool AllowObjCConversionOnExplicit) { | |||
3305 | assert(AllowExplicit || !AllowObjCConversionOnExplicit)((AllowExplicit || !AllowObjCConversionOnExplicit) ? static_cast <void> (0) : __assert_fail ("AllowExplicit || !AllowObjCConversionOnExplicit" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 3305, __PRETTY_FUNCTION__)); | |||
3306 | CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); | |||
3307 | ||||
3308 | // Whether we will only visit constructors. | |||
3309 | bool ConstructorsOnly = false; | |||
3310 | ||||
3311 | // If the type we are conversion to is a class type, enumerate its | |||
3312 | // constructors. | |||
3313 | if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { | |||
3314 | // C++ [over.match.ctor]p1: | |||
3315 | // When objects of class type are direct-initialized (8.5), or | |||
3316 | // copy-initialized from an expression of the same or a | |||
3317 | // derived class type (8.5), overload resolution selects the | |||
3318 | // constructor. [...] For copy-initialization, the candidate | |||
3319 | // functions are all the converting constructors (12.3.1) of | |||
3320 | // that class. The argument list is the expression-list within | |||
3321 | // the parentheses of the initializer. | |||
3322 | if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || | |||
3323 | (From->getType()->getAs<RecordType>() && | |||
3324 | S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) | |||
3325 | ConstructorsOnly = true; | |||
3326 | ||||
3327 | if (!S.isCompleteType(From->getExprLoc(), ToType)) { | |||
3328 | // We're not going to find any constructors. | |||
3329 | } else if (CXXRecordDecl *ToRecordDecl | |||
3330 | = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { | |||
3331 | ||||
3332 | Expr **Args = &From; | |||
3333 | unsigned NumArgs = 1; | |||
3334 | bool ListInitializing = false; | |||
3335 | if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { | |||
3336 | // But first, see if there is an init-list-constructor that will work. | |||
3337 | OverloadingResult Result = IsInitializerListConstructorConversion( | |||
3338 | S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); | |||
3339 | if (Result != OR_No_Viable_Function) | |||
3340 | return Result; | |||
3341 | // Never mind. | |||
3342 | CandidateSet.clear( | |||
3343 | OverloadCandidateSet::CSK_InitByUserDefinedConversion); | |||
3344 | ||||
3345 | // If we're list-initializing, we pass the individual elements as | |||
3346 | // arguments, not the entire list. | |||
3347 | Args = InitList->getInits(); | |||
3348 | NumArgs = InitList->getNumInits(); | |||
3349 | ListInitializing = true; | |||
3350 | } | |||
3351 | ||||
3352 | for (auto *D : S.LookupConstructors(ToRecordDecl)) { | |||
3353 | auto Info = getConstructorInfo(D); | |||
3354 | if (!Info) | |||
3355 | continue; | |||
3356 | ||||
3357 | bool Usable = !Info.Constructor->isInvalidDecl(); | |||
3358 | if (ListInitializing) | |||
3359 | Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); | |||
3360 | else | |||
3361 | Usable = Usable && | |||
3362 | Info.Constructor->isConvertingConstructor(AllowExplicit); | |||
3363 | if (Usable) { | |||
3364 | bool SuppressUserConversions = !ConstructorsOnly; | |||
3365 | if (SuppressUserConversions && ListInitializing) { | |||
3366 | SuppressUserConversions = false; | |||
3367 | if (NumArgs == 1) { | |||
3368 | // If the first argument is (a reference to) the target type, | |||
3369 | // suppress conversions. | |||
3370 | SuppressUserConversions = isFirstArgumentCompatibleWithType( | |||
3371 | S.Context, Info.Constructor, ToType); | |||
3372 | } | |||
3373 | } | |||
3374 | if (Info.ConstructorTmpl) | |||
3375 | S.AddTemplateOverloadCandidate( | |||
3376 | Info.ConstructorTmpl, Info.FoundDecl, | |||
3377 | /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), | |||
3378 | CandidateSet, SuppressUserConversions, | |||
3379 | /*PartialOverloading*/ false, AllowExplicit); | |||
3380 | else | |||
3381 | // Allow one user-defined conversion when user specifies a | |||
3382 | // From->ToType conversion via an static cast (c-style, etc). | |||
3383 | S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, | |||
3384 | llvm::makeArrayRef(Args, NumArgs), | |||
3385 | CandidateSet, SuppressUserConversions, | |||
3386 | /*PartialOverloading*/ false, AllowExplicit); | |||
3387 | } | |||
3388 | } | |||
3389 | } | |||
3390 | } | |||
3391 | ||||
3392 | // Enumerate conversion functions, if we're allowed to. | |||
3393 | if (ConstructorsOnly || isa<InitListExpr>(From)) { | |||
3394 | } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { | |||
3395 | // No conversion functions from incomplete types. | |||
3396 | } else if (const RecordType *FromRecordType = | |||
3397 | From->getType()->getAs<RecordType>()) { | |||
3398 | if (CXXRecordDecl *FromRecordDecl | |||
3399 | = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { | |||
3400 | // Add all of the conversion functions as candidates. | |||
3401 | const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); | |||
3402 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { | |||
3403 | DeclAccessPair FoundDecl = I.getPair(); | |||
3404 | NamedDecl *D = FoundDecl.getDecl(); | |||
3405 | CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); | |||
3406 | if (isa<UsingShadowDecl>(D)) | |||
3407 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | |||
3408 | ||||
3409 | CXXConversionDecl *Conv; | |||
3410 | FunctionTemplateDecl *ConvTemplate; | |||
3411 | if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) | |||
3412 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); | |||
3413 | else | |||
3414 | Conv = cast<CXXConversionDecl>(D); | |||
3415 | ||||
3416 | if (AllowExplicit || !Conv->isExplicit()) { | |||
3417 | if (ConvTemplate) | |||
3418 | S.AddTemplateConversionCandidate( | |||
3419 | ConvTemplate, FoundDecl, ActingContext, From, ToType, | |||
3420 | CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit); | |||
3421 | else | |||
3422 | S.AddConversionCandidate( | |||
3423 | Conv, FoundDecl, ActingContext, From, ToType, CandidateSet, | |||
3424 | AllowObjCConversionOnExplicit, AllowExplicit); | |||
3425 | } | |||
3426 | } | |||
3427 | } | |||
3428 | } | |||
3429 | ||||
3430 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | |||
3431 | ||||
3432 | OverloadCandidateSet::iterator Best; | |||
3433 | switch (auto Result = | |||
3434 | CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { | |||
3435 | case OR_Success: | |||
3436 | case OR_Deleted: | |||
3437 | // Record the standard conversion we used and the conversion function. | |||
3438 | if (CXXConstructorDecl *Constructor | |||
3439 | = dyn_cast<CXXConstructorDecl>(Best->Function)) { | |||
3440 | // C++ [over.ics.user]p1: | |||
3441 | // If the user-defined conversion is specified by a | |||
3442 | // constructor (12.3.1), the initial standard conversion | |||
3443 | // sequence converts the source type to the type required by | |||
3444 | // the argument of the constructor. | |||
3445 | // | |||
3446 | QualType ThisType = Constructor->getThisType(); | |||
3447 | if (isa<InitListExpr>(From)) { | |||
3448 | // Initializer lists don't have conversions as such. | |||
3449 | User.Before.setAsIdentityConversion(); | |||
3450 | } else { | |||
3451 | if (Best->Conversions[0].isEllipsis()) | |||
3452 | User.EllipsisConversion = true; | |||
3453 | else { | |||
3454 | User.Before = Best->Conversions[0].Standard; | |||
3455 | User.EllipsisConversion = false; | |||
3456 | } | |||
3457 | } | |||
3458 | User.HadMultipleCandidates = HadMultipleCandidates; | |||
3459 | User.ConversionFunction = Constructor; | |||
3460 | User.FoundConversionFunction = Best->FoundDecl; | |||
3461 | User.After.setAsIdentityConversion(); | |||
3462 | User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); | |||
3463 | User.After.setAllToTypes(ToType); | |||
3464 | return Result; | |||
3465 | } | |||
3466 | if (CXXConversionDecl *Conversion | |||
3467 | = dyn_cast<CXXConversionDecl>(Best->Function)) { | |||
3468 | // C++ [over.ics.user]p1: | |||
3469 | // | |||
3470 | // [...] If the user-defined conversion is specified by a | |||
3471 | // conversion function (12.3.2), the initial standard | |||
3472 | // conversion sequence converts the source type to the | |||
3473 | // implicit object parameter of the conversion function. | |||
3474 | User.Before = Best->Conversions[0].Standard; | |||
3475 | User.HadMultipleCandidates = HadMultipleCandidates; | |||
3476 | User.ConversionFunction = Conversion; | |||
3477 | User.FoundConversionFunction = Best->FoundDecl; | |||
3478 | User.EllipsisConversion = false; | |||
3479 | ||||
3480 | // C++ [over.ics.user]p2: | |||
3481 | // The second standard conversion sequence converts the | |||
3482 | // result of the user-defined conversion to the target type | |||
3483 | // for the sequence. Since an implicit conversion sequence | |||
3484 | // is an initialization, the special rules for | |||
3485 | // initialization by user-defined conversion apply when | |||
3486 | // selecting the best user-defined conversion for a | |||
3487 | // user-defined conversion sequence (see 13.3.3 and | |||
3488 | // 13.3.3.1). | |||
3489 | User.After = Best->FinalConversion; | |||
3490 | return Result; | |||
3491 | } | |||
3492 | llvm_unreachable("Not a constructor or conversion function?")::llvm::llvm_unreachable_internal("Not a constructor or conversion function?" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 3492); | |||
3493 | ||||
3494 | case OR_No_Viable_Function: | |||
3495 | return OR_No_Viable_Function; | |||
3496 | ||||
3497 | case OR_Ambiguous: | |||
3498 | return OR_Ambiguous; | |||
3499 | } | |||
3500 | ||||
3501 | llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 3501); | |||
3502 | } | |||
3503 | ||||
3504 | bool | |||
3505 | Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { | |||
3506 | ImplicitConversionSequence ICS; | |||
3507 | OverloadCandidateSet CandidateSet(From->getExprLoc(), | |||
3508 | OverloadCandidateSet::CSK_Normal); | |||
3509 | OverloadingResult OvResult = | |||
3510 | IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, | |||
3511 | CandidateSet, false, false); | |||
3512 | ||||
3513 | if (!(OvResult == OR_Ambiguous || | |||
3514 | (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) | |||
3515 | return false; | |||
3516 | ||||
3517 | auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, From); | |||
3518 | if (OvResult == OR_Ambiguous) | |||
3519 | Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) | |||
3520 | << From->getType() << ToType << From->getSourceRange(); | |||
3521 | else { // OR_No_Viable_Function && !CandidateSet.empty() | |||
3522 | if (!RequireCompleteType(From->getBeginLoc(), ToType, | |||
3523 | diag::err_typecheck_nonviable_condition_incomplete, | |||
3524 | From->getType(), From->getSourceRange())) | |||
3525 | Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) | |||
3526 | << false << From->getType() << From->getSourceRange() << ToType; | |||
3527 | } | |||
3528 | ||||
3529 | CandidateSet.NoteCandidates( | |||
3530 | *this, From, Cands); | |||
3531 | return true; | |||
3532 | } | |||
3533 | ||||
3534 | /// Compare the user-defined conversion functions or constructors | |||
3535 | /// of two user-defined conversion sequences to determine whether any ordering | |||
3536 | /// is possible. | |||
3537 | static ImplicitConversionSequence::CompareKind | |||
3538 | compareConversionFunctions(Sema &S, FunctionDecl *Function1, | |||
3539 | FunctionDecl *Function2) { | |||
3540 | if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11) | |||
3541 | return ImplicitConversionSequence::Indistinguishable; | |||
3542 | ||||
3543 | // Objective-C++: | |||
3544 | // If both conversion functions are implicitly-declared conversions from | |||
3545 | // a lambda closure type to a function pointer and a block pointer, | |||
3546 | // respectively, always prefer the conversion to a function pointer, | |||
3547 | // because the function pointer is more lightweight and is more likely | |||
3548 | // to keep code working. | |||
3549 | CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); | |||
3550 | if (!Conv1) | |||
3551 | return ImplicitConversionSequence::Indistinguishable; | |||
3552 | ||||
3553 | CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); | |||
3554 | if (!Conv2) | |||
3555 | return ImplicitConversionSequence::Indistinguishable; | |||
3556 | ||||
3557 | if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { | |||
3558 | bool Block1 = Conv1->getConversionType()->isBlockPointerType(); | |||
3559 | bool Block2 = Conv2->getConversionType()->isBlockPointerType(); | |||
3560 | if (Block1 != Block2) | |||
3561 | return Block1 ? ImplicitConversionSequence::Worse | |||
3562 | : ImplicitConversionSequence::Better; | |||
3563 | } | |||
3564 | ||||
3565 | return ImplicitConversionSequence::Indistinguishable; | |||
3566 | } | |||
3567 | ||||
3568 | static bool hasDeprecatedStringLiteralToCharPtrConversion( | |||
3569 | const ImplicitConversionSequence &ICS) { | |||
3570 | return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || | |||
3571 | (ICS.isUserDefined() && | |||
3572 | ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); | |||
3573 | } | |||
3574 | ||||
3575 | /// CompareImplicitConversionSequences - Compare two implicit | |||
3576 | /// conversion sequences to determine whether one is better than the | |||
3577 | /// other or if they are indistinguishable (C++ 13.3.3.2). | |||
3578 | static ImplicitConversionSequence::CompareKind | |||
3579 | CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, | |||
3580 | const ImplicitConversionSequence& ICS1, | |||
3581 | const ImplicitConversionSequence& ICS2) | |||
3582 | { | |||
3583 | // (C++ 13.3.3.2p2): When comparing the basic forms of implicit | |||
3584 | // conversion sequences (as defined in 13.3.3.1) | |||
3585 | // -- a standard conversion sequence (13.3.3.1.1) is a better | |||
3586 | // conversion sequence than a user-defined conversion sequence or | |||
3587 | // an ellipsis conversion sequence, and | |||
3588 | // -- a user-defined conversion sequence (13.3.3.1.2) is a better | |||
3589 | // conversion sequence than an ellipsis conversion sequence | |||
3590 | // (13.3.3.1.3). | |||
3591 | // | |||
3592 | // C++0x [over.best.ics]p10: | |||
3593 | // For the purpose of ranking implicit conversion sequences as | |||
3594 | // described in 13.3.3.2, the ambiguous conversion sequence is | |||
3595 | // treated as a user-defined sequence that is indistinguishable | |||
3596 | // from any other user-defined conversion sequence. | |||
3597 | ||||
3598 | // String literal to 'char *' conversion has been deprecated in C++03. It has | |||
3599 | // been removed from C++11. We still accept this conversion, if it happens at | |||
3600 | // the best viable function. Otherwise, this conversion is considered worse | |||
3601 | // than ellipsis conversion. Consider this as an extension; this is not in the | |||
3602 | // standard. For example: | |||
3603 | // | |||
3604 | // int &f(...); // #1 | |||
3605 | // void f(char*); // #2 | |||
3606 | // void g() { int &r = f("foo"); } | |||
3607 | // | |||
3608 | // In C++03, we pick #2 as the best viable function. | |||
3609 | // In C++11, we pick #1 as the best viable function, because ellipsis | |||
3610 | // conversion is better than string-literal to char* conversion (since there | |||
3611 | // is no such conversion in C++11). If there was no #1 at all or #1 couldn't | |||
3612 | // convert arguments, #2 would be the best viable function in C++11. | |||
3613 | // If the best viable function has this conversion, a warning will be issued | |||
3614 | // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. | |||
3615 | ||||
3616 | if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && | |||
3617 | hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != | |||
3618 | hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) | |||
3619 | return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) | |||
3620 | ? ImplicitConversionSequence::Worse | |||
3621 | : ImplicitConversionSequence::Better; | |||
3622 | ||||
3623 | if (ICS1.getKindRank() < ICS2.getKindRank()) | |||
3624 | return ImplicitConversionSequence::Better; | |||
3625 | if (ICS2.getKindRank() < ICS1.getKindRank()) | |||
3626 | return ImplicitConversionSequence::Worse; | |||
3627 | ||||
3628 | // The following checks require both conversion sequences to be of | |||
3629 | // the same kind. | |||
3630 | if (ICS1.getKind() != ICS2.getKind()) | |||
3631 | return ImplicitConversionSequence::Indistinguishable; | |||
3632 | ||||
3633 | ImplicitConversionSequence::CompareKind Result = | |||
3634 | ImplicitConversionSequence::Indistinguishable; | |||
3635 | ||||
3636 | // Two implicit conversion sequences of the same form are | |||
3637 | // indistinguishable conversion sequences unless one of the | |||
3638 | // following rules apply: (C++ 13.3.3.2p3): | |||
3639 | ||||
3640 | // List-initialization sequence L1 is a better conversion sequence than | |||
3641 | // list-initialization sequence L2 if: | |||
3642 | // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, | |||
3643 | // if not that, | |||
3644 | // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", | |||
3645 | // and N1 is smaller than N2., | |||
3646 | // even if one of the other rules in this paragraph would otherwise apply. | |||
3647 | if (!ICS1.isBad()) { | |||
3648 | if (ICS1.isStdInitializerListElement() && | |||
3649 | !ICS2.isStdInitializerListElement()) | |||
3650 | return ImplicitConversionSequence::Better; | |||
3651 | if (!ICS1.isStdInitializerListElement() && | |||
3652 | ICS2.isStdInitializerListElement()) | |||
3653 | return ImplicitConversionSequence::Worse; | |||
3654 | } | |||
3655 | ||||
3656 | if (ICS1.isStandard()) | |||
3657 | // Standard conversion sequence S1 is a better conversion sequence than | |||
3658 | // standard conversion sequence S2 if [...] | |||
3659 | Result = CompareStandardConversionSequences(S, Loc, | |||
3660 | ICS1.Standard, ICS2.Standard); | |||
3661 | else if (ICS1.isUserDefined()) { | |||
3662 | // User-defined conversion sequence U1 is a better conversion | |||
3663 | // sequence than another user-defined conversion sequence U2 if | |||
3664 | // they contain the same user-defined conversion function or | |||
3665 | // constructor and if the second standard conversion sequence of | |||
3666 | // U1 is better than the second standard conversion sequence of | |||
3667 | // U2 (C++ 13.3.3.2p3). | |||
3668 | if (ICS1.UserDefined.ConversionFunction == | |||
3669 | ICS2.UserDefined.ConversionFunction) | |||
3670 | Result = CompareStandardConversionSequences(S, Loc, | |||
3671 | ICS1.UserDefined.After, | |||
3672 | ICS2.UserDefined.After); | |||
3673 | else | |||
3674 | Result = compareConversionFunctions(S, | |||
3675 | ICS1.UserDefined.ConversionFunction, | |||
3676 | ICS2.UserDefined.ConversionFunction); | |||
3677 | } | |||
3678 | ||||
3679 | return Result; | |||
3680 | } | |||
3681 | ||||
3682 | // Per 13.3.3.2p3, compare the given standard conversion sequences to | |||
3683 | // determine if one is a proper subset of the other. | |||
3684 | static ImplicitConversionSequence::CompareKind | |||
3685 | compareStandardConversionSubsets(ASTContext &Context, | |||
3686 | const StandardConversionSequence& SCS1, | |||
3687 | const StandardConversionSequence& SCS2) { | |||
3688 | ImplicitConversionSequence::CompareKind Result | |||
3689 | = ImplicitConversionSequence::Indistinguishable; | |||
3690 | ||||
3691 | // the identity conversion sequence is considered to be a subsequence of | |||
3692 | // any non-identity conversion sequence | |||
3693 | if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) | |||
3694 | return ImplicitConversionSequence::Better; | |||
3695 | else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) | |||
3696 | return ImplicitConversionSequence::Worse; | |||
3697 | ||||
3698 | if (SCS1.Second != SCS2.Second) { | |||
3699 | if (SCS1.Second == ICK_Identity) | |||
3700 | Result = ImplicitConversionSequence::Better; | |||
3701 | else if (SCS2.Second == ICK_Identity) | |||
3702 | Result = ImplicitConversionSequence::Worse; | |||
3703 | else | |||
3704 | return ImplicitConversionSequence::Indistinguishable; | |||
3705 | } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) | |||
3706 | return ImplicitConversionSequence::Indistinguishable; | |||
3707 | ||||
3708 | if (SCS1.Third == SCS2.Third) { | |||
3709 | return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result | |||
3710 | : ImplicitConversionSequence::Indistinguishable; | |||
3711 | } | |||
3712 | ||||
3713 | if (SCS1.Third == ICK_Identity) | |||
3714 | return Result == ImplicitConversionSequence::Worse | |||
3715 | ? ImplicitConversionSequence::Indistinguishable | |||
3716 | : ImplicitConversionSequence::Better; | |||
3717 | ||||
3718 | if (SCS2.Third == ICK_Identity) | |||
3719 | return Result == ImplicitConversionSequence::Better | |||
3720 | ? ImplicitConversionSequence::Indistinguishable | |||
3721 | : ImplicitConversionSequence::Worse; | |||
3722 | ||||
3723 | return ImplicitConversionSequence::Indistinguishable; | |||
3724 | } | |||
3725 | ||||
3726 | /// Determine whether one of the given reference bindings is better | |||
3727 | /// than the other based on what kind of bindings they are. | |||
3728 | static bool | |||
3729 | isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, | |||
3730 | const StandardConversionSequence &SCS2) { | |||
3731 | // C++0x [over.ics.rank]p3b4: | |||
3732 | // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an | |||
3733 | // implicit object parameter of a non-static member function declared | |||
3734 | // without a ref-qualifier, and *either* S1 binds an rvalue reference | |||
3735 | // to an rvalue and S2 binds an lvalue reference *or S1 binds an | |||
3736 | // lvalue reference to a function lvalue and S2 binds an rvalue | |||
3737 | // reference*. | |||
3738 | // | |||
3739 | // FIXME: Rvalue references. We're going rogue with the above edits, | |||
3740 | // because the semantics in the current C++0x working paper (N3225 at the | |||
3741 | // time of this writing) break the standard definition of std::forward | |||
3742 | // and std::reference_wrapper when dealing with references to functions. | |||
3743 | // Proposed wording changes submitted to CWG for consideration. | |||
3744 | if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || | |||
3745 | SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) | |||
3746 | return false; | |||
3747 | ||||
3748 | return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && | |||
3749 | SCS2.IsLvalueReference) || | |||
3750 | (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && | |||
3751 | !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); | |||
3752 | } | |||
3753 | ||||
3754 | /// CompareStandardConversionSequences - Compare two standard | |||
3755 | /// conversion sequences to determine whether one is better than the | |||
3756 | /// other or if they are indistinguishable (C++ 13.3.3.2p3). | |||
3757 | static ImplicitConversionSequence::CompareKind | |||
3758 | CompareStandardConversionSequences(Sema &S, SourceLocation Loc, | |||
3759 | const StandardConversionSequence& SCS1, | |||
3760 | const StandardConversionSequence& SCS2) | |||
3761 | { | |||
3762 | // Standard conversion sequence S1 is a better conversion sequence | |||
3763 | // than standard conversion sequence S2 if (C++ 13.3.3.2p3): | |||
3764 | ||||
3765 | // -- S1 is a proper subsequence of S2 (comparing the conversion | |||
3766 | // sequences in the canonical form defined by 13.3.3.1.1, | |||
3767 | // excluding any Lvalue Transformation; the identity conversion | |||
3768 | // sequence is considered to be a subsequence of any | |||
3769 | // non-identity conversion sequence) or, if not that, | |||
3770 | if (ImplicitConversionSequence::CompareKind CK | |||
3771 | = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) | |||
3772 | return CK; | |||
3773 | ||||
3774 | // -- the rank of S1 is better than the rank of S2 (by the rules | |||
3775 | // defined below), or, if not that, | |||
3776 | ImplicitConversionRank Rank1 = SCS1.getRank(); | |||
3777 | ImplicitConversionRank Rank2 = SCS2.getRank(); | |||
3778 | if (Rank1 < Rank2) | |||
3779 | return ImplicitConversionSequence::Better; | |||
3780 | else if (Rank2 < Rank1) | |||
3781 | return ImplicitConversionSequence::Worse; | |||
3782 | ||||
3783 | // (C++ 13.3.3.2p4): Two conversion sequences with the same rank | |||
3784 | // are indistinguishable unless one of the following rules | |||
3785 | // applies: | |||
3786 | ||||
3787 | // A conversion that is not a conversion of a pointer, or | |||
3788 | // pointer to member, to bool is better than another conversion | |||
3789 | // that is such a conversion. | |||
3790 | if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) | |||
3791 | return SCS2.isPointerConversionToBool() | |||
3792 | ? ImplicitConversionSequence::Better | |||
3793 | : ImplicitConversionSequence::Worse; | |||
3794 | ||||
3795 | // C++ [over.ics.rank]p4b2: | |||
3796 | // | |||
3797 | // If class B is derived directly or indirectly from class A, | |||
3798 | // conversion of B* to A* is better than conversion of B* to | |||
3799 | // void*, and conversion of A* to void* is better than conversion | |||
3800 | // of B* to void*. | |||
3801 | bool SCS1ConvertsToVoid | |||
3802 | = SCS1.isPointerConversionToVoidPointer(S.Context); | |||
3803 | bool SCS2ConvertsToVoid | |||
3804 | = SCS2.isPointerConversionToVoidPointer(S.Context); | |||
3805 | if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { | |||
3806 | // Exactly one of the conversion sequences is a conversion to | |||
3807 | // a void pointer; it's the worse conversion. | |||
3808 | return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better | |||
3809 | : ImplicitConversionSequence::Worse; | |||
3810 | } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { | |||
3811 | // Neither conversion sequence converts to a void pointer; compare | |||
3812 | // their derived-to-base conversions. | |||
3813 | if (ImplicitConversionSequence::CompareKind DerivedCK | |||
3814 | = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) | |||
3815 | return DerivedCK; | |||
3816 | } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && | |||
3817 | !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { | |||
3818 | // Both conversion sequences are conversions to void | |||
3819 | // pointers. Compare the source types to determine if there's an | |||
3820 | // inheritance relationship in their sources. | |||
3821 | QualType FromType1 = SCS1.getFromType(); | |||
3822 | QualType FromType2 = SCS2.getFromType(); | |||
3823 | ||||
3824 | // Adjust the types we're converting from via the array-to-pointer | |||
3825 | // conversion, if we need to. | |||
3826 | if (SCS1.First == ICK_Array_To_Pointer) | |||
3827 | FromType1 = S.Context.getArrayDecayedType(FromType1); | |||
3828 | if (SCS2.First == ICK_Array_To_Pointer) | |||
3829 | FromType2 = S.Context.getArrayDecayedType(FromType2); | |||
3830 | ||||
3831 | QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); | |||
3832 | QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); | |||
3833 | ||||
3834 | if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) | |||
3835 | return ImplicitConversionSequence::Better; | |||
3836 | else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) | |||
3837 | return ImplicitConversionSequence::Worse; | |||
3838 | ||||
3839 | // Objective-C++: If one interface is more specific than the | |||
3840 | // other, it is the better one. | |||
3841 | const ObjCObjectPointerType* FromObjCPtr1 | |||
3842 | = FromType1->getAs<ObjCObjectPointerType>(); | |||
3843 | const ObjCObjectPointerType* FromObjCPtr2 | |||
3844 | = FromType2->getAs<ObjCObjectPointerType>(); | |||
3845 | if (FromObjCPtr1 && FromObjCPtr2) { | |||
3846 | bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, | |||
3847 | FromObjCPtr2); | |||
3848 | bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, | |||
3849 | FromObjCPtr1); | |||
3850 | if (AssignLeft != AssignRight) { | |||
3851 | return AssignLeft? ImplicitConversionSequence::Better | |||
3852 | : ImplicitConversionSequence::Worse; | |||
3853 | } | |||
3854 | } | |||
3855 | } | |||
3856 | ||||
3857 | // Compare based on qualification conversions (C++ 13.3.3.2p3, | |||
3858 | // bullet 3). | |||
3859 | if (ImplicitConversionSequence::CompareKind QualCK | |||
3860 | = CompareQualificationConversions(S, SCS1, SCS2)) | |||
3861 | return QualCK; | |||
3862 | ||||
3863 | if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { | |||
3864 | // Check for a better reference binding based on the kind of bindings. | |||
3865 | if (isBetterReferenceBindingKind(SCS1, SCS2)) | |||
3866 | return ImplicitConversionSequence::Better; | |||
3867 | else if (isBetterReferenceBindingKind(SCS2, SCS1)) | |||
3868 | return ImplicitConversionSequence::Worse; | |||
3869 | ||||
3870 | // C++ [over.ics.rank]p3b4: | |||
3871 | // -- S1 and S2 are reference bindings (8.5.3), and the types to | |||
3872 | // which the references refer are the same type except for | |||
3873 | // top-level cv-qualifiers, and the type to which the reference | |||
3874 | // initialized by S2 refers is more cv-qualified than the type | |||
3875 | // to which the reference initialized by S1 refers. | |||
3876 | QualType T1 = SCS1.getToType(2); | |||
3877 | QualType T2 = SCS2.getToType(2); | |||
3878 | T1 = S.Context.getCanonicalType(T1); | |||
3879 | T2 = S.Context.getCanonicalType(T2); | |||
3880 | Qualifiers T1Quals, T2Quals; | |||
3881 | QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); | |||
3882 | QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); | |||
3883 | if (UnqualT1 == UnqualT2) { | |||
3884 | // Objective-C++ ARC: If the references refer to objects with different | |||
3885 | // lifetimes, prefer bindings that don't change lifetime. | |||
3886 | if (SCS1.ObjCLifetimeConversionBinding != | |||
3887 | SCS2.ObjCLifetimeConversionBinding) { | |||
3888 | return SCS1.ObjCLifetimeConversionBinding | |||
3889 | ? ImplicitConversionSequence::Worse | |||
3890 | : ImplicitConversionSequence::Better; | |||
3891 | } | |||
3892 | ||||
3893 | // If the type is an array type, promote the element qualifiers to the | |||
3894 | // type for comparison. | |||
3895 | if (isa<ArrayType>(T1) && T1Quals) | |||
3896 | T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); | |||
3897 | if (isa<ArrayType>(T2) && T2Quals) | |||
3898 | T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); | |||
3899 | if (T2.isMoreQualifiedThan(T1)) | |||
3900 | return ImplicitConversionSequence::Better; | |||
3901 | else if (T1.isMoreQualifiedThan(T2)) | |||
3902 | return ImplicitConversionSequence::Worse; | |||
3903 | } | |||
3904 | } | |||
3905 | ||||
3906 | // In Microsoft mode, prefer an integral conversion to a | |||
3907 | // floating-to-integral conversion if the integral conversion | |||
3908 | // is between types of the same size. | |||
3909 | // For example: | |||
3910 | // void f(float); | |||
3911 | // void f(int); | |||
3912 | // int main { | |||
3913 | // long a; | |||
3914 | // f(a); | |||
3915 | // } | |||
3916 | // Here, MSVC will call f(int) instead of generating a compile error | |||
3917 | // as clang will do in standard mode. | |||
3918 | if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && | |||
3919 | SCS2.Second == ICK_Floating_Integral && | |||
3920 | S.Context.getTypeSize(SCS1.getFromType()) == | |||
3921 | S.Context.getTypeSize(SCS1.getToType(2))) | |||
3922 | return ImplicitConversionSequence::Better; | |||
3923 | ||||
3924 | // Prefer a compatible vector conversion over a lax vector conversion | |||
3925 | // For example: | |||
3926 | // | |||
3927 | // typedef float __v4sf __attribute__((__vector_size__(16))); | |||
3928 | // void f(vector float); | |||
3929 | // void f(vector signed int); | |||
3930 | // int main() { | |||
3931 | // __v4sf a; | |||
3932 | // f(a); | |||
3933 | // } | |||
3934 | // Here, we'd like to choose f(vector float) and not | |||
3935 | // report an ambiguous call error | |||
3936 | if (SCS1.Second == ICK_Vector_Conversion && | |||
3937 | SCS2.Second == ICK_Vector_Conversion) { | |||
3938 | bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( | |||
3939 | SCS1.getFromType(), SCS1.getToType(2)); | |||
3940 | bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( | |||
3941 | SCS2.getFromType(), SCS2.getToType(2)); | |||
3942 | ||||
3943 | if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) | |||
3944 | return SCS1IsCompatibleVectorConversion | |||
3945 | ? ImplicitConversionSequence::Better | |||
3946 | : ImplicitConversionSequence::Worse; | |||
3947 | } | |||
3948 | ||||
3949 | return ImplicitConversionSequence::Indistinguishable; | |||
3950 | } | |||
3951 | ||||
3952 | /// CompareQualificationConversions - Compares two standard conversion | |||
3953 | /// sequences to determine whether they can be ranked based on their | |||
3954 | /// qualification conversions (C++ 13.3.3.2p3 bullet 3). | |||
3955 | static ImplicitConversionSequence::CompareKind | |||
3956 | CompareQualificationConversions(Sema &S, | |||
3957 | const StandardConversionSequence& SCS1, | |||
3958 | const StandardConversionSequence& SCS2) { | |||
3959 | // C++ 13.3.3.2p3: | |||
3960 | // -- S1 and S2 differ only in their qualification conversion and | |||
3961 | // yield similar types T1 and T2 (C++ 4.4), respectively, and the | |||
3962 | // cv-qualification signature of type T1 is a proper subset of | |||
3963 | // the cv-qualification signature of type T2, and S1 is not the | |||
3964 | // deprecated string literal array-to-pointer conversion (4.2). | |||
3965 | if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || | |||
3966 | SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) | |||
3967 | return ImplicitConversionSequence::Indistinguishable; | |||
3968 | ||||
3969 | // FIXME: the example in the standard doesn't use a qualification | |||
3970 | // conversion (!) | |||
3971 | QualType T1 = SCS1.getToType(2); | |||
3972 | QualType T2 = SCS2.getToType(2); | |||
3973 | T1 = S.Context.getCanonicalType(T1); | |||
3974 | T2 = S.Context.getCanonicalType(T2); | |||
3975 | Qualifiers T1Quals, T2Quals; | |||
3976 | QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); | |||
3977 | QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); | |||
3978 | ||||
3979 | // If the types are the same, we won't learn anything by unwrapped | |||
3980 | // them. | |||
3981 | if (UnqualT1 == UnqualT2) | |||
3982 | return ImplicitConversionSequence::Indistinguishable; | |||
3983 | ||||
3984 | // If the type is an array type, promote the element qualifiers to the type | |||
3985 | // for comparison. | |||
3986 | if (isa<ArrayType>(T1) && T1Quals) | |||
3987 | T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); | |||
3988 | if (isa<ArrayType>(T2) && T2Quals) | |||
3989 | T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); | |||
3990 | ||||
3991 | ImplicitConversionSequence::CompareKind Result | |||
3992 | = ImplicitConversionSequence::Indistinguishable; | |||
3993 | ||||
3994 | // Objective-C++ ARC: | |||
3995 | // Prefer qualification conversions not involving a change in lifetime | |||
3996 | // to qualification conversions that do not change lifetime. | |||
3997 | if (SCS1.QualificationIncludesObjCLifetime != | |||
3998 | SCS2.QualificationIncludesObjCLifetime) { | |||
3999 | Result = SCS1.QualificationIncludesObjCLifetime | |||
4000 | ? ImplicitConversionSequence::Worse | |||
4001 | : ImplicitConversionSequence::Better; | |||
4002 | } | |||
4003 | ||||
4004 | while (S.Context.UnwrapSimilarTypes(T1, T2)) { | |||
4005 | // Within each iteration of the loop, we check the qualifiers to | |||
4006 | // determine if this still looks like a qualification | |||
4007 | // conversion. Then, if all is well, we unwrap one more level of | |||
4008 | // pointers or pointers-to-members and do it all again | |||
4009 | // until there are no more pointers or pointers-to-members left | |||
4010 | // to unwrap. This essentially mimics what | |||
4011 | // IsQualificationConversion does, but here we're checking for a | |||
4012 | // strict subset of qualifiers. | |||
4013 | if (T1.getQualifiers().withoutObjCLifetime() == | |||
4014 | T2.getQualifiers().withoutObjCLifetime()) | |||
4015 | // The qualifiers are the same, so this doesn't tell us anything | |||
4016 | // about how the sequences rank. | |||
4017 | // ObjC ownership quals are omitted above as they interfere with | |||
4018 | // the ARC overload rule. | |||
4019 | ; | |||
4020 | else if (T2.isMoreQualifiedThan(T1)) { | |||
4021 | // T1 has fewer qualifiers, so it could be the better sequence. | |||
4022 | if (Result == ImplicitConversionSequence::Worse) | |||
4023 | // Neither has qualifiers that are a subset of the other's | |||
4024 | // qualifiers. | |||
4025 | return ImplicitConversionSequence::Indistinguishable; | |||
4026 | ||||
4027 | Result = ImplicitConversionSequence::Better; | |||
4028 | } else if (T1.isMoreQualifiedThan(T2)) { | |||
4029 | // T2 has fewer qualifiers, so it could be the better sequence. | |||
4030 | if (Result == ImplicitConversionSequence::Better) | |||
4031 | // Neither has qualifiers that are a subset of the other's | |||
4032 | // qualifiers. | |||
4033 | return ImplicitConversionSequence::Indistinguishable; | |||
4034 | ||||
4035 | Result = ImplicitConversionSequence::Worse; | |||
4036 | } else { | |||
4037 | // Qualifiers are disjoint. | |||
4038 | return ImplicitConversionSequence::Indistinguishable; | |||
4039 | } | |||
4040 | ||||
4041 | // If the types after this point are equivalent, we're done. | |||
4042 | if (S.Context.hasSameUnqualifiedType(T1, T2)) | |||
4043 | break; | |||
4044 | } | |||
4045 | ||||
4046 | // Check that the winning standard conversion sequence isn't using | |||
4047 | // the deprecated string literal array to pointer conversion. | |||
4048 | switch (Result) { | |||
4049 | case ImplicitConversionSequence::Better: | |||
4050 | if (SCS1.DeprecatedStringLiteralToCharPtr) | |||
4051 | Result = ImplicitConversionSequence::Indistinguishable; | |||
4052 | break; | |||
4053 | ||||
4054 | case ImplicitConversionSequence::Indistinguishable: | |||
4055 | break; | |||
4056 | ||||
4057 | case ImplicitConversionSequence::Worse: | |||
4058 | if (SCS2.DeprecatedStringLiteralToCharPtr) | |||
4059 | Result = ImplicitConversionSequence::Indistinguishable; | |||
4060 | break; | |||
4061 | } | |||
4062 | ||||
4063 | return Result; | |||
4064 | } | |||
4065 | ||||
4066 | /// CompareDerivedToBaseConversions - Compares two standard conversion | |||
4067 | /// sequences to determine whether they can be ranked based on their | |||
4068 | /// various kinds of derived-to-base conversions (C++ | |||
4069 | /// [over.ics.rank]p4b3). As part of these checks, we also look at | |||
4070 | /// conversions between Objective-C interface types. | |||
4071 | static ImplicitConversionSequence::CompareKind | |||
4072 | CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, | |||
4073 | const StandardConversionSequence& SCS1, | |||
4074 | const StandardConversionSequence& SCS2) { | |||
4075 | QualType FromType1 = SCS1.getFromType(); | |||
4076 | QualType ToType1 = SCS1.getToType(1); | |||
4077 | QualType FromType2 = SCS2.getFromType(); | |||
4078 | QualType ToType2 = SCS2.getToType(1); | |||
4079 | ||||
4080 | // Adjust the types we're converting from via the array-to-pointer | |||
4081 | // conversion, if we need to. | |||
4082 | if (SCS1.First == ICK_Array_To_Pointer) | |||
4083 | FromType1 = S.Context.getArrayDecayedType(FromType1); | |||
4084 | if (SCS2.First == ICK_Array_To_Pointer) | |||
4085 | FromType2 = S.Context.getArrayDecayedType(FromType2); | |||
4086 | ||||
4087 | // Canonicalize all of the types. | |||
4088 | FromType1 = S.Context.getCanonicalType(FromType1); | |||
4089 | ToType1 = S.Context.getCanonicalType(ToType1); | |||
4090 | FromType2 = S.Context.getCanonicalType(FromType2); | |||
4091 | ToType2 = S.Context.getCanonicalType(ToType2); | |||
4092 | ||||
4093 | // C++ [over.ics.rank]p4b3: | |||
4094 | // | |||
4095 | // If class B is derived directly or indirectly from class A and | |||
4096 | // class C is derived directly or indirectly from B, | |||
4097 | // | |||
4098 | // Compare based on pointer conversions. | |||
4099 | if (SCS1.Second == ICK_Pointer_Conversion && | |||
4100 | SCS2.Second == ICK_Pointer_Conversion && | |||
4101 | /*FIXME: Remove if Objective-C id conversions get their own rank*/ | |||
4102 | FromType1->isPointerType() && FromType2->isPointerType() && | |||
4103 | ToType1->isPointerType() && ToType2->isPointerType()) { | |||
4104 | QualType FromPointee1 | |||
4105 | = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); | |||
4106 | QualType ToPointee1 | |||
4107 | = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); | |||
4108 | QualType FromPointee2 | |||
4109 | = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); | |||
4110 | QualType ToPointee2 | |||
4111 | = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); | |||
4112 | ||||
4113 | // -- conversion of C* to B* is better than conversion of C* to A*, | |||
4114 | if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { | |||
4115 | if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) | |||
4116 | return ImplicitConversionSequence::Better; | |||
4117 | else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) | |||
4118 | return ImplicitConversionSequence::Worse; | |||
4119 | } | |||
4120 | ||||
4121 | // -- conversion of B* to A* is better than conversion of C* to A*, | |||
4122 | if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { | |||
4123 | if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) | |||
4124 | return ImplicitConversionSequence::Better; | |||
4125 | else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) | |||
4126 | return ImplicitConversionSequence::Worse; | |||
4127 | } | |||
4128 | } else if (SCS1.Second == ICK_Pointer_Conversion && | |||
4129 | SCS2.Second == ICK_Pointer_Conversion) { | |||
4130 | const ObjCObjectPointerType *FromPtr1 | |||
4131 | = FromType1->getAs<ObjCObjectPointerType>(); | |||
4132 | const ObjCObjectPointerType *FromPtr2 | |||
4133 | = FromType2->getAs<ObjCObjectPointerType>(); | |||
4134 | const ObjCObjectPointerType *ToPtr1 | |||
4135 | = ToType1->getAs<ObjCObjectPointerType>(); | |||
4136 | const ObjCObjectPointerType *ToPtr2 | |||
4137 | = ToType2->getAs<ObjCObjectPointerType>(); | |||
4138 | ||||
4139 | if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { | |||
4140 | // Apply the same conversion ranking rules for Objective-C pointer types | |||
4141 | // that we do for C++ pointers to class types. However, we employ the | |||
4142 | // Objective-C pseudo-subtyping relationship used for assignment of | |||
4143 | // Objective-C pointer types. | |||
4144 | bool FromAssignLeft | |||
4145 | = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); | |||
4146 | bool FromAssignRight | |||
4147 | = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); | |||
4148 | bool ToAssignLeft | |||
4149 | = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); | |||
4150 | bool ToAssignRight | |||
4151 | = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); | |||
4152 | ||||
4153 | // A conversion to an a non-id object pointer type or qualified 'id' | |||
4154 | // type is better than a conversion to 'id'. | |||
4155 | if (ToPtr1->isObjCIdType() && | |||
4156 | (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) | |||
4157 | return ImplicitConversionSequence::Worse; | |||
4158 | if (ToPtr2->isObjCIdType() && | |||
4159 | (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) | |||
4160 | return ImplicitConversionSequence::Better; | |||
4161 | ||||
4162 | // A conversion to a non-id object pointer type is better than a | |||
4163 | // conversion to a qualified 'id' type | |||
4164 | if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) | |||
4165 | return ImplicitConversionSequence::Worse; | |||
4166 | if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) | |||
4167 | return ImplicitConversionSequence::Better; | |||
4168 | ||||
4169 | // A conversion to an a non-Class object pointer type or qualified 'Class' | |||
4170 | // type is better than a conversion to 'Class'. | |||
4171 | if (ToPtr1->isObjCClassType() && | |||
4172 | (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) | |||
4173 | return ImplicitConversionSequence::Worse; | |||
4174 | if (ToPtr2->isObjCClassType() && | |||
4175 | (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) | |||
4176 | return ImplicitConversionSequence::Better; | |||
4177 | ||||
4178 | // A conversion to a non-Class object pointer type is better than a | |||
4179 | // conversion to a qualified 'Class' type. | |||
4180 | if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) | |||
4181 | return ImplicitConversionSequence::Worse; | |||
4182 | if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) | |||
4183 | return ImplicitConversionSequence::Better; | |||
4184 | ||||
4185 | // -- "conversion of C* to B* is better than conversion of C* to A*," | |||
4186 | if (S.Context.hasSameType(FromType1, FromType2) && | |||
4187 | !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && | |||
4188 | (ToAssignLeft != ToAssignRight)) { | |||
4189 | if (FromPtr1->isSpecialized()) { | |||
4190 | // "conversion of B<A> * to B * is better than conversion of B * to | |||
4191 | // C *. | |||
4192 | bool IsFirstSame = | |||
4193 | FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); | |||
4194 | bool IsSecondSame = | |||
4195 | FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); | |||
4196 | if (IsFirstSame) { | |||
4197 | if (!IsSecondSame) | |||
4198 | return ImplicitConversionSequence::Better; | |||
4199 | } else if (IsSecondSame) | |||
4200 | return ImplicitConversionSequence::Worse; | |||
4201 | } | |||
4202 | return ToAssignLeft? ImplicitConversionSequence::Worse | |||
4203 | : ImplicitConversionSequence::Better; | |||
4204 | } | |||
4205 | ||||
4206 | // -- "conversion of B* to A* is better than conversion of C* to A*," | |||
4207 | if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && | |||
4208 | (FromAssignLeft != FromAssignRight)) | |||
4209 | return FromAssignLeft? ImplicitConversionSequence::Better | |||
4210 | : ImplicitConversionSequence::Worse; | |||
4211 | } | |||
4212 | } | |||
4213 | ||||
4214 | // Ranking of member-pointer types. | |||
4215 | if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && | |||
4216 | FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && | |||
4217 | ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { | |||
4218 | const MemberPointerType * FromMemPointer1 = | |||
4219 | FromType1->getAs<MemberPointerType>(); | |||
4220 | const MemberPointerType * ToMemPointer1 = | |||
4221 | ToType1->getAs<MemberPointerType>(); | |||
4222 | const MemberPointerType * FromMemPointer2 = | |||
4223 | FromType2->getAs<MemberPointerType>(); | |||
4224 | const MemberPointerType * ToMemPointer2 = | |||
4225 | ToType2->getAs<MemberPointerType>(); | |||
4226 | const Type *FromPointeeType1 = FromMemPointer1->getClass(); | |||
4227 | const Type *ToPointeeType1 = ToMemPointer1->getClass(); | |||
4228 | const Type *FromPointeeType2 = FromMemPointer2->getClass(); | |||
4229 | const Type *ToPointeeType2 = ToMemPointer2->getClass(); | |||
4230 | QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); | |||
4231 | QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); | |||
4232 | QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); | |||
4233 | QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); | |||
4234 | // conversion of A::* to B::* is better than conversion of A::* to C::*, | |||
4235 | if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { | |||
4236 | if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) | |||
4237 | return ImplicitConversionSequence::Worse; | |||
4238 | else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) | |||
4239 | return ImplicitConversionSequence::Better; | |||
4240 | } | |||
4241 | // conversion of B::* to C::* is better than conversion of A::* to C::* | |||
4242 | if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { | |||
4243 | if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) | |||
4244 | return ImplicitConversionSequence::Better; | |||
4245 | else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) | |||
4246 | return ImplicitConversionSequence::Worse; | |||
4247 | } | |||
4248 | } | |||
4249 | ||||
4250 | if (SCS1.Second == ICK_Derived_To_Base) { | |||
4251 | // -- conversion of C to B is better than conversion of C to A, | |||
4252 | // -- binding of an expression of type C to a reference of type | |||
4253 | // B& is better than binding an expression of type C to a | |||
4254 | // reference of type A&, | |||
4255 | if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && | |||
4256 | !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { | |||
4257 | if (S.IsDerivedFrom(Loc, ToType1, ToType2)) | |||
4258 | return ImplicitConversionSequence::Better; | |||
4259 | else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) | |||
4260 | return ImplicitConversionSequence::Worse; | |||
4261 | } | |||
4262 | ||||
4263 | // -- conversion of B to A is better than conversion of C to A. | |||
4264 | // -- binding of an expression of type B to a reference of type | |||
4265 | // A& is better than binding an expression of type C to a | |||
4266 | // reference of type A&, | |||
4267 | if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && | |||
4268 | S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { | |||
4269 | if (S.IsDerivedFrom(Loc, FromType2, FromType1)) | |||
4270 | return ImplicitConversionSequence::Better; | |||
4271 | else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) | |||
4272 | return ImplicitConversionSequence::Worse; | |||
4273 | } | |||
4274 | } | |||
4275 | ||||
4276 | return ImplicitConversionSequence::Indistinguishable; | |||
4277 | } | |||
4278 | ||||
4279 | /// Determine whether the given type is valid, e.g., it is not an invalid | |||
4280 | /// C++ class. | |||
4281 | static bool isTypeValid(QualType T) { | |||
4282 | if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) | |||
4283 | return !Record->isInvalidDecl(); | |||
4284 | ||||
4285 | return true; | |||
4286 | } | |||
4287 | ||||
4288 | /// CompareReferenceRelationship - Compare the two types T1 and T2 to | |||
4289 | /// determine whether they are reference-related, | |||
4290 | /// reference-compatible, reference-compatible with added | |||
4291 | /// qualification, or incompatible, for use in C++ initialization by | |||
4292 | /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference | |||
4293 | /// type, and the first type (T1) is the pointee type of the reference | |||
4294 | /// type being initialized. | |||
4295 | Sema::ReferenceCompareResult | |||
4296 | Sema::CompareReferenceRelationship(SourceLocation Loc, | |||
4297 | QualType OrigT1, QualType OrigT2, | |||
4298 | bool &DerivedToBase, | |||
4299 | bool &ObjCConversion, | |||
4300 | bool &ObjCLifetimeConversion) { | |||
4301 | assert(!OrigT1->isReferenceType() &&((!OrigT1->isReferenceType() && "T1 must be the pointee type of the reference type" ) ? static_cast<void> (0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 4302, __PRETTY_FUNCTION__)) | |||
4302 | "T1 must be the pointee type of the reference type")((!OrigT1->isReferenceType() && "T1 must be the pointee type of the reference type" ) ? static_cast<void> (0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 4302, __PRETTY_FUNCTION__)); | |||
4303 | assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type")((!OrigT2->isReferenceType() && "T2 cannot be a reference type" ) ? static_cast<void> (0) : __assert_fail ("!OrigT2->isReferenceType() && \"T2 cannot be a reference type\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 4303, __PRETTY_FUNCTION__)); | |||
4304 | ||||
4305 | QualType T1 = Context.getCanonicalType(OrigT1); | |||
4306 | QualType T2 = Context.getCanonicalType(OrigT2); | |||
4307 | Qualifiers T1Quals, T2Quals; | |||
4308 | QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); | |||
4309 | QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); | |||
4310 | ||||
4311 | // C++ [dcl.init.ref]p4: | |||
4312 | // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is | |||
4313 | // reference-related to "cv2 T2" if T1 is the same type as T2, or | |||
4314 | // T1 is a base class of T2. | |||
4315 | DerivedToBase = false; | |||
4316 | ObjCConversion = false; | |||
4317 | ObjCLifetimeConversion = false; | |||
4318 | QualType ConvertedT2; | |||
4319 | if (UnqualT1 == UnqualT2) { | |||
4320 | // Nothing to do. | |||
4321 | } else if (isCompleteType(Loc, OrigT2) && | |||
4322 | isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && | |||
4323 | IsDerivedFrom(Loc, UnqualT2, UnqualT1)) | |||
4324 | DerivedToBase = true; | |||
4325 | else if (UnqualT1->isObjCObjectOrInterfaceType() && | |||
4326 | UnqualT2->isObjCObjectOrInterfaceType() && | |||
4327 | Context.canBindObjCObjectType(UnqualT1, UnqualT2)) | |||
4328 | ObjCConversion = true; | |||
4329 | else if (UnqualT2->isFunctionType() && | |||
4330 | IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) | |||
4331 | // C++1z [dcl.init.ref]p4: | |||
4332 | // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept | |||
4333 | // function" and T1 is "function" | |||
4334 | // | |||
4335 | // We extend this to also apply to 'noreturn', so allow any function | |||
4336 | // conversion between function types. | |||
4337 | return Ref_Compatible; | |||
4338 | else | |||
4339 | return Ref_Incompatible; | |||
4340 | ||||
4341 | // At this point, we know that T1 and T2 are reference-related (at | |||
4342 | // least). | |||
4343 | ||||
4344 | // If the type is an array type, promote the element qualifiers to the type | |||
4345 | // for comparison. | |||
4346 | if (isa<ArrayType>(T1) && T1Quals) | |||
4347 | T1 = Context.getQualifiedType(UnqualT1, T1Quals); | |||
4348 | if (isa<ArrayType>(T2) && T2Quals) | |||
4349 | T2 = Context.getQualifiedType(UnqualT2, T2Quals); | |||
4350 | ||||
4351 | // C++ [dcl.init.ref]p4: | |||
4352 | // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is | |||
4353 | // reference-related to T2 and cv1 is the same cv-qualification | |||
4354 | // as, or greater cv-qualification than, cv2. For purposes of | |||
4355 | // overload resolution, cases for which cv1 is greater | |||
4356 | // cv-qualification than cv2 are identified as | |||
4357 | // reference-compatible with added qualification (see 13.3.3.2). | |||
4358 | // | |||
4359 | // Note that we also require equivalence of Objective-C GC and address-space | |||
4360 | // qualifiers when performing these computations, so that e.g., an int in | |||
4361 | // address space 1 is not reference-compatible with an int in address | |||
4362 | // space 2. | |||
4363 | if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && | |||
4364 | T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { | |||
4365 | if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) | |||
4366 | ObjCLifetimeConversion = true; | |||
4367 | ||||
4368 | T1Quals.removeObjCLifetime(); | |||
4369 | T2Quals.removeObjCLifetime(); | |||
4370 | } | |||
4371 | ||||
4372 | // MS compiler ignores __unaligned qualifier for references; do the same. | |||
4373 | T1Quals.removeUnaligned(); | |||
4374 | T2Quals.removeUnaligned(); | |||
4375 | ||||
4376 | if (T1Quals.compatiblyIncludes(T2Quals)) | |||
4377 | return Ref_Compatible; | |||
4378 | else | |||
4379 | return Ref_Related; | |||
4380 | } | |||
4381 | ||||
4382 | /// Look for a user-defined conversion to a value reference-compatible | |||
4383 | /// with DeclType. Return true if something definite is found. | |||
4384 | static bool | |||
4385 | FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, | |||
4386 | QualType DeclType, SourceLocation DeclLoc, | |||
4387 | Expr *Init, QualType T2, bool AllowRvalues, | |||
4388 | bool AllowExplicit) { | |||
4389 | assert(T2->isRecordType() && "Can only find conversions of record types.")((T2->isRecordType() && "Can only find conversions of record types." ) ? static_cast<void> (0) : __assert_fail ("T2->isRecordType() && \"Can only find conversions of record types.\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 4389, __PRETTY_FUNCTION__)); | |||
4390 | CXXRecordDecl *T2RecordDecl | |||
4391 | = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); | |||
4392 | ||||
4393 | OverloadCandidateSet CandidateSet( | |||
4394 | DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); | |||
4395 | const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); | |||
4396 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { | |||
4397 | NamedDecl *D = *I; | |||
4398 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); | |||
4399 | if (isa<UsingShadowDecl>(D)) | |||
4400 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | |||
4401 | ||||
4402 | FunctionTemplateDecl *ConvTemplate | |||
4403 | = dyn_cast<FunctionTemplateDecl>(D); | |||
4404 | CXXConversionDecl *Conv; | |||
4405 | if (ConvTemplate) | |||
4406 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); | |||
4407 | else | |||
4408 | Conv = cast<CXXConversionDecl>(D); | |||
4409 | ||||
4410 | // If this is an explicit conversion, and we're not allowed to consider | |||
4411 | // explicit conversions, skip it. | |||
4412 | if (!AllowExplicit && Conv->isExplicit()) | |||
4413 | continue; | |||
4414 | ||||
4415 | if (AllowRvalues) { | |||
4416 | bool DerivedToBase = false; | |||
4417 | bool ObjCConversion = false; | |||
4418 | bool ObjCLifetimeConversion = false; | |||
4419 | ||||
4420 | // If we are initializing an rvalue reference, don't permit conversion | |||
4421 | // functions that return lvalues. | |||
4422 | if (!ConvTemplate && DeclType->isRValueReferenceType()) { | |||
4423 | const ReferenceType *RefType | |||
4424 | = Conv->getConversionType()->getAs<LValueReferenceType>(); | |||
4425 | if (RefType && !RefType->getPointeeType()->isFunctionType()) | |||
4426 | continue; | |||
4427 | } | |||
4428 | ||||
4429 | if (!ConvTemplate && | |||
4430 | S.CompareReferenceRelationship( | |||
4431 | DeclLoc, | |||
4432 | Conv->getConversionType().getNonReferenceType() | |||
4433 | .getUnqualifiedType(), | |||
4434 | DeclType.getNonReferenceType().getUnqualifiedType(), | |||
4435 | DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == | |||
4436 | Sema::Ref_Incompatible) | |||
4437 | continue; | |||
4438 | } else { | |||
4439 | // If the conversion function doesn't return a reference type, | |||
4440 | // it can't be considered for this conversion. An rvalue reference | |||
4441 | // is only acceptable if its referencee is a function type. | |||
4442 | ||||
4443 | const ReferenceType *RefType = | |||
4444 | Conv->getConversionType()->getAs<ReferenceType>(); | |||
4445 | if (!RefType || | |||
4446 | (!RefType->isLValueReferenceType() && | |||
4447 | !RefType->getPointeeType()->isFunctionType())) | |||
4448 | continue; | |||
4449 | } | |||
4450 | ||||
4451 | if (ConvTemplate) | |||
4452 | S.AddTemplateConversionCandidate( | |||
4453 | ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, | |||
4454 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); | |||
4455 | else | |||
4456 | S.AddConversionCandidate( | |||
4457 | Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, | |||
4458 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); | |||
4459 | } | |||
4460 | ||||
4461 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | |||
4462 | ||||
4463 | OverloadCandidateSet::iterator Best; | |||
4464 | switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { | |||
4465 | case OR_Success: | |||
4466 | // C++ [over.ics.ref]p1: | |||
4467 | // | |||
4468 | // [...] If the parameter binds directly to the result of | |||
4469 | // applying a conversion function to the argument | |||
4470 | // expression, the implicit conversion sequence is a | |||
4471 | // user-defined conversion sequence (13.3.3.1.2), with the | |||
4472 | // second standard conversion sequence either an identity | |||
4473 | // conversion or, if the conversion function returns an | |||
4474 | // entity of a type that is a derived class of the parameter | |||
4475 | // type, a derived-to-base Conversion. | |||
4476 | if (!Best->FinalConversion.DirectBinding) | |||
4477 | return false; | |||
4478 | ||||
4479 | ICS.setUserDefined(); | |||
4480 | ICS.UserDefined.Before = Best->Conversions[0].Standard; | |||
4481 | ICS.UserDefined.After = Best->FinalConversion; | |||
4482 | ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; | |||
4483 | ICS.UserDefined.ConversionFunction = Best->Function; | |||
4484 | ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; | |||
4485 | ICS.UserDefined.EllipsisConversion = false; | |||
4486 | assert(ICS.UserDefined.After.ReferenceBinding &&((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined .After.DirectBinding && "Expected a direct reference binding!" ) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 4488, __PRETTY_FUNCTION__)) | |||
4487 | ICS.UserDefined.After.DirectBinding &&((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined .After.DirectBinding && "Expected a direct reference binding!" ) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 4488, __PRETTY_FUNCTION__)) | |||
4488 | "Expected a direct reference binding!")((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined .After.DirectBinding && "Expected a direct reference binding!" ) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 4488, __PRETTY_FUNCTION__)); | |||
4489 | return true; | |||
4490 | ||||
4491 | case OR_Ambiguous: | |||
4492 | ICS.setAmbiguous(); | |||
4493 | for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); | |||
4494 | Cand != CandidateSet.end(); ++Cand) | |||
4495 | if (Cand->Viable) | |||
4496 | ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); | |||
4497 | return true; | |||
4498 | ||||
4499 | case OR_No_Viable_Function: | |||
4500 | case OR_Deleted: | |||
4501 | // There was no suitable conversion, or we found a deleted | |||
4502 | // conversion; continue with other checks. | |||
4503 | return false; | |||
4504 | } | |||
4505 | ||||
4506 | llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 4506); | |||
4507 | } | |||
4508 | ||||
4509 | /// Compute an implicit conversion sequence for reference | |||
4510 | /// initialization. | |||
4511 | static ImplicitConversionSequence | |||
4512 | TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, | |||
4513 | SourceLocation DeclLoc, | |||
4514 | bool SuppressUserConversions, | |||
4515 | bool AllowExplicit) { | |||
4516 | assert(DeclType->isReferenceType() && "Reference init needs a reference")((DeclType->isReferenceType() && "Reference init needs a reference" ) ? static_cast<void> (0) : __assert_fail ("DeclType->isReferenceType() && \"Reference init needs a reference\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 4516, __PRETTY_FUNCTION__)); | |||
4517 | ||||
4518 | // Most paths end in a failed conversion. | |||
4519 | ImplicitConversionSequence ICS; | |||
4520 | ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); | |||
4521 | ||||
4522 | QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); | |||
4523 | QualType T2 = Init->getType(); | |||
4524 | ||||
4525 | // If the initializer is the address of an overloaded function, try | |||
4526 | // to resolve the overloaded function. If all goes well, T2 is the | |||
4527 | // type of the resulting function. | |||
4528 | if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { | |||
4529 | DeclAccessPair Found; | |||
4530 | if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, | |||
4531 | false, Found)) | |||
4532 | T2 = Fn->getType(); | |||
4533 | } | |||
4534 | ||||
4535 | // Compute some basic properties of the types and the initializer. | |||
4536 | bool isRValRef = DeclType->isRValueReferenceType(); | |||
4537 | bool DerivedToBase = false; | |||
4538 | bool ObjCConversion = false; | |||
4539 | bool ObjCLifetimeConversion = false; | |||
4540 | Expr::Classification InitCategory = Init->Classify(S.Context); | |||
4541 | Sema::ReferenceCompareResult RefRelationship | |||
4542 | = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, | |||
4543 | ObjCConversion, ObjCLifetimeConversion); | |||
4544 | ||||
4545 | ||||
4546 | // C++0x [dcl.init.ref]p5: | |||
4547 | // A reference to type "cv1 T1" is initialized by an expression | |||
4548 | // of type "cv2 T2" as follows: | |||
4549 | ||||
4550 | // -- If reference is an lvalue reference and the initializer expression | |||
4551 | if (!isRValRef) { | |||
4552 | // -- is an lvalue (but is not a bit-field), and "cv1 T1" is | |||
4553 | // reference-compatible with "cv2 T2," or | |||
4554 | // | |||
4555 | // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. | |||
4556 | if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { | |||
4557 | // C++ [over.ics.ref]p1: | |||
4558 | // When a parameter of reference type binds directly (8.5.3) | |||
4559 | // to an argument expression, the implicit conversion sequence | |||
4560 | // is the identity conversion, unless the argument expression | |||
4561 | // has a type that is a derived class of the parameter type, | |||
4562 | // in which case the implicit conversion sequence is a | |||
4563 | // derived-to-base Conversion (13.3.3.1). | |||
4564 | ICS.setStandard(); | |||
4565 | ICS.Standard.First = ICK_Identity; | |||
4566 | ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base | |||
4567 | : ObjCConversion? ICK_Compatible_Conversion | |||
4568 | : ICK_Identity; | |||
4569 | ICS.Standard.Third = ICK_Identity; | |||
4570 | ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); | |||
4571 | ICS.Standard.setToType(0, T2); | |||
4572 | ICS.Standard.setToType(1, T1); | |||
4573 | ICS.Standard.setToType(2, T1); | |||
4574 | ICS.Standard.ReferenceBinding = true; | |||
4575 | ICS.Standard.DirectBinding = true; | |||
4576 | ICS.Standard.IsLvalueReference = !isRValRef; | |||
4577 | ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); | |||
4578 | ICS.Standard.BindsToRvalue = false; | |||
4579 | ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; | |||
4580 | ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; | |||
4581 | ICS.Standard.CopyConstructor = nullptr; | |||
4582 | ICS.Standard.DeprecatedStringLiteralToCharPtr = false; | |||
4583 | ||||
4584 | // Nothing more to do: the inaccessibility/ambiguity check for | |||
4585 | // derived-to-base conversions is suppressed when we're | |||
4586 | // computing the implicit conversion sequence (C++ | |||
4587 | // [over.best.ics]p2). | |||
4588 | return ICS; | |||
4589 | } | |||
4590 | ||||
4591 | // -- has a class type (i.e., T2 is a class type), where T1 is | |||
4592 | // not reference-related to T2, and can be implicitly | |||
4593 | // converted to an lvalue of type "cv3 T3," where "cv1 T1" | |||
4594 | // is reference-compatible with "cv3 T3" 92) (this | |||
4595 | // conversion is selected by enumerating the applicable | |||
4596 | // conversion functions (13.3.1.6) and choosing the best | |||
4597 | // one through overload resolution (13.3)), | |||
4598 | if (!SuppressUserConversions && T2->isRecordType() && | |||
4599 | S.isCompleteType(DeclLoc, T2) && | |||
4600 | RefRelationship == Sema::Ref_Incompatible) { | |||
4601 | if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, | |||
4602 | Init, T2, /*AllowRvalues=*/false, | |||
4603 | AllowExplicit)) | |||
4604 | return ICS; | |||
4605 | } | |||
4606 | } | |||
4607 | ||||
4608 | // -- Otherwise, the reference shall be an lvalue reference to a | |||
4609 | // non-volatile const type (i.e., cv1 shall be const), or the reference | |||
4610 | // shall be an rvalue reference. | |||
4611 | if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) | |||
4612 | return ICS; | |||
4613 | ||||
4614 | // -- If the initializer expression | |||
4615 | // | |||
4616 | // -- is an xvalue, class prvalue, array prvalue or function | |||
4617 | // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or | |||
4618 | if (RefRelationship == Sema::Ref_Compatible && | |||
4619 | (InitCategory.isXValue() || | |||
4620 | (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || | |||
4621 | (InitCategory.isLValue() && T2->isFunctionType()))) { | |||
4622 | ICS.setStandard(); | |||
4623 | ICS.Standard.First = ICK_Identity; | |||
4624 | ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base | |||
4625 | : ObjCConversion? ICK_Compatible_Conversion | |||
4626 | : ICK_Identity; | |||
4627 | ICS.Standard.Third = ICK_Identity; | |||
4628 | ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); | |||
4629 | ICS.Standard.setToType(0, T2); | |||
4630 | ICS.Standard.setToType(1, T1); | |||
4631 | ICS.Standard.setToType(2, T1); | |||
4632 | ICS.Standard.ReferenceBinding = true; | |||
4633 | // In C++0x, this is always a direct binding. In C++98/03, it's a direct | |||
4634 | // binding unless we're binding to a class prvalue. | |||
4635 | // Note: Although xvalues wouldn't normally show up in C++98/03 code, we | |||
4636 | // allow the use of rvalue references in C++98/03 for the benefit of | |||
4637 | // standard library implementors; therefore, we need the xvalue check here. | |||
4638 | ICS.Standard.DirectBinding = | |||
4639 | S.getLangOpts().CPlusPlus11 || | |||
4640 | !(InitCategory.isPRValue() || T2->isRecordType()); | |||
4641 | ICS.Standard.IsLvalueReference = !isRValRef; | |||
4642 | ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); | |||
4643 | ICS.Standard.BindsToRvalue = InitCategory.isRValue(); | |||
4644 | ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; | |||
4645 | ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; | |||
4646 | ICS.Standard.CopyConstructor = nullptr; | |||
4647 | ICS.Standard.DeprecatedStringLiteralToCharPtr = false; | |||
4648 | return ICS; | |||
4649 | } | |||
4650 | ||||
4651 | // -- has a class type (i.e., T2 is a class type), where T1 is not | |||
4652 | // reference-related to T2, and can be implicitly converted to | |||
4653 | // an xvalue, class prvalue, or function lvalue of type | |||
4654 | // "cv3 T3", where "cv1 T1" is reference-compatible with | |||
4655 | // "cv3 T3", | |||
4656 | // | |||
4657 | // then the reference is bound to the value of the initializer | |||
4658 | // expression in the first case and to the result of the conversion | |||
4659 | // in the second case (or, in either case, to an appropriate base | |||
4660 | // class subobject). | |||
4661 | if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && | |||
4662 | T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && | |||
4663 | FindConversionForRefInit(S, ICS, DeclType, DeclLoc, | |||
4664 | Init, T2, /*AllowRvalues=*/true, | |||
4665 | AllowExplicit)) { | |||
4666 | // In the second case, if the reference is an rvalue reference | |||
4667 | // and the second standard conversion sequence of the | |||
4668 | // user-defined conversion sequence includes an lvalue-to-rvalue | |||
4669 | // conversion, the program is ill-formed. | |||
4670 | if (ICS.isUserDefined() && isRValRef && | |||
4671 | ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) | |||
4672 | ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); | |||
4673 | ||||
4674 | return ICS; | |||
4675 | } | |||
4676 | ||||
4677 | // A temporary of function type cannot be created; don't even try. | |||
4678 | if (T1->isFunctionType()) | |||
4679 | return ICS; | |||
4680 | ||||
4681 | // -- Otherwise, a temporary of type "cv1 T1" is created and | |||
4682 | // initialized from the initializer expression using the | |||
4683 | // rules for a non-reference copy initialization (8.5). The | |||
4684 | // reference is then bound to the temporary. If T1 is | |||
4685 | // reference-related to T2, cv1 must be the same | |||
4686 | // cv-qualification as, or greater cv-qualification than, | |||
4687 | // cv2; otherwise, the program is ill-formed. | |||
4688 | if (RefRelationship == Sema::Ref_Related) { | |||
4689 | // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then | |||
4690 | // we would be reference-compatible or reference-compatible with | |||
4691 | // added qualification. But that wasn't the case, so the reference | |||
4692 | // initialization fails. | |||
4693 | // | |||
4694 | // Note that we only want to check address spaces and cvr-qualifiers here. | |||
4695 | // ObjC GC, lifetime and unaligned qualifiers aren't important. | |||
4696 | Qualifiers T1Quals = T1.getQualifiers(); | |||
4697 | Qualifiers T2Quals = T2.getQualifiers(); | |||
4698 | T1Quals.removeObjCGCAttr(); | |||
4699 | T1Quals.removeObjCLifetime(); | |||
4700 | T2Quals.removeObjCGCAttr(); | |||
4701 | T2Quals.removeObjCLifetime(); | |||
4702 | // MS compiler ignores __unaligned qualifier for references; do the same. | |||
4703 | T1Quals.removeUnaligned(); | |||
4704 | T2Quals.removeUnaligned(); | |||
4705 | if (!T1Quals.compatiblyIncludes(T2Quals)) | |||
4706 | return ICS; | |||
4707 | } | |||
4708 | ||||
4709 | // If at least one of the types is a class type, the types are not | |||
4710 | // related, and we aren't allowed any user conversions, the | |||
4711 | // reference binding fails. This case is important for breaking | |||
4712 | // recursion, since TryImplicitConversion below will attempt to | |||
4713 | // create a temporary through the use of a copy constructor. | |||
4714 | if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && | |||
4715 | (T1->isRecordType() || T2->isRecordType())) | |||
4716 | return ICS; | |||
4717 | ||||
4718 | // If T1 is reference-related to T2 and the reference is an rvalue | |||
4719 | // reference, the initializer expression shall not be an lvalue. | |||
4720 | if (RefRelationship >= Sema::Ref_Related && | |||
4721 | isRValRef && Init->Classify(S.Context).isLValue()) | |||
4722 | return ICS; | |||
4723 | ||||
4724 | // C++ [over.ics.ref]p2: | |||
4725 | // When a parameter of reference type is not bound directly to | |||
4726 | // an argument expression, the conversion sequence is the one | |||
4727 | // required to convert the argument expression to the | |||
4728 | // underlying type of the reference according to | |||
4729 | // 13.3.3.1. Conceptually, this conversion sequence corresponds | |||
4730 | // to copy-initializing a temporary of the underlying type with | |||
4731 | // the argument expression. Any difference in top-level | |||
4732 | // cv-qualification is subsumed by the initialization itself | |||
4733 | // and does not constitute a conversion. | |||
4734 | ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, | |||
4735 | /*AllowExplicit=*/false, | |||
4736 | /*InOverloadResolution=*/false, | |||
4737 | /*CStyle=*/false, | |||
4738 | /*AllowObjCWritebackConversion=*/false, | |||
4739 | /*AllowObjCConversionOnExplicit=*/false); | |||
4740 | ||||
4741 | // Of course, that's still a reference binding. | |||
4742 | if (ICS.isStandard()) { | |||
4743 | ICS.Standard.ReferenceBinding = true; | |||
4744 | ICS.Standard.IsLvalueReference = !isRValRef; | |||
4745 | ICS.Standard.BindsToFunctionLvalue = false; | |||
4746 | ICS.Standard.BindsToRvalue = true; | |||
4747 | ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; | |||
4748 | ICS.Standard.ObjCLifetimeConversionBinding = false; | |||
4749 | } else if (ICS.isUserDefined()) { | |||
4750 | const ReferenceType *LValRefType = | |||
4751 | ICS.UserDefined.ConversionFunction->getReturnType() | |||
4752 | ->getAs<LValueReferenceType>(); | |||
4753 | ||||
4754 | // C++ [over.ics.ref]p3: | |||
4755 | // Except for an implicit object parameter, for which see 13.3.1, a | |||
4756 | // standard conversion sequence cannot be formed if it requires [...] | |||
4757 | // binding an rvalue reference to an lvalue other than a function | |||
4758 | // lvalue. | |||
4759 | // Note that the function case is not possible here. | |||
4760 | if (DeclType->isRValueReferenceType() && LValRefType) { | |||
4761 | // FIXME: This is the wrong BadConversionSequence. The problem is binding | |||
4762 | // an rvalue reference to a (non-function) lvalue, not binding an lvalue | |||
4763 | // reference to an rvalue! | |||
4764 | ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); | |||
4765 | return ICS; | |||
4766 | } | |||
4767 | ||||
4768 | ICS.UserDefined.After.ReferenceBinding = true; | |||
4769 | ICS.UserDefined.After.IsLvalueReference = !isRValRef; | |||
4770 | ICS.UserDefined.After.BindsToFunctionLvalue = false; | |||
4771 | ICS.UserDefined.After.BindsToRvalue = !LValRefType; | |||
4772 | ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; | |||
4773 | ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; | |||
4774 | } | |||
4775 | ||||
4776 | return ICS; | |||
4777 | } | |||
4778 | ||||
4779 | static ImplicitConversionSequence | |||
4780 | TryCopyInitialization(Sema &S, Expr *From, QualType ToType, | |||
4781 | bool SuppressUserConversions, | |||
4782 | bool InOverloadResolution, | |||
4783 | bool AllowObjCWritebackConversion, | |||
4784 | bool AllowExplicit = false); | |||
4785 | ||||
4786 | /// TryListConversion - Try to copy-initialize a value of type ToType from the | |||
4787 | /// initializer list From. | |||
4788 | static ImplicitConversionSequence | |||
4789 | TryListConversion(Sema &S, InitListExpr *From, QualType ToType, | |||
4790 | bool SuppressUserConversions, | |||
4791 | bool InOverloadResolution, | |||
4792 | bool AllowObjCWritebackConversion) { | |||
4793 | // C++11 [over.ics.list]p1: | |||
4794 | // When an argument is an initializer list, it is not an expression and | |||
4795 | // special rules apply for converting it to a parameter type. | |||
4796 | ||||
4797 | ImplicitConversionSequence Result; | |||
4798 | Result.setBad(BadConversionSequence::no_conversion, From, ToType); | |||
4799 | ||||
4800 | // We need a complete type for what follows. Incomplete types can never be | |||
4801 | // initialized from init lists. | |||
4802 | if (!S.isCompleteType(From->getBeginLoc(), ToType)) | |||
4803 | return Result; | |||
4804 | ||||
4805 | // Per DR1467: | |||
4806 | // If the parameter type is a class X and the initializer list has a single | |||
4807 | // element of type cv U, where U is X or a class derived from X, the | |||
4808 | // implicit conversion sequence is the one required to convert the element | |||
4809 | // to the parameter type. | |||
4810 | // | |||
4811 | // Otherwise, if the parameter type is a character array [... ] | |||
4812 | // and the initializer list has a single element that is an | |||
4813 | // appropriately-typed string literal (8.5.2 [dcl.init.string]), the | |||
4814 | // implicit conversion sequence is the identity conversion. | |||
4815 | if (From->getNumInits() == 1) { | |||
4816 | if (ToType->isRecordType()) { | |||
4817 | QualType InitType = From->getInit(0)->getType(); | |||
4818 | if (S.Context.hasSameUnqualifiedType(InitType, ToType) || | |||
4819 | S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) | |||
4820 | return TryCopyInitialization(S, From->getInit(0), ToType, | |||
4821 | SuppressUserConversions, | |||
4822 | InOverloadResolution, | |||
4823 | AllowObjCWritebackConversion); | |||
4824 | } | |||
4825 | // FIXME: Check the other conditions here: array of character type, | |||
4826 | // initializer is a string literal. | |||
4827 | if (ToType->isArrayType()) { | |||
4828 | InitializedEntity Entity = | |||
4829 | InitializedEntity::InitializeParameter(S.Context, ToType, | |||
4830 | /*Consumed=*/false); | |||
4831 | if (S.CanPerformCopyInitialization(Entity, From)) { | |||
4832 | Result.setStandard(); | |||
4833 | Result.Standard.setAsIdentityConversion(); | |||
4834 | Result.Standard.setFromType(ToType); | |||
4835 | Result.Standard.setAllToTypes(ToType); | |||
4836 | return Result; | |||
4837 | } | |||
4838 | } | |||
4839 | } | |||
4840 | ||||
4841 | // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). | |||
4842 | // C++11 [over.ics.list]p2: | |||
4843 | // If the parameter type is std::initializer_list<X> or "array of X" and | |||
4844 | // all the elements can be implicitly converted to X, the implicit | |||
4845 | // conversion sequence is the worst conversion necessary to convert an | |||
4846 | // element of the list to X. | |||
4847 | // | |||
4848 | // C++14 [over.ics.list]p3: | |||
4849 | // Otherwise, if the parameter type is "array of N X", if the initializer | |||
4850 | // list has exactly N elements or if it has fewer than N elements and X is | |||
4851 | // default-constructible, and if all the elements of the initializer list | |||
4852 | // can be implicitly converted to X, the implicit conversion sequence is | |||
4853 | // the worst conversion necessary to convert an element of the list to X. | |||
4854 | // | |||
4855 | // FIXME: We're missing a lot of these checks. | |||
4856 | bool toStdInitializerList = false; | |||
4857 | QualType X; | |||
4858 | if (ToType->isArrayType()) | |||
4859 | X = S.Context.getAsArrayType(ToType)->getElementType(); | |||
4860 | else | |||
4861 | toStdInitializerList = S.isStdInitializerList(ToType, &X); | |||
4862 | if (!X.isNull()) { | |||
4863 | for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { | |||
4864 | Expr *Init = From->getInit(i); | |||
4865 | ImplicitConversionSequence ICS = | |||
4866 | TryCopyInitialization(S, Init, X, SuppressUserConversions, | |||
4867 | InOverloadResolution, | |||
4868 | AllowObjCWritebackConversion); | |||
4869 | // If a single element isn't convertible, fail. | |||
4870 | if (ICS.isBad()) { | |||
4871 | Result = ICS; | |||
4872 | break; | |||
4873 | } | |||
4874 | // Otherwise, look for the worst conversion. | |||
4875 | if (Result.isBad() || CompareImplicitConversionSequences( | |||
4876 | S, From->getBeginLoc(), ICS, Result) == | |||
4877 | ImplicitConversionSequence::Worse) | |||
4878 | Result = ICS; | |||
4879 | } | |||
4880 | ||||
4881 | // For an empty list, we won't have computed any conversion sequence. | |||
4882 | // Introduce the identity conversion sequence. | |||
4883 | if (From->getNumInits() == 0) { | |||
4884 | Result.setStandard(); | |||
4885 | Result.Standard.setAsIdentityConversion(); | |||
4886 | Result.Standard.setFromType(ToType); | |||
4887 | Result.Standard.setAllToTypes(ToType); | |||
4888 | } | |||
4889 | ||||
4890 | Result.setStdInitializerListElement(toStdInitializerList); | |||
4891 | return Result; | |||
4892 | } | |||
4893 | ||||
4894 | // C++14 [over.ics.list]p4: | |||
4895 | // C++11 [over.ics.list]p3: | |||
4896 | // Otherwise, if the parameter is a non-aggregate class X and overload | |||
4897 | // resolution chooses a single best constructor [...] the implicit | |||
4898 | // conversion sequence is a user-defined conversion sequence. If multiple | |||
4899 | // constructors are viable but none is better than the others, the | |||
4900 | // implicit conversion sequence is a user-defined conversion sequence. | |||
4901 | if (ToType->isRecordType() && !ToType->isAggregateType()) { | |||
4902 | // This function can deal with initializer lists. | |||
4903 | return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, | |||
4904 | /*AllowExplicit=*/false, | |||
4905 | InOverloadResolution, /*CStyle=*/false, | |||
4906 | AllowObjCWritebackConversion, | |||
4907 | /*AllowObjCConversionOnExplicit=*/false); | |||
4908 | } | |||
4909 | ||||
4910 | // C++14 [over.ics.list]p5: | |||
4911 | // C++11 [over.ics.list]p4: | |||
4912 | // Otherwise, if the parameter has an aggregate type which can be | |||
4913 | // initialized from the initializer list [...] the implicit conversion | |||
4914 | // sequence is a user-defined conversion sequence. | |||
4915 | if (ToType->isAggregateType()) { | |||
4916 | // Type is an aggregate, argument is an init list. At this point it comes | |||
4917 | // down to checking whether the initialization works. | |||
4918 | // FIXME: Find out whether this parameter is consumed or not. | |||
4919 | // FIXME: Expose SemaInit's aggregate initialization code so that we don't | |||
4920 | // need to call into the initialization code here; overload resolution | |||
4921 | // should not be doing that. | |||
4922 | InitializedEntity Entity = | |||
4923 | InitializedEntity::InitializeParameter(S.Context, ToType, | |||
4924 | /*Consumed=*/false); | |||
4925 | if (S.CanPerformCopyInitialization(Entity, From)) { | |||
4926 | Result.setUserDefined(); | |||
4927 | Result.UserDefined.Before.setAsIdentityConversion(); | |||
4928 | // Initializer lists don't have a type. | |||
4929 | Result.UserDefined.Before.setFromType(QualType()); | |||
4930 | Result.UserDefined.Before.setAllToTypes(QualType()); | |||
4931 | ||||
4932 | Result.UserDefined.After.setAsIdentityConversion(); | |||
4933 | Result.UserDefined.After.setFromType(ToType); | |||
4934 | Result.UserDefined.After.setAllToTypes(ToType); | |||
4935 | Result.UserDefined.ConversionFunction = nullptr; | |||
4936 | } | |||
4937 | return Result; | |||
4938 | } | |||
4939 | ||||
4940 | // C++14 [over.ics.list]p6: | |||
4941 | // C++11 [over.ics.list]p5: | |||
4942 | // Otherwise, if the parameter is a reference, see 13.3.3.1.4. | |||
4943 | if (ToType->isReferenceType()) { | |||
4944 | // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't | |||
4945 | // mention initializer lists in any way. So we go by what list- | |||
4946 | // initialization would do and try to extrapolate from that. | |||
4947 | ||||
4948 | QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); | |||
4949 | ||||
4950 | // If the initializer list has a single element that is reference-related | |||
4951 | // to the parameter type, we initialize the reference from that. | |||
4952 | if (From->getNumInits() == 1) { | |||
4953 | Expr *Init = From->getInit(0); | |||
4954 | ||||
4955 | QualType T2 = Init->getType(); | |||
4956 | ||||
4957 | // If the initializer is the address of an overloaded function, try | |||
4958 | // to resolve the overloaded function. If all goes well, T2 is the | |||
4959 | // type of the resulting function. | |||
4960 | if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { | |||
4961 | DeclAccessPair Found; | |||
4962 | if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( | |||
4963 | Init, ToType, false, Found)) | |||
4964 | T2 = Fn->getType(); | |||
4965 | } | |||
4966 | ||||
4967 | // Compute some basic properties of the types and the initializer. | |||
4968 | bool dummy1 = false; | |||
4969 | bool dummy2 = false; | |||
4970 | bool dummy3 = false; | |||
4971 | Sema::ReferenceCompareResult RefRelationship = | |||
4972 | S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1, | |||
4973 | dummy2, dummy3); | |||
4974 | ||||
4975 | if (RefRelationship >= Sema::Ref_Related) { | |||
4976 | return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), | |||
4977 | SuppressUserConversions, | |||
4978 | /*AllowExplicit=*/false); | |||
4979 | } | |||
4980 | } | |||
4981 | ||||
4982 | // Otherwise, we bind the reference to a temporary created from the | |||
4983 | // initializer list. | |||
4984 | Result = TryListConversion(S, From, T1, SuppressUserConversions, | |||
4985 | InOverloadResolution, | |||
4986 | AllowObjCWritebackConversion); | |||
4987 | if (Result.isFailure()) | |||
4988 | return Result; | |||
4989 | assert(!Result.isEllipsis() &&((!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion." ) ? static_cast<void> (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 4990, __PRETTY_FUNCTION__)) | |||
4990 | "Sub-initialization cannot result in ellipsis conversion.")((!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion." ) ? static_cast<void> (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 4990, __PRETTY_FUNCTION__)); | |||
4991 | ||||
4992 | // Can we even bind to a temporary? | |||
4993 | if (ToType->isRValueReferenceType() || | |||
4994 | (T1.isConstQualified() && !T1.isVolatileQualified())) { | |||
4995 | StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : | |||
4996 | Result.UserDefined.After; | |||
4997 | SCS.ReferenceBinding = true; | |||
4998 | SCS.IsLvalueReference = ToType->isLValueReferenceType(); | |||
4999 | SCS.BindsToRvalue = true; | |||
5000 | SCS.BindsToFunctionLvalue = false; | |||
5001 | SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; | |||
5002 | SCS.ObjCLifetimeConversionBinding = false; | |||
5003 | } else | |||
5004 | Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, | |||
5005 | From, ToType); | |||
5006 | return Result; | |||
5007 | } | |||
5008 | ||||
5009 | // C++14 [over.ics.list]p7: | |||
5010 | // C++11 [over.ics.list]p6: | |||
5011 | // Otherwise, if the parameter type is not a class: | |||
5012 | if (!ToType->isRecordType()) { | |||
5013 | // - if the initializer list has one element that is not itself an | |||
5014 | // initializer list, the implicit conversion sequence is the one | |||
5015 | // required to convert the element to the parameter type. | |||
5016 | unsigned NumInits = From->getNumInits(); | |||
5017 | if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) | |||
5018 | Result = TryCopyInitialization(S, From->getInit(0), ToType, | |||
5019 | SuppressUserConversions, | |||
5020 | InOverloadResolution, | |||
5021 | AllowObjCWritebackConversion); | |||
5022 | // - if the initializer list has no elements, the implicit conversion | |||
5023 | // sequence is the identity conversion. | |||
5024 | else if (NumInits == 0) { | |||
5025 | Result.setStandard(); | |||
5026 | Result.Standard.setAsIdentityConversion(); | |||
5027 | Result.Standard.setFromType(ToType); | |||
5028 | Result.Standard.setAllToTypes(ToType); | |||
5029 | } | |||
5030 | return Result; | |||
5031 | } | |||
5032 | ||||
5033 | // C++14 [over.ics.list]p8: | |||
5034 | // C++11 [over.ics.list]p7: | |||
5035 | // In all cases other than those enumerated above, no conversion is possible | |||
5036 | return Result; | |||
5037 | } | |||
5038 | ||||
5039 | /// TryCopyInitialization - Try to copy-initialize a value of type | |||
5040 | /// ToType from the expression From. Return the implicit conversion | |||
5041 | /// sequence required to pass this argument, which may be a bad | |||
5042 | /// conversion sequence (meaning that the argument cannot be passed to | |||
5043 | /// a parameter of this type). If @p SuppressUserConversions, then we | |||
5044 | /// do not permit any user-defined conversion sequences. | |||
5045 | static ImplicitConversionSequence | |||
5046 | TryCopyInitialization(Sema &S, Expr *From, QualType ToType, | |||
5047 | bool SuppressUserConversions, | |||
5048 | bool InOverloadResolution, | |||
5049 | bool AllowObjCWritebackConversion, | |||
5050 | bool AllowExplicit) { | |||
5051 | if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) | |||
5052 | return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, | |||
5053 | InOverloadResolution,AllowObjCWritebackConversion); | |||
5054 | ||||
5055 | if (ToType->isReferenceType()) | |||
5056 | return TryReferenceInit(S, From, ToType, | |||
5057 | /*FIXME:*/ From->getBeginLoc(), | |||
5058 | SuppressUserConversions, AllowExplicit); | |||
5059 | ||||
5060 | return TryImplicitConversion(S, From, ToType, | |||
5061 | SuppressUserConversions, | |||
5062 | /*AllowExplicit=*/false, | |||
5063 | InOverloadResolution, | |||
5064 | /*CStyle=*/false, | |||
5065 | AllowObjCWritebackConversion, | |||
5066 | /*AllowObjCConversionOnExplicit=*/false); | |||
5067 | } | |||
5068 | ||||
5069 | static bool TryCopyInitialization(const CanQualType FromQTy, | |||
5070 | const CanQualType ToQTy, | |||
5071 | Sema &S, | |||
5072 | SourceLocation Loc, | |||
5073 | ExprValueKind FromVK) { | |||
5074 | OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); | |||
5075 | ImplicitConversionSequence ICS = | |||
5076 | TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); | |||
5077 | ||||
5078 | return !ICS.isBad(); | |||
5079 | } | |||
5080 | ||||
5081 | /// TryObjectArgumentInitialization - Try to initialize the object | |||
5082 | /// parameter of the given member function (@c Method) from the | |||
5083 | /// expression @p From. | |||
5084 | static ImplicitConversionSequence | |||
5085 | TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, | |||
5086 | Expr::Classification FromClassification, | |||
5087 | CXXMethodDecl *Method, | |||
5088 | CXXRecordDecl *ActingContext) { | |||
5089 | QualType ClassType = S.Context.getTypeDeclType(ActingContext); | |||
5090 | // [class.dtor]p2: A destructor can be invoked for a const, volatile or | |||
5091 | // const volatile object. | |||
5092 | Qualifiers Quals; | |||
5093 | if (isa<CXXDestructorDecl>(Method)) { | |||
5094 | Quals.addConst(); | |||
5095 | Quals.addVolatile(); | |||
5096 | } else { | |||
5097 | Quals = Method->getMethodQualifiers(); | |||
5098 | } | |||
5099 | ||||
5100 | QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); | |||
5101 | ||||
5102 | // Set up the conversion sequence as a "bad" conversion, to allow us | |||
5103 | // to exit early. | |||
5104 | ImplicitConversionSequence ICS; | |||
5105 | ||||
5106 | // We need to have an object of class type. | |||
5107 | if (const PointerType *PT = FromType->getAs<PointerType>()) { | |||
5108 | FromType = PT->getPointeeType(); | |||
5109 | ||||
5110 | // When we had a pointer, it's implicitly dereferenced, so we | |||
5111 | // better have an lvalue. | |||
5112 | assert(FromClassification.isLValue())((FromClassification.isLValue()) ? static_cast<void> (0 ) : __assert_fail ("FromClassification.isLValue()", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 5112, __PRETTY_FUNCTION__)); | |||
5113 | } | |||
5114 | ||||
5115 | assert(FromType->isRecordType())((FromType->isRecordType()) ? static_cast<void> (0) : __assert_fail ("FromType->isRecordType()", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 5115, __PRETTY_FUNCTION__)); | |||
5116 | ||||
5117 | // C++0x [over.match.funcs]p4: | |||
5118 | // For non-static member functions, the type of the implicit object | |||
5119 | // parameter is | |||
5120 | // | |||
5121 | // - "lvalue reference to cv X" for functions declared without a | |||
5122 | // ref-qualifier or with the & ref-qualifier | |||
5123 | // - "rvalue reference to cv X" for functions declared with the && | |||
5124 | // ref-qualifier | |||
5125 | // | |||
5126 | // where X is the class of which the function is a member and cv is the | |||
5127 | // cv-qualification on the member function declaration. | |||
5128 | // | |||
5129 | // However, when finding an implicit conversion sequence for the argument, we | |||
5130 | // are not allowed to perform user-defined conversions | |||
5131 | // (C++ [over.match.funcs]p5). We perform a simplified version of | |||
5132 | // reference binding here, that allows class rvalues to bind to | |||
5133 | // non-constant references. | |||
5134 | ||||
5135 | // First check the qualifiers. | |||
5136 | QualType FromTypeCanon = S.Context.getCanonicalType(FromType); | |||
5137 | if (ImplicitParamType.getCVRQualifiers() | |||
5138 | != FromTypeCanon.getLocalCVRQualifiers() && | |||
5139 | !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { | |||
5140 | ICS.setBad(BadConversionSequence::bad_qualifiers, | |||
5141 | FromType, ImplicitParamType); | |||
5142 | return ICS; | |||
5143 | } | |||
5144 | ||||
5145 | if (FromTypeCanon.getQualifiers().hasAddressSpace()) { | |||
5146 | Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); | |||
5147 | Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); | |||
5148 | if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { | |||
5149 | ICS.setBad(BadConversionSequence::bad_qualifiers, | |||
5150 | FromType, ImplicitParamType); | |||
5151 | return ICS; | |||
5152 | } | |||
5153 | } | |||
5154 | ||||
5155 | // Check that we have either the same type or a derived type. It | |||
5156 | // affects the conversion rank. | |||
5157 | QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); | |||
5158 | ImplicitConversionKind SecondKind; | |||
5159 | if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { | |||
5160 | SecondKind = ICK_Identity; | |||
5161 | } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) | |||
5162 | SecondKind = ICK_Derived_To_Base; | |||
5163 | else { | |||
5164 | ICS.setBad(BadConversionSequence::unrelated_class, | |||
5165 | FromType, ImplicitParamType); | |||
5166 | return ICS; | |||
5167 | } | |||
5168 | ||||
5169 | // Check the ref-qualifier. | |||
5170 | switch (Method->getRefQualifier()) { | |||
5171 | case RQ_None: | |||
5172 | // Do nothing; we don't care about lvalueness or rvalueness. | |||
5173 | break; | |||
5174 | ||||
5175 | case RQ_LValue: | |||
5176 | if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { | |||
5177 | // non-const lvalue reference cannot bind to an rvalue | |||
5178 | ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, | |||
5179 | ImplicitParamType); | |||
5180 | return ICS; | |||
5181 | } | |||
5182 | break; | |||
5183 | ||||
5184 | case RQ_RValue: | |||
5185 | if (!FromClassification.isRValue()) { | |||
5186 | // rvalue reference cannot bind to an lvalue | |||
5187 | ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, | |||
5188 | ImplicitParamType); | |||
5189 | return ICS; | |||
5190 | } | |||
5191 | break; | |||
5192 | } | |||
5193 | ||||
5194 | // Success. Mark this as a reference binding. | |||
5195 | ICS.setStandard(); | |||
5196 | ICS.Standard.setAsIdentityConversion(); | |||
5197 | ICS.Standard.Second = SecondKind; | |||
5198 | ICS.Standard.setFromType(FromType); | |||
5199 | ICS.Standard.setAllToTypes(ImplicitParamType); | |||
5200 | ICS.Standard.ReferenceBinding = true; | |||
5201 | ICS.Standard.DirectBinding = true; | |||
5202 | ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; | |||
5203 | ICS.Standard.BindsToFunctionLvalue = false; | |||
5204 | ICS.Standard.BindsToRvalue = FromClassification.isRValue(); | |||
5205 | ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier | |||
5206 | = (Method->getRefQualifier() == RQ_None); | |||
5207 | return ICS; | |||
5208 | } | |||
5209 | ||||
5210 | /// PerformObjectArgumentInitialization - Perform initialization of | |||
5211 | /// the implicit object parameter for the given Method with the given | |||
5212 | /// expression. | |||
5213 | ExprResult | |||
5214 | Sema::PerformObjectArgumentInitialization(Expr *From, | |||
5215 | NestedNameSpecifier *Qualifier, | |||
5216 | NamedDecl *FoundDecl, | |||
5217 | CXXMethodDecl *Method) { | |||
5218 | QualType FromRecordType, DestType; | |||
5219 | QualType ImplicitParamRecordType = | |||
5220 | Method->getThisType()->getAs<PointerType>()->getPointeeType(); | |||
5221 | ||||
5222 | Expr::Classification FromClassification; | |||
5223 | if (const PointerType *PT = From->getType()->getAs<PointerType>()) { | |||
5224 | FromRecordType = PT->getPointeeType(); | |||
5225 | DestType = Method->getThisType(); | |||
5226 | FromClassification = Expr::Classification::makeSimpleLValue(); | |||
5227 | } else { | |||
5228 | FromRecordType = From->getType(); | |||
5229 | DestType = ImplicitParamRecordType; | |||
5230 | FromClassification = From->Classify(Context); | |||
5231 | ||||
5232 | // When performing member access on an rvalue, materialize a temporary. | |||
5233 | if (From->isRValue()) { | |||
5234 | From = CreateMaterializeTemporaryExpr(FromRecordType, From, | |||
5235 | Method->getRefQualifier() != | |||
5236 | RefQualifierKind::RQ_RValue); | |||
5237 | } | |||
5238 | } | |||
5239 | ||||
5240 | // Note that we always use the true parent context when performing | |||
5241 | // the actual argument initialization. | |||
5242 | ImplicitConversionSequence ICS = TryObjectArgumentInitialization( | |||
5243 | *this, From->getBeginLoc(), From->getType(), FromClassification, Method, | |||
5244 | Method->getParent()); | |||
5245 | if (ICS.isBad()) { | |||
5246 | switch (ICS.Bad.Kind) { | |||
5247 | case BadConversionSequence::bad_qualifiers: { | |||
5248 | Qualifiers FromQs = FromRecordType.getQualifiers(); | |||
5249 | Qualifiers ToQs = DestType.getQualifiers(); | |||
5250 | unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); | |||
5251 | if (CVR) { | |||
5252 | Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) | |||
5253 | << Method->getDeclName() << FromRecordType << (CVR - 1) | |||
5254 | << From->getSourceRange(); | |||
5255 | Diag(Method->getLocation(), diag::note_previous_decl) | |||
5256 | << Method->getDeclName(); | |||
5257 | return ExprError(); | |||
5258 | } | |||
5259 | break; | |||
5260 | } | |||
5261 | ||||
5262 | case BadConversionSequence::lvalue_ref_to_rvalue: | |||
5263 | case BadConversionSequence::rvalue_ref_to_lvalue: { | |||
5264 | bool IsRValueQualified = | |||
5265 | Method->getRefQualifier() == RefQualifierKind::RQ_RValue; | |||
5266 | Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) | |||
5267 | << Method->getDeclName() << FromClassification.isRValue() | |||
5268 | << IsRValueQualified; | |||
5269 | Diag(Method->getLocation(), diag::note_previous_decl) | |||
5270 | << Method->getDeclName(); | |||
5271 | return ExprError(); | |||
5272 | } | |||
5273 | ||||
5274 | case BadConversionSequence::no_conversion: | |||
5275 | case BadConversionSequence::unrelated_class: | |||
5276 | break; | |||
5277 | } | |||
5278 | ||||
5279 | return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) | |||
5280 | << ImplicitParamRecordType << FromRecordType | |||
5281 | << From->getSourceRange(); | |||
5282 | } | |||
5283 | ||||
5284 | if (ICS.Standard.Second == ICK_Derived_To_Base) { | |||
5285 | ExprResult FromRes = | |||
5286 | PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); | |||
5287 | if (FromRes.isInvalid()) | |||
5288 | return ExprError(); | |||
5289 | From = FromRes.get(); | |||
5290 | } | |||
5291 | ||||
5292 | if (!Context.hasSameType(From->getType(), DestType)) { | |||
5293 | CastKind CK; | |||
5294 | if (FromRecordType.getAddressSpace() != DestType.getAddressSpace()) | |||
5295 | CK = CK_AddressSpaceConversion; | |||
5296 | else | |||
5297 | CK = CK_NoOp; | |||
5298 | From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); | |||
5299 | } | |||
5300 | return From; | |||
5301 | } | |||
5302 | ||||
5303 | /// TryContextuallyConvertToBool - Attempt to contextually convert the | |||
5304 | /// expression From to bool (C++0x [conv]p3). | |||
5305 | static ImplicitConversionSequence | |||
5306 | TryContextuallyConvertToBool(Sema &S, Expr *From) { | |||
5307 | return TryImplicitConversion(S, From, S.Context.BoolTy, | |||
5308 | /*SuppressUserConversions=*/false, | |||
5309 | /*AllowExplicit=*/true, | |||
5310 | /*InOverloadResolution=*/false, | |||
5311 | /*CStyle=*/false, | |||
5312 | /*AllowObjCWritebackConversion=*/false, | |||
5313 | /*AllowObjCConversionOnExplicit=*/false); | |||
5314 | } | |||
5315 | ||||
5316 | /// PerformContextuallyConvertToBool - Perform a contextual conversion | |||
5317 | /// of the expression From to bool (C++0x [conv]p3). | |||
5318 | ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { | |||
5319 | if (checkPlaceholderForOverload(*this, From)) | |||
5320 | return ExprError(); | |||
5321 | ||||
5322 | ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); | |||
5323 | if (!ICS.isBad()) | |||
5324 | return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); | |||
5325 | ||||
5326 | if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) | |||
5327 | return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) | |||
5328 | << From->getType() << From->getSourceRange(); | |||
5329 | return ExprError(); | |||
5330 | } | |||
5331 | ||||
5332 | /// Check that the specified conversion is permitted in a converted constant | |||
5333 | /// expression, according to C++11 [expr.const]p3. Return true if the conversion | |||
5334 | /// is acceptable. | |||
5335 | static bool CheckConvertedConstantConversions(Sema &S, | |||
5336 | StandardConversionSequence &SCS) { | |||
5337 | // Since we know that the target type is an integral or unscoped enumeration | |||
5338 | // type, most conversion kinds are impossible. All possible First and Third | |||
5339 | // conversions are fine. | |||
5340 | switch (SCS.Second) { | |||
5341 | case ICK_Identity: | |||
5342 | case ICK_Function_Conversion: | |||
5343 | case ICK_Integral_Promotion: | |||
5344 | case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. | |||
5345 | case ICK_Zero_Queue_Conversion: | |||
5346 | return true; | |||
5347 | ||||
5348 | case ICK_Boolean_Conversion: | |||
5349 | // Conversion from an integral or unscoped enumeration type to bool is | |||
5350 | // classified as ICK_Boolean_Conversion, but it's also arguably an integral | |||
5351 | // conversion, so we allow it in a converted constant expression. | |||
5352 | // | |||
5353 | // FIXME: Per core issue 1407, we should not allow this, but that breaks | |||
5354 | // a lot of popular code. We should at least add a warning for this | |||
5355 | // (non-conforming) extension. | |||
5356 | return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && | |||
5357 | SCS.getToType(2)->isBooleanType(); | |||
5358 | ||||
5359 | case ICK_Pointer_Conversion: | |||
5360 | case ICK_Pointer_Member: | |||
5361 | // C++1z: null pointer conversions and null member pointer conversions are | |||
5362 | // only permitted if the source type is std::nullptr_t. | |||
5363 | return SCS.getFromType()->isNullPtrType(); | |||
5364 | ||||
5365 | case ICK_Floating_Promotion: | |||
5366 | case ICK_Complex_Promotion: | |||
5367 | case ICK_Floating_Conversion: | |||
5368 | case ICK_Complex_Conversion: | |||
5369 | case ICK_Floating_Integral: | |||
5370 | case ICK_Compatible_Conversion: | |||
5371 | case ICK_Derived_To_Base: | |||
5372 | case ICK_Vector_Conversion: | |||
5373 | case ICK_Vector_Splat: | |||
5374 | case ICK_Complex_Real: | |||
5375 | case ICK_Block_Pointer_Conversion: | |||
5376 | case ICK_TransparentUnionConversion: | |||
5377 | case ICK_Writeback_Conversion: | |||
5378 | case ICK_Zero_Event_Conversion: | |||
5379 | case ICK_C_Only_Conversion: | |||
5380 | case ICK_Incompatible_Pointer_Conversion: | |||
5381 | return false; | |||
5382 | ||||
5383 | case ICK_Lvalue_To_Rvalue: | |||
5384 | case ICK_Array_To_Pointer: | |||
5385 | case ICK_Function_To_Pointer: | |||
5386 | llvm_unreachable("found a first conversion kind in Second")::llvm::llvm_unreachable_internal("found a first conversion kind in Second" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 5386); | |||
5387 | ||||
5388 | case ICK_Qualification: | |||
5389 | llvm_unreachable("found a third conversion kind in Second")::llvm::llvm_unreachable_internal("found a third conversion kind in Second" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 5389); | |||
5390 | ||||
5391 | case ICK_Num_Conversion_Kinds: | |||
5392 | break; | |||
5393 | } | |||
5394 | ||||
5395 | llvm_unreachable("unknown conversion kind")::llvm::llvm_unreachable_internal("unknown conversion kind", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 5395); | |||
5396 | } | |||
5397 | ||||
5398 | /// CheckConvertedConstantExpression - Check that the expression From is a | |||
5399 | /// converted constant expression of type T, perform the conversion and produce | |||
5400 | /// the converted expression, per C++11 [expr.const]p3. | |||
5401 | static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, | |||
5402 | QualType T, APValue &Value, | |||
5403 | Sema::CCEKind CCE, | |||
5404 | bool RequireInt) { | |||
5405 | assert(S.getLangOpts().CPlusPlus11 &&((S.getLangOpts().CPlusPlus11 && "converted constant expression outside C++11" ) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 5406, __PRETTY_FUNCTION__)) | |||
5406 | "converted constant expression outside C++11")((S.getLangOpts().CPlusPlus11 && "converted constant expression outside C++11" ) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 5406, __PRETTY_FUNCTION__)); | |||
5407 | ||||
5408 | if (checkPlaceholderForOverload(S, From)) | |||
5409 | return ExprError(); | |||
5410 | ||||
5411 | // C++1z [expr.const]p3: | |||
5412 | // A converted constant expression of type T is an expression, | |||
5413 | // implicitly converted to type T, where the converted | |||
5414 | // expression is a constant expression and the implicit conversion | |||
5415 | // sequence contains only [... list of conversions ...]. | |||
5416 | // C++1z [stmt.if]p2: | |||
5417 | // If the if statement is of the form if constexpr, the value of the | |||
5418 | // condition shall be a contextually converted constant expression of type | |||
5419 | // bool. | |||
5420 | ImplicitConversionSequence ICS = | |||
5421 | CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool | |||
5422 | ? TryContextuallyConvertToBool(S, From) | |||
5423 | : TryCopyInitialization(S, From, T, | |||
5424 | /*SuppressUserConversions=*/false, | |||
5425 | /*InOverloadResolution=*/false, | |||
5426 | /*AllowObjcWritebackConversion=*/false, | |||
5427 | /*AllowExplicit=*/false); | |||
5428 | StandardConversionSequence *SCS = nullptr; | |||
5429 | switch (ICS.getKind()) { | |||
5430 | case ImplicitConversionSequence::StandardConversion: | |||
5431 | SCS = &ICS.Standard; | |||
5432 | break; | |||
5433 | case ImplicitConversionSequence::UserDefinedConversion: | |||
5434 | // We are converting to a non-class type, so the Before sequence | |||
5435 | // must be trivial. | |||
5436 | SCS = &ICS.UserDefined.After; | |||
5437 | break; | |||
5438 | case ImplicitConversionSequence::AmbiguousConversion: | |||
5439 | case ImplicitConversionSequence::BadConversion: | |||
5440 | if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) | |||
5441 | return S.Diag(From->getBeginLoc(), | |||
5442 | diag::err_typecheck_converted_constant_expression) | |||
5443 | << From->getType() << From->getSourceRange() << T; | |||
5444 | return ExprError(); | |||
5445 | ||||
5446 | case ImplicitConversionSequence::EllipsisConversion: | |||
5447 | llvm_unreachable("ellipsis conversion in converted constant expression")::llvm::llvm_unreachable_internal("ellipsis conversion in converted constant expression" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 5447); | |||
5448 | } | |||
5449 | ||||
5450 | // Check that we would only use permitted conversions. | |||
5451 | if (!CheckConvertedConstantConversions(S, *SCS)) { | |||
5452 | return S.Diag(From->getBeginLoc(), | |||
5453 | diag::err_typecheck_converted_constant_expression_disallowed) | |||
5454 | << From->getType() << From->getSourceRange() << T; | |||
5455 | } | |||
5456 | // [...] and where the reference binding (if any) binds directly. | |||
5457 | if (SCS->ReferenceBinding && !SCS->DirectBinding) { | |||
5458 | return S.Diag(From->getBeginLoc(), | |||
5459 | diag::err_typecheck_converted_constant_expression_indirect) | |||
5460 | << From->getType() << From->getSourceRange() << T; | |||
5461 | } | |||
5462 | ||||
5463 | ExprResult Result = | |||
5464 | S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); | |||
5465 | if (Result.isInvalid()) | |||
5466 | return Result; | |||
5467 | ||||
5468 | // Check for a narrowing implicit conversion. | |||
5469 | APValue PreNarrowingValue; | |||
5470 | QualType PreNarrowingType; | |||
5471 | switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, | |||
5472 | PreNarrowingType)) { | |||
5473 | case NK_Dependent_Narrowing: | |||
5474 | // Implicit conversion to a narrower type, but the expression is | |||
5475 | // value-dependent so we can't tell whether it's actually narrowing. | |||
5476 | case NK_Variable_Narrowing: | |||
5477 | // Implicit conversion to a narrower type, and the value is not a constant | |||
5478 | // expression. We'll diagnose this in a moment. | |||
5479 | case NK_Not_Narrowing: | |||
5480 | break; | |||
5481 | ||||
5482 | case NK_Constant_Narrowing: | |||
5483 | S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) | |||
5484 | << CCE << /*Constant*/ 1 | |||
5485 | << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; | |||
5486 | break; | |||
5487 | ||||
5488 | case NK_Type_Narrowing: | |||
5489 | S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) | |||
5490 | << CCE << /*Constant*/ 0 << From->getType() << T; | |||
5491 | break; | |||
5492 | } | |||
5493 | ||||
5494 | if (Result.get()->isValueDependent()) { | |||
5495 | Value = APValue(); | |||
5496 | return Result; | |||
5497 | } | |||
5498 | ||||
5499 | // Check the expression is a constant expression. | |||
5500 | SmallVector<PartialDiagnosticAt, 8> Notes; | |||
5501 | Expr::EvalResult Eval; | |||
5502 | Eval.Diag = &Notes; | |||
5503 | Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg | |||
5504 | ? Expr::EvaluateForMangling | |||
5505 | : Expr::EvaluateForCodeGen; | |||
5506 | ||||
5507 | if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || | |||
5508 | (RequireInt && !Eval.Val.isInt())) { | |||
5509 | // The expression can't be folded, so we can't keep it at this position in | |||
5510 | // the AST. | |||
5511 | Result = ExprError(); | |||
5512 | } else { | |||
5513 | Value = Eval.Val; | |||
5514 | ||||
5515 | if (Notes.empty()) { | |||
5516 | // It's a constant expression. | |||
5517 | return ConstantExpr::Create(S.Context, Result.get()); | |||
5518 | } | |||
5519 | } | |||
5520 | ||||
5521 | // It's not a constant expression. Produce an appropriate diagnostic. | |||
5522 | if (Notes.size() == 1 && | |||
5523 | Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) | |||
5524 | S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; | |||
5525 | else { | |||
5526 | S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) | |||
5527 | << CCE << From->getSourceRange(); | |||
5528 | for (unsigned I = 0; I < Notes.size(); ++I) | |||
5529 | S.Diag(Notes[I].first, Notes[I].second); | |||
5530 | } | |||
5531 | return ExprError(); | |||
5532 | } | |||
5533 | ||||
5534 | ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, | |||
5535 | APValue &Value, CCEKind CCE) { | |||
5536 | return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); | |||
5537 | } | |||
5538 | ||||
5539 | ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, | |||
5540 | llvm::APSInt &Value, | |||
5541 | CCEKind CCE) { | |||
5542 | assert(T->isIntegralOrEnumerationType() && "unexpected converted const type")((T->isIntegralOrEnumerationType() && "unexpected converted const type" ) ? static_cast<void> (0) : __assert_fail ("T->isIntegralOrEnumerationType() && \"unexpected converted const type\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 5542, __PRETTY_FUNCTION__)); | |||
5543 | ||||
5544 | APValue V; | |||
5545 | auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); | |||
5546 | if (!R.isInvalid() && !R.get()->isValueDependent()) | |||
5547 | Value = V.getInt(); | |||
5548 | return R; | |||
5549 | } | |||
5550 | ||||
5551 | ||||
5552 | /// dropPointerConversions - If the given standard conversion sequence | |||
5553 | /// involves any pointer conversions, remove them. This may change | |||
5554 | /// the result type of the conversion sequence. | |||
5555 | static void dropPointerConversion(StandardConversionSequence &SCS) { | |||
5556 | if (SCS.Second == ICK_Pointer_Conversion) { | |||
5557 | SCS.Second = ICK_Identity; | |||
5558 | SCS.Third = ICK_Identity; | |||
5559 | SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; | |||
5560 | } | |||
5561 | } | |||
5562 | ||||
5563 | /// TryContextuallyConvertToObjCPointer - Attempt to contextually | |||
5564 | /// convert the expression From to an Objective-C pointer type. | |||
5565 | static ImplicitConversionSequence | |||
5566 | TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { | |||
5567 | // Do an implicit conversion to 'id'. | |||
5568 | QualType Ty = S.Context.getObjCIdType(); | |||
5569 | ImplicitConversionSequence ICS | |||
5570 | = TryImplicitConversion(S, From, Ty, | |||
5571 | // FIXME: Are these flags correct? | |||
5572 | /*SuppressUserConversions=*/false, | |||
5573 | /*AllowExplicit=*/true, | |||
5574 | /*InOverloadResolution=*/false, | |||
5575 | /*CStyle=*/false, | |||
5576 | /*AllowObjCWritebackConversion=*/false, | |||
5577 | /*AllowObjCConversionOnExplicit=*/true); | |||
5578 | ||||
5579 | // Strip off any final conversions to 'id'. | |||
5580 | switch (ICS.getKind()) { | |||
5581 | case ImplicitConversionSequence::BadConversion: | |||
5582 | case ImplicitConversionSequence::AmbiguousConversion: | |||
5583 | case ImplicitConversionSequence::EllipsisConversion: | |||
5584 | break; | |||
5585 | ||||
5586 | case ImplicitConversionSequence::UserDefinedConversion: | |||
5587 | dropPointerConversion(ICS.UserDefined.After); | |||
5588 | break; | |||
5589 | ||||
5590 | case ImplicitConversionSequence::StandardConversion: | |||
5591 | dropPointerConversion(ICS.Standard); | |||
5592 | break; | |||
5593 | } | |||
5594 | ||||
5595 | return ICS; | |||
5596 | } | |||
5597 | ||||
5598 | /// PerformContextuallyConvertToObjCPointer - Perform a contextual | |||
5599 | /// conversion of the expression From to an Objective-C pointer type. | |||
5600 | /// Returns a valid but null ExprResult if no conversion sequence exists. | |||
5601 | ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { | |||
5602 | if (checkPlaceholderForOverload(*this, From)) | |||
5603 | return ExprError(); | |||
5604 | ||||
5605 | QualType Ty = Context.getObjCIdType(); | |||
5606 | ImplicitConversionSequence ICS = | |||
5607 | TryContextuallyConvertToObjCPointer(*this, From); | |||
5608 | if (!ICS.isBad()) | |||
5609 | return PerformImplicitConversion(From, Ty, ICS, AA_Converting); | |||
5610 | return ExprResult(); | |||
5611 | } | |||
5612 | ||||
5613 | /// Determine whether the provided type is an integral type, or an enumeration | |||
5614 | /// type of a permitted flavor. | |||
5615 | bool Sema::ICEConvertDiagnoser::match(QualType T) { | |||
5616 | return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() | |||
5617 | : T->isIntegralOrUnscopedEnumerationType(); | |||
5618 | } | |||
5619 | ||||
5620 | static ExprResult | |||
5621 | diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, | |||
5622 | Sema::ContextualImplicitConverter &Converter, | |||
5623 | QualType T, UnresolvedSetImpl &ViableConversions) { | |||
5624 | ||||
5625 | if (Converter.Suppress) | |||
5626 | return ExprError(); | |||
5627 | ||||
5628 | Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); | |||
5629 | for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { | |||
5630 | CXXConversionDecl *Conv = | |||
5631 | cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); | |||
5632 | QualType ConvTy = Conv->getConversionType().getNonReferenceType(); | |||
5633 | Converter.noteAmbiguous(SemaRef, Conv, ConvTy); | |||
5634 | } | |||
5635 | return From; | |||
5636 | } | |||
5637 | ||||
5638 | static bool | |||
5639 | diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, | |||
5640 | Sema::ContextualImplicitConverter &Converter, | |||
5641 | QualType T, bool HadMultipleCandidates, | |||
5642 | UnresolvedSetImpl &ExplicitConversions) { | |||
5643 | if (ExplicitConversions.size() == 1 && !Converter.Suppress) { | |||
5644 | DeclAccessPair Found = ExplicitConversions[0]; | |||
5645 | CXXConversionDecl *Conversion = | |||
5646 | cast<CXXConversionDecl>(Found->getUnderlyingDecl()); | |||
5647 | ||||
5648 | // The user probably meant to invoke the given explicit | |||
5649 | // conversion; use it. | |||
5650 | QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); | |||
5651 | std::string TypeStr; | |||
5652 | ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); | |||
5653 | ||||
5654 | Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) | |||
5655 | << FixItHint::CreateInsertion(From->getBeginLoc(), | |||
5656 | "static_cast<" + TypeStr + ">(") | |||
5657 | << FixItHint::CreateInsertion( | |||
5658 | SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); | |||
5659 | Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); | |||
5660 | ||||
5661 | // If we aren't in a SFINAE context, build a call to the | |||
5662 | // explicit conversion function. | |||
5663 | if (SemaRef.isSFINAEContext()) | |||
5664 | return true; | |||
5665 | ||||
5666 | SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); | |||
5667 | ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, | |||
5668 | HadMultipleCandidates); | |||
5669 | if (Result.isInvalid()) | |||
5670 | return true; | |||
5671 | // Record usage of conversion in an implicit cast. | |||
5672 | From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), | |||
5673 | CK_UserDefinedConversion, Result.get(), | |||
5674 | nullptr, Result.get()->getValueKind()); | |||
5675 | } | |||
5676 | return false; | |||
5677 | } | |||
5678 | ||||
5679 | static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, | |||
5680 | Sema::ContextualImplicitConverter &Converter, | |||
5681 | QualType T, bool HadMultipleCandidates, | |||
5682 | DeclAccessPair &Found) { | |||
5683 | CXXConversionDecl *Conversion = | |||
5684 | cast<CXXConversionDecl>(Found->getUnderlyingDecl()); | |||
5685 | SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); | |||
5686 | ||||
5687 | QualType ToType = Conversion->getConversionType().getNonReferenceType(); | |||
5688 | if (!Converter.SuppressConversion) { | |||
5689 | if (SemaRef.isSFINAEContext()) | |||
5690 | return true; | |||
5691 | ||||
5692 | Converter.diagnoseConversion(SemaRef, Loc, T, ToType) | |||
5693 | << From->getSourceRange(); | |||
5694 | } | |||
5695 | ||||
5696 | ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, | |||
5697 | HadMultipleCandidates); | |||
5698 | if (Result.isInvalid()) | |||
5699 | return true; | |||
5700 | // Record usage of conversion in an implicit cast. | |||
5701 | From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), | |||
5702 | CK_UserDefinedConversion, Result.get(), | |||
5703 | nullptr, Result.get()->getValueKind()); | |||
5704 | return false; | |||
5705 | } | |||
5706 | ||||
5707 | static ExprResult finishContextualImplicitConversion( | |||
5708 | Sema &SemaRef, SourceLocation Loc, Expr *From, | |||
5709 | Sema::ContextualImplicitConverter &Converter) { | |||
5710 | if (!Converter.match(From->getType()) && !Converter.Suppress) | |||
5711 | Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) | |||
5712 | << From->getSourceRange(); | |||
5713 | ||||
5714 | return SemaRef.DefaultLvalueConversion(From); | |||
5715 | } | |||
5716 | ||||
5717 | static void | |||
5718 | collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, | |||
5719 | UnresolvedSetImpl &ViableConversions, | |||
5720 | OverloadCandidateSet &CandidateSet) { | |||
5721 | for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { | |||
5722 | DeclAccessPair FoundDecl = ViableConversions[I]; | |||
5723 | NamedDecl *D = FoundDecl.getDecl(); | |||
5724 | CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); | |||
5725 | if (isa<UsingShadowDecl>(D)) | |||
5726 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | |||
5727 | ||||
5728 | CXXConversionDecl *Conv; | |||
5729 | FunctionTemplateDecl *ConvTemplate; | |||
5730 | if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) | |||
5731 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); | |||
5732 | else | |||
5733 | Conv = cast<CXXConversionDecl>(D); | |||
5734 | ||||
5735 | if (ConvTemplate) | |||
5736 | SemaRef.AddTemplateConversionCandidate( | |||
5737 | ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, | |||
5738 | /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); | |||
5739 | else | |||
5740 | SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, | |||
5741 | ToType, CandidateSet, | |||
5742 | /*AllowObjCConversionOnExplicit=*/false, | |||
5743 | /*AllowExplicit*/ true); | |||
5744 | } | |||
5745 | } | |||
5746 | ||||
5747 | /// Attempt to convert the given expression to a type which is accepted | |||
5748 | /// by the given converter. | |||
5749 | /// | |||
5750 | /// This routine will attempt to convert an expression of class type to a | |||
5751 | /// type accepted by the specified converter. In C++11 and before, the class | |||
5752 | /// must have a single non-explicit conversion function converting to a matching | |||
5753 | /// type. In C++1y, there can be multiple such conversion functions, but only | |||
5754 | /// one target type. | |||
5755 | /// | |||
5756 | /// \param Loc The source location of the construct that requires the | |||
5757 | /// conversion. | |||
5758 | /// | |||
5759 | /// \param From The expression we're converting from. | |||
5760 | /// | |||
5761 | /// \param Converter Used to control and diagnose the conversion process. | |||
5762 | /// | |||
5763 | /// \returns The expression, converted to an integral or enumeration type if | |||
5764 | /// successful. | |||
5765 | ExprResult Sema::PerformContextualImplicitConversion( | |||
5766 | SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { | |||
5767 | // We can't perform any more checking for type-dependent expressions. | |||
5768 | if (From->isTypeDependent()) | |||
5769 | return From; | |||
5770 | ||||
5771 | // Process placeholders immediately. | |||
5772 | if (From->hasPlaceholderType()) { | |||
5773 | ExprResult result = CheckPlaceholderExpr(From); | |||
5774 | if (result.isInvalid()) | |||
5775 | return result; | |||
5776 | From = result.get(); | |||
5777 | } | |||
5778 | ||||
5779 | // If the expression already has a matching type, we're golden. | |||
5780 | QualType T = From->getType(); | |||
5781 | if (Converter.match(T)) | |||
5782 | return DefaultLvalueConversion(From); | |||
5783 | ||||
5784 | // FIXME: Check for missing '()' if T is a function type? | |||
5785 | ||||
5786 | // We can only perform contextual implicit conversions on objects of class | |||
5787 | // type. | |||
5788 | const RecordType *RecordTy = T->getAs<RecordType>(); | |||
5789 | if (!RecordTy || !getLangOpts().CPlusPlus) { | |||
5790 | if (!Converter.Suppress) | |||
5791 | Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); | |||
5792 | return From; | |||
5793 | } | |||
5794 | ||||
5795 | // We must have a complete class type. | |||
5796 | struct TypeDiagnoserPartialDiag : TypeDiagnoser { | |||
5797 | ContextualImplicitConverter &Converter; | |||
5798 | Expr *From; | |||
5799 | ||||
5800 | TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) | |||
5801 | : Converter(Converter), From(From) {} | |||
5802 | ||||
5803 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { | |||
5804 | Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); | |||
5805 | } | |||
5806 | } IncompleteDiagnoser(Converter, From); | |||
5807 | ||||
5808 | if (Converter.Suppress ? !isCompleteType(Loc, T) | |||
5809 | : RequireCompleteType(Loc, T, IncompleteDiagnoser)) | |||
5810 | return From; | |||
5811 | ||||
5812 | // Look for a conversion to an integral or enumeration type. | |||
5813 | UnresolvedSet<4> | |||
5814 | ViableConversions; // These are *potentially* viable in C++1y. | |||
5815 | UnresolvedSet<4> ExplicitConversions; | |||
5816 | const auto &Conversions = | |||
5817 | cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); | |||
5818 | ||||
5819 | bool HadMultipleCandidates = | |||
5820 | (std::distance(Conversions.begin(), Conversions.end()) > 1); | |||
5821 | ||||
5822 | // To check that there is only one target type, in C++1y: | |||
5823 | QualType ToType; | |||
5824 | bool HasUniqueTargetType = true; | |||
5825 | ||||
5826 | // Collect explicit or viable (potentially in C++1y) conversions. | |||
5827 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { | |||
5828 | NamedDecl *D = (*I)->getUnderlyingDecl(); | |||
5829 | CXXConversionDecl *Conversion; | |||
5830 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); | |||
5831 | if (ConvTemplate) { | |||
5832 | if (getLangOpts().CPlusPlus14) | |||
5833 | Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); | |||
5834 | else | |||
5835 | continue; // C++11 does not consider conversion operator templates(?). | |||
5836 | } else | |||
5837 | Conversion = cast<CXXConversionDecl>(D); | |||
5838 | ||||
5839 | assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially " "viable in C++1y") ? static_cast<void> (0) : __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 5841, __PRETTY_FUNCTION__)) | |||
5840 | "Conversion operator templates are considered potentially "(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially " "viable in C++1y") ? static_cast<void> (0) : __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 5841, __PRETTY_FUNCTION__)) | |||
5841 | "viable in C++1y")(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially " "viable in C++1y") ? static_cast<void> (0) : __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 5841, __PRETTY_FUNCTION__)); | |||
5842 | ||||
5843 | QualType CurToType = Conversion->getConversionType().getNonReferenceType(); | |||
5844 | if (Converter.match(CurToType) || ConvTemplate) { | |||
5845 | ||||
5846 | if (Conversion->isExplicit()) { | |||
5847 | // FIXME: For C++1y, do we need this restriction? | |||
5848 | // cf. diagnoseNoViableConversion() | |||
5849 | if (!ConvTemplate) | |||
5850 | ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); | |||
5851 | } else { | |||
5852 | if (!ConvTemplate && getLangOpts().CPlusPlus14) { | |||
5853 | if (ToType.isNull()) | |||
5854 | ToType = CurToType.getUnqualifiedType(); | |||
5855 | else if (HasUniqueTargetType && | |||
5856 | (CurToType.getUnqualifiedType() != ToType)) | |||
5857 | HasUniqueTargetType = false; | |||
5858 | } | |||
5859 | ViableConversions.addDecl(I.getDecl(), I.getAccess()); | |||
5860 | } | |||
5861 | } | |||
5862 | } | |||
5863 | ||||
5864 | if (getLangOpts().CPlusPlus14) { | |||
5865 | // C++1y [conv]p6: | |||
5866 | // ... An expression e of class type E appearing in such a context | |||
5867 | // is said to be contextually implicitly converted to a specified | |||
5868 | // type T and is well-formed if and only if e can be implicitly | |||
5869 | // converted to a type T that is determined as follows: E is searched | |||
5870 | // for conversion functions whose return type is cv T or reference to | |||
5871 | // cv T such that T is allowed by the context. There shall be | |||
5872 | // exactly one such T. | |||
5873 | ||||
5874 | // If no unique T is found: | |||
5875 | if (ToType.isNull()) { | |||
5876 | if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, | |||
5877 | HadMultipleCandidates, | |||
5878 | ExplicitConversions)) | |||
5879 | return ExprError(); | |||
5880 | return finishContextualImplicitConversion(*this, Loc, From, Converter); | |||
5881 | } | |||
5882 | ||||
5883 | // If more than one unique Ts are found: | |||
5884 | if (!HasUniqueTargetType) | |||
5885 | return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, | |||
5886 | ViableConversions); | |||
5887 | ||||
5888 | // If one unique T is found: | |||
5889 | // First, build a candidate set from the previously recorded | |||
5890 | // potentially viable conversions. | |||
5891 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); | |||
5892 | collectViableConversionCandidates(*this, From, ToType, ViableConversions, | |||
5893 | CandidateSet); | |||
5894 | ||||
5895 | // Then, perform overload resolution over the candidate set. | |||
5896 | OverloadCandidateSet::iterator Best; | |||
5897 | switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { | |||
5898 | case OR_Success: { | |||
5899 | // Apply this conversion. | |||
5900 | DeclAccessPair Found = | |||
5901 | DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); | |||
5902 | if (recordConversion(*this, Loc, From, Converter, T, | |||
5903 | HadMultipleCandidates, Found)) | |||
5904 | return ExprError(); | |||
5905 | break; | |||
5906 | } | |||
5907 | case OR_Ambiguous: | |||
5908 | return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, | |||
5909 | ViableConversions); | |||
5910 | case OR_No_Viable_Function: | |||
5911 | if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, | |||
5912 | HadMultipleCandidates, | |||
5913 | ExplicitConversions)) | |||
5914 | return ExprError(); | |||
5915 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
5916 | case OR_Deleted: | |||
5917 | // We'll complain below about a non-integral condition type. | |||
5918 | break; | |||
5919 | } | |||
5920 | } else { | |||
5921 | switch (ViableConversions.size()) { | |||
5922 | case 0: { | |||
5923 | if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, | |||
5924 | HadMultipleCandidates, | |||
5925 | ExplicitConversions)) | |||
5926 | return ExprError(); | |||
5927 | ||||
5928 | // We'll complain below about a non-integral condition type. | |||
5929 | break; | |||
5930 | } | |||
5931 | case 1: { | |||
5932 | // Apply this conversion. | |||
5933 | DeclAccessPair Found = ViableConversions[0]; | |||
5934 | if (recordConversion(*this, Loc, From, Converter, T, | |||
5935 | HadMultipleCandidates, Found)) | |||
5936 | return ExprError(); | |||
5937 | break; | |||
5938 | } | |||
5939 | default: | |||
5940 | return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, | |||
5941 | ViableConversions); | |||
5942 | } | |||
5943 | } | |||
5944 | ||||
5945 | return finishContextualImplicitConversion(*this, Loc, From, Converter); | |||
5946 | } | |||
5947 | ||||
5948 | /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is | |||
5949 | /// an acceptable non-member overloaded operator for a call whose | |||
5950 | /// arguments have types T1 (and, if non-empty, T2). This routine | |||
5951 | /// implements the check in C++ [over.match.oper]p3b2 concerning | |||
5952 | /// enumeration types. | |||
5953 | static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, | |||
5954 | FunctionDecl *Fn, | |||
5955 | ArrayRef<Expr *> Args) { | |||
5956 | QualType T1 = Args[0]->getType(); | |||
5957 | QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); | |||
5958 | ||||
5959 | if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) | |||
5960 | return true; | |||
5961 | ||||
5962 | if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) | |||
5963 | return true; | |||
5964 | ||||
5965 | const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); | |||
5966 | if (Proto->getNumParams() < 1) | |||
5967 | return false; | |||
5968 | ||||
5969 | if (T1->isEnumeralType()) { | |||
5970 | QualType ArgType = Proto->getParamType(0).getNonReferenceType(); | |||
5971 | if (Context.hasSameUnqualifiedType(T1, ArgType)) | |||
5972 | return true; | |||
5973 | } | |||
5974 | ||||
5975 | if (Proto->getNumParams() < 2) | |||
5976 | return false; | |||
5977 | ||||
5978 | if (!T2.isNull() && T2->isEnumeralType()) { | |||
5979 | QualType ArgType = Proto->getParamType(1).getNonReferenceType(); | |||
5980 | if (Context.hasSameUnqualifiedType(T2, ArgType)) | |||
5981 | return true; | |||
5982 | } | |||
5983 | ||||
5984 | return false; | |||
5985 | } | |||
5986 | ||||
5987 | /// AddOverloadCandidate - Adds the given function to the set of | |||
5988 | /// candidate functions, using the given function call arguments. If | |||
5989 | /// @p SuppressUserConversions, then don't allow user-defined | |||
5990 | /// conversions via constructors or conversion operators. | |||
5991 | /// | |||
5992 | /// \param PartialOverloading true if we are performing "partial" overloading | |||
5993 | /// based on an incomplete set of function arguments. This feature is used by | |||
5994 | /// code completion. | |||
5995 | void Sema::AddOverloadCandidate( | |||
5996 | FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, | |||
5997 | OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, | |||
5998 | bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, | |||
5999 | ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions) { | |||
6000 | const FunctionProtoType *Proto | |||
6001 | = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); | |||
6002 | assert(Proto && "Functions without a prototype cannot be overloaded")((Proto && "Functions without a prototype cannot be overloaded" ) ? static_cast<void> (0) : __assert_fail ("Proto && \"Functions without a prototype cannot be overloaded\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 6002, __PRETTY_FUNCTION__)); | |||
6003 | assert(!Function->getDescribedFunctionTemplate() &&((!Function->getDescribedFunctionTemplate() && "Use AddTemplateOverloadCandidate for function templates" ) ? static_cast<void> (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 6004, __PRETTY_FUNCTION__)) | |||
6004 | "Use AddTemplateOverloadCandidate for function templates")((!Function->getDescribedFunctionTemplate() && "Use AddTemplateOverloadCandidate for function templates" ) ? static_cast<void> (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 6004, __PRETTY_FUNCTION__)); | |||
6005 | ||||
6006 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { | |||
6007 | if (!isa<CXXConstructorDecl>(Method)) { | |||
6008 | // If we get here, it's because we're calling a member function | |||
6009 | // that is named without a member access expression (e.g., | |||
6010 | // "this->f") that was either written explicitly or created | |||
6011 | // implicitly. This can happen with a qualified call to a member | |||
6012 | // function, e.g., X::f(). We use an empty type for the implied | |||
6013 | // object argument (C++ [over.call.func]p3), and the acting context | |||
6014 | // is irrelevant. | |||
6015 | AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), | |||
6016 | Expr::Classification::makeSimpleLValue(), Args, | |||
6017 | CandidateSet, SuppressUserConversions, | |||
6018 | PartialOverloading, EarlyConversions); | |||
6019 | return; | |||
6020 | } | |||
6021 | // We treat a constructor like a non-member function, since its object | |||
6022 | // argument doesn't participate in overload resolution. | |||
6023 | } | |||
6024 | ||||
6025 | if (!CandidateSet.isNewCandidate(Function)) | |||
6026 | return; | |||
6027 | ||||
6028 | // C++ [over.match.oper]p3: | |||
6029 | // if no operand has a class type, only those non-member functions in the | |||
6030 | // lookup set that have a first parameter of type T1 or "reference to | |||
6031 | // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there | |||
6032 | // is a right operand) a second parameter of type T2 or "reference to | |||
6033 | // (possibly cv-qualified) T2", when T2 is an enumeration type, are | |||
6034 | // candidate functions. | |||
6035 | if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && | |||
6036 | !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) | |||
6037 | return; | |||
6038 | ||||
6039 | // C++11 [class.copy]p11: [DR1402] | |||
6040 | // A defaulted move constructor that is defined as deleted is ignored by | |||
6041 | // overload resolution. | |||
6042 | CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); | |||
6043 | if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && | |||
6044 | Constructor->isMoveConstructor()) | |||
6045 | return; | |||
6046 | ||||
6047 | // Overload resolution is always an unevaluated context. | |||
6048 | EnterExpressionEvaluationContext Unevaluated( | |||
6049 | *this, Sema::ExpressionEvaluationContext::Unevaluated); | |||
6050 | ||||
6051 | // Add this candidate | |||
6052 | OverloadCandidate &Candidate = | |||
6053 | CandidateSet.addCandidate(Args.size(), EarlyConversions); | |||
6054 | Candidate.FoundDecl = FoundDecl; | |||
6055 | Candidate.Function = Function; | |||
6056 | Candidate.Viable = true; | |||
6057 | Candidate.IsSurrogate = false; | |||
6058 | Candidate.IsADLCandidate = IsADLCandidate; | |||
6059 | Candidate.IgnoreObjectArgument = false; | |||
6060 | Candidate.ExplicitCallArguments = Args.size(); | |||
6061 | ||||
6062 | if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && | |||
6063 | !Function->getAttr<TargetAttr>()->isDefaultVersion()) { | |||
6064 | Candidate.Viable = false; | |||
6065 | Candidate.FailureKind = ovl_non_default_multiversion_function; | |||
6066 | return; | |||
6067 | } | |||
6068 | ||||
6069 | if (Constructor) { | |||
6070 | // C++ [class.copy]p3: | |||
6071 | // A member function template is never instantiated to perform the copy | |||
6072 | // of a class object to an object of its class type. | |||
6073 | QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); | |||
6074 | if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && | |||
6075 | (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || | |||
6076 | IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), | |||
6077 | ClassType))) { | |||
6078 | Candidate.Viable = false; | |||
6079 | Candidate.FailureKind = ovl_fail_illegal_constructor; | |||
6080 | return; | |||
6081 | } | |||
6082 | ||||
6083 | // C++ [over.match.funcs]p8: (proposed DR resolution) | |||
6084 | // A constructor inherited from class type C that has a first parameter | |||
6085 | // of type "reference to P" (including such a constructor instantiated | |||
6086 | // from a template) is excluded from the set of candidate functions when | |||
6087 | // constructing an object of type cv D if the argument list has exactly | |||
6088 | // one argument and D is reference-related to P and P is reference-related | |||
6089 | // to C. | |||
6090 | auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); | |||
6091 | if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && | |||
6092 | Constructor->getParamDecl(0)->getType()->isReferenceType()) { | |||
6093 | QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); | |||
6094 | QualType C = Context.getRecordType(Constructor->getParent()); | |||
6095 | QualType D = Context.getRecordType(Shadow->getParent()); | |||
6096 | SourceLocation Loc = Args.front()->getExprLoc(); | |||
6097 | if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && | |||
6098 | (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { | |||
6099 | Candidate.Viable = false; | |||
6100 | Candidate.FailureKind = ovl_fail_inhctor_slice; | |||
6101 | return; | |||
6102 | } | |||
6103 | } | |||
6104 | } | |||
6105 | ||||
6106 | unsigned NumParams = Proto->getNumParams(); | |||
6107 | ||||
6108 | // (C++ 13.3.2p2): A candidate function having fewer than m | |||
6109 | // parameters is viable only if it has an ellipsis in its parameter | |||
6110 | // list (8.3.5). | |||
6111 | if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && | |||
6112 | !Proto->isVariadic()) { | |||
6113 | Candidate.Viable = false; | |||
6114 | Candidate.FailureKind = ovl_fail_too_many_arguments; | |||
6115 | return; | |||
6116 | } | |||
6117 | ||||
6118 | // (C++ 13.3.2p2): A candidate function having more than m parameters | |||
6119 | // is viable only if the (m+1)st parameter has a default argument | |||
6120 | // (8.3.6). For the purposes of overload resolution, the | |||
6121 | // parameter list is truncated on the right, so that there are | |||
6122 | // exactly m parameters. | |||
6123 | unsigned MinRequiredArgs = Function->getMinRequiredArguments(); | |||
6124 | if (Args.size() < MinRequiredArgs && !PartialOverloading) { | |||
6125 | // Not enough arguments. | |||
6126 | Candidate.Viable = false; | |||
6127 | Candidate.FailureKind = ovl_fail_too_few_arguments; | |||
6128 | return; | |||
6129 | } | |||
6130 | ||||
6131 | // (CUDA B.1): Check for invalid calls between targets. | |||
6132 | if (getLangOpts().CUDA) | |||
6133 | if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) | |||
6134 | // Skip the check for callers that are implicit members, because in this | |||
6135 | // case we may not yet know what the member's target is; the target is | |||
6136 | // inferred for the member automatically, based on the bases and fields of | |||
6137 | // the class. | |||
6138 | if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { | |||
6139 | Candidate.Viable = false; | |||
6140 | Candidate.FailureKind = ovl_fail_bad_target; | |||
6141 | return; | |||
6142 | } | |||
6143 | ||||
6144 | // Determine the implicit conversion sequences for each of the | |||
6145 | // arguments. | |||
6146 | for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { | |||
6147 | if (Candidate.Conversions[ArgIdx].isInitialized()) { | |||
6148 | // We already formed a conversion sequence for this parameter during | |||
6149 | // template argument deduction. | |||
6150 | } else if (ArgIdx < NumParams) { | |||
6151 | // (C++ 13.3.2p3): for F to be a viable function, there shall | |||
6152 | // exist for each argument an implicit conversion sequence | |||
6153 | // (13.3.3.1) that converts that argument to the corresponding | |||
6154 | // parameter of F. | |||
6155 | QualType ParamType = Proto->getParamType(ArgIdx); | |||
6156 | Candidate.Conversions[ArgIdx] = TryCopyInitialization( | |||
6157 | *this, Args[ArgIdx], ParamType, SuppressUserConversions, | |||
6158 | /*InOverloadResolution=*/true, | |||
6159 | /*AllowObjCWritebackConversion=*/ | |||
6160 | getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); | |||
6161 | if (Candidate.Conversions[ArgIdx].isBad()) { | |||
6162 | Candidate.Viable = false; | |||
6163 | Candidate.FailureKind = ovl_fail_bad_conversion; | |||
6164 | return; | |||
6165 | } | |||
6166 | } else { | |||
6167 | // (C++ 13.3.2p2): For the purposes of overload resolution, any | |||
6168 | // argument for which there is no corresponding parameter is | |||
6169 | // considered to ""match the ellipsis" (C+ 13.3.3.1.3). | |||
6170 | Candidate.Conversions[ArgIdx].setEllipsis(); | |||
6171 | } | |||
6172 | } | |||
6173 | ||||
6174 | if (!AllowExplicit) { | |||
6175 | ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function); | |||
6176 | if (ES.getKind() != ExplicitSpecKind::ResolvedFalse) { | |||
6177 | Candidate.Viable = false; | |||
6178 | Candidate.FailureKind = ovl_fail_explicit_resolved; | |||
6179 | return; | |||
6180 | } | |||
6181 | } | |||
6182 | ||||
6183 | if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { | |||
6184 | Candidate.Viable = false; | |||
6185 | Candidate.FailureKind = ovl_fail_enable_if; | |||
6186 | Candidate.DeductionFailure.Data = FailedAttr; | |||
6187 | return; | |||
6188 | } | |||
6189 | ||||
6190 | if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { | |||
6191 | Candidate.Viable = false; | |||
6192 | Candidate.FailureKind = ovl_fail_ext_disabled; | |||
6193 | return; | |||
6194 | } | |||
6195 | } | |||
6196 | ||||
6197 | ObjCMethodDecl * | |||
6198 | Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, | |||
6199 | SmallVectorImpl<ObjCMethodDecl *> &Methods) { | |||
6200 | if (Methods.size() <= 1) | |||
6201 | return nullptr; | |||
6202 | ||||
6203 | for (unsigned b = 0, e = Methods.size(); b < e; b++) { | |||
6204 | bool Match = true; | |||
6205 | ObjCMethodDecl *Method = Methods[b]; | |||
6206 | unsigned NumNamedArgs = Sel.getNumArgs(); | |||
6207 | // Method might have more arguments than selector indicates. This is due | |||
6208 | // to addition of c-style arguments in method. | |||
6209 | if (Method->param_size() > NumNamedArgs) | |||
6210 | NumNamedArgs = Method->param_size(); | |||
6211 | if (Args.size() < NumNamedArgs) | |||
6212 | continue; | |||
6213 | ||||
6214 | for (unsigned i = 0; i < NumNamedArgs; i++) { | |||
6215 | // We can't do any type-checking on a type-dependent argument. | |||
6216 | if (Args[i]->isTypeDependent()) { | |||
6217 | Match = false; | |||
6218 | break; | |||
6219 | } | |||
6220 | ||||
6221 | ParmVarDecl *param = Method->parameters()[i]; | |||
6222 | Expr *argExpr = Args[i]; | |||
6223 | assert(argExpr && "SelectBestMethod(): missing expression")((argExpr && "SelectBestMethod(): missing expression" ) ? static_cast<void> (0) : __assert_fail ("argExpr && \"SelectBestMethod(): missing expression\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 6223, __PRETTY_FUNCTION__)); | |||
6224 | ||||
6225 | // Strip the unbridged-cast placeholder expression off unless it's | |||
6226 | // a consumed argument. | |||
6227 | if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && | |||
6228 | !param->hasAttr<CFConsumedAttr>()) | |||
6229 | argExpr = stripARCUnbridgedCast(argExpr); | |||
6230 | ||||
6231 | // If the parameter is __unknown_anytype, move on to the next method. | |||
6232 | if (param->getType() == Context.UnknownAnyTy) { | |||
6233 | Match = false; | |||
6234 | break; | |||
6235 | } | |||
6236 | ||||
6237 | ImplicitConversionSequence ConversionState | |||
6238 | = TryCopyInitialization(*this, argExpr, param->getType(), | |||
6239 | /*SuppressUserConversions*/false, | |||
6240 | /*InOverloadResolution=*/true, | |||
6241 | /*AllowObjCWritebackConversion=*/ | |||
6242 | getLangOpts().ObjCAutoRefCount, | |||
6243 | /*AllowExplicit*/false); | |||
6244 | // This function looks for a reasonably-exact match, so we consider | |||
6245 | // incompatible pointer conversions to be a failure here. | |||
6246 | if (ConversionState.isBad() || | |||
6247 | (ConversionState.isStandard() && | |||
6248 | ConversionState.Standard.Second == | |||
6249 | ICK_Incompatible_Pointer_Conversion)) { | |||
6250 | Match = false; | |||
6251 | break; | |||
6252 | } | |||
6253 | } | |||
6254 | // Promote additional arguments to variadic methods. | |||
6255 | if (Match && Method->isVariadic()) { | |||
6256 | for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { | |||
6257 | if (Args[i]->isTypeDependent()) { | |||
6258 | Match = false; | |||
6259 | break; | |||
6260 | } | |||
6261 | ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, | |||
6262 | nullptr); | |||
6263 | if (Arg.isInvalid()) { | |||
6264 | Match = false; | |||
6265 | break; | |||
6266 | } | |||
6267 | } | |||
6268 | } else { | |||
6269 | // Check for extra arguments to non-variadic methods. | |||
6270 | if (Args.size() != NumNamedArgs) | |||
6271 | Match = false; | |||
6272 | else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { | |||
6273 | // Special case when selectors have no argument. In this case, select | |||
6274 | // one with the most general result type of 'id'. | |||
6275 | for (unsigned b = 0, e = Methods.size(); b < e; b++) { | |||
6276 | QualType ReturnT = Methods[b]->getReturnType(); | |||
6277 | if (ReturnT->isObjCIdType()) | |||
6278 | return Methods[b]; | |||
6279 | } | |||
6280 | } | |||
6281 | } | |||
6282 | ||||
6283 | if (Match) | |||
6284 | return Method; | |||
6285 | } | |||
6286 | return nullptr; | |||
6287 | } | |||
6288 | ||||
6289 | static bool | |||
6290 | convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, | |||
6291 | ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, | |||
6292 | bool MissingImplicitThis, Expr *&ConvertedThis, | |||
6293 | SmallVectorImpl<Expr *> &ConvertedArgs) { | |||
6294 | if (ThisArg) { | |||
6295 | CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); | |||
6296 | assert(!isa<CXXConstructorDecl>(Method) &&((!isa<CXXConstructorDecl>(Method) && "Shouldn't have `this` for ctors!" ) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 6297, __PRETTY_FUNCTION__)) | |||
6297 | "Shouldn't have `this` for ctors!")((!isa<CXXConstructorDecl>(Method) && "Shouldn't have `this` for ctors!" ) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 6297, __PRETTY_FUNCTION__)); | |||
6298 | assert(!Method->isStatic() && "Shouldn't have `this` for static methods!")((!Method->isStatic() && "Shouldn't have `this` for static methods!" ) ? static_cast<void> (0) : __assert_fail ("!Method->isStatic() && \"Shouldn't have `this` for static methods!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 6298, __PRETTY_FUNCTION__)); | |||
6299 | ExprResult R = S.PerformObjectArgumentInitialization( | |||
6300 | ThisArg, /*Qualifier=*/nullptr, Method, Method); | |||
6301 | if (R.isInvalid()) | |||
6302 | return false; | |||
6303 | ConvertedThis = R.get(); | |||
6304 | } else { | |||
6305 | if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { | |||
6306 | (void)MD; | |||
6307 | assert((MissingImplicitThis || MD->isStatic() ||(((MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl >(MD)) && "Expected `this` for non-ctor instance methods" ) ? static_cast<void> (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 6309, __PRETTY_FUNCTION__)) | |||
6308 | isa<CXXConstructorDecl>(MD)) &&(((MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl >(MD)) && "Expected `this` for non-ctor instance methods" ) ? static_cast<void> (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 6309, __PRETTY_FUNCTION__)) | |||
6309 | "Expected `this` for non-ctor instance methods")(((MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl >(MD)) && "Expected `this` for non-ctor instance methods" ) ? static_cast<void> (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 6309, __PRETTY_FUNCTION__)); | |||
6310 | } | |||
6311 | ConvertedThis = nullptr; | |||
6312 | } | |||
6313 | ||||
6314 | // Ignore any variadic arguments. Converting them is pointless, since the | |||
6315 | // user can't refer to them in the function condition. | |||
6316 | unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); | |||
6317 | ||||
6318 | // Convert the arguments. | |||
6319 | for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { | |||
6320 | ExprResult R; | |||
6321 | R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( | |||
6322 | S.Context, Function->getParamDecl(I)), | |||
6323 | SourceLocation(), Args[I]); | |||
6324 | ||||
6325 | if (R.isInvalid()) | |||
6326 | return false; | |||
6327 | ||||
6328 | ConvertedArgs.push_back(R.get()); | |||
6329 | } | |||
6330 | ||||
6331 | if (Trap.hasErrorOccurred()) | |||
6332 | return false; | |||
6333 | ||||
6334 | // Push default arguments if needed. | |||
6335 | if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { | |||
6336 | for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { | |||
6337 | ParmVarDecl *P = Function->getParamDecl(i); | |||
6338 | Expr *DefArg = P->hasUninstantiatedDefaultArg() | |||
6339 | ? P->getUninstantiatedDefaultArg() | |||
6340 | : P->getDefaultArg(); | |||
6341 | // This can only happen in code completion, i.e. when PartialOverloading | |||
6342 | // is true. | |||
6343 | if (!DefArg) | |||
6344 | return false; | |||
6345 | ExprResult R = | |||
6346 | S.PerformCopyInitialization(InitializedEntity::InitializeParameter( | |||
6347 | S.Context, Function->getParamDecl(i)), | |||
6348 | SourceLocation(), DefArg); | |||
6349 | if (R.isInvalid()) | |||
6350 | return false; | |||
6351 | ConvertedArgs.push_back(R.get()); | |||
6352 | } | |||
6353 | ||||
6354 | if (Trap.hasErrorOccurred()) | |||
6355 | return false; | |||
6356 | } | |||
6357 | return true; | |||
6358 | } | |||
6359 | ||||
6360 | EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, | |||
6361 | bool MissingImplicitThis) { | |||
6362 | auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); | |||
6363 | if (EnableIfAttrs.begin() == EnableIfAttrs.end()) | |||
6364 | return nullptr; | |||
6365 | ||||
6366 | SFINAETrap Trap(*this); | |||
6367 | SmallVector<Expr *, 16> ConvertedArgs; | |||
6368 | // FIXME: We should look into making enable_if late-parsed. | |||
6369 | Expr *DiscardedThis; | |||
6370 | if (!convertArgsForAvailabilityChecks( | |||
6371 | *this, Function, /*ThisArg=*/nullptr, Args, Trap, | |||
6372 | /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) | |||
6373 | return *EnableIfAttrs.begin(); | |||
6374 | ||||
6375 | for (auto *EIA : EnableIfAttrs) { | |||
6376 | APValue Result; | |||
6377 | // FIXME: This doesn't consider value-dependent cases, because doing so is | |||
6378 | // very difficult. Ideally, we should handle them more gracefully. | |||
6379 | if (!EIA->getCond()->EvaluateWithSubstitution( | |||
6380 | Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) | |||
6381 | return EIA; | |||
6382 | ||||
6383 | if (!Result.isInt() || !Result.getInt().getBoolValue()) | |||
6384 | return EIA; | |||
6385 | } | |||
6386 | return nullptr; | |||
6387 | } | |||
6388 | ||||
6389 | template <typename CheckFn> | |||
6390 | static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, | |||
6391 | bool ArgDependent, SourceLocation Loc, | |||
6392 | CheckFn &&IsSuccessful) { | |||
6393 | SmallVector<const DiagnoseIfAttr *, 8> Attrs; | |||
6394 | for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { | |||
6395 | if (ArgDependent == DIA->getArgDependent()) | |||
6396 | Attrs.push_back(DIA); | |||
6397 | } | |||
6398 | ||||
6399 | // Common case: No diagnose_if attributes, so we can quit early. | |||
6400 | if (Attrs.empty()) | |||
6401 | return false; | |||
6402 | ||||
6403 | auto WarningBegin = std::stable_partition( | |||
6404 | Attrs.begin(), Attrs.end(), | |||
6405 | [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); | |||
6406 | ||||
6407 | // Note that diagnose_if attributes are late-parsed, so they appear in the | |||
6408 | // correct order (unlike enable_if attributes). | |||
6409 | auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), | |||
6410 | IsSuccessful); | |||
6411 | if (ErrAttr != WarningBegin) { | |||
6412 | const DiagnoseIfAttr *DIA = *ErrAttr; | |||
6413 | S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); | |||
6414 | S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) | |||
6415 | << DIA->getParent() << DIA->getCond()->getSourceRange(); | |||
6416 | return true; | |||
6417 | } | |||
6418 | ||||
6419 | for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) | |||
6420 | if (IsSuccessful(DIA)) { | |||
6421 | S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); | |||
6422 | S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) | |||
6423 | << DIA->getParent() << DIA->getCond()->getSourceRange(); | |||
6424 | } | |||
6425 | ||||
6426 | return false; | |||
6427 | } | |||
6428 | ||||
6429 | bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, | |||
6430 | const Expr *ThisArg, | |||
6431 | ArrayRef<const Expr *> Args, | |||
6432 | SourceLocation Loc) { | |||
6433 | return diagnoseDiagnoseIfAttrsWith( | |||
6434 | *this, Function, /*ArgDependent=*/true, Loc, | |||
6435 | [&](const DiagnoseIfAttr *DIA) { | |||
6436 | APValue Result; | |||
6437 | // It's sane to use the same Args for any redecl of this function, since | |||
6438 | // EvaluateWithSubstitution only cares about the position of each | |||
6439 | // argument in the arg list, not the ParmVarDecl* it maps to. | |||
6440 | if (!DIA->getCond()->EvaluateWithSubstitution( | |||
6441 | Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) | |||
6442 | return false; | |||
6443 | return Result.isInt() && Result.getInt().getBoolValue(); | |||
6444 | }); | |||
6445 | } | |||
6446 | ||||
6447 | bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, | |||
6448 | SourceLocation Loc) { | |||
6449 | return diagnoseDiagnoseIfAttrsWith( | |||
6450 | *this, ND, /*ArgDependent=*/false, Loc, | |||
6451 | [&](const DiagnoseIfAttr *DIA) { | |||
6452 | bool Result; | |||
6453 | return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && | |||
6454 | Result; | |||
6455 | }); | |||
6456 | } | |||
6457 | ||||
6458 | /// Add all of the function declarations in the given function set to | |||
6459 | /// the overload candidate set. | |||
6460 | void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, | |||
6461 | ArrayRef<Expr *> Args, | |||
6462 | OverloadCandidateSet &CandidateSet, | |||
6463 | TemplateArgumentListInfo *ExplicitTemplateArgs, | |||
6464 | bool SuppressUserConversions, | |||
6465 | bool PartialOverloading, | |||
6466 | bool FirstArgumentIsBase) { | |||
6467 | for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { | |||
6468 | NamedDecl *D = F.getDecl()->getUnderlyingDecl(); | |||
6469 | ArrayRef<Expr *> FunctionArgs = Args; | |||
6470 | ||||
6471 | FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); | |||
6472 | FunctionDecl *FD = | |||
6473 | FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); | |||
6474 | ||||
6475 | if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { | |||
6476 | QualType ObjectType; | |||
6477 | Expr::Classification ObjectClassification; | |||
6478 | if (Args.size() > 0) { | |||
6479 | if (Expr *E = Args[0]) { | |||
6480 | // Use the explicit base to restrict the lookup: | |||
6481 | ObjectType = E->getType(); | |||
6482 | // Pointers in the object arguments are implicitly dereferenced, so we | |||
6483 | // always classify them as l-values. | |||
6484 | if (!ObjectType.isNull() && ObjectType->isPointerType()) | |||
6485 | ObjectClassification = Expr::Classification::makeSimpleLValue(); | |||
6486 | else | |||
6487 | ObjectClassification = E->Classify(Context); | |||
6488 | } // .. else there is an implicit base. | |||
6489 | FunctionArgs = Args.slice(1); | |||
6490 | } | |||
6491 | if (FunTmpl) { | |||
6492 | AddMethodTemplateCandidate( | |||
6493 | FunTmpl, F.getPair(), | |||
6494 | cast<CXXRecordDecl>(FunTmpl->getDeclContext()), | |||
6495 | ExplicitTemplateArgs, ObjectType, ObjectClassification, | |||
6496 | FunctionArgs, CandidateSet, SuppressUserConversions, | |||
6497 | PartialOverloading); | |||
6498 | } else { | |||
6499 | AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), | |||
6500 | cast<CXXMethodDecl>(FD)->getParent(), ObjectType, | |||
6501 | ObjectClassification, FunctionArgs, CandidateSet, | |||
6502 | SuppressUserConversions, PartialOverloading); | |||
6503 | } | |||
6504 | } else { | |||
6505 | // This branch handles both standalone functions and static methods. | |||
6506 | ||||
6507 | // Slice the first argument (which is the base) when we access | |||
6508 | // static method as non-static. | |||
6509 | if (Args.size() > 0 && | |||
6510 | (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && | |||
6511 | !isa<CXXConstructorDecl>(FD)))) { | |||
6512 | assert(cast<CXXMethodDecl>(FD)->isStatic())((cast<CXXMethodDecl>(FD)->isStatic()) ? static_cast <void> (0) : __assert_fail ("cast<CXXMethodDecl>(FD)->isStatic()" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 6512, __PRETTY_FUNCTION__)); | |||
6513 | FunctionArgs = Args.slice(1); | |||
6514 | } | |||
6515 | if (FunTmpl) { | |||
6516 | AddTemplateOverloadCandidate( | |||
6517 | FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs, | |||
6518 | CandidateSet, SuppressUserConversions, PartialOverloading); | |||
6519 | } else { | |||
6520 | AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, | |||
6521 | SuppressUserConversions, PartialOverloading); | |||
6522 | } | |||
6523 | } | |||
6524 | } | |||
6525 | } | |||
6526 | ||||
6527 | /// AddMethodCandidate - Adds a named decl (which is some kind of | |||
6528 | /// method) as a method candidate to the given overload set. | |||
6529 | void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, | |||
6530 | QualType ObjectType, | |||
6531 | Expr::Classification ObjectClassification, | |||
6532 | ArrayRef<Expr *> Args, | |||
6533 | OverloadCandidateSet& CandidateSet, | |||
6534 | bool SuppressUserConversions) { | |||
6535 | NamedDecl *Decl = FoundDecl.getDecl(); | |||
6536 | CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); | |||
6537 | ||||
6538 | if (isa<UsingShadowDecl>(Decl)) | |||
6539 | Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); | |||
6540 | ||||
6541 | if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { | |||
6542 | assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&((isa<CXXMethodDecl>(TD->getTemplatedDecl()) && "Expected a member function template") ? static_cast<void > (0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 6543, __PRETTY_FUNCTION__)) | |||
6543 | "Expected a member function template")((isa<CXXMethodDecl>(TD->getTemplatedDecl()) && "Expected a member function template") ? static_cast<void > (0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 6543, __PRETTY_FUNCTION__)); | |||
6544 | AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, | |||
6545 | /*ExplicitArgs*/ nullptr, ObjectType, | |||
6546 | ObjectClassification, Args, CandidateSet, | |||
6547 | SuppressUserConversions); | |||
6548 | } else { | |||
6549 | AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, | |||
6550 | ObjectType, ObjectClassification, Args, CandidateSet, | |||
6551 | SuppressUserConversions); | |||
6552 | } | |||
6553 | } | |||
6554 | ||||
6555 | /// AddMethodCandidate - Adds the given C++ member function to the set | |||
6556 | /// of candidate functions, using the given function call arguments | |||
6557 | /// and the object argument (@c Object). For example, in a call | |||
6558 | /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain | |||
6559 | /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't | |||
6560 | /// allow user-defined conversions via constructors or conversion | |||
6561 | /// operators. | |||
6562 | void | |||
6563 | Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, | |||
6564 | CXXRecordDecl *ActingContext, QualType ObjectType, | |||
6565 | Expr::Classification ObjectClassification, | |||
6566 | ArrayRef<Expr *> Args, | |||
6567 | OverloadCandidateSet &CandidateSet, | |||
6568 | bool SuppressUserConversions, | |||
6569 | bool PartialOverloading, | |||
6570 | ConversionSequenceList EarlyConversions) { | |||
6571 | const FunctionProtoType *Proto | |||
6572 | = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); | |||
6573 | assert(Proto && "Methods without a prototype cannot be overloaded")((Proto && "Methods without a prototype cannot be overloaded" ) ? static_cast<void> (0) : __assert_fail ("Proto && \"Methods without a prototype cannot be overloaded\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 6573, __PRETTY_FUNCTION__)); | |||
6574 | assert(!isa<CXXConstructorDecl>(Method) &&((!isa<CXXConstructorDecl>(Method) && "Use AddOverloadCandidate for constructors" ) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 6575, __PRETTY_FUNCTION__)) | |||
6575 | "Use AddOverloadCandidate for constructors")((!isa<CXXConstructorDecl>(Method) && "Use AddOverloadCandidate for constructors" ) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 6575, __PRETTY_FUNCTION__)); | |||
6576 | ||||
6577 | if (!CandidateSet.isNewCandidate(Method)) | |||
6578 | return; | |||
6579 | ||||
6580 | // C++11 [class.copy]p23: [DR1402] | |||
6581 | // A defaulted move assignment operator that is defined as deleted is | |||
6582 | // ignored by overload resolution. | |||
6583 | if (Method->isDefaulted() && Method->isDeleted() && | |||
6584 | Method->isMoveAssignmentOperator()) | |||
6585 | return; | |||
6586 | ||||
6587 | // Overload resolution is always an unevaluated context. | |||
6588 | EnterExpressionEvaluationContext Unevaluated( | |||
6589 | *this, Sema::ExpressionEvaluationContext::Unevaluated); | |||
6590 | ||||
6591 | // Add this candidate | |||
6592 | OverloadCandidate &Candidate = | |||
6593 | CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); | |||
6594 | Candidate.FoundDecl = FoundDecl; | |||
6595 | Candidate.Function = Method; | |||
6596 | Candidate.IsSurrogate = false; | |||
6597 | Candidate.IgnoreObjectArgument = false; | |||
6598 | Candidate.ExplicitCallArguments = Args.size(); | |||
6599 | ||||
6600 | unsigned NumParams = Proto->getNumParams(); | |||
6601 | ||||
6602 | // (C++ 13.3.2p2): A candidate function having fewer than m | |||
6603 | // parameters is viable only if it has an ellipsis in its parameter | |||
6604 | // list (8.3.5). | |||
6605 | if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && | |||
6606 | !Proto->isVariadic()) { | |||
6607 | Candidate.Viable = false; | |||
6608 | Candidate.FailureKind = ovl_fail_too_many_arguments; | |||
6609 | return; | |||
6610 | } | |||
6611 | ||||
6612 | // (C++ 13.3.2p2): A candidate function having more than m parameters | |||
6613 | // is viable only if the (m+1)st parameter has a default argument | |||
6614 | // (8.3.6). For the purposes of overload resolution, the | |||
6615 | // parameter list is truncated on the right, so that there are | |||
6616 | // exactly m parameters. | |||
6617 | unsigned MinRequiredArgs = Method->getMinRequiredArguments(); | |||
6618 | if (Args.size() < MinRequiredArgs && !PartialOverloading) { | |||
6619 | // Not enough arguments. | |||
6620 | Candidate.Viable = false; | |||
6621 | Candidate.FailureKind = ovl_fail_too_few_arguments; | |||
6622 | return; | |||
6623 | } | |||
6624 | ||||
6625 | Candidate.Viable = true; | |||
6626 | ||||
6627 | if (Method->isStatic() || ObjectType.isNull()) | |||
6628 | // The implicit object argument is ignored. | |||
6629 | Candidate.IgnoreObjectArgument = true; | |||
6630 | else { | |||
6631 | // Determine the implicit conversion sequence for the object | |||
6632 | // parameter. | |||
6633 | Candidate.Conversions[0] = TryObjectArgumentInitialization( | |||
6634 | *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, | |||
6635 | Method, ActingContext); | |||
6636 | if (Candidate.Conversions[0].isBad()) { | |||
6637 | Candidate.Viable = false; | |||
6638 | Candidate.FailureKind = ovl_fail_bad_conversion; | |||
6639 | return; | |||
6640 | } | |||
6641 | } | |||
6642 | ||||
6643 | // (CUDA B.1): Check for invalid calls between targets. | |||
6644 | if (getLangOpts().CUDA) | |||
6645 | if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) | |||
6646 | if (!IsAllowedCUDACall(Caller, Method)) { | |||
6647 | Candidate.Viable = false; | |||
6648 | Candidate.FailureKind = ovl_fail_bad_target; | |||
6649 | return; | |||
6650 | } | |||
6651 | ||||
6652 | // Determine the implicit conversion sequences for each of the | |||
6653 | // arguments. | |||
6654 | for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { | |||
6655 | if (Candidate.Conversions[ArgIdx + 1].isInitialized()) { | |||
6656 | // We already formed a conversion sequence for this parameter during | |||
6657 | // template argument deduction. | |||
6658 | } else if (ArgIdx < NumParams) { | |||
6659 | // (C++ 13.3.2p3): for F to be a viable function, there shall | |||
6660 | // exist for each argument an implicit conversion sequence | |||
6661 | // (13.3.3.1) that converts that argument to the corresponding | |||
6662 | // parameter of F. | |||
6663 | QualType ParamType = Proto->getParamType(ArgIdx); | |||
6664 | Candidate.Conversions[ArgIdx + 1] | |||
6665 | = TryCopyInitialization(*this, Args[ArgIdx], ParamType, | |||
6666 | SuppressUserConversions, | |||
6667 | /*InOverloadResolution=*/true, | |||
6668 | /*AllowObjCWritebackConversion=*/ | |||
6669 | getLangOpts().ObjCAutoRefCount); | |||
6670 | if (Candidate.Conversions[ArgIdx + 1].isBad()) { | |||
6671 | Candidate.Viable = false; | |||
6672 | Candidate.FailureKind = ovl_fail_bad_conversion; | |||
6673 | return; | |||
6674 | } | |||
6675 | } else { | |||
6676 | // (C++ 13.3.2p2): For the purposes of overload resolution, any | |||
6677 | // argument for which there is no corresponding parameter is | |||
6678 | // considered to "match the ellipsis" (C+ 13.3.3.1.3). | |||
6679 | Candidate.Conversions[ArgIdx + 1].setEllipsis(); | |||
6680 | } | |||
6681 | } | |||
6682 | ||||
6683 | if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { | |||
6684 | Candidate.Viable = false; | |||
6685 | Candidate.FailureKind = ovl_fail_enable_if; | |||
6686 | Candidate.DeductionFailure.Data = FailedAttr; | |||
6687 | return; | |||
6688 | } | |||
6689 | ||||
6690 | if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && | |||
6691 | !Method->getAttr<TargetAttr>()->isDefaultVersion()) { | |||
6692 | Candidate.Viable = false; | |||
6693 | Candidate.FailureKind = ovl_non_default_multiversion_function; | |||
6694 | } | |||
6695 | } | |||
6696 | ||||
6697 | /// Add a C++ member function template as a candidate to the candidate | |||
6698 | /// set, using template argument deduction to produce an appropriate member | |||
6699 | /// function template specialization. | |||
6700 | void | |||
6701 | Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, | |||
6702 | DeclAccessPair FoundDecl, | |||
6703 | CXXRecordDecl *ActingContext, | |||
6704 | TemplateArgumentListInfo *ExplicitTemplateArgs, | |||
6705 | QualType ObjectType, | |||
6706 | Expr::Classification ObjectClassification, | |||
6707 | ArrayRef<Expr *> Args, | |||
6708 | OverloadCandidateSet& CandidateSet, | |||
6709 | bool SuppressUserConversions, | |||
6710 | bool PartialOverloading) { | |||
6711 | if (!CandidateSet.isNewCandidate(MethodTmpl)) | |||
6712 | return; | |||
6713 | ||||
6714 | // C++ [over.match.funcs]p7: | |||
6715 | // In each case where a candidate is a function template, candidate | |||
6716 | // function template specializations are generated using template argument | |||
6717 | // deduction (14.8.3, 14.8.2). Those candidates are then handled as | |||
6718 | // candidate functions in the usual way.113) A given name can refer to one | |||
6719 | // or more function templates and also to a set of overloaded non-template | |||
6720 | // functions. In such a case, the candidate functions generated from each | |||
6721 | // function template are combined with the set of non-template candidate | |||
6722 | // functions. | |||
6723 | TemplateDeductionInfo Info(CandidateSet.getLocation()); | |||
6724 | FunctionDecl *Specialization = nullptr; | |||
6725 | ConversionSequenceList Conversions; | |||
6726 | if (TemplateDeductionResult Result = DeduceTemplateArguments( | |||
6727 | MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, | |||
6728 | PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { | |||
6729 | return CheckNonDependentConversions( | |||
6730 | MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, | |||
6731 | SuppressUserConversions, ActingContext, ObjectType, | |||
6732 | ObjectClassification); | |||
6733 | })) { | |||
6734 | OverloadCandidate &Candidate = | |||
6735 | CandidateSet.addCandidate(Conversions.size(), Conversions); | |||
6736 | Candidate.FoundDecl = FoundDecl; | |||
6737 | Candidate.Function = MethodTmpl->getTemplatedDecl(); | |||
6738 | Candidate.Viable = false; | |||
6739 | Candidate.IsSurrogate = false; | |||
6740 | Candidate.IgnoreObjectArgument = | |||
6741 | cast<CXXMethodDecl>(Candidate.Function)->isStatic() || | |||
6742 | ObjectType.isNull(); | |||
6743 | Candidate.ExplicitCallArguments = Args.size(); | |||
6744 | if (Result == TDK_NonDependentConversionFailure) | |||
6745 | Candidate.FailureKind = ovl_fail_bad_conversion; | |||
6746 | else { | |||
6747 | Candidate.FailureKind = ovl_fail_bad_deduction; | |||
6748 | Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, | |||
6749 | Info); | |||
6750 | } | |||
6751 | return; | |||
6752 | } | |||
6753 | ||||
6754 | // Add the function template specialization produced by template argument | |||
6755 | // deduction as a candidate. | |||
6756 | assert(Specialization && "Missing member function template specialization?")((Specialization && "Missing member function template specialization?" ) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing member function template specialization?\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 6756, __PRETTY_FUNCTION__)); | |||
6757 | assert(isa<CXXMethodDecl>(Specialization) &&((isa<CXXMethodDecl>(Specialization) && "Specialization is not a member function?" ) ? static_cast<void> (0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 6758, __PRETTY_FUNCTION__)) | |||
6758 | "Specialization is not a member function?")((isa<CXXMethodDecl>(Specialization) && "Specialization is not a member function?" ) ? static_cast<void> (0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 6758, __PRETTY_FUNCTION__)); | |||
6759 | AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, | |||
6760 | ActingContext, ObjectType, ObjectClassification, Args, | |||
6761 | CandidateSet, SuppressUserConversions, PartialOverloading, | |||
6762 | Conversions); | |||
6763 | } | |||
6764 | ||||
6765 | /// Add a C++ function template specialization as a candidate | |||
6766 | /// in the candidate set, using template argument deduction to produce | |||
6767 | /// an appropriate function template specialization. | |||
6768 | void Sema::AddTemplateOverloadCandidate( | |||
6769 | FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, | |||
6770 | TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, | |||
6771 | OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, | |||
6772 | bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate) { | |||
6773 | if (!CandidateSet.isNewCandidate(FunctionTemplate)) | |||
6774 | return; | |||
6775 | ||||
6776 | // C++ [over.match.funcs]p7: | |||
6777 | // In each case where a candidate is a function template, candidate | |||
6778 | // function template specializations are generated using template argument | |||
6779 | // deduction (14.8.3, 14.8.2). Those candidates are then handled as | |||
6780 | // candidate functions in the usual way.113) A given name can refer to one | |||
6781 | // or more function templates and also to a set of overloaded non-template | |||
6782 | // functions. In such a case, the candidate functions generated from each | |||
6783 | // function template are combined with the set of non-template candidate | |||
6784 | // functions. | |||
6785 | TemplateDeductionInfo Info(CandidateSet.getLocation()); | |||
6786 | FunctionDecl *Specialization = nullptr; | |||
6787 | ConversionSequenceList Conversions; | |||
6788 | if (TemplateDeductionResult Result = DeduceTemplateArguments( | |||
6789 | FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, | |||
6790 | PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { | |||
6791 | return CheckNonDependentConversions(FunctionTemplate, ParamTypes, | |||
6792 | Args, CandidateSet, Conversions, | |||
6793 | SuppressUserConversions); | |||
6794 | })) { | |||
6795 | OverloadCandidate &Candidate = | |||
6796 | CandidateSet.addCandidate(Conversions.size(), Conversions); | |||
6797 | Candidate.FoundDecl = FoundDecl; | |||
6798 | Candidate.Function = FunctionTemplate->getTemplatedDecl(); | |||
6799 | Candidate.Viable = false; | |||
6800 | Candidate.IsSurrogate = false; | |||
6801 | Candidate.IsADLCandidate = IsADLCandidate; | |||
6802 | // Ignore the object argument if there is one, since we don't have an object | |||
6803 | // type. | |||
6804 | Candidate.IgnoreObjectArgument = | |||
6805 | isa<CXXMethodDecl>(Candidate.Function) && | |||
6806 | !isa<CXXConstructorDecl>(Candidate.Function); | |||
6807 | Candidate.ExplicitCallArguments = Args.size(); | |||
6808 | if (Result == TDK_NonDependentConversionFailure) | |||
6809 | Candidate.FailureKind = ovl_fail_bad_conversion; | |||
6810 | else { | |||
6811 | Candidate.FailureKind = ovl_fail_bad_deduction; | |||
6812 | Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, | |||
6813 | Info); | |||
6814 | } | |||
6815 | return; | |||
6816 | } | |||
6817 | ||||
6818 | // Add the function template specialization produced by template argument | |||
6819 | // deduction as a candidate. | |||
6820 | assert(Specialization && "Missing function template specialization?")((Specialization && "Missing function template specialization?" ) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing function template specialization?\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 6820, __PRETTY_FUNCTION__)); | |||
6821 | AddOverloadCandidate( | |||
6822 | Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, | |||
6823 | PartialOverloading, AllowExplicit, | |||
6824 | /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions); | |||
6825 | } | |||
6826 | ||||
6827 | /// Check that implicit conversion sequences can be formed for each argument | |||
6828 | /// whose corresponding parameter has a non-dependent type, per DR1391's | |||
6829 | /// [temp.deduct.call]p10. | |||
6830 | bool Sema::CheckNonDependentConversions( | |||
6831 | FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, | |||
6832 | ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, | |||
6833 | ConversionSequenceList &Conversions, bool SuppressUserConversions, | |||
6834 | CXXRecordDecl *ActingContext, QualType ObjectType, | |||
6835 | Expr::Classification ObjectClassification) { | |||
6836 | // FIXME: The cases in which we allow explicit conversions for constructor | |||
6837 | // arguments never consider calling a constructor template. It's not clear | |||
6838 | // that is correct. | |||
6839 | const bool AllowExplicit = false; | |||
6840 | ||||
6841 | auto *FD = FunctionTemplate->getTemplatedDecl(); | |||
6842 | auto *Method = dyn_cast<CXXMethodDecl>(FD); | |||
6843 | bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); | |||
6844 | unsigned ThisConversions = HasThisConversion ? 1 : 0; | |||
6845 | ||||
6846 | Conversions = | |||
6847 | CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); | |||
6848 | ||||
6849 | // Overload resolution is always an unevaluated context. | |||
6850 | EnterExpressionEvaluationContext Unevaluated( | |||
6851 | *this, Sema::ExpressionEvaluationContext::Unevaluated); | |||
6852 | ||||
6853 | // For a method call, check the 'this' conversion here too. DR1391 doesn't | |||
6854 | // require that, but this check should never result in a hard error, and | |||
6855 | // overload resolution is permitted to sidestep instantiations. | |||
6856 | if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && | |||
6857 | !ObjectType.isNull()) { | |||
6858 | Conversions[0] = TryObjectArgumentInitialization( | |||
6859 | *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, | |||
6860 | Method, ActingContext); | |||
6861 | if (Conversions[0].isBad()) | |||
6862 | return true; | |||
6863 | } | |||
6864 | ||||
6865 | for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; | |||
6866 | ++I) { | |||
6867 | QualType ParamType = ParamTypes[I]; | |||
6868 | if (!ParamType->isDependentType()) { | |||
6869 | Conversions[ThisConversions + I] | |||
6870 | = TryCopyInitialization(*this, Args[I], ParamType, | |||
6871 | SuppressUserConversions, | |||
6872 | /*InOverloadResolution=*/true, | |||
6873 | /*AllowObjCWritebackConversion=*/ | |||
6874 | getLangOpts().ObjCAutoRefCount, | |||
6875 | AllowExplicit); | |||
6876 | if (Conversions[ThisConversions + I].isBad()) | |||
6877 | return true; | |||
6878 | } | |||
6879 | } | |||
6880 | ||||
6881 | return false; | |||
6882 | } | |||
6883 | ||||
6884 | /// Determine whether this is an allowable conversion from the result | |||
6885 | /// of an explicit conversion operator to the expected type, per C++ | |||
6886 | /// [over.match.conv]p1 and [over.match.ref]p1. | |||
6887 | /// | |||
6888 | /// \param ConvType The return type of the conversion function. | |||
6889 | /// | |||
6890 | /// \param ToType The type we are converting to. | |||
6891 | /// | |||
6892 | /// \param AllowObjCPointerConversion Allow a conversion from one | |||
6893 | /// Objective-C pointer to another. | |||
6894 | /// | |||
6895 | /// \returns true if the conversion is allowable, false otherwise. | |||
6896 | static bool isAllowableExplicitConversion(Sema &S, | |||
6897 | QualType ConvType, QualType ToType, | |||
6898 | bool AllowObjCPointerConversion) { | |||
6899 | QualType ToNonRefType = ToType.getNonReferenceType(); | |||
6900 | ||||
6901 | // Easy case: the types are the same. | |||
6902 | if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) | |||
6903 | return true; | |||
6904 | ||||
6905 | // Allow qualification conversions. | |||
6906 | bool ObjCLifetimeConversion; | |||
6907 | if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, | |||
6908 | ObjCLifetimeConversion)) | |||
6909 | return true; | |||
6910 | ||||
6911 | // If we're not allowed to consider Objective-C pointer conversions, | |||
6912 | // we're done. | |||
6913 | if (!AllowObjCPointerConversion) | |||
6914 | return false; | |||
6915 | ||||
6916 | // Is this an Objective-C pointer conversion? | |||
6917 | bool IncompatibleObjC = false; | |||
6918 | QualType ConvertedType; | |||
6919 | return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, | |||
6920 | IncompatibleObjC); | |||
6921 | } | |||
6922 | ||||
6923 | /// AddConversionCandidate - Add a C++ conversion function as a | |||
6924 | /// candidate in the candidate set (C++ [over.match.conv], | |||
6925 | /// C++ [over.match.copy]). From is the expression we're converting from, | |||
6926 | /// and ToType is the type that we're eventually trying to convert to | |||
6927 | /// (which may or may not be the same type as the type that the | |||
6928 | /// conversion function produces). | |||
6929 | void Sema::AddConversionCandidate( | |||
6930 | CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, | |||
6931 | CXXRecordDecl *ActingContext, Expr *From, QualType ToType, | |||
6932 | OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, | |||
6933 | bool AllowExplicit, bool AllowResultConversion) { | |||
6934 | assert(!Conversion->getDescribedFunctionTemplate() &&((!Conversion->getDescribedFunctionTemplate() && "Conversion function templates use AddTemplateConversionCandidate" ) ? static_cast<void> (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 6935, __PRETTY_FUNCTION__)) | |||
6935 | "Conversion function templates use AddTemplateConversionCandidate")((!Conversion->getDescribedFunctionTemplate() && "Conversion function templates use AddTemplateConversionCandidate" ) ? static_cast<void> (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 6935, __PRETTY_FUNCTION__)); | |||
6936 | QualType ConvType = Conversion->getConversionType().getNonReferenceType(); | |||
6937 | if (!CandidateSet.isNewCandidate(Conversion)) | |||
6938 | return; | |||
6939 | ||||
6940 | // If the conversion function has an undeduced return type, trigger its | |||
6941 | // deduction now. | |||
6942 | if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { | |||
6943 | if (DeduceReturnType(Conversion, From->getExprLoc())) | |||
6944 | return; | |||
6945 | ConvType = Conversion->getConversionType().getNonReferenceType(); | |||
6946 | } | |||
6947 | ||||
6948 | // If we don't allow any conversion of the result type, ignore conversion | |||
6949 | // functions that don't convert to exactly (possibly cv-qualified) T. | |||
6950 | if (!AllowResultConversion && | |||
6951 | !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) | |||
6952 | return; | |||
6953 | ||||
6954 | // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion | |||
6955 | // operator is only a candidate if its return type is the target type or | |||
6956 | // can be converted to the target type with a qualification conversion. | |||
6957 | if (Conversion->isExplicit() && | |||
6958 | !isAllowableExplicitConversion(*this, ConvType, ToType, | |||
6959 | AllowObjCConversionOnExplicit)) | |||
6960 | return; | |||
6961 | ||||
6962 | // Overload resolution is always an unevaluated context. | |||
6963 | EnterExpressionEvaluationContext Unevaluated( | |||
6964 | *this, Sema::ExpressionEvaluationContext::Unevaluated); | |||
6965 | ||||
6966 | // Add this candidate | |||
6967 | OverloadCandidate &Candidate = CandidateSet.addCandidate(1); | |||
6968 | Candidate.FoundDecl = FoundDecl; | |||
6969 | Candidate.Function = Conversion; | |||
6970 | Candidate.IsSurrogate = false; | |||
6971 | Candidate.IgnoreObjectArgument = false; | |||
6972 | Candidate.FinalConversion.setAsIdentityConversion(); | |||
6973 | Candidate.FinalConversion.setFromType(ConvType); | |||
6974 | Candidate.FinalConversion.setAllToTypes(ToType); | |||
6975 | Candidate.Viable = true; | |||
6976 | Candidate.ExplicitCallArguments = 1; | |||
6977 | ||||
6978 | // C++ [over.match.funcs]p4: | |||
6979 | // For conversion functions, the function is considered to be a member of | |||
6980 | // the class of the implicit implied object argument for the purpose of | |||
6981 | // defining the type of the implicit object parameter. | |||
6982 | // | |||
6983 | // Determine the implicit conversion sequence for the implicit | |||
6984 | // object parameter. | |||
6985 | QualType ImplicitParamType = From->getType(); | |||
6986 | if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) | |||
6987 | ImplicitParamType = FromPtrType->getPointeeType(); | |||
6988 | CXXRecordDecl *ConversionContext | |||
6989 | = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); | |||
6990 | ||||
6991 | Candidate.Conversions[0] = TryObjectArgumentInitialization( | |||
6992 | *this, CandidateSet.getLocation(), From->getType(), | |||
6993 | From->Classify(Context), Conversion, ConversionContext); | |||
6994 | ||||
6995 | if (Candidate.Conversions[0].isBad()) { | |||
6996 | Candidate.Viable = false; | |||
6997 | Candidate.FailureKind = ovl_fail_bad_conversion; | |||
6998 | return; | |||
6999 | } | |||
7000 | ||||
7001 | // We won't go through a user-defined type conversion function to convert a | |||
7002 | // derived to base as such conversions are given Conversion Rank. They only | |||
7003 | // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] | |||
7004 | QualType FromCanon | |||
7005 | = Context.getCanonicalType(From->getType().getUnqualifiedType()); | |||
7006 | QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); | |||
7007 | if (FromCanon == ToCanon || | |||
7008 | IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { | |||
7009 | Candidate.Viable = false; | |||
7010 | Candidate.FailureKind = ovl_fail_trivial_conversion; | |||
7011 | return; | |||
7012 | } | |||
7013 | ||||
7014 | // To determine what the conversion from the result of calling the | |||
7015 | // conversion function to the type we're eventually trying to | |||
7016 | // convert to (ToType), we need to synthesize a call to the | |||
7017 | // conversion function and attempt copy initialization from it. This | |||
7018 | // makes sure that we get the right semantics with respect to | |||
7019 | // lvalues/rvalues and the type. Fortunately, we can allocate this | |||
7020 | // call on the stack and we don't need its arguments to be | |||
7021 | // well-formed. | |||
7022 | DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), | |||
7023 | VK_LValue, From->getBeginLoc()); | |||
7024 | ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, | |||
7025 | Context.getPointerType(Conversion->getType()), | |||
7026 | CK_FunctionToPointerDecay, | |||
7027 | &ConversionRef, VK_RValue); | |||
7028 | ||||
7029 | QualType ConversionType = Conversion->getConversionType(); | |||
7030 | if (!isCompleteType(From->getBeginLoc(), ConversionType)) { | |||
7031 | Candidate.Viable = false; | |||
7032 | Candidate.FailureKind = ovl_fail_bad_final_conversion; | |||
7033 | return; | |||
7034 | } | |||
7035 | ||||
7036 | ExprValueKind VK = Expr::getValueKindForType(ConversionType); | |||
7037 | ||||
7038 | // Note that it is safe to allocate CallExpr on the stack here because | |||
7039 | // there are 0 arguments (i.e., nothing is allocated using ASTContext's | |||
7040 | // allocator). | |||
7041 | QualType CallResultType = ConversionType.getNonLValueExprType(Context); | |||
7042 | ||||
7043 | llvm::AlignedCharArray<alignof(CallExpr), sizeof(CallExpr) + sizeof(Stmt *)> | |||
7044 | Buffer; | |||
7045 | CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( | |||
7046 | Buffer.buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); | |||
7047 | ||||
7048 | ImplicitConversionSequence ICS = | |||
7049 | TryCopyInitialization(*this, TheTemporaryCall, ToType, | |||
7050 | /*SuppressUserConversions=*/true, | |||
7051 | /*InOverloadResolution=*/false, | |||
7052 | /*AllowObjCWritebackConversion=*/false); | |||
7053 | ||||
7054 | switch (ICS.getKind()) { | |||
7055 | case ImplicitConversionSequence::StandardConversion: | |||
7056 | Candidate.FinalConversion = ICS.Standard; | |||
7057 | ||||
7058 | // C++ [over.ics.user]p3: | |||
7059 | // If the user-defined conversion is specified by a specialization of a | |||
7060 | // conversion function template, the second standard conversion sequence | |||
7061 | // shall have exact match rank. | |||
7062 | if (Conversion->getPrimaryTemplate() && | |||
7063 | GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { | |||
7064 | Candidate.Viable = false; | |||
7065 | Candidate.FailureKind = ovl_fail_final_conversion_not_exact; | |||
7066 | return; | |||
7067 | } | |||
7068 | ||||
7069 | // C++0x [dcl.init.ref]p5: | |||
7070 | // In the second case, if the reference is an rvalue reference and | |||
7071 | // the second standard conversion sequence of the user-defined | |||
7072 | // conversion sequence includes an lvalue-to-rvalue conversion, the | |||
7073 | // program is ill-formed. | |||
7074 | if (ToType->isRValueReferenceType() && | |||
7075 | ICS.Standard.First == ICK_Lvalue_To_Rvalue) { | |||
7076 | Candidate.Viable = false; | |||
7077 | Candidate.FailureKind = ovl_fail_bad_final_conversion; | |||
7078 | return; | |||
7079 | } | |||
7080 | break; | |||
7081 | ||||
7082 | case ImplicitConversionSequence::BadConversion: | |||
7083 | Candidate.Viable = false; | |||
7084 | Candidate.FailureKind = ovl_fail_bad_final_conversion; | |||
7085 | return; | |||
7086 | ||||
7087 | default: | |||
7088 | llvm_unreachable(::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 7089) | |||
7089 | "Can only end up with a standard conversion sequence or failure")::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 7089); | |||
7090 | } | |||
7091 | ||||
7092 | if (!AllowExplicit && Conversion->getExplicitSpecifier().getKind() != | |||
7093 | ExplicitSpecKind::ResolvedFalse) { | |||
7094 | Candidate.Viable = false; | |||
7095 | Candidate.FailureKind = ovl_fail_explicit_resolved; | |||
7096 | return; | |||
7097 | } | |||
7098 | ||||
7099 | if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { | |||
7100 | Candidate.Viable = false; | |||
7101 | Candidate.FailureKind = ovl_fail_enable_if; | |||
7102 | Candidate.DeductionFailure.Data = FailedAttr; | |||
7103 | return; | |||
7104 | } | |||
7105 | ||||
7106 | if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && | |||
7107 | !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { | |||
7108 | Candidate.Viable = false; | |||
7109 | Candidate.FailureKind = ovl_non_default_multiversion_function; | |||
7110 | } | |||
7111 | } | |||
7112 | ||||
7113 | /// Adds a conversion function template specialization | |||
7114 | /// candidate to the overload set, using template argument deduction | |||
7115 | /// to deduce the template arguments of the conversion function | |||
7116 | /// template from the type that we are converting to (C++ | |||
7117 | /// [temp.deduct.conv]). | |||
7118 | void Sema::AddTemplateConversionCandidate( | |||
7119 | FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, | |||
7120 | CXXRecordDecl *ActingDC, Expr *From, QualType ToType, | |||
7121 | OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, | |||
7122 | bool AllowExplicit, bool AllowResultConversion) { | |||
7123 | assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&((isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl ()) && "Only conversion function templates permitted here" ) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 7124, __PRETTY_FUNCTION__)) | |||
7124 | "Only conversion function templates permitted here")((isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl ()) && "Only conversion function templates permitted here" ) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 7124, __PRETTY_FUNCTION__)); | |||
7125 | ||||
7126 | if (!CandidateSet.isNewCandidate(FunctionTemplate)) | |||
7127 | return; | |||
7128 | ||||
7129 | TemplateDeductionInfo Info(CandidateSet.getLocation()); | |||
7130 | CXXConversionDecl *Specialization = nullptr; | |||
7131 | if (TemplateDeductionResult Result | |||
7132 | = DeduceTemplateArguments(FunctionTemplate, ToType, | |||
7133 | Specialization, Info)) { | |||
7134 | OverloadCandidate &Candidate = CandidateSet.addCandidate(); | |||
7135 | Candidate.FoundDecl = FoundDecl; | |||
7136 | Candidate.Function = FunctionTemplate->getTemplatedDecl(); | |||
7137 | Candidate.Viable = false; | |||
7138 | Candidate.FailureKind = ovl_fail_bad_deduction; | |||
7139 | Candidate.IsSurrogate = false; | |||
7140 | Candidate.IgnoreObjectArgument = false; | |||
7141 | Candidate.ExplicitCallArguments = 1; | |||
7142 | Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, | |||
7143 | Info); | |||
7144 | return; | |||
7145 | } | |||
7146 | ||||
7147 | // Add the conversion function template specialization produced by | |||
7148 | // template argument deduction as a candidate. | |||
7149 | assert(Specialization && "Missing function template specialization?")((Specialization && "Missing function template specialization?" ) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing function template specialization?\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 7149, __PRETTY_FUNCTION__)); | |||
7150 | AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, | |||
7151 | CandidateSet, AllowObjCConversionOnExplicit, | |||
7152 | AllowExplicit, AllowResultConversion); | |||
7153 | } | |||
7154 | ||||
7155 | /// AddSurrogateCandidate - Adds a "surrogate" candidate function that | |||
7156 | /// converts the given @c Object to a function pointer via the | |||
7157 | /// conversion function @c Conversion, and then attempts to call it | |||
7158 | /// with the given arguments (C++ [over.call.object]p2-4). Proto is | |||
7159 | /// the type of function that we'll eventually be calling. | |||
7160 | void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, | |||
7161 | DeclAccessPair FoundDecl, | |||
7162 | CXXRecordDecl *ActingContext, | |||
7163 | const FunctionProtoType *Proto, | |||
7164 | Expr *Object, | |||
7165 | ArrayRef<Expr *> Args, | |||
7166 | OverloadCandidateSet& CandidateSet) { | |||
7167 | if (!CandidateSet.isNewCandidate(Conversion)) | |||
7168 | return; | |||
7169 | ||||
7170 | // Overload resolution is always an unevaluated context. | |||
7171 | EnterExpressionEvaluationContext Unevaluated( | |||
7172 | *this, Sema::ExpressionEvaluationContext::Unevaluated); | |||
7173 | ||||
7174 | OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); | |||
7175 | Candidate.FoundDecl = FoundDecl; | |||
7176 | Candidate.Function = nullptr; | |||
7177 | Candidate.Surrogate = Conversion; | |||
7178 | Candidate.Viable = true; | |||
7179 | Candidate.IsSurrogate = true; | |||
7180 | Candidate.IgnoreObjectArgument = false; | |||
7181 | Candidate.ExplicitCallArguments = Args.size(); | |||
7182 | ||||
7183 | // Determine the implicit conversion sequence for the implicit | |||
7184 | // object parameter. | |||
7185 | ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( | |||
7186 | *this, CandidateSet.getLocation(), Object->getType(), | |||
7187 | Object->Classify(Context), Conversion, ActingContext); | |||
7188 | if (ObjectInit.isBad()) { | |||
7189 | Candidate.Viable = false; | |||
7190 | Candidate.FailureKind = ovl_fail_bad_conversion; | |||
7191 | Candidate.Conversions[0] = ObjectInit; | |||
7192 | return; | |||
7193 | } | |||
7194 | ||||
7195 | // The first conversion is actually a user-defined conversion whose | |||
7196 | // first conversion is ObjectInit's standard conversion (which is | |||
7197 | // effectively a reference binding). Record it as such. | |||
7198 | Candidate.Conversions[0].setUserDefined(); | |||
7199 | Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; | |||
7200 | Candidate.Conversions[0].UserDefined.EllipsisConversion = false; | |||
7201 | Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; | |||
7202 | Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; | |||
7203 | Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; | |||
7204 | Candidate.Conversions[0].UserDefined.After | |||
7205 | = Candidate.Conversions[0].UserDefined.Before; | |||
7206 | Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); | |||
7207 | ||||
7208 | // Find the | |||
7209 | unsigned NumParams = Proto->getNumParams(); | |||
7210 | ||||
7211 | // (C++ 13.3.2p2): A candidate function having fewer than m | |||
7212 | // parameters is viable only if it has an ellipsis in its parameter | |||
7213 | // list (8.3.5). | |||
7214 | if (Args.size() > NumParams && !Proto->isVariadic()) { | |||
7215 | Candidate.Viable = false; | |||
7216 | Candidate.FailureKind = ovl_fail_too_many_arguments; | |||
7217 | return; | |||
7218 | } | |||
7219 | ||||
7220 | // Function types don't have any default arguments, so just check if | |||
7221 | // we have enough arguments. | |||
7222 | if (Args.size() < NumParams) { | |||
7223 | // Not enough arguments. | |||
7224 | Candidate.Viable = false; | |||
7225 | Candidate.FailureKind = ovl_fail_too_few_arguments; | |||
7226 | return; | |||
7227 | } | |||
7228 | ||||
7229 | // Determine the implicit conversion sequences for each of the | |||
7230 | // arguments. | |||
7231 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { | |||
7232 | if (ArgIdx < NumParams) { | |||
7233 | // (C++ 13.3.2p3): for F to be a viable function, there shall | |||
7234 | // exist for each argument an implicit conversion sequence | |||
7235 | // (13.3.3.1) that converts that argument to the corresponding | |||
7236 | // parameter of F. | |||
7237 | QualType ParamType = Proto->getParamType(ArgIdx); | |||
7238 | Candidate.Conversions[ArgIdx + 1] | |||
7239 | = TryCopyInitialization(*this, Args[ArgIdx], ParamType, | |||
7240 | /*SuppressUserConversions=*/false, | |||
7241 | /*InOverloadResolution=*/false, | |||
7242 | /*AllowObjCWritebackConversion=*/ | |||
7243 | getLangOpts().ObjCAutoRefCount); | |||
7244 | if (Candidate.Conversions[ArgIdx + 1].isBad()) { | |||
7245 | Candidate.Viable = false; | |||
7246 | Candidate.FailureKind = ovl_fail_bad_conversion; | |||
7247 | return; | |||
7248 | } | |||
7249 | } else { | |||
7250 | // (C++ 13.3.2p2): For the purposes of overload resolution, any | |||
7251 | // argument for which there is no corresponding parameter is | |||
7252 | // considered to ""match the ellipsis" (C+ 13.3.3.1.3). | |||
7253 | Candidate.Conversions[ArgIdx + 1].setEllipsis(); | |||
7254 | } | |||
7255 | } | |||
7256 | ||||
7257 | if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { | |||
7258 | Candidate.Viable = false; | |||
7259 | Candidate.FailureKind = ovl_fail_enable_if; | |||
7260 | Candidate.DeductionFailure.Data = FailedAttr; | |||
7261 | return; | |||
7262 | } | |||
7263 | } | |||
7264 | ||||
7265 | /// Add overload candidates for overloaded operators that are | |||
7266 | /// member functions. | |||
7267 | /// | |||
7268 | /// Add the overloaded operator candidates that are member functions | |||
7269 | /// for the operator Op that was used in an operator expression such | |||
7270 | /// as "x Op y". , Args/NumArgs provides the operator arguments, and | |||
7271 | /// CandidateSet will store the added overload candidates. (C++ | |||
7272 | /// [over.match.oper]). | |||
7273 | void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, | |||
7274 | SourceLocation OpLoc, | |||
7275 | ArrayRef<Expr *> Args, | |||
7276 | OverloadCandidateSet& CandidateSet, | |||
7277 | SourceRange OpRange) { | |||
7278 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); | |||
7279 | ||||
7280 | // C++ [over.match.oper]p3: | |||
7281 | // For a unary operator @ with an operand of a type whose | |||
7282 | // cv-unqualified version is T1, and for a binary operator @ with | |||
7283 | // a left operand of a type whose cv-unqualified version is T1 and | |||
7284 | // a right operand of a type whose cv-unqualified version is T2, | |||
7285 | // three sets of candidate functions, designated member | |||
7286 | // candidates, non-member candidates and built-in candidates, are | |||
7287 | // constructed as follows: | |||
7288 | QualType T1 = Args[0]->getType(); | |||
7289 | ||||
7290 | // -- If T1 is a complete class type or a class currently being | |||
7291 | // defined, the set of member candidates is the result of the | |||
7292 | // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, | |||
7293 | // the set of member candidates is empty. | |||
7294 | if (const RecordType *T1Rec = T1->getAs<RecordType>()) { | |||
7295 | // Complete the type if it can be completed. | |||
7296 | if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) | |||
7297 | return; | |||
7298 | // If the type is neither complete nor being defined, bail out now. | |||
7299 | if (!T1Rec->getDecl()->getDefinition()) | |||
7300 | return; | |||
7301 | ||||
7302 | LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); | |||
7303 | LookupQualifiedName(Operators, T1Rec->getDecl()); | |||
7304 | Operators.suppressDiagnostics(); | |||
7305 | ||||
7306 | for (LookupResult::iterator Oper = Operators.begin(), | |||
7307 | OperEnd = Operators.end(); | |||
7308 | Oper != OperEnd; | |||
7309 | ++Oper) | |||
7310 | AddMethodCandidate(Oper.getPair(), Args[0]->getType(), | |||
7311 | Args[0]->Classify(Context), Args.slice(1), | |||
7312 | CandidateSet, /*SuppressUserConversions=*/false); | |||
7313 | } | |||
7314 | } | |||
7315 | ||||
7316 | /// AddBuiltinCandidate - Add a candidate for a built-in | |||
7317 | /// operator. ResultTy and ParamTys are the result and parameter types | |||
7318 | /// of the built-in candidate, respectively. Args and NumArgs are the | |||
7319 | /// arguments being passed to the candidate. IsAssignmentOperator | |||
7320 | /// should be true when this built-in candidate is an assignment | |||
7321 | /// operator. NumContextualBoolArguments is the number of arguments | |||
7322 | /// (at the beginning of the argument list) that will be contextually | |||
7323 | /// converted to bool. | |||
7324 | void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, | |||
7325 | OverloadCandidateSet& CandidateSet, | |||
7326 | bool IsAssignmentOperator, | |||
7327 | unsigned NumContextualBoolArguments) { | |||
7328 | // Overload resolution is always an unevaluated context. | |||
7329 | EnterExpressionEvaluationContext Unevaluated( | |||
7330 | *this, Sema::ExpressionEvaluationContext::Unevaluated); | |||
7331 | ||||
7332 | // Add this candidate | |||
7333 | OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); | |||
7334 | Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); | |||
7335 | Candidate.Function = nullptr; | |||
7336 | Candidate.IsSurrogate = false; | |||
7337 | Candidate.IgnoreObjectArgument = false; | |||
7338 | std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); | |||
7339 | ||||
7340 | // Determine the implicit conversion sequences for each of the | |||
7341 | // arguments. | |||
7342 | Candidate.Viable = true; | |||
7343 | Candidate.ExplicitCallArguments = Args.size(); | |||
7344 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { | |||
7345 | // C++ [over.match.oper]p4: | |||
7346 | // For the built-in assignment operators, conversions of the | |||
7347 | // left operand are restricted as follows: | |||
7348 | // -- no temporaries are introduced to hold the left operand, and | |||
7349 | // -- no user-defined conversions are applied to the left | |||
7350 | // operand to achieve a type match with the left-most | |||
7351 | // parameter of a built-in candidate. | |||
7352 | // | |||
7353 | // We block these conversions by turning off user-defined | |||
7354 | // conversions, since that is the only way that initialization of | |||
7355 | // a reference to a non-class type can occur from something that | |||
7356 | // is not of the same type. | |||
7357 | if (ArgIdx < NumContextualBoolArguments) { | |||
7358 | assert(ParamTys[ArgIdx] == Context.BoolTy &&((ParamTys[ArgIdx] == Context.BoolTy && "Contextual conversion to bool requires bool type" ) ? static_cast<void> (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 7359, __PRETTY_FUNCTION__)) | |||
7359 | "Contextual conversion to bool requires bool type")((ParamTys[ArgIdx] == Context.BoolTy && "Contextual conversion to bool requires bool type" ) ? static_cast<void> (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 7359, __PRETTY_FUNCTION__)); | |||
7360 | Candidate.Conversions[ArgIdx] | |||
7361 | = TryContextuallyConvertToBool(*this, Args[ArgIdx]); | |||
7362 | } else { | |||
7363 | Candidate.Conversions[ArgIdx] | |||
7364 | = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], | |||
7365 | ArgIdx == 0 && IsAssignmentOperator, | |||
7366 | /*InOverloadResolution=*/false, | |||
7367 | /*AllowObjCWritebackConversion=*/ | |||
7368 | getLangOpts().ObjCAutoRefCount); | |||
7369 | } | |||
7370 | if (Candidate.Conversions[ArgIdx].isBad()) { | |||
7371 | Candidate.Viable = false; | |||
7372 | Candidate.FailureKind = ovl_fail_bad_conversion; | |||
7373 | break; | |||
7374 | } | |||
7375 | } | |||
7376 | } | |||
7377 | ||||
7378 | namespace { | |||
7379 | ||||
7380 | /// BuiltinCandidateTypeSet - A set of types that will be used for the | |||
7381 | /// candidate operator functions for built-in operators (C++ | |||
7382 | /// [over.built]). The types are separated into pointer types and | |||
7383 | /// enumeration types. | |||
7384 | class BuiltinCandidateTypeSet { | |||
7385 | /// TypeSet - A set of types. | |||
7386 | typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, | |||
7387 | llvm::SmallPtrSet<QualType, 8>> TypeSet; | |||
7388 | ||||
7389 | /// PointerTypes - The set of pointer types that will be used in the | |||
7390 | /// built-in candidates. | |||
7391 | TypeSet PointerTypes; | |||
7392 | ||||
7393 | /// MemberPointerTypes - The set of member pointer types that will be | |||
7394 | /// used in the built-in candidates. | |||
7395 | TypeSet MemberPointerTypes; | |||
7396 | ||||
7397 | /// EnumerationTypes - The set of enumeration types that will be | |||
7398 | /// used in the built-in candidates. | |||
7399 | TypeSet EnumerationTypes; | |||
7400 | ||||
7401 | /// The set of vector types that will be used in the built-in | |||
7402 | /// candidates. | |||
7403 | TypeSet VectorTypes; | |||
7404 | ||||
7405 | /// A flag indicating non-record types are viable candidates | |||
7406 | bool HasNonRecordTypes; | |||
7407 | ||||
7408 | /// A flag indicating whether either arithmetic or enumeration types | |||
7409 | /// were present in the candidate set. | |||
7410 | bool HasArithmeticOrEnumeralTypes; | |||
7411 | ||||
7412 | /// A flag indicating whether the nullptr type was present in the | |||
7413 | /// candidate set. | |||
7414 | bool HasNullPtrType; | |||
7415 | ||||
7416 | /// Sema - The semantic analysis instance where we are building the | |||
7417 | /// candidate type set. | |||
7418 | Sema &SemaRef; | |||
7419 | ||||
7420 | /// Context - The AST context in which we will build the type sets. | |||
7421 | ASTContext &Context; | |||
7422 | ||||
7423 | bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, | |||
7424 | const Qualifiers &VisibleQuals); | |||
7425 | bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); | |||
7426 | ||||
7427 | public: | |||
7428 | /// iterator - Iterates through the types that are part of the set. | |||
7429 | typedef TypeSet::iterator iterator; | |||
7430 | ||||
7431 | BuiltinCandidateTypeSet(Sema &SemaRef) | |||
7432 | : HasNonRecordTypes(false), | |||
7433 | HasArithmeticOrEnumeralTypes(false), | |||
7434 | HasNullPtrType(false), | |||
7435 | SemaRef(SemaRef), | |||
7436 | Context(SemaRef.Context) { } | |||
7437 | ||||
7438 | void AddTypesConvertedFrom(QualType Ty, | |||
7439 | SourceLocation Loc, | |||
7440 | bool AllowUserConversions, | |||
7441 | bool AllowExplicitConversions, | |||
7442 | const Qualifiers &VisibleTypeConversionsQuals); | |||
7443 | ||||
7444 | /// pointer_begin - First pointer type found; | |||
7445 | iterator pointer_begin() { return PointerTypes.begin(); } | |||
7446 | ||||
7447 | /// pointer_end - Past the last pointer type found; | |||
7448 | iterator pointer_end() { return PointerTypes.end(); } | |||
7449 | ||||
7450 | /// member_pointer_begin - First member pointer type found; | |||
7451 | iterator member_pointer_begin() { return MemberPointerTypes.begin(); } | |||
7452 | ||||
7453 | /// member_pointer_end - Past the last member pointer type found; | |||
7454 | iterator member_pointer_end() { return MemberPointerTypes.end(); } | |||
7455 | ||||
7456 | /// enumeration_begin - First enumeration type found; | |||
7457 | iterator enumeration_begin() { return EnumerationTypes.begin(); } | |||
7458 | ||||
7459 | /// enumeration_end - Past the last enumeration type found; | |||
7460 | iterator enumeration_end() { return EnumerationTypes.end(); } | |||
7461 | ||||
7462 | iterator vector_begin() { return VectorTypes.begin(); } | |||
7463 | iterator vector_end() { return VectorTypes.end(); } | |||
7464 | ||||
7465 | bool hasNonRecordTypes() { return HasNonRecordTypes; } | |||
7466 | bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } | |||
7467 | bool hasNullPtrType() const { return HasNullPtrType; } | |||
7468 | }; | |||
7469 | ||||
7470 | } // end anonymous namespace | |||
7471 | ||||
7472 | /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to | |||
7473 | /// the set of pointer types along with any more-qualified variants of | |||
7474 | /// that type. For example, if @p Ty is "int const *", this routine | |||
7475 | /// will add "int const *", "int const volatile *", "int const | |||
7476 | /// restrict *", and "int const volatile restrict *" to the set of | |||
7477 | /// pointer types. Returns true if the add of @p Ty itself succeeded, | |||
7478 | /// false otherwise. | |||
7479 | /// | |||
7480 | /// FIXME: what to do about extended qualifiers? | |||
7481 | bool | |||
7482 | BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, | |||
7483 | const Qualifiers &VisibleQuals) { | |||
7484 | ||||
7485 | // Insert this type. | |||
7486 | if (!PointerTypes.insert(Ty)) | |||
7487 | return false; | |||
7488 | ||||
7489 | QualType PointeeTy; | |||
7490 | const PointerType *PointerTy = Ty->getAs<PointerType>(); | |||
7491 | bool buildObjCPtr = false; | |||
7492 | if (!PointerTy) { | |||
7493 | const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); | |||
7494 | PointeeTy = PTy->getPointeeType(); | |||
7495 | buildObjCPtr = true; | |||
7496 | } else { | |||
7497 | PointeeTy = PointerTy->getPointeeType(); | |||
7498 | } | |||
7499 | ||||
7500 | // Don't add qualified variants of arrays. For one, they're not allowed | |||
7501 | // (the qualifier would sink to the element type), and for another, the | |||
7502 | // only overload situation where it matters is subscript or pointer +- int, | |||
7503 | // and those shouldn't have qualifier variants anyway. | |||
7504 | if (PointeeTy->isArrayType()) | |||
7505 | return true; | |||
7506 | ||||
7507 | unsigned BaseCVR = PointeeTy.getCVRQualifiers(); | |||
7508 | bool hasVolatile = VisibleQuals.hasVolatile(); | |||
7509 | bool hasRestrict = VisibleQuals.hasRestrict(); | |||
7510 | ||||
7511 | // Iterate through all strict supersets of BaseCVR. | |||
7512 | for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { | |||
7513 | if ((CVR | BaseCVR) != CVR) continue; | |||
7514 | // Skip over volatile if no volatile found anywhere in the types. | |||
7515 | if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; | |||
7516 | ||||
7517 | // Skip over restrict if no restrict found anywhere in the types, or if | |||
7518 | // the type cannot be restrict-qualified. | |||
7519 | if ((CVR & Qualifiers::Restrict) && | |||
7520 | (!hasRestrict || | |||
7521 | (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) | |||
7522 | continue; | |||
7523 | ||||
7524 | // Build qualified pointee type. | |||
7525 | QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); | |||
7526 | ||||
7527 | // Build qualified pointer type. | |||
7528 | QualType QPointerTy; | |||
7529 | if (!buildObjCPtr) | |||
7530 | QPointerTy = Context.getPointerType(QPointeeTy); | |||
7531 | else | |||
7532 | QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); | |||
7533 | ||||
7534 | // Insert qualified pointer type. | |||
7535 | PointerTypes.insert(QPointerTy); | |||
7536 | } | |||
7537 | ||||
7538 | return true; | |||
7539 | } | |||
7540 | ||||
7541 | /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty | |||
7542 | /// to the set of pointer types along with any more-qualified variants of | |||
7543 | /// that type. For example, if @p Ty is "int const *", this routine | |||
7544 | /// will add "int const *", "int const volatile *", "int const | |||
7545 | /// restrict *", and "int const volatile restrict *" to the set of | |||
7546 | /// pointer types. Returns true if the add of @p Ty itself succeeded, | |||
7547 | /// false otherwise. | |||
7548 | /// | |||
7549 | /// FIXME: what to do about extended qualifiers? | |||
7550 | bool | |||
7551 | BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( | |||
7552 | QualType Ty) { | |||
7553 | // Insert this type. | |||
7554 | if (!MemberPointerTypes.insert(Ty)) | |||
7555 | return false; | |||
7556 | ||||
7557 | const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); | |||
7558 | assert(PointerTy && "type was not a member pointer type!")((PointerTy && "type was not a member pointer type!") ? static_cast<void> (0) : __assert_fail ("PointerTy && \"type was not a member pointer type!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 7558, __PRETTY_FUNCTION__)); | |||
7559 | ||||
7560 | QualType PointeeTy = PointerTy->getPointeeType(); | |||
7561 | // Don't add qualified variants of arrays. For one, they're not allowed | |||
7562 | // (the qualifier would sink to the element type), and for another, the | |||
7563 | // only overload situation where it matters is subscript or pointer +- int, | |||
7564 | // and those shouldn't have qualifier variants anyway. | |||
7565 | if (PointeeTy->isArrayType()) | |||
7566 | return true; | |||
7567 | const Type *ClassTy = PointerTy->getClass(); | |||
7568 | ||||
7569 | // Iterate through all strict supersets of the pointee type's CVR | |||
7570 | // qualifiers. | |||
7571 | unsigned BaseCVR = PointeeTy.getCVRQualifiers(); | |||
7572 | for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { | |||
7573 | if ((CVR | BaseCVR) != CVR) continue; | |||
7574 | ||||
7575 | QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); | |||
7576 | MemberPointerTypes.insert( | |||
7577 | Context.getMemberPointerType(QPointeeTy, ClassTy)); | |||
7578 | } | |||
7579 | ||||
7580 | return true; | |||
7581 | } | |||
7582 | ||||
7583 | /// AddTypesConvertedFrom - Add each of the types to which the type @p | |||
7584 | /// Ty can be implicit converted to the given set of @p Types. We're | |||
7585 | /// primarily interested in pointer types and enumeration types. We also | |||
7586 | /// take member pointer types, for the conditional operator. | |||
7587 | /// AllowUserConversions is true if we should look at the conversion | |||
7588 | /// functions of a class type, and AllowExplicitConversions if we | |||
7589 | /// should also include the explicit conversion functions of a class | |||
7590 | /// type. | |||
7591 | void | |||
7592 | BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, | |||
7593 | SourceLocation Loc, | |||
7594 | bool AllowUserConversions, | |||
7595 | bool AllowExplicitConversions, | |||
7596 | const Qualifiers &VisibleQuals) { | |||
7597 | // Only deal with canonical types. | |||
7598 | Ty = Context.getCanonicalType(Ty); | |||
7599 | ||||
7600 | // Look through reference types; they aren't part of the type of an | |||
7601 | // expression for the purposes of conversions. | |||
7602 | if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) | |||
7603 | Ty = RefTy->getPointeeType(); | |||
7604 | ||||
7605 | // If we're dealing with an array type, decay to the pointer. | |||
7606 | if (Ty->isArrayType()) | |||
7607 | Ty = SemaRef.Context.getArrayDecayedType(Ty); | |||
7608 | ||||
7609 | // Otherwise, we don't care about qualifiers on the type. | |||
7610 | Ty = Ty.getLocalUnqualifiedType(); | |||
7611 | ||||
7612 | // Flag if we ever add a non-record type. | |||
7613 | const RecordType *TyRec = Ty->getAs<RecordType>(); | |||
7614 | HasNonRecordTypes = HasNonRecordTypes || !TyRec; | |||
7615 | ||||
7616 | // Flag if we encounter an arithmetic type. | |||
7617 | HasArithmeticOrEnumeralTypes = | |||
7618 | HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); | |||
7619 | ||||
7620 | if (Ty->isObjCIdType() || Ty->isObjCClassType()) | |||
7621 | PointerTypes.insert(Ty); | |||
7622 | else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { | |||
7623 | // Insert our type, and its more-qualified variants, into the set | |||
7624 | // of types. | |||
7625 | if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) | |||
7626 | return; | |||
7627 | } else if (Ty->isMemberPointerType()) { | |||
7628 | // Member pointers are far easier, since the pointee can't be converted. | |||
7629 | if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) | |||
7630 | return; | |||
7631 | } else if (Ty->isEnumeralType()) { | |||
7632 | HasArithmeticOrEnumeralTypes = true; | |||
7633 | EnumerationTypes.insert(Ty); | |||
7634 | } else if (Ty->isVectorType()) { | |||
7635 | // We treat vector types as arithmetic types in many contexts as an | |||
7636 | // extension. | |||
7637 | HasArithmeticOrEnumeralTypes = true; | |||
7638 | VectorTypes.insert(Ty); | |||
7639 | } else if (Ty->isNullPtrType()) { | |||
7640 | HasNullPtrType = true; | |||
7641 | } else if (AllowUserConversions && TyRec) { | |||
7642 | // No conversion functions in incomplete types. | |||
7643 | if (!SemaRef.isCompleteType(Loc, Ty)) | |||
7644 | return; | |||
7645 | ||||
7646 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); | |||
7647 | for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { | |||
7648 | if (isa<UsingShadowDecl>(D)) | |||
7649 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | |||
7650 | ||||
7651 | // Skip conversion function templates; they don't tell us anything | |||
7652 | // about which builtin types we can convert to. | |||
7653 | if (isa<FunctionTemplateDecl>(D)) | |||
7654 | continue; | |||
7655 | ||||
7656 | CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); | |||
7657 | if (AllowExplicitConversions || !Conv->isExplicit()) { | |||
7658 | AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, | |||
7659 | VisibleQuals); | |||
7660 | } | |||
7661 | } | |||
7662 | } | |||
7663 | } | |||
7664 | /// Helper function for adjusting address spaces for the pointer or reference | |||
7665 | /// operands of builtin operators depending on the argument. | |||
7666 | static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, | |||
7667 | Expr *Arg) { | |||
7668 | return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); | |||
7669 | } | |||
7670 | ||||
7671 | /// Helper function for AddBuiltinOperatorCandidates() that adds | |||
7672 | /// the volatile- and non-volatile-qualified assignment operators for the | |||
7673 | /// given type to the candidate set. | |||
7674 | static void AddBuiltinAssignmentOperatorCandidates(Sema &S, | |||
7675 | QualType T, | |||
7676 | ArrayRef<Expr *> Args, | |||
7677 | OverloadCandidateSet &CandidateSet) { | |||
7678 | QualType ParamTypes[2]; | |||
7679 | ||||
7680 | // T& operator=(T&, T) | |||
7681 | ParamTypes[0] = S.Context.getLValueReferenceType( | |||
7682 | AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); | |||
7683 | ParamTypes[1] = T; | |||
7684 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
7685 | /*IsAssignmentOperator=*/true); | |||
7686 | ||||
7687 | if (!S.Context.getCanonicalType(T).isVolatileQualified()) { | |||
7688 | // volatile T& operator=(volatile T&, T) | |||
7689 | ParamTypes[0] = S.Context.getLValueReferenceType( | |||
7690 | AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), | |||
7691 | Args[0])); | |||
7692 | ParamTypes[1] = T; | |||
7693 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
7694 | /*IsAssignmentOperator=*/true); | |||
7695 | } | |||
7696 | } | |||
7697 | ||||
7698 | /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, | |||
7699 | /// if any, found in visible type conversion functions found in ArgExpr's type. | |||
7700 | static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { | |||
7701 | Qualifiers VRQuals; | |||
7702 | const RecordType *TyRec; | |||
7703 | if (const MemberPointerType *RHSMPType = | |||
7704 | ArgExpr->getType()->getAs<MemberPointerType>()) | |||
7705 | TyRec = RHSMPType->getClass()->getAs<RecordType>(); | |||
7706 | else | |||
7707 | TyRec = ArgExpr->getType()->getAs<RecordType>(); | |||
7708 | if (!TyRec) { | |||
7709 | // Just to be safe, assume the worst case. | |||
7710 | VRQuals.addVolatile(); | |||
7711 | VRQuals.addRestrict(); | |||
7712 | return VRQuals; | |||
7713 | } | |||
7714 | ||||
7715 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); | |||
7716 | if (!ClassDecl->hasDefinition()) | |||
7717 | return VRQuals; | |||
7718 | ||||
7719 | for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { | |||
7720 | if (isa<UsingShadowDecl>(D)) | |||
7721 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | |||
7722 | if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { | |||
7723 | QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); | |||
7724 | if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) | |||
7725 | CanTy = ResTypeRef->getPointeeType(); | |||
7726 | // Need to go down the pointer/mempointer chain and add qualifiers | |||
7727 | // as see them. | |||
7728 | bool done = false; | |||
7729 | while (!done) { | |||
7730 | if (CanTy.isRestrictQualified()) | |||
7731 | VRQuals.addRestrict(); | |||
7732 | if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) | |||
7733 | CanTy = ResTypePtr->getPointeeType(); | |||
7734 | else if (const MemberPointerType *ResTypeMPtr = | |||
7735 | CanTy->getAs<MemberPointerType>()) | |||
7736 | CanTy = ResTypeMPtr->getPointeeType(); | |||
7737 | else | |||
7738 | done = true; | |||
7739 | if (CanTy.isVolatileQualified()) | |||
7740 | VRQuals.addVolatile(); | |||
7741 | if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) | |||
7742 | return VRQuals; | |||
7743 | } | |||
7744 | } | |||
7745 | } | |||
7746 | return VRQuals; | |||
7747 | } | |||
7748 | ||||
7749 | namespace { | |||
7750 | ||||
7751 | /// Helper class to manage the addition of builtin operator overload | |||
7752 | /// candidates. It provides shared state and utility methods used throughout | |||
7753 | /// the process, as well as a helper method to add each group of builtin | |||
7754 | /// operator overloads from the standard to a candidate set. | |||
7755 | class BuiltinOperatorOverloadBuilder { | |||
7756 | // Common instance state available to all overload candidate addition methods. | |||
7757 | Sema &S; | |||
7758 | ArrayRef<Expr *> Args; | |||
7759 | Qualifiers VisibleTypeConversionsQuals; | |||
7760 | bool HasArithmeticOrEnumeralCandidateType; | |||
7761 | SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; | |||
7762 | OverloadCandidateSet &CandidateSet; | |||
7763 | ||||
7764 | static constexpr int ArithmeticTypesCap = 24; | |||
7765 | SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; | |||
7766 | ||||
7767 | // Define some indices used to iterate over the arithemetic types in | |||
7768 | // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic | |||
7769 | // types are that preserved by promotion (C++ [over.built]p2). | |||
7770 | unsigned FirstIntegralType, | |||
7771 | LastIntegralType; | |||
7772 | unsigned FirstPromotedIntegralType, | |||
7773 | LastPromotedIntegralType; | |||
7774 | unsigned FirstPromotedArithmeticType, | |||
7775 | LastPromotedArithmeticType; | |||
7776 | unsigned NumArithmeticTypes; | |||
7777 | ||||
7778 | void InitArithmeticTypes() { | |||
7779 | // Start of promoted types. | |||
7780 | FirstPromotedArithmeticType = 0; | |||
7781 | ArithmeticTypes.push_back(S.Context.FloatTy); | |||
7782 | ArithmeticTypes.push_back(S.Context.DoubleTy); | |||
7783 | ArithmeticTypes.push_back(S.Context.LongDoubleTy); | |||
7784 | if (S.Context.getTargetInfo().hasFloat128Type()) | |||
7785 | ArithmeticTypes.push_back(S.Context.Float128Ty); | |||
7786 | ||||
7787 | // Start of integral types. | |||
7788 | FirstIntegralType = ArithmeticTypes.size(); | |||
7789 | FirstPromotedIntegralType = ArithmeticTypes.size(); | |||
7790 | ArithmeticTypes.push_back(S.Context.IntTy); | |||
7791 | ArithmeticTypes.push_back(S.Context.LongTy); | |||
7792 | ArithmeticTypes.push_back(S.Context.LongLongTy); | |||
7793 | if (S.Context.getTargetInfo().hasInt128Type()) | |||
7794 | ArithmeticTypes.push_back(S.Context.Int128Ty); | |||
7795 | ArithmeticTypes.push_back(S.Context.UnsignedIntTy); | |||
7796 | ArithmeticTypes.push_back(S.Context.UnsignedLongTy); | |||
7797 | ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); | |||
7798 | if (S.Context.getTargetInfo().hasInt128Type()) | |||
7799 | ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); | |||
7800 | LastPromotedIntegralType = ArithmeticTypes.size(); | |||
7801 | LastPromotedArithmeticType = ArithmeticTypes.size(); | |||
7802 | // End of promoted types. | |||
7803 | ||||
7804 | ArithmeticTypes.push_back(S.Context.BoolTy); | |||
7805 | ArithmeticTypes.push_back(S.Context.CharTy); | |||
7806 | ArithmeticTypes.push_back(S.Context.WCharTy); | |||
7807 | if (S.Context.getLangOpts().Char8) | |||
7808 | ArithmeticTypes.push_back(S.Context.Char8Ty); | |||
7809 | ArithmeticTypes.push_back(S.Context.Char16Ty); | |||
7810 | ArithmeticTypes.push_back(S.Context.Char32Ty); | |||
7811 | ArithmeticTypes.push_back(S.Context.SignedCharTy); | |||
7812 | ArithmeticTypes.push_back(S.Context.ShortTy); | |||
7813 | ArithmeticTypes.push_back(S.Context.UnsignedCharTy); | |||
7814 | ArithmeticTypes.push_back(S.Context.UnsignedShortTy); | |||
7815 | LastIntegralType = ArithmeticTypes.size(); | |||
7816 | NumArithmeticTypes = ArithmeticTypes.size(); | |||
7817 | // End of integral types. | |||
7818 | // FIXME: What about complex? What about half? | |||
7819 | ||||
7820 | assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&((ArithmeticTypes.size() <= ArithmeticTypesCap && "Enough inline storage for all arithmetic types." ) ? static_cast<void> (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 7821, __PRETTY_FUNCTION__)) | |||
7821 | "Enough inline storage for all arithmetic types.")((ArithmeticTypes.size() <= ArithmeticTypesCap && "Enough inline storage for all arithmetic types." ) ? static_cast<void> (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 7821, __PRETTY_FUNCTION__)); | |||
7822 | } | |||
7823 | ||||
7824 | /// Helper method to factor out the common pattern of adding overloads | |||
7825 | /// for '++' and '--' builtin operators. | |||
7826 | void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, | |||
7827 | bool HasVolatile, | |||
7828 | bool HasRestrict) { | |||
7829 | QualType ParamTypes[2] = { | |||
7830 | S.Context.getLValueReferenceType(CandidateTy), | |||
7831 | S.Context.IntTy | |||
7832 | }; | |||
7833 | ||||
7834 | // Non-volatile version. | |||
7835 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
7836 | ||||
7837 | // Use a heuristic to reduce number of builtin candidates in the set: | |||
7838 | // add volatile version only if there are conversions to a volatile type. | |||
7839 | if (HasVolatile) { | |||
7840 | ParamTypes[0] = | |||
7841 | S.Context.getLValueReferenceType( | |||
7842 | S.Context.getVolatileType(CandidateTy)); | |||
7843 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
7844 | } | |||
7845 | ||||
7846 | // Add restrict version only if there are conversions to a restrict type | |||
7847 | // and our candidate type is a non-restrict-qualified pointer. | |||
7848 | if (HasRestrict && CandidateTy->isAnyPointerType() && | |||
7849 | !CandidateTy.isRestrictQualified()) { | |||
7850 | ParamTypes[0] | |||
7851 | = S.Context.getLValueReferenceType( | |||
7852 | S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); | |||
7853 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
7854 | ||||
7855 | if (HasVolatile) { | |||
7856 | ParamTypes[0] | |||
7857 | = S.Context.getLValueReferenceType( | |||
7858 | S.Context.getCVRQualifiedType(CandidateTy, | |||
7859 | (Qualifiers::Volatile | | |||
7860 | Qualifiers::Restrict))); | |||
7861 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
7862 | } | |||
7863 | } | |||
7864 | ||||
7865 | } | |||
7866 | ||||
7867 | public: | |||
7868 | BuiltinOperatorOverloadBuilder( | |||
7869 | Sema &S, ArrayRef<Expr *> Args, | |||
7870 | Qualifiers VisibleTypeConversionsQuals, | |||
7871 | bool HasArithmeticOrEnumeralCandidateType, | |||
7872 | SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, | |||
7873 | OverloadCandidateSet &CandidateSet) | |||
7874 | : S(S), Args(Args), | |||
7875 | VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), | |||
7876 | HasArithmeticOrEnumeralCandidateType( | |||
7877 | HasArithmeticOrEnumeralCandidateType), | |||
7878 | CandidateTypes(CandidateTypes), | |||
7879 | CandidateSet(CandidateSet) { | |||
7880 | ||||
7881 | InitArithmeticTypes(); | |||
7882 | } | |||
7883 | ||||
7884 | // Increment is deprecated for bool since C++17. | |||
7885 | // | |||
7886 | // C++ [over.built]p3: | |||
7887 | // | |||
7888 | // For every pair (T, VQ), where T is an arithmetic type other | |||
7889 | // than bool, and VQ is either volatile or empty, there exist | |||
7890 | // candidate operator functions of the form | |||
7891 | // | |||
7892 | // VQ T& operator++(VQ T&); | |||
7893 | // T operator++(VQ T&, int); | |||
7894 | // | |||
7895 | // C++ [over.built]p4: | |||
7896 | // | |||
7897 | // For every pair (T, VQ), where T is an arithmetic type other | |||
7898 | // than bool, and VQ is either volatile or empty, there exist | |||
7899 | // candidate operator functions of the form | |||
7900 | // | |||
7901 | // VQ T& operator--(VQ T&); | |||
7902 | // T operator--(VQ T&, int); | |||
7903 | void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { | |||
7904 | if (!HasArithmeticOrEnumeralCandidateType) | |||
7905 | return; | |||
7906 | ||||
7907 | for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { | |||
7908 | const auto TypeOfT = ArithmeticTypes[Arith]; | |||
7909 | if (TypeOfT == S.Context.BoolTy) { | |||
7910 | if (Op == OO_MinusMinus) | |||
7911 | continue; | |||
7912 | if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) | |||
7913 | continue; | |||
7914 | } | |||
7915 | addPlusPlusMinusMinusStyleOverloads( | |||
7916 | TypeOfT, | |||
7917 | VisibleTypeConversionsQuals.hasVolatile(), | |||
7918 | VisibleTypeConversionsQuals.hasRestrict()); | |||
7919 | } | |||
7920 | } | |||
7921 | ||||
7922 | // C++ [over.built]p5: | |||
7923 | // | |||
7924 | // For every pair (T, VQ), where T is a cv-qualified or | |||
7925 | // cv-unqualified object type, and VQ is either volatile or | |||
7926 | // empty, there exist candidate operator functions of the form | |||
7927 | // | |||
7928 | // T*VQ& operator++(T*VQ&); | |||
7929 | // T*VQ& operator--(T*VQ&); | |||
7930 | // T* operator++(T*VQ&, int); | |||
7931 | // T* operator--(T*VQ&, int); | |||
7932 | void addPlusPlusMinusMinusPointerOverloads() { | |||
7933 | for (BuiltinCandidateTypeSet::iterator | |||
7934 | Ptr = CandidateTypes[0].pointer_begin(), | |||
7935 | PtrEnd = CandidateTypes[0].pointer_end(); | |||
7936 | Ptr != PtrEnd; ++Ptr) { | |||
7937 | // Skip pointer types that aren't pointers to object types. | |||
7938 | if (!(*Ptr)->getPointeeType()->isObjectType()) | |||
7939 | continue; | |||
7940 | ||||
7941 | addPlusPlusMinusMinusStyleOverloads(*Ptr, | |||
7942 | (!(*Ptr).isVolatileQualified() && | |||
7943 | VisibleTypeConversionsQuals.hasVolatile()), | |||
7944 | (!(*Ptr).isRestrictQualified() && | |||
7945 | VisibleTypeConversionsQuals.hasRestrict())); | |||
7946 | } | |||
7947 | } | |||
7948 | ||||
7949 | // C++ [over.built]p6: | |||
7950 | // For every cv-qualified or cv-unqualified object type T, there | |||
7951 | // exist candidate operator functions of the form | |||
7952 | // | |||
7953 | // T& operator*(T*); | |||
7954 | // | |||
7955 | // C++ [over.built]p7: | |||
7956 | // For every function type T that does not have cv-qualifiers or a | |||
7957 | // ref-qualifier, there exist candidate operator functions of the form | |||
7958 | // T& operator*(T*); | |||
7959 | void addUnaryStarPointerOverloads() { | |||
7960 | for (BuiltinCandidateTypeSet::iterator | |||
7961 | Ptr = CandidateTypes[0].pointer_begin(), | |||
7962 | PtrEnd = CandidateTypes[0].pointer_end(); | |||
7963 | Ptr != PtrEnd; ++Ptr) { | |||
7964 | QualType ParamTy = *Ptr; | |||
7965 | QualType PointeeTy = ParamTy->getPointeeType(); | |||
7966 | if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) | |||
7967 | continue; | |||
7968 | ||||
7969 | if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) | |||
7970 | if (Proto->getMethodQuals() || Proto->getRefQualifier()) | |||
7971 | continue; | |||
7972 | ||||
7973 | S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); | |||
7974 | } | |||
7975 | } | |||
7976 | ||||
7977 | // C++ [over.built]p9: | |||
7978 | // For every promoted arithmetic type T, there exist candidate | |||
7979 | // operator functions of the form | |||
7980 | // | |||
7981 | // T operator+(T); | |||
7982 | // T operator-(T); | |||
7983 | void addUnaryPlusOrMinusArithmeticOverloads() { | |||
7984 | if (!HasArithmeticOrEnumeralCandidateType) | |||
7985 | return; | |||
7986 | ||||
7987 | for (unsigned Arith = FirstPromotedArithmeticType; | |||
7988 | Arith < LastPromotedArithmeticType; ++Arith) { | |||
7989 | QualType ArithTy = ArithmeticTypes[Arith]; | |||
7990 | S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); | |||
7991 | } | |||
7992 | ||||
7993 | // Extension: We also add these operators for vector types. | |||
7994 | for (BuiltinCandidateTypeSet::iterator | |||
7995 | Vec = CandidateTypes[0].vector_begin(), | |||
7996 | VecEnd = CandidateTypes[0].vector_end(); | |||
7997 | Vec != VecEnd; ++Vec) { | |||
7998 | QualType VecTy = *Vec; | |||
7999 | S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); | |||
8000 | } | |||
8001 | } | |||
8002 | ||||
8003 | // C++ [over.built]p8: | |||
8004 | // For every type T, there exist candidate operator functions of | |||
8005 | // the form | |||
8006 | // | |||
8007 | // T* operator+(T*); | |||
8008 | void addUnaryPlusPointerOverloads() { | |||
8009 | for (BuiltinCandidateTypeSet::iterator | |||
8010 | Ptr = CandidateTypes[0].pointer_begin(), | |||
8011 | PtrEnd = CandidateTypes[0].pointer_end(); | |||
8012 | Ptr != PtrEnd; ++Ptr) { | |||
8013 | QualType ParamTy = *Ptr; | |||
8014 | S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); | |||
8015 | } | |||
8016 | } | |||
8017 | ||||
8018 | // C++ [over.built]p10: | |||
8019 | // For every promoted integral type T, there exist candidate | |||
8020 | // operator functions of the form | |||
8021 | // | |||
8022 | // T operator~(T); | |||
8023 | void addUnaryTildePromotedIntegralOverloads() { | |||
8024 | if (!HasArithmeticOrEnumeralCandidateType) | |||
8025 | return; | |||
8026 | ||||
8027 | for (unsigned Int = FirstPromotedIntegralType; | |||
8028 | Int < LastPromotedIntegralType; ++Int) { | |||
8029 | QualType IntTy = ArithmeticTypes[Int]; | |||
8030 | S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); | |||
8031 | } | |||
8032 | ||||
8033 | // Extension: We also add this operator for vector types. | |||
8034 | for (BuiltinCandidateTypeSet::iterator | |||
8035 | Vec = CandidateTypes[0].vector_begin(), | |||
8036 | VecEnd = CandidateTypes[0].vector_end(); | |||
8037 | Vec != VecEnd; ++Vec) { | |||
8038 | QualType VecTy = *Vec; | |||
8039 | S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); | |||
8040 | } | |||
8041 | } | |||
8042 | ||||
8043 | // C++ [over.match.oper]p16: | |||
8044 | // For every pointer to member type T or type std::nullptr_t, there | |||
8045 | // exist candidate operator functions of the form | |||
8046 | // | |||
8047 | // bool operator==(T,T); | |||
8048 | // bool operator!=(T,T); | |||
8049 | void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { | |||
8050 | /// Set of (canonical) types that we've already handled. | |||
8051 | llvm::SmallPtrSet<QualType, 8> AddedTypes; | |||
8052 | ||||
8053 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { | |||
8054 | for (BuiltinCandidateTypeSet::iterator | |||
8055 | MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), | |||
8056 | MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); | |||
8057 | MemPtr != MemPtrEnd; | |||
8058 | ++MemPtr) { | |||
8059 | // Don't add the same builtin candidate twice. | |||
8060 | if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) | |||
8061 | continue; | |||
8062 | ||||
8063 | QualType ParamTypes[2] = { *MemPtr, *MemPtr }; | |||
8064 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
8065 | } | |||
8066 | ||||
8067 | if (CandidateTypes[ArgIdx].hasNullPtrType()) { | |||
8068 | CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); | |||
8069 | if (AddedTypes.insert(NullPtrTy).second) { | |||
8070 | QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; | |||
8071 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
8072 | } | |||
8073 | } | |||
8074 | } | |||
8075 | } | |||
8076 | ||||
8077 | // C++ [over.built]p15: | |||
8078 | // | |||
8079 | // For every T, where T is an enumeration type or a pointer type, | |||
8080 | // there exist candidate operator functions of the form | |||
8081 | // | |||
8082 | // bool operator<(T, T); | |||
8083 | // bool operator>(T, T); | |||
8084 | // bool operator<=(T, T); | |||
8085 | // bool operator>=(T, T); | |||
8086 | // bool operator==(T, T); | |||
8087 | // bool operator!=(T, T); | |||
8088 | // R operator<=>(T, T) | |||
8089 | void addGenericBinaryPointerOrEnumeralOverloads() { | |||
8090 | // C++ [over.match.oper]p3: | |||
8091 | // [...]the built-in candidates include all of the candidate operator | |||
8092 | // functions defined in 13.6 that, compared to the given operator, [...] | |||
8093 | // do not have the same parameter-type-list as any non-template non-member | |||
8094 | // candidate. | |||
8095 | // | |||
8096 | // Note that in practice, this only affects enumeration types because there | |||
8097 | // aren't any built-in candidates of record type, and a user-defined operator | |||
8098 | // must have an operand of record or enumeration type. Also, the only other | |||
8099 | // overloaded operator with enumeration arguments, operator=, | |||
8100 | // cannot be overloaded for enumeration types, so this is the only place | |||
8101 | // where we must suppress candidates like this. | |||
8102 | llvm::DenseSet<std::pair<CanQualType, CanQualType> > | |||
8103 | UserDefinedBinaryOperators; | |||
8104 | ||||
8105 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { | |||
8106 | if (CandidateTypes[ArgIdx].enumeration_begin() != | |||
8107 | CandidateTypes[ArgIdx].enumeration_end()) { | |||
8108 | for (OverloadCandidateSet::iterator C = CandidateSet.begin(), | |||
8109 | CEnd = CandidateSet.end(); | |||
8110 | C != CEnd; ++C) { | |||
8111 | if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) | |||
8112 | continue; | |||
8113 | ||||
8114 | if (C->Function->isFunctionTemplateSpecialization()) | |||
8115 | continue; | |||
8116 | ||||
8117 | QualType FirstParamType = | |||
8118 | C->Function->getParamDecl(0)->getType().getUnqualifiedType(); | |||
8119 | QualType SecondParamType = | |||
8120 | C->Function->getParamDecl(1)->getType().getUnqualifiedType(); | |||
8121 | ||||
8122 | // Skip if either parameter isn't of enumeral type. | |||
8123 | if (!FirstParamType->isEnumeralType() || | |||
8124 | !SecondParamType->isEnumeralType()) | |||
8125 | continue; | |||
8126 | ||||
8127 | // Add this operator to the set of known user-defined operators. | |||
8128 | UserDefinedBinaryOperators.insert( | |||
8129 | std::make_pair(S.Context.getCanonicalType(FirstParamType), | |||
8130 | S.Context.getCanonicalType(SecondParamType))); | |||
8131 | } | |||
8132 | } | |||
8133 | } | |||
8134 | ||||
8135 | /// Set of (canonical) types that we've already handled. | |||
8136 | llvm::SmallPtrSet<QualType, 8> AddedTypes; | |||
8137 | ||||
8138 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { | |||
8139 | for (BuiltinCandidateTypeSet::iterator | |||
8140 | Ptr = CandidateTypes[ArgIdx].pointer_begin(), | |||
8141 | PtrEnd = CandidateTypes[ArgIdx].pointer_end(); | |||
8142 | Ptr != PtrEnd; ++Ptr) { | |||
8143 | // Don't add the same builtin candidate twice. | |||
8144 | if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) | |||
8145 | continue; | |||
8146 | ||||
8147 | QualType ParamTypes[2] = { *Ptr, *Ptr }; | |||
8148 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
8149 | } | |||
8150 | for (BuiltinCandidateTypeSet::iterator | |||
8151 | Enum = CandidateTypes[ArgIdx].enumeration_begin(), | |||
8152 | EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); | |||
8153 | Enum != EnumEnd; ++Enum) { | |||
8154 | CanQualType CanonType = S.Context.getCanonicalType(*Enum); | |||
8155 | ||||
8156 | // Don't add the same builtin candidate twice, or if a user defined | |||
8157 | // candidate exists. | |||
8158 | if (!AddedTypes.insert(CanonType).second || | |||
8159 | UserDefinedBinaryOperators.count(std::make_pair(CanonType, | |||
8160 | CanonType))) | |||
8161 | continue; | |||
8162 | QualType ParamTypes[2] = { *Enum, *Enum }; | |||
8163 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
8164 | } | |||
8165 | } | |||
8166 | } | |||
8167 | ||||
8168 | // C++ [over.built]p13: | |||
8169 | // | |||
8170 | // For every cv-qualified or cv-unqualified object type T | |||
8171 | // there exist candidate operator functions of the form | |||
8172 | // | |||
8173 | // T* operator+(T*, ptrdiff_t); | |||
8174 | // T& operator[](T*, ptrdiff_t); [BELOW] | |||
8175 | // T* operator-(T*, ptrdiff_t); | |||
8176 | // T* operator+(ptrdiff_t, T*); | |||
8177 | // T& operator[](ptrdiff_t, T*); [BELOW] | |||
8178 | // | |||
8179 | // C++ [over.built]p14: | |||
8180 | // | |||
8181 | // For every T, where T is a pointer to object type, there | |||
8182 | // exist candidate operator functions of the form | |||
8183 | // | |||
8184 | // ptrdiff_t operator-(T, T); | |||
8185 | void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { | |||
8186 | /// Set of (canonical) types that we've already handled. | |||
8187 | llvm::SmallPtrSet<QualType, 8> AddedTypes; | |||
8188 | ||||
8189 | for (int Arg = 0; Arg < 2; ++Arg) { | |||
8190 | QualType AsymmetricParamTypes[2] = { | |||
8191 | S.Context.getPointerDiffType(), | |||
8192 | S.Context.getPointerDiffType(), | |||
8193 | }; | |||
8194 | for (BuiltinCandidateTypeSet::iterator | |||
8195 | Ptr = CandidateTypes[Arg].pointer_begin(), | |||
8196 | PtrEnd = CandidateTypes[Arg].pointer_end(); | |||
8197 | Ptr != PtrEnd; ++Ptr) { | |||
8198 | QualType PointeeTy = (*Ptr)->getPointeeType(); | |||
8199 | if (!PointeeTy->isObjectType()) | |||
8200 | continue; | |||
8201 | ||||
8202 | AsymmetricParamTypes[Arg] = *Ptr; | |||
8203 | if (Arg == 0 || Op == OO_Plus) { | |||
8204 | // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) | |||
8205 | // T* operator+(ptrdiff_t, T*); | |||
8206 | S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); | |||
8207 | } | |||
8208 | if (Op == OO_Minus) { | |||
8209 | // ptrdiff_t operator-(T, T); | |||
8210 | if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) | |||
8211 | continue; | |||
8212 | ||||
8213 | QualType ParamTypes[2] = { *Ptr, *Ptr }; | |||
8214 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
8215 | } | |||
8216 | } | |||
8217 | } | |||
8218 | } | |||
8219 | ||||
8220 | // C++ [over.built]p12: | |||
8221 | // | |||
8222 | // For every pair of promoted arithmetic types L and R, there | |||
8223 | // exist candidate operator functions of the form | |||
8224 | // | |||
8225 | // LR operator*(L, R); | |||
8226 | // LR operator/(L, R); | |||
8227 | // LR operator+(L, R); | |||
8228 | // LR operator-(L, R); | |||
8229 | // bool operator<(L, R); | |||
8230 | // bool operator>(L, R); | |||
8231 | // bool operator<=(L, R); | |||
8232 | // bool operator>=(L, R); | |||
8233 | // bool operator==(L, R); | |||
8234 | // bool operator!=(L, R); | |||
8235 | // | |||
8236 | // where LR is the result of the usual arithmetic conversions | |||
8237 | // between types L and R. | |||
8238 | // | |||
8239 | // C++ [over.built]p24: | |||
8240 | // | |||
8241 | // For every pair of promoted arithmetic types L and R, there exist | |||
8242 | // candidate operator functions of the form | |||
8243 | // | |||
8244 | // LR operator?(bool, L, R); | |||
8245 | // | |||
8246 | // where LR is the result of the usual arithmetic conversions | |||
8247 | // between types L and R. | |||
8248 | // Our candidates ignore the first parameter. | |||
8249 | void addGenericBinaryArithmeticOverloads() { | |||
8250 | if (!HasArithmeticOrEnumeralCandidateType) | |||
8251 | return; | |||
8252 | ||||
8253 | for (unsigned Left = FirstPromotedArithmeticType; | |||
8254 | Left < LastPromotedArithmeticType; ++Left) { | |||
8255 | for (unsigned Right = FirstPromotedArithmeticType; | |||
8256 | Right < LastPromotedArithmeticType; ++Right) { | |||
8257 | QualType LandR[2] = { ArithmeticTypes[Left], | |||
8258 | ArithmeticTypes[Right] }; | |||
8259 | S.AddBuiltinCandidate(LandR, Args, CandidateSet); | |||
8260 | } | |||
8261 | } | |||
8262 | ||||
8263 | // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the | |||
8264 | // conditional operator for vector types. | |||
8265 | for (BuiltinCandidateTypeSet::iterator | |||
8266 | Vec1 = CandidateTypes[0].vector_begin(), | |||
8267 | Vec1End = CandidateTypes[0].vector_end(); | |||
8268 | Vec1 != Vec1End; ++Vec1) { | |||
8269 | for (BuiltinCandidateTypeSet::iterator | |||
8270 | Vec2 = CandidateTypes[1].vector_begin(), | |||
8271 | Vec2End = CandidateTypes[1].vector_end(); | |||
8272 | Vec2 != Vec2End; ++Vec2) { | |||
8273 | QualType LandR[2] = { *Vec1, *Vec2 }; | |||
8274 | S.AddBuiltinCandidate(LandR, Args, CandidateSet); | |||
8275 | } | |||
8276 | } | |||
8277 | } | |||
8278 | ||||
8279 | // C++2a [over.built]p14: | |||
8280 | // | |||
8281 | // For every integral type T there exists a candidate operator function | |||
8282 | // of the form | |||
8283 | // | |||
8284 | // std::strong_ordering operator<=>(T, T) | |||
8285 | // | |||
8286 | // C++2a [over.built]p15: | |||
8287 | // | |||
8288 | // For every pair of floating-point types L and R, there exists a candidate | |||
8289 | // operator function of the form | |||
8290 | // | |||
8291 | // std::partial_ordering operator<=>(L, R); | |||
8292 | // | |||
8293 | // FIXME: The current specification for integral types doesn't play nice with | |||
8294 | // the direction of p0946r0, which allows mixed integral and unscoped-enum | |||
8295 | // comparisons. Under the current spec this can lead to ambiguity during | |||
8296 | // overload resolution. For example: | |||
8297 | // | |||
8298 | // enum A : int {a}; | |||
8299 | // auto x = (a <=> (long)42); | |||
8300 | // | |||
8301 | // error: call is ambiguous for arguments 'A' and 'long'. | |||
8302 | // note: candidate operator<=>(int, int) | |||
8303 | // note: candidate operator<=>(long, long) | |||
8304 | // | |||
8305 | // To avoid this error, this function deviates from the specification and adds | |||
8306 | // the mixed overloads `operator<=>(L, R)` where L and R are promoted | |||
8307 | // arithmetic types (the same as the generic relational overloads). | |||
8308 | // | |||
8309 | // For now this function acts as a placeholder. | |||
8310 | void addThreeWayArithmeticOverloads() { | |||
8311 | addGenericBinaryArithmeticOverloads(); | |||
8312 | } | |||
8313 | ||||
8314 | // C++ [over.built]p17: | |||
8315 | // | |||
8316 | // For every pair of promoted integral types L and R, there | |||
8317 | // exist candidate operator functions of the form | |||
8318 | // | |||
8319 | // LR operator%(L, R); | |||
8320 | // LR operator&(L, R); | |||
8321 | // LR operator^(L, R); | |||
8322 | // LR operator|(L, R); | |||
8323 | // L operator<<(L, R); | |||
8324 | // L operator>>(L, R); | |||
8325 | // | |||
8326 | // where LR is the result of the usual arithmetic conversions | |||
8327 | // between types L and R. | |||
8328 | void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { | |||
8329 | if (!HasArithmeticOrEnumeralCandidateType) | |||
8330 | return; | |||
8331 | ||||
8332 | for (unsigned Left = FirstPromotedIntegralType; | |||
8333 | Left < LastPromotedIntegralType; ++Left) { | |||
8334 | for (unsigned Right = FirstPromotedIntegralType; | |||
8335 | Right < LastPromotedIntegralType; ++Right) { | |||
8336 | QualType LandR[2] = { ArithmeticTypes[Left], | |||
8337 | ArithmeticTypes[Right] }; | |||
8338 | S.AddBuiltinCandidate(LandR, Args, CandidateSet); | |||
8339 | } | |||
8340 | } | |||
8341 | } | |||
8342 | ||||
8343 | // C++ [over.built]p20: | |||
8344 | // | |||
8345 | // For every pair (T, VQ), where T is an enumeration or | |||
8346 | // pointer to member type and VQ is either volatile or | |||
8347 | // empty, there exist candidate operator functions of the form | |||
8348 | // | |||
8349 | // VQ T& operator=(VQ T&, T); | |||
8350 | void addAssignmentMemberPointerOrEnumeralOverloads() { | |||
8351 | /// Set of (canonical) types that we've already handled. | |||
8352 | llvm::SmallPtrSet<QualType, 8> AddedTypes; | |||
8353 | ||||
8354 | for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { | |||
8355 | for (BuiltinCandidateTypeSet::iterator | |||
8356 | Enum = CandidateTypes[ArgIdx].enumeration_begin(), | |||
8357 | EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); | |||
8358 | Enum != EnumEnd; ++Enum) { | |||
8359 | if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) | |||
8360 | continue; | |||
8361 | ||||
8362 | AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); | |||
8363 | } | |||
8364 | ||||
8365 | for (BuiltinCandidateTypeSet::iterator | |||
8366 | MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), | |||
8367 | MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); | |||
8368 | MemPtr != MemPtrEnd; ++MemPtr) { | |||
8369 | if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) | |||
8370 | continue; | |||
8371 | ||||
8372 | AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); | |||
8373 | } | |||
8374 | } | |||
8375 | } | |||
8376 | ||||
8377 | // C++ [over.built]p19: | |||
8378 | // | |||
8379 | // For every pair (T, VQ), where T is any type and VQ is either | |||
8380 | // volatile or empty, there exist candidate operator functions | |||
8381 | // of the form | |||
8382 | // | |||
8383 | // T*VQ& operator=(T*VQ&, T*); | |||
8384 | // | |||
8385 | // C++ [over.built]p21: | |||
8386 | // | |||
8387 | // For every pair (T, VQ), where T is a cv-qualified or | |||
8388 | // cv-unqualified object type and VQ is either volatile or | |||
8389 | // empty, there exist candidate operator functions of the form | |||
8390 | // | |||
8391 | // T*VQ& operator+=(T*VQ&, ptrdiff_t); | |||
8392 | // T*VQ& operator-=(T*VQ&, ptrdiff_t); | |||
8393 | void addAssignmentPointerOverloads(bool isEqualOp) { | |||
8394 | /// Set of (canonical) types that we've already handled. | |||
8395 | llvm::SmallPtrSet<QualType, 8> AddedTypes; | |||
8396 | ||||
8397 | for (BuiltinCandidateTypeSet::iterator | |||
8398 | Ptr = CandidateTypes[0].pointer_begin(), | |||
8399 | PtrEnd = CandidateTypes[0].pointer_end(); | |||
8400 | Ptr != PtrEnd; ++Ptr) { | |||
8401 | // If this is operator=, keep track of the builtin candidates we added. | |||
8402 | if (isEqualOp) | |||
8403 | AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); | |||
8404 | else if (!(*Ptr)->getPointeeType()->isObjectType()) | |||
8405 | continue; | |||
8406 | ||||
8407 | // non-volatile version | |||
8408 | QualType ParamTypes[2] = { | |||
8409 | S.Context.getLValueReferenceType(*Ptr), | |||
8410 | isEqualOp ? *Ptr : S.Context.getPointerDiffType(), | |||
8411 | }; | |||
8412 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8413 | /*IsAssigmentOperator=*/ isEqualOp); | |||
8414 | ||||
8415 | bool NeedVolatile = !(*Ptr).isVolatileQualified() && | |||
8416 | VisibleTypeConversionsQuals.hasVolatile(); | |||
8417 | if (NeedVolatile) { | |||
8418 | // volatile version | |||
8419 | ParamTypes[0] = | |||
8420 | S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); | |||
8421 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8422 | /*IsAssigmentOperator=*/isEqualOp); | |||
8423 | } | |||
8424 | ||||
8425 | if (!(*Ptr).isRestrictQualified() && | |||
8426 | VisibleTypeConversionsQuals.hasRestrict()) { | |||
8427 | // restrict version | |||
8428 | ParamTypes[0] | |||
8429 | = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); | |||
8430 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8431 | /*IsAssigmentOperator=*/isEqualOp); | |||
8432 | ||||
8433 | if (NeedVolatile) { | |||
8434 | // volatile restrict version | |||
8435 | ParamTypes[0] | |||
8436 | = S.Context.getLValueReferenceType( | |||
8437 | S.Context.getCVRQualifiedType(*Ptr, | |||
8438 | (Qualifiers::Volatile | | |||
8439 | Qualifiers::Restrict))); | |||
8440 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8441 | /*IsAssigmentOperator=*/isEqualOp); | |||
8442 | } | |||
8443 | } | |||
8444 | } | |||
8445 | ||||
8446 | if (isEqualOp) { | |||
8447 | for (BuiltinCandidateTypeSet::iterator | |||
8448 | Ptr = CandidateTypes[1].pointer_begin(), | |||
8449 | PtrEnd = CandidateTypes[1].pointer_end(); | |||
8450 | Ptr != PtrEnd; ++Ptr) { | |||
8451 | // Make sure we don't add the same candidate twice. | |||
8452 | if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) | |||
8453 | continue; | |||
8454 | ||||
8455 | QualType ParamTypes[2] = { | |||
8456 | S.Context.getLValueReferenceType(*Ptr), | |||
8457 | *Ptr, | |||
8458 | }; | |||
8459 | ||||
8460 | // non-volatile version | |||
8461 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8462 | /*IsAssigmentOperator=*/true); | |||
8463 | ||||
8464 | bool NeedVolatile = !(*Ptr).isVolatileQualified() && | |||
8465 | VisibleTypeConversionsQuals.hasVolatile(); | |||
8466 | if (NeedVolatile) { | |||
8467 | // volatile version | |||
8468 | ParamTypes[0] = | |||
8469 | S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); | |||
8470 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8471 | /*IsAssigmentOperator=*/true); | |||
8472 | } | |||
8473 | ||||
8474 | if (!(*Ptr).isRestrictQualified() && | |||
8475 | VisibleTypeConversionsQuals.hasRestrict()) { | |||
8476 | // restrict version | |||
8477 | ParamTypes[0] | |||
8478 | = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); | |||
8479 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8480 | /*IsAssigmentOperator=*/true); | |||
8481 | ||||
8482 | if (NeedVolatile) { | |||
8483 | // volatile restrict version | |||
8484 | ParamTypes[0] | |||
8485 | = S.Context.getLValueReferenceType( | |||
8486 | S.Context.getCVRQualifiedType(*Ptr, | |||
8487 | (Qualifiers::Volatile | | |||
8488 | Qualifiers::Restrict))); | |||
8489 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8490 | /*IsAssigmentOperator=*/true); | |||
8491 | } | |||
8492 | } | |||
8493 | } | |||
8494 | } | |||
8495 | } | |||
8496 | ||||
8497 | // C++ [over.built]p18: | |||
8498 | // | |||
8499 | // For every triple (L, VQ, R), where L is an arithmetic type, | |||
8500 | // VQ is either volatile or empty, and R is a promoted | |||
8501 | // arithmetic type, there exist candidate operator functions of | |||
8502 | // the form | |||
8503 | // | |||
8504 | // VQ L& operator=(VQ L&, R); | |||
8505 | // VQ L& operator*=(VQ L&, R); | |||
8506 | // VQ L& operator/=(VQ L&, R); | |||
8507 | // VQ L& operator+=(VQ L&, R); | |||
8508 | // VQ L& operator-=(VQ L&, R); | |||
8509 | void addAssignmentArithmeticOverloads(bool isEqualOp) { | |||
8510 | if (!HasArithmeticOrEnumeralCandidateType) | |||
8511 | return; | |||
8512 | ||||
8513 | for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { | |||
8514 | for (unsigned Right = FirstPromotedArithmeticType; | |||
8515 | Right < LastPromotedArithmeticType; ++Right) { | |||
8516 | QualType ParamTypes[2]; | |||
8517 | ParamTypes[1] = ArithmeticTypes[Right]; | |||
8518 | auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( | |||
8519 | S, ArithmeticTypes[Left], Args[0]); | |||
8520 | // Add this built-in operator as a candidate (VQ is empty). | |||
8521 | ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); | |||
8522 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8523 | /*IsAssigmentOperator=*/isEqualOp); | |||
8524 | ||||
8525 | // Add this built-in operator as a candidate (VQ is 'volatile'). | |||
8526 | if (VisibleTypeConversionsQuals.hasVolatile()) { | |||
8527 | ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); | |||
8528 | ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); | |||
8529 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8530 | /*IsAssigmentOperator=*/isEqualOp); | |||
8531 | } | |||
8532 | } | |||
8533 | } | |||
8534 | ||||
8535 | // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. | |||
8536 | for (BuiltinCandidateTypeSet::iterator | |||
8537 | Vec1 = CandidateTypes[0].vector_begin(), | |||
8538 | Vec1End = CandidateTypes[0].vector_end(); | |||
8539 | Vec1 != Vec1End; ++Vec1) { | |||
8540 | for (BuiltinCandidateTypeSet::iterator | |||
8541 | Vec2 = CandidateTypes[1].vector_begin(), | |||
8542 | Vec2End = CandidateTypes[1].vector_end(); | |||
8543 | Vec2 != Vec2End; ++Vec2) { | |||
8544 | QualType ParamTypes[2]; | |||
8545 | ParamTypes[1] = *Vec2; | |||
8546 | // Add this built-in operator as a candidate (VQ is empty). | |||
8547 | ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); | |||
8548 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8549 | /*IsAssigmentOperator=*/isEqualOp); | |||
8550 | ||||
8551 | // Add this built-in operator as a candidate (VQ is 'volatile'). | |||
8552 | if (VisibleTypeConversionsQuals.hasVolatile()) { | |||
8553 | ParamTypes[0] = S.Context.getVolatileType(*Vec1); | |||
8554 | ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); | |||
8555 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8556 | /*IsAssigmentOperator=*/isEqualOp); | |||
8557 | } | |||
8558 | } | |||
8559 | } | |||
8560 | } | |||
8561 | ||||
8562 | // C++ [over.built]p22: | |||
8563 | // | |||
8564 | // For every triple (L, VQ, R), where L is an integral type, VQ | |||
8565 | // is either volatile or empty, and R is a promoted integral | |||
8566 | // type, there exist candidate operator functions of the form | |||
8567 | // | |||
8568 | // VQ L& operator%=(VQ L&, R); | |||
8569 | // VQ L& operator<<=(VQ L&, R); | |||
8570 | // VQ L& operator>>=(VQ L&, R); | |||
8571 | // VQ L& operator&=(VQ L&, R); | |||
8572 | // VQ L& operator^=(VQ L&, R); | |||
8573 | // VQ L& operator|=(VQ L&, R); | |||
8574 | void addAssignmentIntegralOverloads() { | |||
8575 | if (!HasArithmeticOrEnumeralCandidateType) | |||
8576 | return; | |||
8577 | ||||
8578 | for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { | |||
8579 | for (unsigned Right = FirstPromotedIntegralType; | |||
8580 | Right < LastPromotedIntegralType; ++Right) { | |||
8581 | QualType ParamTypes[2]; | |||
8582 | ParamTypes[1] = ArithmeticTypes[Right]; | |||
8583 | auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( | |||
8584 | S, ArithmeticTypes[Left], Args[0]); | |||
8585 | // Add this built-in operator as a candidate (VQ is empty). | |||
8586 | ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); | |||
8587 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
8588 | if (VisibleTypeConversionsQuals.hasVolatile()) { | |||
8589 | // Add this built-in operator as a candidate (VQ is 'volatile'). | |||
8590 | ParamTypes[0] = LeftBaseTy; | |||
8591 | ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); | |||
8592 | ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); | |||
8593 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
8594 | } | |||
8595 | } | |||
8596 | } | |||
8597 | } | |||
8598 | ||||
8599 | // C++ [over.operator]p23: | |||
8600 | // | |||
8601 | // There also exist candidate operator functions of the form | |||
8602 | // | |||
8603 | // bool operator!(bool); | |||
8604 | // bool operator&&(bool, bool); | |||
8605 | // bool operator||(bool, bool); | |||
8606 | void addExclaimOverload() { | |||
8607 | QualType ParamTy = S.Context.BoolTy; | |||
8608 | S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, | |||
8609 | /*IsAssignmentOperator=*/false, | |||
8610 | /*NumContextualBoolArguments=*/1); | |||
8611 | } | |||
8612 | void addAmpAmpOrPipePipeOverload() { | |||
8613 | QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; | |||
8614 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, | |||
8615 | /*IsAssignmentOperator=*/false, | |||
8616 | /*NumContextualBoolArguments=*/2); | |||
8617 | } | |||
8618 | ||||
8619 | // C++ [over.built]p13: | |||
8620 | // | |||
8621 | // For every cv-qualified or cv-unqualified object type T there | |||
8622 | // exist candidate operator functions of the form | |||
8623 | // | |||
8624 | // T* operator+(T*, ptrdiff_t); [ABOVE] | |||
8625 | // T& operator[](T*, ptrdiff_t); | |||
8626 | // T* operator-(T*, ptrdiff_t); [ABOVE] | |||
8627 | // T* operator+(ptrdiff_t, T*); [ABOVE] | |||
8628 | // T& operator[](ptrdiff_t, T*); | |||
8629 | void addSubscriptOverloads() { | |||
8630 | for (BuiltinCandidateTypeSet::iterator | |||
8631 | Ptr = CandidateTypes[0].pointer_begin(), | |||
8632 | PtrEnd = CandidateTypes[0].pointer_end(); | |||
8633 | Ptr != PtrEnd; ++Ptr) { | |||
8634 | QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; | |||
8635 | QualType PointeeType = (*Ptr)->getPointeeType(); | |||
8636 | if (!PointeeType->isObjectType()) | |||
8637 | continue; | |||
8638 | ||||
8639 | // T& operator[](T*, ptrdiff_t) | |||
8640 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
8641 | } | |||
8642 | ||||
8643 | for (BuiltinCandidateTypeSet::iterator | |||
8644 | Ptr = CandidateTypes[1].pointer_begin(), | |||
8645 | PtrEnd = CandidateTypes[1].pointer_end(); | |||
8646 | Ptr != PtrEnd; ++Ptr) { | |||
8647 | QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; | |||
8648 | QualType PointeeType = (*Ptr)->getPointeeType(); | |||
8649 | if (!PointeeType->isObjectType()) | |||
8650 | continue; | |||
8651 | ||||
8652 | // T& operator[](ptrdiff_t, T*) | |||
8653 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
8654 | } | |||
8655 | } | |||
8656 | ||||
8657 | // C++ [over.built]p11: | |||
8658 | // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, | |||
8659 | // C1 is the same type as C2 or is a derived class of C2, T is an object | |||
8660 | // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, | |||
8661 | // there exist candidate operator functions of the form | |||
8662 | // | |||
8663 | // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); | |||
8664 | // | |||
8665 | // where CV12 is the union of CV1 and CV2. | |||
8666 | void addArrowStarOverloads() { | |||
8667 | for (BuiltinCandidateTypeSet::iterator | |||
8668 | Ptr = CandidateTypes[0].pointer_begin(), | |||
8669 | PtrEnd = CandidateTypes[0].pointer_end(); | |||
8670 | Ptr != PtrEnd; ++Ptr) { | |||
8671 | QualType C1Ty = (*Ptr); | |||
8672 | QualType C1; | |||
8673 | QualifierCollector Q1; | |||
8674 | C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); | |||
8675 | if (!isa<RecordType>(C1)) | |||
8676 | continue; | |||
8677 | // heuristic to reduce number of builtin candidates in the set. | |||
8678 | // Add volatile/restrict version only if there are conversions to a | |||
8679 | // volatile/restrict type. | |||
8680 | if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) | |||
8681 | continue; | |||
8682 | if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) | |||
8683 | continue; | |||
8684 | for (BuiltinCandidateTypeSet::iterator | |||
8685 | MemPtr = CandidateTypes[1].member_pointer_begin(), | |||
8686 | MemPtrEnd = CandidateTypes[1].member_pointer_end(); | |||
8687 | MemPtr != MemPtrEnd; ++MemPtr) { | |||
8688 | const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); | |||
8689 | QualType C2 = QualType(mptr->getClass(), 0); | |||
8690 | C2 = C2.getUnqualifiedType(); | |||
8691 | if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) | |||
8692 | break; | |||
8693 | QualType ParamTypes[2] = { *Ptr, *MemPtr }; | |||
8694 | // build CV12 T& | |||
8695 | QualType T = mptr->getPointeeType(); | |||
8696 | if (!VisibleTypeConversionsQuals.hasVolatile() && | |||
8697 | T.isVolatileQualified()) | |||
8698 | continue; | |||
8699 | if (!VisibleTypeConversionsQuals.hasRestrict() && | |||
8700 | T.isRestrictQualified()) | |||
8701 | continue; | |||
8702 | T = Q1.apply(S.Context, T); | |||
8703 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
8704 | } | |||
8705 | } | |||
8706 | } | |||
8707 | ||||
8708 | // Note that we don't consider the first argument, since it has been | |||
8709 | // contextually converted to bool long ago. The candidates below are | |||
8710 | // therefore added as binary. | |||
8711 | // | |||
8712 | // C++ [over.built]p25: | |||
8713 | // For every type T, where T is a pointer, pointer-to-member, or scoped | |||
8714 | // enumeration type, there exist candidate operator functions of the form | |||
8715 | // | |||
8716 | // T operator?(bool, T, T); | |||
8717 | // | |||
8718 | void addConditionalOperatorOverloads() { | |||
8719 | /// Set of (canonical) types that we've already handled. | |||
8720 | llvm::SmallPtrSet<QualType, 8> AddedTypes; | |||
8721 | ||||
8722 | for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { | |||
8723 | for (BuiltinCandidateTypeSet::iterator | |||
8724 | Ptr = CandidateTypes[ArgIdx].pointer_begin(), | |||
8725 | PtrEnd = CandidateTypes[ArgIdx].pointer_end(); | |||
8726 | Ptr != PtrEnd; ++Ptr) { | |||
8727 | if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) | |||
8728 | continue; | |||
8729 | ||||
8730 | QualType ParamTypes[2] = { *Ptr, *Ptr }; | |||
8731 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
8732 | } | |||
8733 | ||||
8734 | for (BuiltinCandidateTypeSet::iterator | |||
8735 | MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), | |||
8736 | MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); | |||
8737 | MemPtr != MemPtrEnd; ++MemPtr) { | |||
8738 | if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) | |||
8739 | continue; | |||
8740 | ||||
8741 | QualType ParamTypes[2] = { *MemPtr, *MemPtr }; | |||
8742 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
8743 | } | |||
8744 | ||||
8745 | if (S.getLangOpts().CPlusPlus11) { | |||
8746 | for (BuiltinCandidateTypeSet::iterator | |||
8747 | Enum = CandidateTypes[ArgIdx].enumeration_begin(), | |||
8748 | EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); | |||
8749 | Enum != EnumEnd; ++Enum) { | |||
8750 | if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) | |||
8751 | continue; | |||
8752 | ||||
8753 | if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) | |||
8754 | continue; | |||
8755 | ||||
8756 | QualType ParamTypes[2] = { *Enum, *Enum }; | |||
8757 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); | |||
8758 | } | |||
8759 | } | |||
8760 | } | |||
8761 | } | |||
8762 | }; | |||
8763 | ||||
8764 | } // end anonymous namespace | |||
8765 | ||||
8766 | /// AddBuiltinOperatorCandidates - Add the appropriate built-in | |||
8767 | /// operator overloads to the candidate set (C++ [over.built]), based | |||
8768 | /// on the operator @p Op and the arguments given. For example, if the | |||
8769 | /// operator is a binary '+', this routine might add "int | |||
8770 | /// operator+(int, int)" to cover integer addition. | |||
8771 | void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, | |||
8772 | SourceLocation OpLoc, | |||
8773 | ArrayRef<Expr *> Args, | |||
8774 | OverloadCandidateSet &CandidateSet) { | |||
8775 | // Find all of the types that the arguments can convert to, but only | |||
8776 | // if the operator we're looking at has built-in operator candidates | |||
8777 | // that make use of these types. Also record whether we encounter non-record | |||
8778 | // candidate types or either arithmetic or enumeral candidate types. | |||
8779 | Qualifiers VisibleTypeConversionsQuals; | |||
8780 | VisibleTypeConversionsQuals.addConst(); | |||
8781 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) | |||
8782 | VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); | |||
8783 | ||||
8784 | bool HasNonRecordCandidateType = false; | |||
8785 | bool HasArithmeticOrEnumeralCandidateType = false; | |||
8786 | SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; | |||
8787 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { | |||
8788 | CandidateTypes.emplace_back(*this); | |||
8789 | CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), | |||
8790 | OpLoc, | |||
8791 | true, | |||
8792 | (Op == OO_Exclaim || | |||
8793 | Op == OO_AmpAmp || | |||
8794 | Op == OO_PipePipe), | |||
8795 | VisibleTypeConversionsQuals); | |||
8796 | HasNonRecordCandidateType = HasNonRecordCandidateType || | |||
8797 | CandidateTypes[ArgIdx].hasNonRecordTypes(); | |||
8798 | HasArithmeticOrEnumeralCandidateType = | |||
8799 | HasArithmeticOrEnumeralCandidateType || | |||
8800 | CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); | |||
8801 | } | |||
8802 | ||||
8803 | // Exit early when no non-record types have been added to the candidate set | |||
8804 | // for any of the arguments to the operator. | |||
8805 | // | |||
8806 | // We can't exit early for !, ||, or &&, since there we have always have | |||
8807 | // 'bool' overloads. | |||
8808 | if (!HasNonRecordCandidateType && | |||
8809 | !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) | |||
8810 | return; | |||
8811 | ||||
8812 | // Setup an object to manage the common state for building overloads. | |||
8813 | BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, | |||
8814 | VisibleTypeConversionsQuals, | |||
8815 | HasArithmeticOrEnumeralCandidateType, | |||
8816 | CandidateTypes, CandidateSet); | |||
8817 | ||||
8818 | // Dispatch over the operation to add in only those overloads which apply. | |||
8819 | switch (Op) { | |||
8820 | case OO_None: | |||
8821 | case NUM_OVERLOADED_OPERATORS: | |||
8822 | llvm_unreachable("Expected an overloaded operator")::llvm::llvm_unreachable_internal("Expected an overloaded operator" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 8822); | |||
8823 | ||||
8824 | case OO_New: | |||
8825 | case OO_Delete: | |||
8826 | case OO_Array_New: | |||
8827 | case OO_Array_Delete: | |||
8828 | case OO_Call: | |||
8829 | llvm_unreachable(::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 8830) | |||
8830 | "Special operators don't use AddBuiltinOperatorCandidates")::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 8830); | |||
8831 | ||||
8832 | case OO_Comma: | |||
8833 | case OO_Arrow: | |||
8834 | case OO_Coawait: | |||
8835 | // C++ [over.match.oper]p3: | |||
8836 | // -- For the operator ',', the unary operator '&', the | |||
8837 | // operator '->', or the operator 'co_await', the | |||
8838 | // built-in candidates set is empty. | |||
8839 | break; | |||
8840 | ||||
8841 | case OO_Plus: // '+' is either unary or binary | |||
8842 | if (Args.size() == 1) | |||
8843 | OpBuilder.addUnaryPlusPointerOverloads(); | |||
8844 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
8845 | ||||
8846 | case OO_Minus: // '-' is either unary or binary | |||
8847 | if (Args.size() == 1) { | |||
8848 | OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); | |||
8849 | } else { | |||
8850 | OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); | |||
8851 | OpBuilder.addGenericBinaryArithmeticOverloads(); | |||
8852 | } | |||
8853 | break; | |||
8854 | ||||
8855 | case OO_Star: // '*' is either unary or binary | |||
8856 | if (Args.size() == 1) | |||
8857 | OpBuilder.addUnaryStarPointerOverloads(); | |||
8858 | else | |||
8859 | OpBuilder.addGenericBinaryArithmeticOverloads(); | |||
8860 | break; | |||
8861 | ||||
8862 | case OO_Slash: | |||
8863 | OpBuilder.addGenericBinaryArithmeticOverloads(); | |||
8864 | break; | |||
8865 | ||||
8866 | case OO_PlusPlus: | |||
8867 | case OO_MinusMinus: | |||
8868 | OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); | |||
8869 | OpBuilder.addPlusPlusMinusMinusPointerOverloads(); | |||
8870 | break; | |||
8871 | ||||
8872 | case OO_EqualEqual: | |||
8873 | case OO_ExclaimEqual: | |||
8874 | OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); | |||
8875 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
8876 | ||||
8877 | case OO_Less: | |||
8878 | case OO_Greater: | |||
8879 | case OO_LessEqual: | |||
8880 | case OO_GreaterEqual: | |||
8881 | OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); | |||
8882 | OpBuilder.addGenericBinaryArithmeticOverloads(); | |||
8883 | break; | |||
8884 | ||||
8885 | case OO_Spaceship: | |||
8886 | OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); | |||
8887 | OpBuilder.addThreeWayArithmeticOverloads(); | |||
8888 | break; | |||
8889 | ||||
8890 | case OO_Percent: | |||
8891 | case OO_Caret: | |||
8892 | case OO_Pipe: | |||
8893 | case OO_LessLess: | |||
8894 | case OO_GreaterGreater: | |||
8895 | OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); | |||
8896 | break; | |||
8897 | ||||
8898 | case OO_Amp: // '&' is either unary or binary | |||
8899 | if (Args.size() == 1) | |||
8900 | // C++ [over.match.oper]p3: | |||
8901 | // -- For the operator ',', the unary operator '&', or the | |||
8902 | // operator '->', the built-in candidates set is empty. | |||
8903 | break; | |||
8904 | ||||
8905 | OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); | |||
8906 | break; | |||
8907 | ||||
8908 | case OO_Tilde: | |||
8909 | OpBuilder.addUnaryTildePromotedIntegralOverloads(); | |||
8910 | break; | |||
8911 | ||||
8912 | case OO_Equal: | |||
8913 | OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); | |||
8914 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
8915 | ||||
8916 | case OO_PlusEqual: | |||
8917 | case OO_MinusEqual: | |||
8918 | OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); | |||
8919 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
8920 | ||||
8921 | case OO_StarEqual: | |||
8922 | case OO_SlashEqual: | |||
8923 | OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); | |||
8924 | break; | |||
8925 | ||||
8926 | case OO_PercentEqual: | |||
8927 | case OO_LessLessEqual: | |||
8928 | case OO_GreaterGreaterEqual: | |||
8929 | case OO_AmpEqual: | |||
8930 | case OO_CaretEqual: | |||
8931 | case OO_PipeEqual: | |||
8932 | OpBuilder.addAssignmentIntegralOverloads(); | |||
8933 | break; | |||
8934 | ||||
8935 | case OO_Exclaim: | |||
8936 | OpBuilder.addExclaimOverload(); | |||
8937 | break; | |||
8938 | ||||
8939 | case OO_AmpAmp: | |||
8940 | case OO_PipePipe: | |||
8941 | OpBuilder.addAmpAmpOrPipePipeOverload(); | |||
8942 | break; | |||
8943 | ||||
8944 | case OO_Subscript: | |||
8945 | OpBuilder.addSubscriptOverloads(); | |||
8946 | break; | |||
8947 | ||||
8948 | case OO_ArrowStar: | |||
8949 | OpBuilder.addArrowStarOverloads(); | |||
8950 | break; | |||
8951 | ||||
8952 | case OO_Conditional: | |||
8953 | OpBuilder.addConditionalOperatorOverloads(); | |||
8954 | OpBuilder.addGenericBinaryArithmeticOverloads(); | |||
8955 | break; | |||
8956 | } | |||
8957 | } | |||
8958 | ||||
8959 | /// Add function candidates found via argument-dependent lookup | |||
8960 | /// to the set of overloading candidates. | |||
8961 | /// | |||
8962 | /// This routine performs argument-dependent name lookup based on the | |||
8963 | /// given function name (which may also be an operator name) and adds | |||
8964 | /// all of the overload candidates found by ADL to the overload | |||
8965 | /// candidate set (C++ [basic.lookup.argdep]). | |||
8966 | void | |||
8967 | Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, | |||
8968 | SourceLocation Loc, | |||
8969 | ArrayRef<Expr *> Args, | |||
8970 | TemplateArgumentListInfo *ExplicitTemplateArgs, | |||
8971 | OverloadCandidateSet& CandidateSet, | |||
8972 | bool PartialOverloading) { | |||
8973 | ADLResult Fns; | |||
8974 | ||||
8975 | // FIXME: This approach for uniquing ADL results (and removing | |||
8976 | // redundant candidates from the set) relies on pointer-equality, | |||
8977 | // which means we need to key off the canonical decl. However, | |||
8978 | // always going back to the canonical decl might not get us the | |||
8979 | // right set of default arguments. What default arguments are | |||
8980 | // we supposed to consider on ADL candidates, anyway? | |||
8981 | ||||
8982 | // FIXME: Pass in the explicit template arguments? | |||
8983 | ArgumentDependentLookup(Name, Loc, Args, Fns); | |||
8984 | ||||
8985 | // Erase all of the candidates we already knew about. | |||
8986 | for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), | |||
8987 | CandEnd = CandidateSet.end(); | |||
8988 | Cand != CandEnd; ++Cand) | |||
8989 | if (Cand->Function) { | |||
8990 | Fns.erase(Cand->Function); | |||
8991 | if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) | |||
8992 | Fns.erase(FunTmpl); | |||
8993 | } | |||
8994 | ||||
8995 | // For each of the ADL candidates we found, add it to the overload | |||
8996 | // set. | |||
8997 | for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { | |||
8998 | DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); | |||
8999 | ||||
9000 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { | |||
9001 | if (ExplicitTemplateArgs) | |||
9002 | continue; | |||
9003 | ||||
9004 | AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, | |||
9005 | /*SupressUserConversions=*/false, PartialOverloading, | |||
9006 | /*AllowExplicitConversions*/ false, | |||
9007 | /*AllowExplicit*/ true, ADLCallKind::UsesADL); | |||
9008 | } else { | |||
9009 | AddTemplateOverloadCandidate( | |||
9010 | cast<FunctionTemplateDecl>(*I), FoundDecl, ExplicitTemplateArgs, Args, | |||
9011 | CandidateSet, | |||
9012 | /*SuppressUserConversions=*/false, PartialOverloading, | |||
9013 | /*AllowExplicit*/true, ADLCallKind::UsesADL); | |||
9014 | } | |||
9015 | } | |||
9016 | } | |||
9017 | ||||
9018 | namespace { | |||
9019 | enum class Comparison { Equal, Better, Worse }; | |||
9020 | } | |||
9021 | ||||
9022 | /// Compares the enable_if attributes of two FunctionDecls, for the purposes of | |||
9023 | /// overload resolution. | |||
9024 | /// | |||
9025 | /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff | |||
9026 | /// Cand1's first N enable_if attributes have precisely the same conditions as | |||
9027 | /// Cand2's first N enable_if attributes (where N = the number of enable_if | |||
9028 | /// attributes on Cand2), and Cand1 has more than N enable_if attributes. | |||
9029 | /// | |||
9030 | /// Note that you can have a pair of candidates such that Cand1's enable_if | |||
9031 | /// attributes are worse than Cand2's, and Cand2's enable_if attributes are | |||
9032 | /// worse than Cand1's. | |||
9033 | static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, | |||
9034 | const FunctionDecl *Cand2) { | |||
9035 | // Common case: One (or both) decls don't have enable_if attrs. | |||
9036 | bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); | |||
9037 | bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); | |||
9038 | if (!Cand1Attr || !Cand2Attr) { | |||
9039 | if (Cand1Attr == Cand2Attr) | |||
9040 | return Comparison::Equal; | |||
9041 | return Cand1Attr ? Comparison::Better : Comparison::Worse; | |||
9042 | } | |||
9043 | ||||
9044 | auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); | |||
9045 | auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); | |||
9046 | ||||
9047 | llvm::FoldingSetNodeID Cand1ID, Cand2ID; | |||
9048 | for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { | |||
9049 | Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); | |||
9050 | Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); | |||
9051 | ||||
9052 | // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 | |||
9053 | // has fewer enable_if attributes than Cand2, and vice versa. | |||
9054 | if (!Cand1A) | |||
9055 | return Comparison::Worse; | |||
9056 | if (!Cand2A) | |||
9057 | return Comparison::Better; | |||
9058 | ||||
9059 | Cand1ID.clear(); | |||
9060 | Cand2ID.clear(); | |||
9061 | ||||
9062 | (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); | |||
9063 | (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); | |||
9064 | if (Cand1ID != Cand2ID) | |||
9065 | return Comparison::Worse; | |||
9066 | } | |||
9067 | ||||
9068 | return Comparison::Equal; | |||
9069 | } | |||
9070 | ||||
9071 | static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1, | |||
9072 | const OverloadCandidate &Cand2) { | |||
9073 | if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || | |||
9074 | !Cand2.Function->isMultiVersion()) | |||
9075 | return false; | |||
9076 | ||||
9077 | // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this | |||
9078 | // is obviously better. | |||
9079 | if (Cand1.Function->isInvalidDecl()) return false; | |||
9080 | if (Cand2.Function->isInvalidDecl()) return true; | |||
9081 | ||||
9082 | // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer | |||
9083 | // cpu_dispatch, else arbitrarily based on the identifiers. | |||
9084 | bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); | |||
9085 | bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); | |||
9086 | const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); | |||
9087 | const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); | |||
9088 | ||||
9089 | if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) | |||
9090 | return false; | |||
9091 | ||||
9092 | if (Cand1CPUDisp && !Cand2CPUDisp) | |||
9093 | return true; | |||
9094 | if (Cand2CPUDisp && !Cand1CPUDisp) | |||
9095 | return false; | |||
9096 | ||||
9097 | if (Cand1CPUSpec && Cand2CPUSpec) { | |||
9098 | if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) | |||
9099 | return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size(); | |||
9100 | ||||
9101 | std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> | |||
9102 | FirstDiff = std::mismatch( | |||
9103 | Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), | |||
9104 | Cand2CPUSpec->cpus_begin(), | |||
9105 | [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { | |||
9106 | return LHS->getName() == RHS->getName(); | |||
9107 | }); | |||
9108 | ||||
9109 | assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&((FirstDiff.first != Cand1CPUSpec->cpus_end() && "Two different cpu-specific versions should not have the same " "identifier list, otherwise they'd be the same decl!") ? static_cast <void> (0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 9111, __PRETTY_FUNCTION__)) | |||
9110 | "Two different cpu-specific versions should not have the same "((FirstDiff.first != Cand1CPUSpec->cpus_end() && "Two different cpu-specific versions should not have the same " "identifier list, otherwise they'd be the same decl!") ? static_cast <void> (0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 9111, __PRETTY_FUNCTION__)) | |||
9111 | "identifier list, otherwise they'd be the same decl!")((FirstDiff.first != Cand1CPUSpec->cpus_end() && "Two different cpu-specific versions should not have the same " "identifier list, otherwise they'd be the same decl!") ? static_cast <void> (0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 9111, __PRETTY_FUNCTION__)); | |||
9112 | return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName(); | |||
9113 | } | |||
9114 | llvm_unreachable("No way to get here unless both had cpu_dispatch")::llvm::llvm_unreachable_internal("No way to get here unless both had cpu_dispatch" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 9114); | |||
9115 | } | |||
9116 | ||||
9117 | /// isBetterOverloadCandidate - Determines whether the first overload | |||
9118 | /// candidate is a better candidate than the second (C++ 13.3.3p1). | |||
9119 | bool clang::isBetterOverloadCandidate( | |||
9120 | Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, | |||
9121 | SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { | |||
9122 | // Define viable functions to be better candidates than non-viable | |||
9123 | // functions. | |||
9124 | if (!Cand2.Viable) | |||
9125 | return Cand1.Viable; | |||
9126 | else if (!Cand1.Viable) | |||
9127 | return false; | |||
9128 | ||||
9129 | // C++ [over.match.best]p1: | |||
9130 | // | |||
9131 | // -- if F is a static member function, ICS1(F) is defined such | |||
9132 | // that ICS1(F) is neither better nor worse than ICS1(G) for | |||
9133 | // any function G, and, symmetrically, ICS1(G) is neither | |||
9134 | // better nor worse than ICS1(F). | |||
9135 | unsigned StartArg = 0; | |||
9136 | if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) | |||
9137 | StartArg = 1; | |||
9138 | ||||
9139 | auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { | |||
9140 | // We don't allow incompatible pointer conversions in C++. | |||
9141 | if (!S.getLangOpts().CPlusPlus) | |||
9142 | return ICS.isStandard() && | |||
9143 | ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; | |||
9144 | ||||
9145 | // The only ill-formed conversion we allow in C++ is the string literal to | |||
9146 | // char* conversion, which is only considered ill-formed after C++11. | |||
9147 | return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && | |||
9148 | hasDeprecatedStringLiteralToCharPtrConversion(ICS); | |||
9149 | }; | |||
9150 | ||||
9151 | // Define functions that don't require ill-formed conversions for a given | |||
9152 | // argument to be better candidates than functions that do. | |||
9153 | unsigned NumArgs = Cand1.Conversions.size(); | |||
9154 | assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch")((Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch" ) ? static_cast<void> (0) : __assert_fail ("Cand2.Conversions.size() == NumArgs && \"Overload candidate mismatch\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 9154, __PRETTY_FUNCTION__)); | |||
9155 | bool HasBetterConversion = false; | |||
9156 | for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { | |||
9157 | bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); | |||
9158 | bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); | |||
9159 | if (Cand1Bad != Cand2Bad) { | |||
9160 | if (Cand1Bad) | |||
9161 | return false; | |||
9162 | HasBetterConversion = true; | |||
9163 | } | |||
9164 | } | |||
9165 | ||||
9166 | if (HasBetterConversion) | |||
9167 | return true; | |||
9168 | ||||
9169 | // C++ [over.match.best]p1: | |||
9170 | // A viable function F1 is defined to be a better function than another | |||
9171 | // viable function F2 if for all arguments i, ICSi(F1) is not a worse | |||
9172 | // conversion sequence than ICSi(F2), and then... | |||
9173 | for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { | |||
9174 | switch (CompareImplicitConversionSequences(S, Loc, | |||
9175 | Cand1.Conversions[ArgIdx], | |||
9176 | Cand2.Conversions[ArgIdx])) { | |||
9177 | case ImplicitConversionSequence::Better: | |||
9178 | // Cand1 has a better conversion sequence. | |||
9179 | HasBetterConversion = true; | |||
9180 | break; | |||
9181 | ||||
9182 | case ImplicitConversionSequence::Worse: | |||
9183 | // Cand1 can't be better than Cand2. | |||
9184 | return false; | |||
9185 | ||||
9186 | case ImplicitConversionSequence::Indistinguishable: | |||
9187 | // Do nothing. | |||
9188 | break; | |||
9189 | } | |||
9190 | } | |||
9191 | ||||
9192 | // -- for some argument j, ICSj(F1) is a better conversion sequence than | |||
9193 | // ICSj(F2), or, if not that, | |||
9194 | if (HasBetterConversion) | |||
9195 | return true; | |||
9196 | ||||
9197 | // -- the context is an initialization by user-defined conversion | |||
9198 | // (see 8.5, 13.3.1.5) and the standard conversion sequence | |||
9199 | // from the return type of F1 to the destination type (i.e., | |||
9200 | // the type of the entity being initialized) is a better | |||
9201 | // conversion sequence than the standard conversion sequence | |||
9202 | // from the return type of F2 to the destination type. | |||
9203 | if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && | |||
9204 | Cand1.Function && Cand2.Function && | |||
9205 | isa<CXXConversionDecl>(Cand1.Function) && | |||
9206 | isa<CXXConversionDecl>(Cand2.Function)) { | |||
9207 | // First check whether we prefer one of the conversion functions over the | |||
9208 | // other. This only distinguishes the results in non-standard, extension | |||
9209 | // cases such as the conversion from a lambda closure type to a function | |||
9210 | // pointer or block. | |||
9211 | ImplicitConversionSequence::CompareKind Result = | |||
9212 | compareConversionFunctions(S, Cand1.Function, Cand2.Function); | |||
9213 | if (Result == ImplicitConversionSequence::Indistinguishable) | |||
9214 | Result = CompareStandardConversionSequences(S, Loc, | |||
9215 | Cand1.FinalConversion, | |||
9216 | Cand2.FinalConversion); | |||
9217 | ||||
9218 | if (Result != ImplicitConversionSequence::Indistinguishable) | |||
9219 | return Result == ImplicitConversionSequence::Better; | |||
9220 | ||||
9221 | // FIXME: Compare kind of reference binding if conversion functions | |||
9222 | // convert to a reference type used in direct reference binding, per | |||
9223 | // C++14 [over.match.best]p1 section 2 bullet 3. | |||
9224 | } | |||
9225 | ||||
9226 | // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, | |||
9227 | // as combined with the resolution to CWG issue 243. | |||
9228 | // | |||
9229 | // When the context is initialization by constructor ([over.match.ctor] or | |||
9230 | // either phase of [over.match.list]), a constructor is preferred over | |||
9231 | // a conversion function. | |||
9232 | if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && | |||
9233 | Cand1.Function && Cand2.Function && | |||
9234 | isa<CXXConstructorDecl>(Cand1.Function) != | |||
9235 | isa<CXXConstructorDecl>(Cand2.Function)) | |||
9236 | return isa<CXXConstructorDecl>(Cand1.Function); | |||
9237 | ||||
9238 | // -- F1 is a non-template function and F2 is a function template | |||
9239 | // specialization, or, if not that, | |||
9240 | bool Cand1IsSpecialization = Cand1.Function && | |||
9241 | Cand1.Function->getPrimaryTemplate(); | |||
9242 | bool Cand2IsSpecialization = Cand2.Function && | |||
9243 | Cand2.Function->getPrimaryTemplate(); | |||
9244 | if (Cand1IsSpecialization != Cand2IsSpecialization) | |||
9245 | return Cand2IsSpecialization; | |||
9246 | ||||
9247 | // -- F1 and F2 are function template specializations, and the function | |||
9248 | // template for F1 is more specialized than the template for F2 | |||
9249 | // according to the partial ordering rules described in 14.5.5.2, or, | |||
9250 | // if not that, | |||
9251 | if (Cand1IsSpecialization && Cand2IsSpecialization) { | |||
9252 | if (FunctionTemplateDecl *BetterTemplate | |||
9253 | = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), | |||
9254 | Cand2.Function->getPrimaryTemplate(), | |||
9255 | Loc, | |||
9256 | isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion | |||
9257 | : TPOC_Call, | |||
9258 | Cand1.ExplicitCallArguments, | |||
9259 | Cand2.ExplicitCallArguments)) | |||
9260 | return BetterTemplate == Cand1.Function->getPrimaryTemplate(); | |||
9261 | } | |||
9262 | ||||
9263 | // FIXME: Work around a defect in the C++17 inheriting constructor wording. | |||
9264 | // A derived-class constructor beats an (inherited) base class constructor. | |||
9265 | bool Cand1IsInherited = | |||
9266 | dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); | |||
9267 | bool Cand2IsInherited = | |||
9268 | dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); | |||
9269 | if (Cand1IsInherited != Cand2IsInherited) | |||
9270 | return Cand2IsInherited; | |||
9271 | else if (Cand1IsInherited) { | |||
9272 | assert(Cand2IsInherited)((Cand2IsInherited) ? static_cast<void> (0) : __assert_fail ("Cand2IsInherited", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 9272, __PRETTY_FUNCTION__)); | |||
9273 | auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); | |||
9274 | auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); | |||
9275 | if (Cand1Class->isDerivedFrom(Cand2Class)) | |||
9276 | return true; | |||
9277 | if (Cand2Class->isDerivedFrom(Cand1Class)) | |||
9278 | return false; | |||
9279 | // Inherited from sibling base classes: still ambiguous. | |||
9280 | } | |||
9281 | ||||
9282 | // Check C++17 tie-breakers for deduction guides. | |||
9283 | { | |||
9284 | auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); | |||
9285 | auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); | |||
9286 | if (Guide1 && Guide2) { | |||
9287 | // -- F1 is generated from a deduction-guide and F2 is not | |||
9288 | if (Guide1->isImplicit() != Guide2->isImplicit()) | |||
9289 | return Guide2->isImplicit(); | |||
9290 | ||||
9291 | // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not | |||
9292 | if (Guide1->isCopyDeductionCandidate()) | |||
9293 | return true; | |||
9294 | } | |||
9295 | } | |||
9296 | ||||
9297 | // Check for enable_if value-based overload resolution. | |||
9298 | if (Cand1.Function && Cand2.Function) { | |||
9299 | Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); | |||
9300 | if (Cmp != Comparison::Equal) | |||
9301 | return Cmp == Comparison::Better; | |||
9302 | } | |||
9303 | ||||
9304 | if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { | |||
9305 | FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); | |||
9306 | return S.IdentifyCUDAPreference(Caller, Cand1.Function) > | |||
9307 | S.IdentifyCUDAPreference(Caller, Cand2.Function); | |||
9308 | } | |||
9309 | ||||
9310 | bool HasPS1 = Cand1.Function != nullptr && | |||
9311 | functionHasPassObjectSizeParams(Cand1.Function); | |||
9312 | bool HasPS2 = Cand2.Function != nullptr && | |||
9313 | functionHasPassObjectSizeParams(Cand2.Function); | |||
9314 | if (HasPS1 != HasPS2 && HasPS1) | |||
9315 | return true; | |||
9316 | ||||
9317 | return isBetterMultiversionCandidate(Cand1, Cand2); | |||
9318 | } | |||
9319 | ||||
9320 | /// Determine whether two declarations are "equivalent" for the purposes of | |||
9321 | /// name lookup and overload resolution. This applies when the same internal/no | |||
9322 | /// linkage entity is defined by two modules (probably by textually including | |||
9323 | /// the same header). In such a case, we don't consider the declarations to | |||
9324 | /// declare the same entity, but we also don't want lookups with both | |||
9325 | /// declarations visible to be ambiguous in some cases (this happens when using | |||
9326 | /// a modularized libstdc++). | |||
9327 | bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, | |||
9328 | const NamedDecl *B) { | |||
9329 | auto *VA = dyn_cast_or_null<ValueDecl>(A); | |||
9330 | auto *VB = dyn_cast_or_null<ValueDecl>(B); | |||
9331 | if (!VA || !VB) | |||
9332 | return false; | |||
9333 | ||||
9334 | // The declarations must be declaring the same name as an internal linkage | |||
9335 | // entity in different modules. | |||
9336 | if (!VA->getDeclContext()->getRedeclContext()->Equals( | |||
9337 | VB->getDeclContext()->getRedeclContext()) || | |||
9338 | getOwningModule(const_cast<ValueDecl *>(VA)) == | |||
9339 | getOwningModule(const_cast<ValueDecl *>(VB)) || | |||
9340 | VA->isExternallyVisible() || VB->isExternallyVisible()) | |||
9341 | return false; | |||
9342 | ||||
9343 | // Check that the declarations appear to be equivalent. | |||
9344 | // | |||
9345 | // FIXME: Checking the type isn't really enough to resolve the ambiguity. | |||
9346 | // For constants and functions, we should check the initializer or body is | |||
9347 | // the same. For non-constant variables, we shouldn't allow it at all. | |||
9348 | if (Context.hasSameType(VA->getType(), VB->getType())) | |||
9349 | return true; | |||
9350 | ||||
9351 | // Enum constants within unnamed enumerations will have different types, but | |||
9352 | // may still be similar enough to be interchangeable for our purposes. | |||
9353 | if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { | |||
9354 | if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { | |||
9355 | // Only handle anonymous enums. If the enumerations were named and | |||
9356 | // equivalent, they would have been merged to the same type. | |||
9357 | auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); | |||
9358 | auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); | |||
9359 | if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || | |||
9360 | !Context.hasSameType(EnumA->getIntegerType(), | |||
9361 | EnumB->getIntegerType())) | |||
9362 | return false; | |||
9363 | // Allow this only if the value is the same for both enumerators. | |||
9364 | return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); | |||
9365 | } | |||
9366 | } | |||
9367 | ||||
9368 | // Nothing else is sufficiently similar. | |||
9369 | return false; | |||
9370 | } | |||
9371 | ||||
9372 | void Sema::diagnoseEquivalentInternalLinkageDeclarations( | |||
9373 | SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { | |||
9374 | Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; | |||
9375 | ||||
9376 | Module *M = getOwningModule(const_cast<NamedDecl*>(D)); | |||
9377 | Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) | |||
9378 | << !M << (M ? M->getFullModuleName() : ""); | |||
9379 | ||||
9380 | for (auto *E : Equiv) { | |||
9381 | Module *M = getOwningModule(const_cast<NamedDecl*>(E)); | |||
9382 | Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) | |||
9383 | << !M << (M ? M->getFullModuleName() : ""); | |||
9384 | } | |||
9385 | } | |||
9386 | ||||
9387 | /// Computes the best viable function (C++ 13.3.3) | |||
9388 | /// within an overload candidate set. | |||
9389 | /// | |||
9390 | /// \param Loc The location of the function name (or operator symbol) for | |||
9391 | /// which overload resolution occurs. | |||
9392 | /// | |||
9393 | /// \param Best If overload resolution was successful or found a deleted | |||
9394 | /// function, \p Best points to the candidate function found. | |||
9395 | /// | |||
9396 | /// \returns The result of overload resolution. | |||
9397 | OverloadingResult | |||
9398 | OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, | |||
9399 | iterator &Best) { | |||
9400 | llvm::SmallVector<OverloadCandidate *, 16> Candidates; | |||
9401 | std::transform(begin(), end(), std::back_inserter(Candidates), | |||
9402 | [](OverloadCandidate &Cand) { return &Cand; }); | |||
9403 | ||||
9404 | // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but | |||
9405 | // are accepted by both clang and NVCC. However, during a particular | |||
9406 | // compilation mode only one call variant is viable. We need to | |||
9407 | // exclude non-viable overload candidates from consideration based | |||
9408 | // only on their host/device attributes. Specifically, if one | |||
9409 | // candidate call is WrongSide and the other is SameSide, we ignore | |||
9410 | // the WrongSide candidate. | |||
9411 | if (S.getLangOpts().CUDA) { | |||
9412 | const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); | |||
9413 | bool ContainsSameSideCandidate = | |||
9414 | llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { | |||
9415 | return Cand->Function && | |||
9416 | S.IdentifyCUDAPreference(Caller, Cand->Function) == | |||
9417 | Sema::CFP_SameSide; | |||
9418 | }); | |||
9419 | if (ContainsSameSideCandidate) { | |||
9420 | auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { | |||
9421 | return Cand->Function && | |||
9422 | S.IdentifyCUDAPreference(Caller, Cand->Function) == | |||
9423 | Sema::CFP_WrongSide; | |||
9424 | }; | |||
9425 | llvm::erase_if(Candidates, IsWrongSideCandidate); | |||
9426 | } | |||
9427 | } | |||
9428 | ||||
9429 | // Find the best viable function. | |||
9430 | Best = end(); | |||
9431 | for (auto *Cand : Candidates) | |||
9432 | if (Cand->Viable) | |||
9433 | if (Best == end() || | |||
9434 | isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) | |||
9435 | Best = Cand; | |||
9436 | ||||
9437 | // If we didn't find any viable functions, abort. | |||
9438 | if (Best == end()) | |||
9439 | return OR_No_Viable_Function; | |||
9440 | ||||
9441 | llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; | |||
9442 | ||||
9443 | // Make sure that this function is better than every other viable | |||
9444 | // function. If not, we have an ambiguity. | |||
9445 | for (auto *Cand : Candidates) { | |||
9446 | if (Cand->Viable && Cand != Best && | |||
9447 | !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) { | |||
9448 | if (S.isEquivalentInternalLinkageDeclaration(Best->Function, | |||
9449 | Cand->Function)) { | |||
9450 | EquivalentCands.push_back(Cand->Function); | |||
9451 | continue; | |||
9452 | } | |||
9453 | ||||
9454 | Best = end(); | |||
9455 | return OR_Ambiguous; | |||
9456 | } | |||
9457 | } | |||
9458 | ||||
9459 | // Best is the best viable function. | |||
9460 | if (Best->Function && Best->Function->isDeleted()) | |||
9461 | return OR_Deleted; | |||
9462 | ||||
9463 | if (!EquivalentCands.empty()) | |||
9464 | S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, | |||
9465 | EquivalentCands); | |||
9466 | ||||
9467 | return OR_Success; | |||
9468 | } | |||
9469 | ||||
9470 | namespace { | |||
9471 | ||||
9472 | enum OverloadCandidateKind { | |||
9473 | oc_function, | |||
9474 | oc_method, | |||
9475 | oc_constructor, | |||
9476 | oc_implicit_default_constructor, | |||
9477 | oc_implicit_copy_constructor, | |||
9478 | oc_implicit_move_constructor, | |||
9479 | oc_implicit_copy_assignment, | |||
9480 | oc_implicit_move_assignment, | |||
9481 | oc_inherited_constructor | |||
9482 | }; | |||
9483 | ||||
9484 | enum OverloadCandidateSelect { | |||
9485 | ocs_non_template, | |||
9486 | ocs_template, | |||
9487 | ocs_described_template, | |||
9488 | }; | |||
9489 | ||||
9490 | static std::pair<OverloadCandidateKind, OverloadCandidateSelect> | |||
9491 | ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, | |||
9492 | std::string &Description) { | |||
9493 | ||||
9494 | bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); | |||
9495 | if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { | |||
9496 | isTemplate = true; | |||
9497 | Description = S.getTemplateArgumentBindingsText( | |||
9498 | FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); | |||
9499 | } | |||
9500 | ||||
9501 | OverloadCandidateSelect Select = [&]() { | |||
9502 | if (!Description.empty()) | |||
9503 | return ocs_described_template; | |||
9504 | return isTemplate ? ocs_template : ocs_non_template; | |||
9505 | }(); | |||
9506 | ||||
9507 | OverloadCandidateKind Kind = [&]() { | |||
9508 | if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { | |||
9509 | if (!Ctor->isImplicit()) { | |||
9510 | if (isa<ConstructorUsingShadowDecl>(Found)) | |||
9511 | return oc_inherited_constructor; | |||
9512 | else | |||
9513 | return oc_constructor; | |||
9514 | } | |||
9515 | ||||
9516 | if (Ctor->isDefaultConstructor()) | |||
9517 | return oc_implicit_default_constructor; | |||
9518 | ||||
9519 | if (Ctor->isMoveConstructor()) | |||
9520 | return oc_implicit_move_constructor; | |||
9521 | ||||
9522 | assert(Ctor->isCopyConstructor() &&((Ctor->isCopyConstructor() && "unexpected sort of implicit constructor" ) ? static_cast<void> (0) : __assert_fail ("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 9523, __PRETTY_FUNCTION__)) | |||
9523 | "unexpected sort of implicit constructor")((Ctor->isCopyConstructor() && "unexpected sort of implicit constructor" ) ? static_cast<void> (0) : __assert_fail ("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 9523, __PRETTY_FUNCTION__)); | |||
9524 | return oc_implicit_copy_constructor; | |||
9525 | } | |||
9526 | ||||
9527 | if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { | |||
9528 | // This actually gets spelled 'candidate function' for now, but | |||
9529 | // it doesn't hurt to split it out. | |||
9530 | if (!Meth->isImplicit()) | |||
9531 | return oc_method; | |||
9532 | ||||
9533 | if (Meth->isMoveAssignmentOperator()) | |||
9534 | return oc_implicit_move_assignment; | |||
9535 | ||||
9536 | if (Meth->isCopyAssignmentOperator()) | |||
9537 | return oc_implicit_copy_assignment; | |||
9538 | ||||
9539 | assert(isa<CXXConversionDecl>(Meth) && "expected conversion")((isa<CXXConversionDecl>(Meth) && "expected conversion" ) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(Meth) && \"expected conversion\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 9539, __PRETTY_FUNCTION__)); | |||
9540 | return oc_method; | |||
9541 | } | |||
9542 | ||||
9543 | return oc_function; | |||
9544 | }(); | |||
9545 | ||||
9546 | return std::make_pair(Kind, Select); | |||
9547 | } | |||
9548 | ||||
9549 | void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { | |||
9550 | // FIXME: It'd be nice to only emit a note once per using-decl per overload | |||
9551 | // set. | |||
9552 | if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) | |||
9553 | S.Diag(FoundDecl->getLocation(), | |||
9554 | diag::note_ovl_candidate_inherited_constructor) | |||
9555 | << Shadow->getNominatedBaseClass(); | |||
9556 | } | |||
9557 | ||||
9558 | } // end anonymous namespace | |||
9559 | ||||
9560 | static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, | |||
9561 | const FunctionDecl *FD) { | |||
9562 | for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { | |||
9563 | bool AlwaysTrue; | |||
9564 | if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) | |||
9565 | return false; | |||
9566 | if (!AlwaysTrue) | |||
9567 | return false; | |||
9568 | } | |||
9569 | return true; | |||
9570 | } | |||
9571 | ||||
9572 | /// Returns true if we can take the address of the function. | |||
9573 | /// | |||
9574 | /// \param Complain - If true, we'll emit a diagnostic | |||
9575 | /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are | |||
9576 | /// we in overload resolution? | |||
9577 | /// \param Loc - The location of the statement we're complaining about. Ignored | |||
9578 | /// if we're not complaining, or if we're in overload resolution. | |||
9579 | static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, | |||
9580 | bool Complain, | |||
9581 | bool InOverloadResolution, | |||
9582 | SourceLocation Loc) { | |||
9583 | if (!isFunctionAlwaysEnabled(S.Context, FD)) { | |||
9584 | if (Complain) { | |||
9585 | if (InOverloadResolution) | |||
9586 | S.Diag(FD->getBeginLoc(), | |||
9587 | diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); | |||
9588 | else | |||
9589 | S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; | |||
9590 | } | |||
9591 | return false; | |||
9592 | } | |||
9593 | ||||
9594 | auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { | |||
9595 | return P->hasAttr<PassObjectSizeAttr>(); | |||
9596 | }); | |||
9597 | if (I == FD->param_end()) | |||
9598 | return true; | |||
9599 | ||||
9600 | if (Complain) { | |||
9601 | // Add one to ParamNo because it's user-facing | |||
9602 | unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; | |||
9603 | if (InOverloadResolution) | |||
9604 | S.Diag(FD->getLocation(), | |||
9605 | diag::note_ovl_candidate_has_pass_object_size_params) | |||
9606 | << ParamNo; | |||
9607 | else | |||
9608 | S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) | |||
9609 | << FD << ParamNo; | |||
9610 | } | |||
9611 | return false; | |||
9612 | } | |||
9613 | ||||
9614 | static bool checkAddressOfCandidateIsAvailable(Sema &S, | |||
9615 | const FunctionDecl *FD) { | |||
9616 | return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, | |||
9617 | /*InOverloadResolution=*/true, | |||
9618 | /*Loc=*/SourceLocation()); | |||
9619 | } | |||
9620 | ||||
9621 | bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, | |||
9622 | bool Complain, | |||
9623 | SourceLocation Loc) { | |||
9624 | return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, | |||
9625 | /*InOverloadResolution=*/false, | |||
9626 | Loc); | |||
9627 | } | |||
9628 | ||||
9629 | // Notes the location of an overload candidate. | |||
9630 | void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, | |||
9631 | QualType DestType, bool TakingAddress) { | |||
9632 | if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) | |||
9633 | return; | |||
9634 | if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && | |||
9635 | !Fn->getAttr<TargetAttr>()->isDefaultVersion()) | |||
9636 | return; | |||
9637 | ||||
9638 | std::string FnDesc; | |||
9639 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = | |||
9640 | ClassifyOverloadCandidate(*this, Found, Fn, FnDesc); | |||
9641 | PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) | |||
9642 | << (unsigned)KSPair.first << (unsigned)KSPair.second | |||
9643 | << Fn << FnDesc; | |||
9644 | ||||
9645 | HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); | |||
9646 | Diag(Fn->getLocation(), PD); | |||
9647 | MaybeEmitInheritedConstructorNote(*this, Found); | |||
9648 | } | |||
9649 | ||||
9650 | // Notes the location of all overload candidates designated through | |||
9651 | // OverloadedExpr | |||
9652 | void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, | |||
9653 | bool TakingAddress) { | |||
9654 | assert(OverloadedExpr->getType() == Context.OverloadTy)((OverloadedExpr->getType() == Context.OverloadTy) ? static_cast <void> (0) : __assert_fail ("OverloadedExpr->getType() == Context.OverloadTy" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 9654, __PRETTY_FUNCTION__)); | |||
9655 | ||||
9656 | OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); | |||
9657 | OverloadExpr *OvlExpr = Ovl.Expression; | |||
9658 | ||||
9659 | for (UnresolvedSetIterator I = OvlExpr->decls_begin(), | |||
9660 | IEnd = OvlExpr->decls_end(); | |||
9661 | I != IEnd; ++I) { | |||
9662 | if (FunctionTemplateDecl *FunTmpl = | |||
9663 | dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { | |||
9664 | NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType, | |||
9665 | TakingAddress); | |||
9666 | } else if (FunctionDecl *Fun | |||
9667 | = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { | |||
9668 | NoteOverloadCandidate(*I, Fun, DestType, TakingAddress); | |||
9669 | } | |||
9670 | } | |||
9671 | } | |||
9672 | ||||
9673 | /// Diagnoses an ambiguous conversion. The partial diagnostic is the | |||
9674 | /// "lead" diagnostic; it will be given two arguments, the source and | |||
9675 | /// target types of the conversion. | |||
9676 | void ImplicitConversionSequence::DiagnoseAmbiguousConversion( | |||
9677 | Sema &S, | |||
9678 | SourceLocation CaretLoc, | |||
9679 | const PartialDiagnostic &PDiag) const { | |||
9680 | S.Diag(CaretLoc, PDiag) | |||
9681 | << Ambiguous.getFromType() << Ambiguous.getToType(); | |||
9682 | // FIXME: The note limiting machinery is borrowed from | |||
9683 | // OverloadCandidateSet::NoteCandidates; there's an opportunity for | |||
9684 | // refactoring here. | |||
9685 | const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); | |||
9686 | unsigned CandsShown = 0; | |||
9687 | AmbiguousConversionSequence::const_iterator I, E; | |||
9688 | for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { | |||
9689 | if (CandsShown >= 4 && ShowOverloads == Ovl_Best) | |||
9690 | break; | |||
9691 | ++CandsShown; | |||
9692 | S.NoteOverloadCandidate(I->first, I->second); | |||
9693 | } | |||
9694 | if (I != E) | |||
9695 | S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); | |||
9696 | } | |||
9697 | ||||
9698 | static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, | |||
9699 | unsigned I, bool TakingCandidateAddress) { | |||
9700 | const ImplicitConversionSequence &Conv = Cand->Conversions[I]; | |||
9701 | assert(Conv.isBad())((Conv.isBad()) ? static_cast<void> (0) : __assert_fail ("Conv.isBad()", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 9701, __PRETTY_FUNCTION__)); | |||
| ||||
9702 | assert(Cand->Function && "for now, candidate must be a function")((Cand->Function && "for now, candidate must be a function" ) ? static_cast<void> (0) : __assert_fail ("Cand->Function && \"for now, candidate must be a function\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 9702, __PRETTY_FUNCTION__)); | |||
9703 | FunctionDecl *Fn = Cand->Function; | |||
9704 | ||||
9705 | // There's a conversion slot for the object argument if this is a | |||
9706 | // non-constructor method. Note that 'I' corresponds the | |||
9707 | // conversion-slot index. | |||
9708 | bool isObjectArgument = false; | |||
9709 | if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { | |||
9710 | if (I == 0) | |||
9711 | isObjectArgument = true; | |||
9712 | else | |||
9713 | I--; | |||
9714 | } | |||
9715 | ||||
9716 | std::string FnDesc; | |||
9717 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = | |||
9718 | ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); | |||
9719 | ||||
9720 | Expr *FromExpr = Conv.Bad.FromExpr; | |||
9721 | QualType FromTy = Conv.Bad.getFromType(); | |||
9722 | QualType ToTy = Conv.Bad.getToType(); | |||
9723 | ||||
9724 | if (FromTy == S.Context.OverloadTy) { | |||
9725 | assert(FromExpr && "overload set argument came from implicit argument?")((FromExpr && "overload set argument came from implicit argument?" ) ? static_cast<void> (0) : __assert_fail ("FromExpr && \"overload set argument came from implicit argument?\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 9725, __PRETTY_FUNCTION__)); | |||
9726 | Expr *E = FromExpr->IgnoreParens(); | |||
9727 | if (isa<UnaryOperator>(E)) | |||
9728 | E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); | |||
9729 | DeclarationName Name = cast<OverloadExpr>(E)->getName(); | |||
9730 | ||||
9731 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) | |||
9732 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc | |||
9733 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy | |||
9734 | << Name << I + 1; | |||
9735 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
9736 | return; | |||
9737 | } | |||
9738 | ||||
9739 | // Do some hand-waving analysis to see if the non-viability is due | |||
9740 | // to a qualifier mismatch. | |||
9741 | CanQualType CFromTy = S.Context.getCanonicalType(FromTy); | |||
9742 | CanQualType CToTy = S.Context.getCanonicalType(ToTy); | |||
9743 | if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) | |||
9744 | CToTy = RT->getPointeeType(); | |||
9745 | else { | |||
9746 | // TODO: detect and diagnose the full richness of const mismatches. | |||
9747 | if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) | |||
9748 | if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { | |||
9749 | CFromTy = FromPT->getPointeeType(); | |||
9750 | CToTy = ToPT->getPointeeType(); | |||
9751 | } | |||
9752 | } | |||
9753 | ||||
9754 | if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && | |||
9755 | !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { | |||
9756 | Qualifiers FromQs = CFromTy.getQualifiers(); | |||
9757 | Qualifiers ToQs = CToTy.getQualifiers(); | |||
9758 | ||||
9759 | if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { | |||
9760 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) | |||
9761 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc | |||
9762 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy | |||
9763 | << ToTy << (unsigned)isObjectArgument << I + 1; | |||
9764 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
9765 | return; | |||
9766 | } | |||
9767 | ||||
9768 | if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { | |||
9769 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) | |||
9770 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc | |||
9771 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy | |||
9772 | << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() | |||
9773 | << (unsigned)isObjectArgument << I + 1; | |||
9774 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
9775 | return; | |||
9776 | } | |||
9777 | ||||
9778 | if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { | |||
9779 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) | |||
9780 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc | |||
9781 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy | |||
9782 | << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() | |||
9783 | << (unsigned)isObjectArgument << I + 1; | |||
9784 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
9785 | return; | |||
9786 | } | |||
9787 | ||||
9788 | if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { | |||
9789 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) | |||
9790 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc | |||
9791 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy | |||
9792 | << FromQs.hasUnaligned() << I + 1; | |||
9793 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
9794 | return; | |||
9795 | } | |||
9796 | ||||
9797 | unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); | |||
9798 | assert(CVR && "unexpected qualifiers mismatch")((CVR && "unexpected qualifiers mismatch") ? static_cast <void> (0) : __assert_fail ("CVR && \"unexpected qualifiers mismatch\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 9798, __PRETTY_FUNCTION__)); | |||
9799 | ||||
9800 | if (isObjectArgument) { | |||
9801 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) | |||
9802 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc | |||
9803 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy | |||
9804 | << (CVR - 1); | |||
9805 | } else { | |||
9806 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) | |||
9807 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc | |||
9808 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy | |||
9809 | << (CVR - 1) << I + 1; | |||
9810 | } | |||
9811 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
9812 | return; | |||
9813 | } | |||
9814 | ||||
9815 | // Special diagnostic for failure to convert an initializer list, since | |||
9816 | // telling the user that it has type void is not useful. | |||
9817 | if (FromExpr && isa<InitListExpr>(FromExpr)) { | |||
9818 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) | |||
9819 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc | |||
9820 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy | |||
9821 | << ToTy << (unsigned)isObjectArgument << I + 1; | |||
9822 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
9823 | return; | |||
9824 | } | |||
9825 | ||||
9826 | // Diagnose references or pointers to incomplete types differently, | |||
9827 | // since it's far from impossible that the incompleteness triggered | |||
9828 | // the failure. | |||
9829 | QualType TempFromTy = FromTy.getNonReferenceType(); | |||
9830 | if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) | |||
9831 | TempFromTy = PTy->getPointeeType(); | |||
9832 | if (TempFromTy->isIncompleteType()) { | |||
9833 | // Emit the generic diagnostic and, optionally, add the hints to it. | |||
9834 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) | |||
9835 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc | |||
9836 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy | |||
9837 | << ToTy << (unsigned)isObjectArgument << I + 1 | |||
9838 | << (unsigned)(Cand->Fix.Kind); | |||
9839 | ||||
9840 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
9841 | return; | |||
9842 | } | |||
9843 | ||||
9844 | // Diagnose base -> derived pointer conversions. | |||
9845 | unsigned BaseToDerivedConversion = 0; | |||
9846 | if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { | |||
9847 | if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { | |||
9848 | if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( | |||
9849 | FromPtrTy->getPointeeType()) && | |||
9850 | !FromPtrTy->getPointeeType()->isIncompleteType() && | |||
9851 | !ToPtrTy->getPointeeType()->isIncompleteType() && | |||
9852 | S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), | |||
9853 | FromPtrTy->getPointeeType())) | |||
9854 | BaseToDerivedConversion = 1; | |||
9855 | } | |||
9856 | } else if (const ObjCObjectPointerType *FromPtrTy | |||
9857 | = FromTy->getAs<ObjCObjectPointerType>()) { | |||
9858 | if (const ObjCObjectPointerType *ToPtrTy | |||
9859 | = ToTy->getAs<ObjCObjectPointerType>()) | |||
9860 | if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) | |||
9861 | if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) | |||
9862 | if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( | |||
9863 | FromPtrTy->getPointeeType()) && | |||
9864 | FromIface->isSuperClassOf(ToIface)) | |||
9865 | BaseToDerivedConversion = 2; | |||
9866 | } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { | |||
9867 | if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && | |||
9868 | !FromTy->isIncompleteType() && | |||
9869 | !ToRefTy->getPointeeType()->isIncompleteType() && | |||
9870 | S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { | |||
9871 | BaseToDerivedConversion = 3; | |||
9872 | } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && | |||
| ||||
9873 | ToTy.getNonReferenceType().getCanonicalType() == | |||
9874 | FromTy.getNonReferenceType().getCanonicalType()) { | |||
9875 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) | |||
9876 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc | |||
9877 | << (unsigned)isObjectArgument << I + 1 | |||
9878 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); | |||
9879 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
9880 | return; | |||
9881 | } | |||
9882 | } | |||
9883 | ||||
9884 | if (BaseToDerivedConversion) { | |||
9885 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) | |||
9886 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc | |||
9887 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) | |||
9888 | << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; | |||
9889 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
9890 | return; | |||
9891 | } | |||
9892 | ||||
9893 | if (isa<ObjCObjectPointerType>(CFromTy) && | |||
9894 | isa<PointerType>(CToTy)) { | |||
9895 | Qualifiers FromQs = CFromTy.getQualifiers(); | |||
9896 | Qualifiers ToQs = CToTy.getQualifiers(); | |||
9897 | if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { | |||
9898 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) | |||
9899 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second | |||
9900 | << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) | |||
9901 | << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; | |||
9902 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
9903 | return; | |||
9904 | } | |||
9905 | } | |||
9906 | ||||
9907 | if (TakingCandidateAddress && | |||
9908 | !checkAddressOfCandidateIsAvailable(S, Cand->Function)) | |||
9909 | return; | |||
9910 | ||||
9911 | // Emit the generic diagnostic and, optionally, add the hints to it. | |||
9912 | PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); | |||
9913 | FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc | |||
9914 | << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy | |||
9915 | << ToTy << (unsigned)isObjectArgument << I + 1 | |||
9916 | << (unsigned)(Cand->Fix.Kind); | |||
9917 | ||||
9918 | // If we can fix the conversion, suggest the FixIts. | |||
9919 | for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), | |||
9920 | HE = Cand->Fix.Hints.end(); HI != HE; ++HI) | |||
9921 | FDiag << *HI; | |||
9922 | S.Diag(Fn->getLocation(), FDiag); | |||
9923 | ||||
9924 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
9925 | } | |||
9926 | ||||
9927 | /// Additional arity mismatch diagnosis specific to a function overload | |||
9928 | /// candidates. This is not covered by the more general DiagnoseArityMismatch() | |||
9929 | /// over a candidate in any candidate set. | |||
9930 | static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, | |||
9931 | unsigned NumArgs) { | |||
9932 | FunctionDecl *Fn = Cand->Function; | |||
9933 | unsigned MinParams = Fn->getMinRequiredArguments(); | |||
9934 | ||||
9935 | // With invalid overloaded operators, it's possible that we think we | |||
9936 | // have an arity mismatch when in fact it looks like we have the | |||
9937 | // right number of arguments, because only overloaded operators have | |||
9938 | // the weird behavior of overloading member and non-member functions. | |||
9939 | // Just don't report anything. | |||
9940 | if (Fn->isInvalidDecl() && | |||
9941 | Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) | |||
9942 | return true; | |||
9943 | ||||
9944 | if (NumArgs < MinParams) { | |||
9945 | assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand ->FailureKind == ovl_fail_bad_deduction && Cand-> DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast <void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 9947, __PRETTY_FUNCTION__)) | |||
9946 | (Cand->FailureKind == ovl_fail_bad_deduction &&(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand ->FailureKind == ovl_fail_bad_deduction && Cand-> DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast <void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 9947, __PRETTY_FUNCTION__)) | |||
9947 | Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments))(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand ->FailureKind == ovl_fail_bad_deduction && Cand-> DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast <void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 9947, __PRETTY_FUNCTION__)); | |||
9948 | } else { | |||
9949 | assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand ->FailureKind == ovl_fail_bad_deduction && Cand-> DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast <void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 9951, __PRETTY_FUNCTION__)) | |||
9950 | (Cand->FailureKind == ovl_fail_bad_deduction &&(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand ->FailureKind == ovl_fail_bad_deduction && Cand-> DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast <void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 9951, __PRETTY_FUNCTION__)) | |||
9951 | Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments))(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand ->FailureKind == ovl_fail_bad_deduction && Cand-> DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast <void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 9951, __PRETTY_FUNCTION__)); | |||
9952 | } | |||
9953 | ||||
9954 | return false; | |||
9955 | } | |||
9956 | ||||
9957 | /// General arity mismatch diagnosis over a candidate in a candidate set. | |||
9958 | static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, | |||
9959 | unsigned NumFormalArgs) { | |||
9960 | assert(isa<FunctionDecl>(D) &&((isa<FunctionDecl>(D) && "The templated declaration should at least be a function" " when diagnosing bad template argument deduction due to too many" " or too few arguments") ? static_cast<void> (0) : __assert_fail ("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 9963, __PRETTY_FUNCTION__)) | |||
9961 | "The templated declaration should at least be a function"((isa<FunctionDecl>(D) && "The templated declaration should at least be a function" " when diagnosing bad template argument deduction due to too many" " or too few arguments") ? static_cast<void> (0) : __assert_fail ("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 9963, __PRETTY_FUNCTION__)) | |||
9962 | " when diagnosing bad template argument deduction due to too many"((isa<FunctionDecl>(D) && "The templated declaration should at least be a function" " when diagnosing bad template argument deduction due to too many" " or too few arguments") ? static_cast<void> (0) : __assert_fail ("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 9963, __PRETTY_FUNCTION__)) | |||
9963 | " or too few arguments")((isa<FunctionDecl>(D) && "The templated declaration should at least be a function" " when diagnosing bad template argument deduction due to too many" " or too few arguments") ? static_cast<void> (0) : __assert_fail ("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 9963, __PRETTY_FUNCTION__)); | |||
9964 | ||||
9965 | FunctionDecl *Fn = cast<FunctionDecl>(D); | |||
9966 | ||||
9967 | // TODO: treat calls to a missing default constructor as a special case | |||
9968 | const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); | |||
9969 | unsigned MinParams = Fn->getMinRequiredArguments(); | |||
9970 | ||||
9971 | // at least / at most / exactly | |||
9972 | unsigned mode, modeCount; | |||
9973 | if (NumFormalArgs < MinParams) { | |||
9974 | if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || | |||
9975 | FnTy->isTemplateVariadic()) | |||
9976 | mode = 0; // "at least" | |||
9977 | else | |||
9978 | mode = 2; // "exactly" | |||
9979 | modeCount = MinParams; | |||
9980 | } else { | |||
9981 | if (MinParams != FnTy->getNumParams()) | |||
9982 | mode = 1; // "at most" | |||
9983 | else | |||
9984 | mode = 2; // "exactly" | |||
9985 | modeCount = FnTy->getNumParams(); | |||
9986 | } | |||
9987 | ||||
9988 | std::string Description; | |||
9989 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = | |||
9990 | ClassifyOverloadCandidate(S, Found, Fn, Description); | |||
9991 | ||||
9992 | if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) | |||
9993 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) | |||
9994 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second | |||
9995 | << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; | |||
9996 | else | |||
9997 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) | |||
9998 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second | |||
9999 | << Description << mode << modeCount << NumFormalArgs; | |||
10000 | ||||
10001 | MaybeEmitInheritedConstructorNote(S, Found); | |||
10002 | } | |||
10003 | ||||
10004 | /// Arity mismatch diagnosis specific to a function overload candidate. | |||
10005 | static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, | |||
10006 | unsigned NumFormalArgs) { | |||
10007 | if (!CheckArityMismatch(S, Cand, NumFormalArgs)) | |||
10008 | DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); | |||
10009 | } | |||
10010 | ||||
10011 | static TemplateDecl *getDescribedTemplate(Decl *Templated) { | |||
10012 | if (TemplateDecl *TD = Templated->getDescribedTemplate()) | |||
10013 | return TD; | |||
10014 | llvm_unreachable("Unsupported: Getting the described template declaration"::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration" " for bad deduction diagnosis", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 10015) | |||
10015 | " for bad deduction diagnosis")::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration" " for bad deduction diagnosis", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 10015); | |||
10016 | } | |||
10017 | ||||
10018 | /// Diagnose a failed template-argument deduction. | |||
10019 | static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, | |||
10020 | DeductionFailureInfo &DeductionFailure, | |||
10021 | unsigned NumArgs, | |||
10022 | bool TakingCandidateAddress) { | |||
10023 | TemplateParameter Param = DeductionFailure.getTemplateParameter(); | |||
10024 | NamedDecl *ParamD; | |||
10025 | (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || | |||
10026 | (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || | |||
10027 | (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); | |||
10028 | switch (DeductionFailure.Result) { | |||
10029 | case Sema::TDK_Success: | |||
10030 | llvm_unreachable("TDK_success while diagnosing bad deduction")::llvm::llvm_unreachable_internal("TDK_success while diagnosing bad deduction" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 10030); | |||
10031 | ||||
10032 | case Sema::TDK_Incomplete: { | |||
10033 | assert(ParamD && "no parameter found for incomplete deduction result")((ParamD && "no parameter found for incomplete deduction result" ) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 10033, __PRETTY_FUNCTION__)); | |||
10034 | S.Diag(Templated->getLocation(), | |||
10035 | diag::note_ovl_candidate_incomplete_deduction) | |||
10036 | << ParamD->getDeclName(); | |||
10037 | MaybeEmitInheritedConstructorNote(S, Found); | |||
10038 | return; | |||
10039 | } | |||
10040 | ||||
10041 | case Sema::TDK_IncompletePack: { | |||
10042 | assert(ParamD && "no parameter found for incomplete deduction result")((ParamD && "no parameter found for incomplete deduction result" ) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 10042, __PRETTY_FUNCTION__)); | |||
10043 | S.Diag(Templated->getLocation(), | |||
10044 | diag::note_ovl_candidate_incomplete_deduction_pack) | |||
10045 | << ParamD->getDeclName() | |||
10046 | << (DeductionFailure.getFirstArg()->pack_size() + 1) | |||
10047 | << *DeductionFailure.getFirstArg(); | |||
10048 | MaybeEmitInheritedConstructorNote(S, Found); | |||
10049 | return; | |||
10050 | } | |||
10051 | ||||
10052 | case Sema::TDK_Underqualified: { | |||
10053 | assert(ParamD && "no parameter found for bad qualifiers deduction result")((ParamD && "no parameter found for bad qualifiers deduction result" ) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for bad qualifiers deduction result\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 10053, __PRETTY_FUNCTION__)); | |||
10054 | TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); | |||
10055 | ||||
10056 | QualType Param = DeductionFailure.getFirstArg()->getAsType(); | |||
10057 | ||||
10058 | // Param will have been canonicalized, but it should just be a | |||
10059 | // qualified version of ParamD, so move the qualifiers to that. | |||
10060 | QualifierCollector Qs; | |||
10061 | Qs.strip(Param); | |||
10062 | QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); | |||
10063 | assert(S.Context.hasSameType(Param, NonCanonParam))((S.Context.hasSameType(Param, NonCanonParam)) ? static_cast< void> (0) : __assert_fail ("S.Context.hasSameType(Param, NonCanonParam)" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 10063, __PRETTY_FUNCTION__)); | |||
10064 | ||||
10065 | // Arg has also been canonicalized, but there's nothing we can do | |||
10066 | // about that. It also doesn't matter as much, because it won't | |||
10067 | // have any template parameters in it (because deduction isn't | |||
10068 | // done on dependent types). | |||
10069 | QualType Arg = DeductionFailure.getSecondArg()->getAsType(); | |||
10070 | ||||
10071 | S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) | |||
10072 | << ParamD->getDeclName() << Arg << NonCanonParam; | |||
10073 | MaybeEmitInheritedConstructorNote(S, Found); | |||
10074 | return; | |||
10075 | } | |||
10076 | ||||
10077 | case Sema::TDK_Inconsistent: { | |||
10078 | assert(ParamD && "no parameter found for inconsistent deduction result")((ParamD && "no parameter found for inconsistent deduction result" ) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for inconsistent deduction result\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 10078, __PRETTY_FUNCTION__)); | |||
10079 | int which = 0; | |||
10080 | if (isa<TemplateTypeParmDecl>(ParamD)) | |||
10081 | which = 0; | |||
10082 | else if (isa<NonTypeTemplateParmDecl>(ParamD)) { | |||
10083 | // Deduction might have failed because we deduced arguments of two | |||
10084 | // different types for a non-type template parameter. | |||
10085 | // FIXME: Use a different TDK value for this. | |||
10086 | QualType T1 = | |||
10087 | DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); | |||
10088 | QualType T2 = | |||
10089 | DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); | |||
10090 | if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { | |||
10091 | S.Diag(Templated->getLocation(), | |||
10092 | diag::note_ovl_candidate_inconsistent_deduction_types) | |||
10093 | << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 | |||
10094 | << *DeductionFailure.getSecondArg() << T2; | |||
10095 | MaybeEmitInheritedConstructorNote(S, Found); | |||
10096 | return; | |||
10097 | } | |||
10098 | ||||
10099 | which = 1; | |||
10100 | } else { | |||
10101 | which = 2; | |||
10102 | } | |||
10103 | ||||
10104 | S.Diag(Templated->getLocation(), | |||
10105 | diag::note_ovl_candidate_inconsistent_deduction) | |||
10106 | << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() | |||
10107 | << *DeductionFailure.getSecondArg(); | |||
10108 | MaybeEmitInheritedConstructorNote(S, Found); | |||
10109 | return; | |||
10110 | } | |||
10111 | ||||
10112 | case Sema::TDK_InvalidExplicitArguments: | |||
10113 | assert(ParamD && "no parameter found for invalid explicit arguments")((ParamD && "no parameter found for invalid explicit arguments" ) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for invalid explicit arguments\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 10113, __PRETTY_FUNCTION__)); | |||
10114 | if (ParamD->getDeclName()) | |||
10115 | S.Diag(Templated->getLocation(), | |||
10116 | diag::note_ovl_candidate_explicit_arg_mismatch_named) | |||
10117 | << ParamD->getDeclName(); | |||
10118 | else { | |||
10119 | int index = 0; | |||
10120 | if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) | |||
10121 | index = TTP->getIndex(); | |||
10122 | else if (NonTypeTemplateParmDecl *NTTP | |||
10123 | = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) | |||
10124 | index = NTTP->getIndex(); | |||
10125 | else | |||
10126 | index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); | |||
10127 | S.Diag(Templated->getLocation(), | |||
10128 | diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) | |||
10129 | << (index + 1); | |||
10130 | } | |||
10131 | MaybeEmitInheritedConstructorNote(S, Found); | |||
10132 | return; | |||
10133 | ||||
10134 | case Sema::TDK_TooManyArguments: | |||
10135 | case Sema::TDK_TooFewArguments: | |||
10136 | DiagnoseArityMismatch(S, Found, Templated, NumArgs); | |||
10137 | return; | |||
10138 | ||||
10139 | case Sema::TDK_InstantiationDepth: | |||
10140 | S.Diag(Templated->getLocation(), | |||
10141 | diag::note_ovl_candidate_instantiation_depth); | |||
10142 | MaybeEmitInheritedConstructorNote(S, Found); | |||
10143 | return; | |||
10144 | ||||
10145 | case Sema::TDK_SubstitutionFailure: { | |||
10146 | // Format the template argument list into the argument string. | |||
10147 | SmallString<128> TemplateArgString; | |||
10148 | if (TemplateArgumentList *Args = | |||
10149 | DeductionFailure.getTemplateArgumentList()) { | |||
10150 | TemplateArgString = " "; | |||
10151 | TemplateArgString += S.getTemplateArgumentBindingsText( | |||
10152 | getDescribedTemplate(Templated)->getTemplateParameters(), *Args); | |||
10153 | } | |||
10154 | ||||
10155 | // If this candidate was disabled by enable_if, say so. | |||
10156 | PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); | |||
10157 | if (PDiag && PDiag->second.getDiagID() == | |||
10158 | diag::err_typename_nested_not_found_enable_if) { | |||
10159 | // FIXME: Use the source range of the condition, and the fully-qualified | |||
10160 | // name of the enable_if template. These are both present in PDiag. | |||
10161 | S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) | |||
10162 | << "'enable_if'" << TemplateArgString; | |||
10163 | return; | |||
10164 | } | |||
10165 | ||||
10166 | // We found a specific requirement that disabled the enable_if. | |||
10167 | if (PDiag && PDiag->second.getDiagID() == | |||
10168 | diag::err_typename_nested_not_found_requirement) { | |||
10169 | S.Diag(Templated->getLocation(), | |||
10170 | diag::note_ovl_candidate_disabled_by_requirement) | |||
10171 | << PDiag->second.getStringArg(0) << TemplateArgString; | |||
10172 | return; | |||
10173 | } | |||
10174 | ||||
10175 | // Format the SFINAE diagnostic into the argument string. | |||
10176 | // FIXME: Add a general mechanism to include a PartialDiagnostic *'s | |||
10177 | // formatted message in another diagnostic. | |||
10178 | SmallString<128> SFINAEArgString; | |||
10179 | SourceRange R; | |||
10180 | if (PDiag) { | |||
10181 | SFINAEArgString = ": "; | |||
10182 | R = SourceRange(PDiag->first, PDiag->first); | |||
10183 | PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); | |||
10184 | } | |||
10185 | ||||
10186 | S.Diag(Templated->getLocation(), | |||
10187 | diag::note_ovl_candidate_substitution_failure) | |||
10188 | << TemplateArgString << SFINAEArgString << R; | |||
10189 | MaybeEmitInheritedConstructorNote(S, Found); | |||
10190 | return; | |||
10191 | } | |||
10192 | ||||
10193 | case Sema::TDK_DeducedMismatch: | |||
10194 | case Sema::TDK_DeducedMismatchNested: { | |||
10195 | // Format the template argument list into the argument string. | |||
10196 | SmallString<128> TemplateArgString; | |||
10197 | if (TemplateArgumentList *Args = | |||
10198 | DeductionFailure.getTemplateArgumentList()) { | |||
10199 | TemplateArgString = " "; | |||
10200 | TemplateArgString += S.getTemplateArgumentBindingsText( | |||
10201 | getDescribedTemplate(Templated)->getTemplateParameters(), *Args); | |||
10202 | } | |||
10203 | ||||
10204 | S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) | |||
10205 | << (*DeductionFailure.getCallArgIndex() + 1) | |||
10206 | << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() | |||
10207 | << TemplateArgString | |||
10208 | << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); | |||
10209 | break; | |||
10210 | } | |||
10211 | ||||
10212 | case Sema::TDK_NonDeducedMismatch: { | |||
10213 | // FIXME: Provide a source location to indicate what we couldn't match. | |||
10214 | TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); | |||
10215 | TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); | |||
10216 | if (FirstTA.getKind() == TemplateArgument::Template && | |||
10217 | SecondTA.getKind() == TemplateArgument::Template) { | |||
10218 | TemplateName FirstTN = FirstTA.getAsTemplate(); | |||
10219 | TemplateName SecondTN = SecondTA.getAsTemplate(); | |||
10220 | if (FirstTN.getKind() == TemplateName::Template && | |||
10221 | SecondTN.getKind() == TemplateName::Template) { | |||
10222 | if (FirstTN.getAsTemplateDecl()->getName() == | |||
10223 | SecondTN.getAsTemplateDecl()->getName()) { | |||
10224 | // FIXME: This fixes a bad diagnostic where both templates are named | |||
10225 | // the same. This particular case is a bit difficult since: | |||
10226 | // 1) It is passed as a string to the diagnostic printer. | |||
10227 | // 2) The diagnostic printer only attempts to find a better | |||
10228 | // name for types, not decls. | |||
10229 | // Ideally, this should folded into the diagnostic printer. | |||
10230 | S.Diag(Templated->getLocation(), | |||
10231 | diag::note_ovl_candidate_non_deduced_mismatch_qualified) | |||
10232 | << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); | |||
10233 | return; | |||
10234 | } | |||
10235 | } | |||
10236 | } | |||
10237 | ||||
10238 | if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && | |||
10239 | !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) | |||
10240 | return; | |||
10241 | ||||
10242 | // FIXME: For generic lambda parameters, check if the function is a lambda | |||
10243 | // call operator, and if so, emit a prettier and more informative | |||
10244 | // diagnostic that mentions 'auto' and lambda in addition to | |||
10245 | // (or instead of?) the canonical template type parameters. | |||
10246 | S.Diag(Templated->getLocation(), | |||
10247 | diag::note_ovl_candidate_non_deduced_mismatch) | |||
10248 | << FirstTA << SecondTA; | |||
10249 | return; | |||
10250 | } | |||
10251 | // TODO: diagnose these individually, then kill off | |||
10252 | // note_ovl_candidate_bad_deduction, which is uselessly vague. | |||
10253 | case Sema::TDK_MiscellaneousDeductionFailure: | |||
10254 | S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); | |||
10255 | MaybeEmitInheritedConstructorNote(S, Found); | |||
10256 | return; | |||
10257 | case Sema::TDK_CUDATargetMismatch: | |||
10258 | S.Diag(Templated->getLocation(), | |||
10259 | diag::note_cuda_ovl_candidate_target_mismatch); | |||
10260 | return; | |||
10261 | } | |||
10262 | } | |||
10263 | ||||
10264 | /// Diagnose a failed template-argument deduction, for function calls. | |||
10265 | static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, | |||
10266 | unsigned NumArgs, | |||
10267 | bool TakingCandidateAddress) { | |||
10268 | unsigned TDK = Cand->DeductionFailure.Result; | |||
10269 | if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { | |||
10270 | if (CheckArityMismatch(S, Cand, NumArgs)) | |||
10271 | return; | |||
10272 | } | |||
10273 | DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern | |||
10274 | Cand->DeductionFailure, NumArgs, TakingCandidateAddress); | |||
10275 | } | |||
10276 | ||||
10277 | /// CUDA: diagnose an invalid call across targets. | |||
10278 | static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { | |||
10279 | FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); | |||
10280 | FunctionDecl *Callee = Cand->Function; | |||
10281 | ||||
10282 | Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), | |||
10283 | CalleeTarget = S.IdentifyCUDATarget(Callee); | |||
10284 | ||||
10285 | std::string FnDesc; | |||
10286 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = | |||
10287 | ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc); | |||
10288 | ||||
10289 | S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) | |||
10290 | << (unsigned)FnKindPair.first << (unsigned)ocs_non_template | |||
10291 | << FnDesc /* Ignored */ | |||
10292 | << CalleeTarget << CallerTarget; | |||
10293 | ||||
10294 | // This could be an implicit constructor for which we could not infer the | |||
10295 | // target due to a collsion. Diagnose that case. | |||
10296 | CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); | |||
10297 | if (Meth != nullptr && Meth->isImplicit()) { | |||
10298 | CXXRecordDecl *ParentClass = Meth->getParent(); | |||
10299 | Sema::CXXSpecialMember CSM; | |||
10300 | ||||
10301 | switch (FnKindPair.first) { | |||
10302 | default: | |||
10303 | return; | |||
10304 | case oc_implicit_default_constructor: | |||
10305 | CSM = Sema::CXXDefaultConstructor; | |||
10306 | break; | |||
10307 | case oc_implicit_copy_constructor: | |||
10308 | CSM = Sema::CXXCopyConstructor; | |||
10309 | break; | |||
10310 | case oc_implicit_move_constructor: | |||
10311 | CSM = Sema::CXXMoveConstructor; | |||
10312 | break; | |||
10313 | case oc_implicit_copy_assignment: | |||
10314 | CSM = Sema::CXXCopyAssignment; | |||
10315 | break; | |||
10316 | case oc_implicit_move_assignment: | |||
10317 | CSM = Sema::CXXMoveAssignment; | |||
10318 | break; | |||
10319 | }; | |||
10320 | ||||
10321 | bool ConstRHS = false; | |||
10322 | if (Meth->getNumParams()) { | |||
10323 | if (const ReferenceType *RT = | |||
10324 | Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { | |||
10325 | ConstRHS = RT->getPointeeType().isConstQualified(); | |||
10326 | } | |||
10327 | } | |||
10328 | ||||
10329 | S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, | |||
10330 | /* ConstRHS */ ConstRHS, | |||
10331 | /* Diagnose */ true); | |||
10332 | } | |||
10333 | } | |||
10334 | ||||
10335 | static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { | |||
10336 | FunctionDecl *Callee = Cand->Function; | |||
10337 | EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); | |||
10338 | ||||
10339 | S.Diag(Callee->getLocation(), | |||
10340 | diag::note_ovl_candidate_disabled_by_function_cond_attr) | |||
10341 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); | |||
10342 | } | |||
10343 | ||||
10344 | static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { | |||
10345 | ExplicitSpecifier ES; | |||
10346 | const char *DeclName; | |||
10347 | switch (Cand->Function->getDeclKind()) { | |||
10348 | case Decl::Kind::CXXConstructor: | |||
10349 | ES = cast<CXXConstructorDecl>(Cand->Function)->getExplicitSpecifier(); | |||
10350 | DeclName = "constructor"; | |||
10351 | break; | |||
10352 | case Decl::Kind::CXXConversion: | |||
10353 | ES = cast<CXXConversionDecl>(Cand->Function)->getExplicitSpecifier(); | |||
10354 | DeclName = "conversion operator"; | |||
10355 | break; | |||
10356 | case Decl::Kind::CXXDeductionGuide: | |||
10357 | ES = cast<CXXDeductionGuideDecl>(Cand->Function)->getExplicitSpecifier(); | |||
10358 | DeclName = "deductiong guide"; | |||
10359 | break; | |||
10360 | default: | |||
10361 | llvm_unreachable("invalid Decl")::llvm::llvm_unreachable_internal("invalid Decl", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 10361); | |||
10362 | } | |||
10363 | assert(ES.getExpr() && "null expression should be handled before")((ES.getExpr() && "null expression should be handled before" ) ? static_cast<void> (0) : __assert_fail ("ES.getExpr() && \"null expression should be handled before\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 10363, __PRETTY_FUNCTION__)); | |||
10364 | S.Diag(Cand->Function->getLocation(), | |||
10365 | diag::note_ovl_candidate_explicit_forbidden) | |||
10366 | << DeclName; | |||
10367 | S.Diag(ES.getExpr()->getBeginLoc(), | |||
10368 | diag::note_explicit_bool_resolved_to_true); | |||
10369 | } | |||
10370 | ||||
10371 | static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { | |||
10372 | FunctionDecl *Callee = Cand->Function; | |||
10373 | ||||
10374 | S.Diag(Callee->getLocation(), | |||
10375 | diag::note_ovl_candidate_disabled_by_extension) | |||
10376 | << S.getOpenCLExtensionsFromDeclExtMap(Callee); | |||
10377 | } | |||
10378 | ||||
10379 | /// Generates a 'note' diagnostic for an overload candidate. We've | |||
10380 | /// already generated a primary error at the call site. | |||
10381 | /// | |||
10382 | /// It really does need to be a single diagnostic with its caret | |||
10383 | /// pointed at the candidate declaration. Yes, this creates some | |||
10384 | /// major challenges of technical writing. Yes, this makes pointing | |||
10385 | /// out problems with specific arguments quite awkward. It's still | |||
10386 | /// better than generating twenty screens of text for every failed | |||
10387 | /// overload. | |||
10388 | /// | |||
10389 | /// It would be great to be able to express per-candidate problems | |||
10390 | /// more richly for those diagnostic clients that cared, but we'd | |||
10391 | /// still have to be just as careful with the default diagnostics. | |||
10392 | static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, | |||
10393 | unsigned NumArgs, | |||
10394 | bool TakingCandidateAddress) { | |||
10395 | FunctionDecl *Fn = Cand->Function; | |||
10396 | ||||
10397 | // Note deleted candidates, but only if they're viable. | |||
10398 | if (Cand->Viable) { | |||
10399 | if (Fn->isDeleted()) { | |||
10400 | std::string FnDesc; | |||
10401 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = | |||
10402 | ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); | |||
10403 | ||||
10404 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) | |||
10405 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc | |||
10406 | << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); | |||
10407 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
10408 | return; | |||
10409 | } | |||
10410 | ||||
10411 | // We don't really have anything else to say about viable candidates. | |||
10412 | S.NoteOverloadCandidate(Cand->FoundDecl, Fn); | |||
10413 | return; | |||
10414 | } | |||
10415 | ||||
10416 | switch (Cand->FailureKind) { | |||
10417 | case ovl_fail_too_many_arguments: | |||
10418 | case ovl_fail_too_few_arguments: | |||
10419 | return DiagnoseArityMismatch(S, Cand, NumArgs); | |||
10420 | ||||
10421 | case ovl_fail_bad_deduction: | |||
10422 | return DiagnoseBadDeduction(S, Cand, NumArgs, | |||
10423 | TakingCandidateAddress); | |||
10424 | ||||
10425 | case ovl_fail_illegal_constructor: { | |||
10426 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) | |||
10427 | << (Fn->getPrimaryTemplate() ? 1 : 0); | |||
10428 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
10429 | return; | |||
10430 | } | |||
10431 | ||||
10432 | case ovl_fail_trivial_conversion: | |||
10433 | case ovl_fail_bad_final_conversion: | |||
10434 | case ovl_fail_final_conversion_not_exact: | |||
10435 | return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); | |||
10436 | ||||
10437 | case ovl_fail_bad_conversion: { | |||
10438 | unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); | |||
10439 | for (unsigned N = Cand->Conversions.size(); I != N; ++I) | |||
10440 | if (Cand->Conversions[I].isBad()) | |||
10441 | return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); | |||
10442 | ||||
10443 | // FIXME: this currently happens when we're called from SemaInit | |||
10444 | // when user-conversion overload fails. Figure out how to handle | |||
10445 | // those conditions and diagnose them well. | |||
10446 | return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); | |||
10447 | } | |||
10448 | ||||
10449 | case ovl_fail_bad_target: | |||
10450 | return DiagnoseBadTarget(S, Cand); | |||
10451 | ||||
10452 | case ovl_fail_enable_if: | |||
10453 | return DiagnoseFailedEnableIfAttr(S, Cand); | |||
10454 | ||||
10455 | case ovl_fail_explicit_resolved: | |||
10456 | return DiagnoseFailedExplicitSpec(S, Cand); | |||
10457 | ||||
10458 | case ovl_fail_ext_disabled: | |||
10459 | return DiagnoseOpenCLExtensionDisabled(S, Cand); | |||
10460 | ||||
10461 | case ovl_fail_inhctor_slice: | |||
10462 | // It's generally not interesting to note copy/move constructors here. | |||
10463 | if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) | |||
10464 | return; | |||
10465 | S.Diag(Fn->getLocation(), | |||
10466 | diag::note_ovl_candidate_inherited_constructor_slice) | |||
10467 | << (Fn->getPrimaryTemplate() ? 1 : 0) | |||
10468 | << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); | |||
10469 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); | |||
10470 | return; | |||
10471 | ||||
10472 | case ovl_fail_addr_not_available: { | |||
10473 | bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); | |||
10474 | (void)Available; | |||
10475 | assert(!Available)((!Available) ? static_cast<void> (0) : __assert_fail ( "!Available", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 10475, __PRETTY_FUNCTION__)); | |||
10476 | break; | |||
10477 | } | |||
10478 | case ovl_non_default_multiversion_function: | |||
10479 | // Do nothing, these should simply be ignored. | |||
10480 | break; | |||
10481 | } | |||
10482 | } | |||
10483 | ||||
10484 | static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { | |||
10485 | // Desugar the type of the surrogate down to a function type, | |||
10486 | // retaining as many typedefs as possible while still showing | |||
10487 | // the function type (and, therefore, its parameter types). | |||
10488 | QualType FnType = Cand->Surrogate->getConversionType(); | |||
10489 | bool isLValueReference = false; | |||
10490 | bool isRValueReference = false; | |||
10491 | bool isPointer = false; | |||
10492 | if (const LValueReferenceType *FnTypeRef = | |||
10493 | FnType->getAs<LValueReferenceType>()) { | |||
10494 | FnType = FnTypeRef->getPointeeType(); | |||
10495 | isLValueReference = true; | |||
10496 | } else if (const RValueReferenceType *FnTypeRef = | |||
10497 | FnType->getAs<RValueReferenceType>()) { | |||
10498 | FnType = FnTypeRef->getPointeeType(); | |||
10499 | isRValueReference = true; | |||
10500 | } | |||
10501 | if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { | |||
10502 | FnType = FnTypePtr->getPointeeType(); | |||
10503 | isPointer = true; | |||
10504 | } | |||
10505 | // Desugar down to a function type. | |||
10506 | FnType = QualType(FnType->getAs<FunctionType>(), 0); | |||
10507 | // Reconstruct the pointer/reference as appropriate. | |||
10508 | if (isPointer) FnType = S.Context.getPointerType(FnType); | |||
10509 | if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); | |||
10510 | if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); | |||
10511 | ||||
10512 | S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) | |||
10513 | << FnType; | |||
10514 | } | |||
10515 | ||||
10516 | static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, | |||
10517 | SourceLocation OpLoc, | |||
10518 | OverloadCandidate *Cand) { | |||
10519 | assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary")((Cand->Conversions.size() <= 2 && "builtin operator is not binary" ) ? static_cast<void> (0) : __assert_fail ("Cand->Conversions.size() <= 2 && \"builtin operator is not binary\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 10519, __PRETTY_FUNCTION__)); | |||
10520 | std::string TypeStr("operator"); | |||
10521 | TypeStr += Opc; | |||
10522 | TypeStr += "("; | |||
10523 | TypeStr += Cand->BuiltinParamTypes[0].getAsString(); | |||
10524 | if (Cand->Conversions.size() == 1) { | |||
10525 | TypeStr += ")"; | |||
10526 | S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; | |||
10527 | } else { | |||
10528 | TypeStr += ", "; | |||
10529 | TypeStr += Cand->BuiltinParamTypes[1].getAsString(); | |||
10530 | TypeStr += ")"; | |||
10531 | S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; | |||
10532 | } | |||
10533 | } | |||
10534 | ||||
10535 | static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, | |||
10536 | OverloadCandidate *Cand) { | |||
10537 | for (const ImplicitConversionSequence &ICS : Cand->Conversions) { | |||
10538 | if (ICS.isBad()) break; // all meaningless after first invalid | |||
10539 | if (!ICS.isAmbiguous()) continue; | |||
10540 | ||||
10541 | ICS.DiagnoseAmbiguousConversion( | |||
10542 | S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); | |||
10543 | } | |||
10544 | } | |||
10545 | ||||
10546 | static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { | |||
10547 | if (Cand->Function) | |||
10548 | return Cand->Function->getLocation(); | |||
10549 | if (Cand->IsSurrogate) | |||
10550 | return Cand->Surrogate->getLocation(); | |||
10551 | return SourceLocation(); | |||
10552 | } | |||
10553 | ||||
10554 | static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { | |||
10555 | switch ((Sema::TemplateDeductionResult)DFI.Result) { | |||
10556 | case Sema::TDK_Success: | |||
10557 | case Sema::TDK_NonDependentConversionFailure: | |||
10558 | llvm_unreachable("non-deduction failure while diagnosing bad deduction")::llvm::llvm_unreachable_internal("non-deduction failure while diagnosing bad deduction" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 10558); | |||
10559 | ||||
10560 | case Sema::TDK_Invalid: | |||
10561 | case Sema::TDK_Incomplete: | |||
10562 | case Sema::TDK_IncompletePack: | |||
10563 | return 1; | |||
10564 | ||||
10565 | case Sema::TDK_Underqualified: | |||
10566 | case Sema::TDK_Inconsistent: | |||
10567 | return 2; | |||
10568 | ||||
10569 | case Sema::TDK_SubstitutionFailure: | |||
10570 | case Sema::TDK_DeducedMismatch: | |||
10571 | case Sema::TDK_DeducedMismatchNested: | |||
10572 | case Sema::TDK_NonDeducedMismatch: | |||
10573 | case Sema::TDK_MiscellaneousDeductionFailure: | |||
10574 | case Sema::TDK_CUDATargetMismatch: | |||
10575 | return 3; | |||
10576 | ||||
10577 | case Sema::TDK_InstantiationDepth: | |||
10578 | return 4; | |||
10579 | ||||
10580 | case Sema::TDK_InvalidExplicitArguments: | |||
10581 | return 5; | |||
10582 | ||||
10583 | case Sema::TDK_TooManyArguments: | |||
10584 | case Sema::TDK_TooFewArguments: | |||
10585 | return 6; | |||
10586 | } | |||
10587 | llvm_unreachable("Unhandled deduction result")::llvm::llvm_unreachable_internal("Unhandled deduction result" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 10587); | |||
10588 | } | |||
10589 | ||||
10590 | namespace { | |||
10591 | struct CompareOverloadCandidatesForDisplay { | |||
10592 | Sema &S; | |||
10593 | SourceLocation Loc; | |||
10594 | size_t NumArgs; | |||
10595 | OverloadCandidateSet::CandidateSetKind CSK; | |||
10596 | ||||
10597 | CompareOverloadCandidatesForDisplay( | |||
10598 | Sema &S, SourceLocation Loc, size_t NArgs, | |||
10599 | OverloadCandidateSet::CandidateSetKind CSK) | |||
10600 | : S(S), NumArgs(NArgs), CSK(CSK) {} | |||
10601 | ||||
10602 | bool operator()(const OverloadCandidate *L, | |||
10603 | const OverloadCandidate *R) { | |||
10604 | // Fast-path this check. | |||
10605 | if (L == R) return false; | |||
10606 | ||||
10607 | // Order first by viability. | |||
10608 | if (L->Viable) { | |||
10609 | if (!R->Viable) return true; | |||
10610 | ||||
10611 | // TODO: introduce a tri-valued comparison for overload | |||
10612 | // candidates. Would be more worthwhile if we had a sort | |||
10613 | // that could exploit it. | |||
10614 | if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) | |||
10615 | return true; | |||
10616 | if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) | |||
10617 | return false; | |||
10618 | } else if (R->Viable) | |||
10619 | return false; | |||
10620 | ||||
10621 | assert(L->Viable == R->Viable)((L->Viable == R->Viable) ? static_cast<void> (0) : __assert_fail ("L->Viable == R->Viable", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 10621, __PRETTY_FUNCTION__)); | |||
10622 | ||||
10623 | // Criteria by which we can sort non-viable candidates: | |||
10624 | if (!L->Viable) { | |||
10625 | // 1. Arity mismatches come after other candidates. | |||
10626 | if (L->FailureKind == ovl_fail_too_many_arguments || | |||
10627 | L->FailureKind == ovl_fail_too_few_arguments) { | |||
10628 | if (R->FailureKind == ovl_fail_too_many_arguments || | |||
10629 | R->FailureKind == ovl_fail_too_few_arguments) { | |||
10630 | int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); | |||
10631 | int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); | |||
10632 | if (LDist == RDist) { | |||
10633 | if (L->FailureKind == R->FailureKind) | |||
10634 | // Sort non-surrogates before surrogates. | |||
10635 | return !L->IsSurrogate && R->IsSurrogate; | |||
10636 | // Sort candidates requiring fewer parameters than there were | |||
10637 | // arguments given after candidates requiring more parameters | |||
10638 | // than there were arguments given. | |||
10639 | return L->FailureKind == ovl_fail_too_many_arguments; | |||
10640 | } | |||
10641 | return LDist < RDist; | |||
10642 | } | |||
10643 | return false; | |||
10644 | } | |||
10645 | if (R->FailureKind == ovl_fail_too_many_arguments || | |||
10646 | R->FailureKind == ovl_fail_too_few_arguments) | |||
10647 | return true; | |||
10648 | ||||
10649 | // 2. Bad conversions come first and are ordered by the number | |||
10650 | // of bad conversions and quality of good conversions. | |||
10651 | if (L->FailureKind == ovl_fail_bad_conversion) { | |||
10652 | if (R->FailureKind != ovl_fail_bad_conversion) | |||
10653 | return true; | |||
10654 | ||||
10655 | // The conversion that can be fixed with a smaller number of changes, | |||
10656 | // comes first. | |||
10657 | unsigned numLFixes = L->Fix.NumConversionsFixed; | |||
10658 | unsigned numRFixes = R->Fix.NumConversionsFixed; | |||
10659 | numLFixes = (numLFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numLFixes; | |||
10660 | numRFixes = (numRFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numRFixes; | |||
10661 | if (numLFixes != numRFixes) { | |||
10662 | return numLFixes < numRFixes; | |||
10663 | } | |||
10664 | ||||
10665 | // If there's any ordering between the defined conversions... | |||
10666 | // FIXME: this might not be transitive. | |||
10667 | assert(L->Conversions.size() == R->Conversions.size())((L->Conversions.size() == R->Conversions.size()) ? static_cast <void> (0) : __assert_fail ("L->Conversions.size() == R->Conversions.size()" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 10667, __PRETTY_FUNCTION__)); | |||
10668 | ||||
10669 | int leftBetter = 0; | |||
10670 | unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); | |||
10671 | for (unsigned E = L->Conversions.size(); I != E; ++I) { | |||
10672 | switch (CompareImplicitConversionSequences(S, Loc, | |||
10673 | L->Conversions[I], | |||
10674 | R->Conversions[I])) { | |||
10675 | case ImplicitConversionSequence::Better: | |||
10676 | leftBetter++; | |||
10677 | break; | |||
10678 | ||||
10679 | case ImplicitConversionSequence::Worse: | |||
10680 | leftBetter--; | |||
10681 | break; | |||
10682 | ||||
10683 | case ImplicitConversionSequence::Indistinguishable: | |||
10684 | break; | |||
10685 | } | |||
10686 | } | |||
10687 | if (leftBetter > 0) return true; | |||
10688 | if (leftBetter < 0) return false; | |||
10689 | ||||
10690 | } else if (R->FailureKind == ovl_fail_bad_conversion) | |||
10691 | return false; | |||
10692 | ||||
10693 | if (L->FailureKind == ovl_fail_bad_deduction) { | |||
10694 | if (R->FailureKind != ovl_fail_bad_deduction) | |||
10695 | return true; | |||
10696 | ||||
10697 | if (L->DeductionFailure.Result != R->DeductionFailure.Result) | |||
10698 | return RankDeductionFailure(L->DeductionFailure) | |||
10699 | < RankDeductionFailure(R->DeductionFailure); | |||
10700 | } else if (R->FailureKind == ovl_fail_bad_deduction) | |||
10701 | return false; | |||
10702 | ||||
10703 | // TODO: others? | |||
10704 | } | |||
10705 | ||||
10706 | // Sort everything else by location. | |||
10707 | SourceLocation LLoc = GetLocationForCandidate(L); | |||
10708 | SourceLocation RLoc = GetLocationForCandidate(R); | |||
10709 | ||||
10710 | // Put candidates without locations (e.g. builtins) at the end. | |||
10711 | if (LLoc.isInvalid()) return false; | |||
10712 | if (RLoc.isInvalid()) return true; | |||
10713 | ||||
10714 | return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); | |||
10715 | } | |||
10716 | }; | |||
10717 | } | |||
10718 | ||||
10719 | /// CompleteNonViableCandidate - Normally, overload resolution only | |||
10720 | /// computes up to the first bad conversion. Produces the FixIt set if | |||
10721 | /// possible. | |||
10722 | static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, | |||
10723 | ArrayRef<Expr *> Args) { | |||
10724 | assert(!Cand->Viable)((!Cand->Viable) ? static_cast<void> (0) : __assert_fail ("!Cand->Viable", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 10724, __PRETTY_FUNCTION__)); | |||
10725 | ||||
10726 | // Don't do anything on failures other than bad conversion. | |||
10727 | if (Cand->FailureKind != ovl_fail_bad_conversion) return; | |||
10728 | ||||
10729 | // We only want the FixIts if all the arguments can be corrected. | |||
10730 | bool Unfixable = false; | |||
10731 | // Use a implicit copy initialization to check conversion fixes. | |||
10732 | Cand->Fix.setConversionChecker(TryCopyInitialization); | |||
10733 | ||||
10734 | // Attempt to fix the bad conversion. | |||
10735 | unsigned ConvCount = Cand->Conversions.size(); | |||
10736 | for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; | |||
10737 | ++ConvIdx) { | |||
10738 | assert(ConvIdx != ConvCount && "no bad conversion in candidate")((ConvIdx != ConvCount && "no bad conversion in candidate" ) ? static_cast<void> (0) : __assert_fail ("ConvIdx != ConvCount && \"no bad conversion in candidate\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 10738, __PRETTY_FUNCTION__)); | |||
10739 | if (Cand->Conversions[ConvIdx].isInitialized() && | |||
10740 | Cand->Conversions[ConvIdx].isBad()) { | |||
10741 | Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); | |||
10742 | break; | |||
10743 | } | |||
10744 | } | |||
10745 | ||||
10746 | // FIXME: this should probably be preserved from the overload | |||
10747 | // operation somehow. | |||
10748 | bool SuppressUserConversions = false; | |||
10749 | ||||
10750 | unsigned ConvIdx = 0; | |||
10751 | ArrayRef<QualType> ParamTypes; | |||
10752 | ||||
10753 | if (Cand->IsSurrogate) { | |||
10754 | QualType ConvType | |||
10755 | = Cand->Surrogate->getConversionType().getNonReferenceType(); | |||
10756 | if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) | |||
10757 | ConvType = ConvPtrType->getPointeeType(); | |||
10758 | ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes(); | |||
10759 | // Conversion 0 is 'this', which doesn't have a corresponding argument. | |||
10760 | ConvIdx = 1; | |||
10761 | } else if (Cand->Function) { | |||
10762 | ParamTypes = | |||
10763 | Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes(); | |||
10764 | if (isa<CXXMethodDecl>(Cand->Function) && | |||
10765 | !isa<CXXConstructorDecl>(Cand->Function)) { | |||
10766 | // Conversion 0 is 'this', which doesn't have a corresponding argument. | |||
10767 | ConvIdx = 1; | |||
10768 | } | |||
10769 | } else { | |||
10770 | // Builtin operator. | |||
10771 | assert(ConvCount <= 3)((ConvCount <= 3) ? static_cast<void> (0) : __assert_fail ("ConvCount <= 3", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 10771, __PRETTY_FUNCTION__)); | |||
10772 | ParamTypes = Cand->BuiltinParamTypes; | |||
10773 | } | |||
10774 | ||||
10775 | // Fill in the rest of the conversions. | |||
10776 | for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { | |||
10777 | if (Cand->Conversions[ConvIdx].isInitialized()) { | |||
10778 | // We've already checked this conversion. | |||
10779 | } else if (ArgIdx < ParamTypes.size()) { | |||
10780 | if (ParamTypes[ArgIdx]->isDependentType()) | |||
10781 | Cand->Conversions[ConvIdx].setAsIdentityConversion( | |||
10782 | Args[ArgIdx]->getType()); | |||
10783 | else { | |||
10784 | Cand->Conversions[ConvIdx] = | |||
10785 | TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx], | |||
10786 | SuppressUserConversions, | |||
10787 | /*InOverloadResolution=*/true, | |||
10788 | /*AllowObjCWritebackConversion=*/ | |||
10789 | S.getLangOpts().ObjCAutoRefCount); | |||
10790 | // Store the FixIt in the candidate if it exists. | |||
10791 | if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) | |||
10792 | Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); | |||
10793 | } | |||
10794 | } else | |||
10795 | Cand->Conversions[ConvIdx].setEllipsis(); | |||
10796 | } | |||
10797 | } | |||
10798 | ||||
10799 | SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( | |||
10800 | Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, | |||
10801 | SourceLocation OpLoc, | |||
10802 | llvm::function_ref<bool(OverloadCandidate &)> Filter) { | |||
10803 | // Sort the candidates by viability and position. Sorting directly would | |||
10804 | // be prohibitive, so we make a set of pointers and sort those. | |||
10805 | SmallVector<OverloadCandidate*, 32> Cands; | |||
10806 | if (OCD == OCD_AllCandidates) Cands.reserve(size()); | |||
10807 | for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { | |||
10808 | if (!Filter(*Cand)) | |||
10809 | continue; | |||
10810 | if (Cand->Viable) | |||
10811 | Cands.push_back(Cand); | |||
10812 | else if (OCD == OCD_AllCandidates) { | |||
10813 | CompleteNonViableCandidate(S, Cand, Args); | |||
10814 | if (Cand->Function || Cand->IsSurrogate) | |||
10815 | Cands.push_back(Cand); | |||
10816 | // Otherwise, this a non-viable builtin candidate. We do not, in general, | |||
10817 | // want to list every possible builtin candidate. | |||
10818 | } | |||
10819 | } | |||
10820 | ||||
10821 | llvm::stable_sort( | |||
10822 | Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); | |||
10823 | ||||
10824 | return Cands; | |||
10825 | } | |||
10826 | ||||
10827 | /// When overload resolution fails, prints diagnostic messages containing the | |||
10828 | /// candidates in the candidate set. | |||
10829 | void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD, | |||
10830 | Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, | |||
10831 | StringRef Opc, SourceLocation OpLoc, | |||
10832 | llvm::function_ref<bool(OverloadCandidate &)> Filter) { | |||
10833 | ||||
10834 | auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); | |||
10835 | ||||
10836 | S.Diag(PD.first, PD.second); | |||
10837 | ||||
10838 | NoteCandidates(S, Args, Cands, Opc, OpLoc); | |||
10839 | } | |||
10840 | ||||
10841 | void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, | |||
10842 | ArrayRef<OverloadCandidate *> Cands, | |||
10843 | StringRef Opc, SourceLocation OpLoc) { | |||
10844 | bool ReportedAmbiguousConversions = false; | |||
10845 | ||||
10846 | const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); | |||
10847 | unsigned CandsShown = 0; | |||
10848 | auto I = Cands.begin(), E = Cands.end(); | |||
10849 | for (; I != E; ++I) { | |||
10850 | OverloadCandidate *Cand = *I; | |||
10851 | ||||
10852 | // Set an arbitrary limit on the number of candidate functions we'll spam | |||
10853 | // the user with. FIXME: This limit should depend on details of the | |||
10854 | // candidate list. | |||
10855 | if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { | |||
10856 | break; | |||
10857 | } | |||
10858 | ++CandsShown; | |||
10859 | ||||
10860 | if (Cand->Function) | |||
10861 | NoteFunctionCandidate(S, Cand, Args.size(), | |||
10862 | /*TakingCandidateAddress=*/false); | |||
10863 | else if (Cand->IsSurrogate) | |||
10864 | NoteSurrogateCandidate(S, Cand); | |||
10865 | else { | |||
10866 | assert(Cand->Viable &&((Cand->Viable && "Non-viable built-in candidates are not added to Cands." ) ? static_cast<void> (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 10867, __PRETTY_FUNCTION__)) | |||
10867 | "Non-viable built-in candidates are not added to Cands.")((Cand->Viable && "Non-viable built-in candidates are not added to Cands." ) ? static_cast<void> (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 10867, __PRETTY_FUNCTION__)); | |||
10868 | // Generally we only see ambiguities including viable builtin | |||
10869 | // operators if overload resolution got screwed up by an | |||
10870 | // ambiguous user-defined conversion. | |||
10871 | // | |||
10872 | // FIXME: It's quite possible for different conversions to see | |||
10873 | // different ambiguities, though. | |||
10874 | if (!ReportedAmbiguousConversions) { | |||
10875 | NoteAmbiguousUserConversions(S, OpLoc, Cand); | |||
10876 | ReportedAmbiguousConversions = true; | |||
10877 | } | |||
10878 | ||||
10879 | // If this is a viable builtin, print it. | |||
10880 | NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); | |||
10881 | } | |||
10882 | } | |||
10883 | ||||
10884 | if (I != E) | |||
10885 | S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); | |||
10886 | } | |||
10887 | ||||
10888 | static SourceLocation | |||
10889 | GetLocationForCandidate(const TemplateSpecCandidate *Cand) { | |||
10890 | return Cand->Specialization ? Cand->Specialization->getLocation() | |||
10891 | : SourceLocation(); | |||
10892 | } | |||
10893 | ||||
10894 | namespace { | |||
10895 | struct CompareTemplateSpecCandidatesForDisplay { | |||
10896 | Sema &S; | |||
10897 | CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} | |||
10898 | ||||
10899 | bool operator()(const TemplateSpecCandidate *L, | |||
10900 | const TemplateSpecCandidate *R) { | |||
10901 | // Fast-path this check. | |||
10902 | if (L == R) | |||
10903 | return false; | |||
10904 | ||||
10905 | // Assuming that both candidates are not matches... | |||
10906 | ||||
10907 | // Sort by the ranking of deduction failures. | |||
10908 | if (L->DeductionFailure.Result != R->DeductionFailure.Result) | |||
10909 | return RankDeductionFailure(L->DeductionFailure) < | |||
10910 | RankDeductionFailure(R->DeductionFailure); | |||
10911 | ||||
10912 | // Sort everything else by location. | |||
10913 | SourceLocation LLoc = GetLocationForCandidate(L); | |||
10914 | SourceLocation RLoc = GetLocationForCandidate(R); | |||
10915 | ||||
10916 | // Put candidates without locations (e.g. builtins) at the end. | |||
10917 | if (LLoc.isInvalid()) | |||
10918 | return false; | |||
10919 | if (RLoc.isInvalid()) | |||
10920 | return true; | |||
10921 | ||||
10922 | return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); | |||
10923 | } | |||
10924 | }; | |||
10925 | } | |||
10926 | ||||
10927 | /// Diagnose a template argument deduction failure. | |||
10928 | /// We are treating these failures as overload failures due to bad | |||
10929 | /// deductions. | |||
10930 | void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, | |||
10931 | bool ForTakingAddress) { | |||
10932 | DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern | |||
10933 | DeductionFailure, /*NumArgs=*/0, ForTakingAddress); | |||
10934 | } | |||
10935 | ||||
10936 | void TemplateSpecCandidateSet::destroyCandidates() { | |||
10937 | for (iterator i = begin(), e = end(); i != e; ++i) { | |||
10938 | i->DeductionFailure.Destroy(); | |||
10939 | } | |||
10940 | } | |||
10941 | ||||
10942 | void TemplateSpecCandidateSet::clear() { | |||
10943 | destroyCandidates(); | |||
10944 | Candidates.clear(); | |||
10945 | } | |||
10946 | ||||
10947 | /// NoteCandidates - When no template specialization match is found, prints | |||
10948 | /// diagnostic messages containing the non-matching specializations that form | |||
10949 | /// the candidate set. | |||
10950 | /// This is analoguous to OverloadCandidateSet::NoteCandidates() with | |||
10951 | /// OCD == OCD_AllCandidates and Cand->Viable == false. | |||
10952 | void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { | |||
10953 | // Sort the candidates by position (assuming no candidate is a match). | |||
10954 | // Sorting directly would be prohibitive, so we make a set of pointers | |||
10955 | // and sort those. | |||
10956 | SmallVector<TemplateSpecCandidate *, 32> Cands; | |||
10957 | Cands.reserve(size()); | |||
10958 | for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { | |||
10959 | if (Cand->Specialization) | |||
10960 | Cands.push_back(Cand); | |||
10961 | // Otherwise, this is a non-matching builtin candidate. We do not, | |||
10962 | // in general, want to list every possible builtin candidate. | |||
10963 | } | |||
10964 | ||||
10965 | llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); | |||
10966 | ||||
10967 | // FIXME: Perhaps rename OverloadsShown and getShowOverloads() | |||
10968 | // for generalization purposes (?). | |||
10969 | const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); | |||
10970 | ||||
10971 | SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; | |||
10972 | unsigned CandsShown = 0; | |||
10973 | for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { | |||
10974 | TemplateSpecCandidate *Cand = *I; | |||
10975 | ||||
10976 | // Set an arbitrary limit on the number of candidates we'll spam | |||
10977 | // the user with. FIXME: This limit should depend on details of the | |||
10978 | // candidate list. | |||
10979 | if (CandsShown >= 4 && ShowOverloads == Ovl_Best) | |||
10980 | break; | |||
10981 | ++CandsShown; | |||
10982 | ||||
10983 | assert(Cand->Specialization &&((Cand->Specialization && "Non-matching built-in candidates are not added to Cands." ) ? static_cast<void> (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 10984, __PRETTY_FUNCTION__)) | |||
10984 | "Non-matching built-in candidates are not added to Cands.")((Cand->Specialization && "Non-matching built-in candidates are not added to Cands." ) ? static_cast<void> (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 10984, __PRETTY_FUNCTION__)); | |||
10985 | Cand->NoteDeductionFailure(S, ForTakingAddress); | |||
10986 | } | |||
10987 | ||||
10988 | if (I != E) | |||
10989 | S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); | |||
10990 | } | |||
10991 | ||||
10992 | // [PossiblyAFunctionType] --> [Return] | |||
10993 | // NonFunctionType --> NonFunctionType | |||
10994 | // R (A) --> R(A) | |||
10995 | // R (*)(A) --> R (A) | |||
10996 | // R (&)(A) --> R (A) | |||
10997 | // R (S::*)(A) --> R (A) | |||
10998 | QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { | |||
10999 | QualType Ret = PossiblyAFunctionType; | |||
11000 | if (const PointerType *ToTypePtr = | |||
11001 | PossiblyAFunctionType->getAs<PointerType>()) | |||
11002 | Ret = ToTypePtr->getPointeeType(); | |||
11003 | else if (const ReferenceType *ToTypeRef = | |||
11004 | PossiblyAFunctionType->getAs<ReferenceType>()) | |||
11005 | Ret = ToTypeRef->getPointeeType(); | |||
11006 | else if (const MemberPointerType *MemTypePtr = | |||
11007 | PossiblyAFunctionType->getAs<MemberPointerType>()) | |||
11008 | Ret = MemTypePtr->getPointeeType(); | |||
11009 | Ret = | |||
11010 | Context.getCanonicalType(Ret).getUnqualifiedType(); | |||
11011 | return Ret; | |||
11012 | } | |||
11013 | ||||
11014 | static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, | |||
11015 | bool Complain = true) { | |||
11016 | if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && | |||
11017 | S.DeduceReturnType(FD, Loc, Complain)) | |||
11018 | return true; | |||
11019 | ||||
11020 | auto *FPT = FD->getType()->castAs<FunctionProtoType>(); | |||
11021 | if (S.getLangOpts().CPlusPlus17 && | |||
11022 | isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && | |||
11023 | !S.ResolveExceptionSpec(Loc, FPT)) | |||
11024 | return true; | |||
11025 | ||||
11026 | return false; | |||
11027 | } | |||
11028 | ||||
11029 | namespace { | |||
11030 | // A helper class to help with address of function resolution | |||
11031 | // - allows us to avoid passing around all those ugly parameters | |||
11032 | class AddressOfFunctionResolver { | |||
11033 | Sema& S; | |||
11034 | Expr* SourceExpr; | |||
11035 | const QualType& TargetType; | |||
11036 | QualType TargetFunctionType; // Extracted function type from target type | |||
11037 | ||||
11038 | bool Complain; | |||
11039 | //DeclAccessPair& ResultFunctionAccessPair; | |||
11040 | ASTContext& Context; | |||
11041 | ||||
11042 | bool TargetTypeIsNonStaticMemberFunction; | |||
11043 | bool FoundNonTemplateFunction; | |||
11044 | bool StaticMemberFunctionFromBoundPointer; | |||
11045 | bool HasComplained; | |||
11046 | ||||
11047 | OverloadExpr::FindResult OvlExprInfo; | |||
11048 | OverloadExpr *OvlExpr; | |||
11049 | TemplateArgumentListInfo OvlExplicitTemplateArgs; | |||
11050 | SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; | |||
11051 | TemplateSpecCandidateSet FailedCandidates; | |||
11052 | ||||
11053 | public: | |||
11054 | AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, | |||
11055 | const QualType &TargetType, bool Complain) | |||
11056 | : S(S), SourceExpr(SourceExpr), TargetType(TargetType), | |||
11057 | Complain(Complain), Context(S.getASTContext()), | |||
11058 | TargetTypeIsNonStaticMemberFunction( | |||
11059 | !!TargetType->getAs<MemberPointerType>()), | |||
11060 | FoundNonTemplateFunction(false), | |||
11061 | StaticMemberFunctionFromBoundPointer(false), | |||
11062 | HasComplained(false), | |||
11063 | OvlExprInfo(OverloadExpr::find(SourceExpr)), | |||
11064 | OvlExpr(OvlExprInfo.Expression), | |||
11065 | FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { | |||
11066 | ExtractUnqualifiedFunctionTypeFromTargetType(); | |||
11067 | ||||
11068 | if (TargetFunctionType->isFunctionType()) { | |||
11069 | if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) | |||
11070 | if (!UME->isImplicitAccess() && | |||
11071 | !S.ResolveSingleFunctionTemplateSpecialization(UME)) | |||
11072 | StaticMemberFunctionFromBoundPointer = true; | |||
11073 | } else if (OvlExpr->hasExplicitTemplateArgs()) { | |||
11074 | DeclAccessPair dap; | |||
11075 | if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( | |||
11076 | OvlExpr, false, &dap)) { | |||
11077 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) | |||
11078 | if (!Method->isStatic()) { | |||
11079 | // If the target type is a non-function type and the function found | |||
11080 | // is a non-static member function, pretend as if that was the | |||
11081 | // target, it's the only possible type to end up with. | |||
11082 | TargetTypeIsNonStaticMemberFunction = true; | |||
11083 | ||||
11084 | // And skip adding the function if its not in the proper form. | |||
11085 | // We'll diagnose this due to an empty set of functions. | |||
11086 | if (!OvlExprInfo.HasFormOfMemberPointer) | |||
11087 | return; | |||
11088 | } | |||
11089 | ||||
11090 | Matches.push_back(std::make_pair(dap, Fn)); | |||
11091 | } | |||
11092 | return; | |||
11093 | } | |||
11094 | ||||
11095 | if (OvlExpr->hasExplicitTemplateArgs()) | |||
11096 | OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); | |||
11097 | ||||
11098 | if (FindAllFunctionsThatMatchTargetTypeExactly()) { | |||
11099 | // C++ [over.over]p4: | |||
11100 | // If more than one function is selected, [...] | |||
11101 | if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { | |||
11102 | if (FoundNonTemplateFunction) | |||
11103 | EliminateAllTemplateMatches(); | |||
11104 | else | |||
11105 | EliminateAllExceptMostSpecializedTemplate(); | |||
11106 | } | |||
11107 | } | |||
11108 | ||||
11109 | if (S.getLangOpts().CUDA && Matches.size() > 1) | |||
11110 | EliminateSuboptimalCudaMatches(); | |||
11111 | } | |||
11112 | ||||
11113 | bool hasComplained() const { return HasComplained; } | |||
11114 | ||||
11115 | private: | |||
11116 | bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { | |||
11117 | QualType Discard; | |||
11118 | return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || | |||
11119 | S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); | |||
11120 | } | |||
11121 | ||||
11122 | /// \return true if A is considered a better overload candidate for the | |||
11123 | /// desired type than B. | |||
11124 | bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { | |||
11125 | // If A doesn't have exactly the correct type, we don't want to classify it | |||
11126 | // as "better" than anything else. This way, the user is required to | |||
11127 | // disambiguate for us if there are multiple candidates and no exact match. | |||
11128 | return candidateHasExactlyCorrectType(A) && | |||
11129 | (!candidateHasExactlyCorrectType(B) || | |||
11130 | compareEnableIfAttrs(S, A, B) == Comparison::Better); | |||
11131 | } | |||
11132 | ||||
11133 | /// \return true if we were able to eliminate all but one overload candidate, | |||
11134 | /// false otherwise. | |||
11135 | bool eliminiateSuboptimalOverloadCandidates() { | |||
11136 | // Same algorithm as overload resolution -- one pass to pick the "best", | |||
11137 | // another pass to be sure that nothing is better than the best. | |||
11138 | auto Best = Matches.begin(); | |||
11139 | for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) | |||
11140 | if (isBetterCandidate(I->second, Best->second)) | |||
11141 | Best = I; | |||
11142 | ||||
11143 | const FunctionDecl *BestFn = Best->second; | |||
11144 | auto IsBestOrInferiorToBest = [this, BestFn]( | |||
11145 | const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { | |||
11146 | return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); | |||
11147 | }; | |||
11148 | ||||
11149 | // Note: We explicitly leave Matches unmodified if there isn't a clear best | |||
11150 | // option, so we can potentially give the user a better error | |||
11151 | if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) | |||
11152 | return false; | |||
11153 | Matches[0] = *Best; | |||
11154 | Matches.resize(1); | |||
11155 | return true; | |||
11156 | } | |||
11157 | ||||
11158 | bool isTargetTypeAFunction() const { | |||
11159 | return TargetFunctionType->isFunctionType(); | |||
11160 | } | |||
11161 | ||||
11162 | // [ToType] [Return] | |||
11163 | ||||
11164 | // R (*)(A) --> R (A), IsNonStaticMemberFunction = false | |||
11165 | // R (&)(A) --> R (A), IsNonStaticMemberFunction = false | |||
11166 | // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true | |||
11167 | void inline ExtractUnqualifiedFunctionTypeFromTargetType() { | |||
11168 | TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); | |||
11169 | } | |||
11170 | ||||
11171 | // return true if any matching specializations were found | |||
11172 | bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, | |||
11173 | const DeclAccessPair& CurAccessFunPair) { | |||
11174 | if (CXXMethodDecl *Method | |||
11175 | = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { | |||
11176 | // Skip non-static function templates when converting to pointer, and | |||
11177 | // static when converting to member pointer. | |||
11178 | if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) | |||
11179 | return false; | |||
11180 | } | |||
11181 | else if (TargetTypeIsNonStaticMemberFunction) | |||
11182 | return false; | |||
11183 | ||||
11184 | // C++ [over.over]p2: | |||
11185 | // If the name is a function template, template argument deduction is | |||
11186 | // done (14.8.2.2), and if the argument deduction succeeds, the | |||
11187 | // resulting template argument list is used to generate a single | |||
11188 | // function template specialization, which is added to the set of | |||
11189 | // overloaded functions considered. | |||
11190 | FunctionDecl *Specialization = nullptr; | |||
11191 | TemplateDeductionInfo Info(FailedCandidates.getLocation()); | |||
11192 | if (Sema::TemplateDeductionResult Result | |||
11193 | = S.DeduceTemplateArguments(FunctionTemplate, | |||
11194 | &OvlExplicitTemplateArgs, | |||
11195 | TargetFunctionType, Specialization, | |||
11196 | Info, /*IsAddressOfFunction*/true)) { | |||
11197 | // Make a note of the failed deduction for diagnostics. | |||
11198 | FailedCandidates.addCandidate() | |||
11199 | .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), | |||
11200 | MakeDeductionFailureInfo(Context, Result, Info)); | |||
11201 | return false; | |||
11202 | } | |||
11203 | ||||
11204 | // Template argument deduction ensures that we have an exact match or | |||
11205 | // compatible pointer-to-function arguments that would be adjusted by ICS. | |||
11206 | // This function template specicalization works. | |||
11207 | assert(S.isSameOrCompatibleFunctionType(((S.isSameOrCompatibleFunctionType( Context.getCanonicalType( Specialization->getType()), Context.getCanonicalType(TargetFunctionType ))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 11209, __PRETTY_FUNCTION__)) | |||
11208 | Context.getCanonicalType(Specialization->getType()),((S.isSameOrCompatibleFunctionType( Context.getCanonicalType( Specialization->getType()), Context.getCanonicalType(TargetFunctionType ))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 11209, __PRETTY_FUNCTION__)) | |||
11209 | Context.getCanonicalType(TargetFunctionType)))((S.isSameOrCompatibleFunctionType( Context.getCanonicalType( Specialization->getType()), Context.getCanonicalType(TargetFunctionType ))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 11209, __PRETTY_FUNCTION__)); | |||
11210 | ||||
11211 | if (!S.checkAddressOfFunctionIsAvailable(Specialization)) | |||
11212 | return false; | |||
11213 | ||||
11214 | Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); | |||
11215 | return true; | |||
11216 | } | |||
11217 | ||||
11218 | bool AddMatchingNonTemplateFunction(NamedDecl* Fn, | |||
11219 | const DeclAccessPair& CurAccessFunPair) { | |||
11220 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { | |||
11221 | // Skip non-static functions when converting to pointer, and static | |||
11222 | // when converting to member pointer. | |||
11223 | if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) | |||
11224 | return false; | |||
11225 | } | |||
11226 | else if (TargetTypeIsNonStaticMemberFunction) | |||
11227 | return false; | |||
11228 | ||||
11229 | if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { | |||
11230 | if (S.getLangOpts().CUDA) | |||
11231 | if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) | |||
11232 | if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) | |||
11233 | return false; | |||
11234 | if (FunDecl->isMultiVersion()) { | |||
11235 | const auto *TA = FunDecl->getAttr<TargetAttr>(); | |||
11236 | if (TA && !TA->isDefaultVersion()) | |||
11237 | return false; | |||
11238 | } | |||
11239 | ||||
11240 | // If any candidate has a placeholder return type, trigger its deduction | |||
11241 | // now. | |||
11242 | if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), | |||
11243 | Complain)) { | |||
11244 | HasComplained |= Complain; | |||
11245 | return false; | |||
11246 | } | |||
11247 | ||||
11248 | if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) | |||
11249 | return false; | |||
11250 | ||||
11251 | // If we're in C, we need to support types that aren't exactly identical. | |||
11252 | if (!S.getLangOpts().CPlusPlus || | |||
11253 | candidateHasExactlyCorrectType(FunDecl)) { | |||
11254 | Matches.push_back(std::make_pair( | |||
11255 | CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); | |||
11256 | FoundNonTemplateFunction = true; | |||
11257 | return true; | |||
11258 | } | |||
11259 | } | |||
11260 | ||||
11261 | return false; | |||
11262 | } | |||
11263 | ||||
11264 | bool FindAllFunctionsThatMatchTargetTypeExactly() { | |||
11265 | bool Ret = false; | |||
11266 | ||||
11267 | // If the overload expression doesn't have the form of a pointer to | |||
11268 | // member, don't try to convert it to a pointer-to-member type. | |||
11269 | if (IsInvalidFormOfPointerToMemberFunction()) | |||
11270 | return false; | |||
11271 | ||||
11272 | for (UnresolvedSetIterator I = OvlExpr->decls_begin(), | |||
11273 | E = OvlExpr->decls_end(); | |||
11274 | I != E; ++I) { | |||
11275 | // Look through any using declarations to find the underlying function. | |||
11276 | NamedDecl *Fn = (*I)->getUnderlyingDecl(); | |||
11277 | ||||
11278 | // C++ [over.over]p3: | |||
11279 | // Non-member functions and static member functions match | |||
11280 | // targets of type "pointer-to-function" or "reference-to-function." | |||
11281 | // Nonstatic member functions match targets of | |||
11282 | // type "pointer-to-member-function." | |||
11283 | // Note that according to DR 247, the containing class does not matter. | |||
11284 | if (FunctionTemplateDecl *FunctionTemplate | |||
11285 | = dyn_cast<FunctionTemplateDecl>(Fn)) { | |||
11286 | if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) | |||
11287 | Ret = true; | |||
11288 | } | |||
11289 | // If we have explicit template arguments supplied, skip non-templates. | |||
11290 | else if (!OvlExpr->hasExplicitTemplateArgs() && | |||
11291 | AddMatchingNonTemplateFunction(Fn, I.getPair())) | |||
11292 | Ret = true; | |||
11293 | } | |||
11294 | assert(Ret || Matches.empty())((Ret || Matches.empty()) ? static_cast<void> (0) : __assert_fail ("Ret || Matches.empty()", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 11294, __PRETTY_FUNCTION__)); | |||
11295 | return Ret; | |||
11296 | } | |||
11297 | ||||
11298 | void EliminateAllExceptMostSpecializedTemplate() { | |||
11299 | // [...] and any given function template specialization F1 is | |||
11300 | // eliminated if the set contains a second function template | |||
11301 | // specialization whose function template is more specialized | |||
11302 | // than the function template of F1 according to the partial | |||
11303 | // ordering rules of 14.5.5.2. | |||
11304 | ||||
11305 | // The algorithm specified above is quadratic. We instead use a | |||
11306 | // two-pass algorithm (similar to the one used to identify the | |||
11307 | // best viable function in an overload set) that identifies the | |||
11308 | // best function template (if it exists). | |||
11309 | ||||
11310 | UnresolvedSet<4> MatchesCopy; // TODO: avoid! | |||
11311 | for (unsigned I = 0, E = Matches.size(); I != E; ++I) | |||
11312 | MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); | |||
11313 | ||||
11314 | // TODO: It looks like FailedCandidates does not serve much purpose | |||
11315 | // here, since the no_viable diagnostic has index 0. | |||
11316 | UnresolvedSetIterator Result = S.getMostSpecialized( | |||
11317 | MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, | |||
11318 | SourceExpr->getBeginLoc(), S.PDiag(), | |||
11319 | S.PDiag(diag::err_addr_ovl_ambiguous) | |||
11320 | << Matches[0].second->getDeclName(), | |||
11321 | S.PDiag(diag::note_ovl_candidate) | |||
11322 | << (unsigned)oc_function << (unsigned)ocs_described_template, | |||
11323 | Complain, TargetFunctionType); | |||
11324 | ||||
11325 | if (Result != MatchesCopy.end()) { | |||
11326 | // Make it the first and only element | |||
11327 | Matches[0].first = Matches[Result - MatchesCopy.begin()].first; | |||
11328 | Matches[0].second = cast<FunctionDecl>(*Result); | |||
11329 | Matches.resize(1); | |||
11330 | } else | |||
11331 | HasComplained |= Complain; | |||
11332 | } | |||
11333 | ||||
11334 | void EliminateAllTemplateMatches() { | |||
11335 | // [...] any function template specializations in the set are | |||
11336 | // eliminated if the set also contains a non-template function, [...] | |||
11337 | for (unsigned I = 0, N = Matches.size(); I != N; ) { | |||
11338 | if (Matches[I].second->getPrimaryTemplate() == nullptr) | |||
11339 | ++I; | |||
11340 | else { | |||
11341 | Matches[I] = Matches[--N]; | |||
11342 | Matches.resize(N); | |||
11343 | } | |||
11344 | } | |||
11345 | } | |||
11346 | ||||
11347 | void EliminateSuboptimalCudaMatches() { | |||
11348 | S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); | |||
11349 | } | |||
11350 | ||||
11351 | public: | |||
11352 | void ComplainNoMatchesFound() const { | |||
11353 | assert(Matches.empty())((Matches.empty()) ? static_cast<void> (0) : __assert_fail ("Matches.empty()", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 11353, __PRETTY_FUNCTION__)); | |||
11354 | S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) | |||
11355 | << OvlExpr->getName() << TargetFunctionType | |||
11356 | << OvlExpr->getSourceRange(); | |||
11357 | if (FailedCandidates.empty()) | |||
11358 | S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, | |||
11359 | /*TakingAddress=*/true); | |||
11360 | else { | |||
11361 | // We have some deduction failure messages. Use them to diagnose | |||
11362 | // the function templates, and diagnose the non-template candidates | |||
11363 | // normally. | |||
11364 | for (UnresolvedSetIterator I = OvlExpr->decls_begin(), | |||
11365 | IEnd = OvlExpr->decls_end(); | |||
11366 | I != IEnd; ++I) | |||
11367 | if (FunctionDecl *Fun = | |||
11368 | dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) | |||
11369 | if (!functionHasPassObjectSizeParams(Fun)) | |||
11370 | S.NoteOverloadCandidate(*I, Fun, TargetFunctionType, | |||
11371 | /*TakingAddress=*/true); | |||
11372 | FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); | |||
11373 | } | |||
11374 | } | |||
11375 | ||||
11376 | bool IsInvalidFormOfPointerToMemberFunction() const { | |||
11377 | return TargetTypeIsNonStaticMemberFunction && | |||
11378 | !OvlExprInfo.HasFormOfMemberPointer; | |||
11379 | } | |||
11380 | ||||
11381 | void ComplainIsInvalidFormOfPointerToMemberFunction() const { | |||
11382 | // TODO: Should we condition this on whether any functions might | |||
11383 | // have matched, or is it more appropriate to do that in callers? | |||
11384 | // TODO: a fixit wouldn't hurt. | |||
11385 | S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) | |||
11386 | << TargetType << OvlExpr->getSourceRange(); | |||
11387 | } | |||
11388 | ||||
11389 | bool IsStaticMemberFunctionFromBoundPointer() const { | |||
11390 | return StaticMemberFunctionFromBoundPointer; | |||
11391 | } | |||
11392 | ||||
11393 | void ComplainIsStaticMemberFunctionFromBoundPointer() const { | |||
11394 | S.Diag(OvlExpr->getBeginLoc(), | |||
11395 | diag::err_invalid_form_pointer_member_function) | |||
11396 | << OvlExpr->getSourceRange(); | |||
11397 | } | |||
11398 | ||||
11399 | void ComplainOfInvalidConversion() const { | |||
11400 | S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) | |||
11401 | << OvlExpr->getName() << TargetType; | |||
11402 | } | |||
11403 | ||||
11404 | void ComplainMultipleMatchesFound() const { | |||
11405 | assert(Matches.size() > 1)((Matches.size() > 1) ? static_cast<void> (0) : __assert_fail ("Matches.size() > 1", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 11405, __PRETTY_FUNCTION__)); | |||
11406 | S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) | |||
11407 | << OvlExpr->getName() << OvlExpr->getSourceRange(); | |||
11408 | S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, | |||
11409 | /*TakingAddress=*/true); | |||
11410 | } | |||
11411 | ||||
11412 | bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } | |||
11413 | ||||
11414 | int getNumMatches() const { return Matches.size(); } | |||
11415 | ||||
11416 | FunctionDecl* getMatchingFunctionDecl() const { | |||
11417 | if (Matches.size() != 1) return nullptr; | |||
11418 | return Matches[0].second; | |||
11419 | } | |||
11420 | ||||
11421 | const DeclAccessPair* getMatchingFunctionAccessPair() const { | |||
11422 | if (Matches.size() != 1) return nullptr; | |||
11423 | return &Matches[0].first; | |||
11424 | } | |||
11425 | }; | |||
11426 | } | |||
11427 | ||||
11428 | /// ResolveAddressOfOverloadedFunction - Try to resolve the address of | |||
11429 | /// an overloaded function (C++ [over.over]), where @p From is an | |||
11430 | /// expression with overloaded function type and @p ToType is the type | |||
11431 | /// we're trying to resolve to. For example: | |||
11432 | /// | |||
11433 | /// @code | |||
11434 | /// int f(double); | |||
11435 | /// int f(int); | |||
11436 | /// | |||
11437 | /// int (*pfd)(double) = f; // selects f(double) | |||
11438 | /// @endcode | |||
11439 | /// | |||
11440 | /// This routine returns the resulting FunctionDecl if it could be | |||
11441 | /// resolved, and NULL otherwise. When @p Complain is true, this | |||
11442 | /// routine will emit diagnostics if there is an error. | |||
11443 | FunctionDecl * | |||
11444 | Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, | |||
11445 | QualType TargetType, | |||
11446 | bool Complain, | |||
11447 | DeclAccessPair &FoundResult, | |||
11448 | bool *pHadMultipleCandidates) { | |||
11449 | assert(AddressOfExpr->getType() == Context.OverloadTy)((AddressOfExpr->getType() == Context.OverloadTy) ? static_cast <void> (0) : __assert_fail ("AddressOfExpr->getType() == Context.OverloadTy" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 11449, __PRETTY_FUNCTION__)); | |||
11450 | ||||
11451 | AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, | |||
11452 | Complain); | |||
11453 | int NumMatches = Resolver.getNumMatches(); | |||
11454 | FunctionDecl *Fn = nullptr; | |||
11455 | bool ShouldComplain = Complain && !Resolver.hasComplained(); | |||
11456 | if (NumMatches == 0 && ShouldComplain) { | |||
11457 | if (Resolver.IsInvalidFormOfPointerToMemberFunction()) | |||
11458 | Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); | |||
11459 | else | |||
11460 | Resolver.ComplainNoMatchesFound(); | |||
11461 | } | |||
11462 | else if (NumMatches > 1 && ShouldComplain) | |||
11463 | Resolver.ComplainMultipleMatchesFound(); | |||
11464 | else if (NumMatches == 1) { | |||
11465 | Fn = Resolver.getMatchingFunctionDecl(); | |||
11466 | assert(Fn)((Fn) ? static_cast<void> (0) : __assert_fail ("Fn", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 11466, __PRETTY_FUNCTION__)); | |||
11467 | if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) | |||
11468 | ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); | |||
11469 | FoundResult = *Resolver.getMatchingFunctionAccessPair(); | |||
11470 | if (Complain) { | |||
11471 | if (Resolver.IsStaticMemberFunctionFromBoundPointer()) | |||
11472 | Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); | |||
11473 | else | |||
11474 | CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); | |||
11475 | } | |||
11476 | } | |||
11477 | ||||
11478 | if (pHadMultipleCandidates) | |||
11479 | *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); | |||
11480 | return Fn; | |||
11481 | } | |||
11482 | ||||
11483 | /// Given an expression that refers to an overloaded function, try to | |||
11484 | /// resolve that function to a single function that can have its address taken. | |||
11485 | /// This will modify `Pair` iff it returns non-null. | |||
11486 | /// | |||
11487 | /// This routine can only realistically succeed if all but one candidates in the | |||
11488 | /// overload set for SrcExpr cannot have their addresses taken. | |||
11489 | FunctionDecl * | |||
11490 | Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, | |||
11491 | DeclAccessPair &Pair) { | |||
11492 | OverloadExpr::FindResult R = OverloadExpr::find(E); | |||
11493 | OverloadExpr *Ovl = R.Expression; | |||
11494 | FunctionDecl *Result = nullptr; | |||
11495 | DeclAccessPair DAP; | |||
11496 | // Don't use the AddressOfResolver because we're specifically looking for | |||
11497 | // cases where we have one overload candidate that lacks | |||
11498 | // enable_if/pass_object_size/... | |||
11499 | for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { | |||
11500 | auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); | |||
11501 | if (!FD) | |||
11502 | return nullptr; | |||
11503 | ||||
11504 | if (!checkAddressOfFunctionIsAvailable(FD)) | |||
11505 | continue; | |||
11506 | ||||
11507 | // We have more than one result; quit. | |||
11508 | if (Result) | |||
11509 | return nullptr; | |||
11510 | DAP = I.getPair(); | |||
11511 | Result = FD; | |||
11512 | } | |||
11513 | ||||
11514 | if (Result) | |||
11515 | Pair = DAP; | |||
11516 | return Result; | |||
11517 | } | |||
11518 | ||||
11519 | /// Given an overloaded function, tries to turn it into a non-overloaded | |||
11520 | /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This | |||
11521 | /// will perform access checks, diagnose the use of the resultant decl, and, if | |||
11522 | /// requested, potentially perform a function-to-pointer decay. | |||
11523 | /// | |||
11524 | /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. | |||
11525 | /// Otherwise, returns true. This may emit diagnostics and return true. | |||
11526 | bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( | |||
11527 | ExprResult &SrcExpr, bool DoFunctionPointerConverion) { | |||
11528 | Expr *E = SrcExpr.get(); | |||
11529 | assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload")((E->getType() == Context.OverloadTy && "SrcExpr must be an overload" ) ? static_cast<void> (0) : __assert_fail ("E->getType() == Context.OverloadTy && \"SrcExpr must be an overload\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 11529, __PRETTY_FUNCTION__)); | |||
11530 | ||||
11531 | DeclAccessPair DAP; | |||
11532 | FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); | |||
11533 | if (!Found || Found->isCPUDispatchMultiVersion() || | |||
11534 | Found->isCPUSpecificMultiVersion()) | |||
11535 | return false; | |||
11536 | ||||
11537 | // Emitting multiple diagnostics for a function that is both inaccessible and | |||
11538 | // unavailable is consistent with our behavior elsewhere. So, always check | |||
11539 | // for both. | |||
11540 | DiagnoseUseOfDecl(Found, E->getExprLoc()); | |||
11541 | CheckAddressOfMemberAccess(E, DAP); | |||
11542 | Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); | |||
11543 | if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) | |||
11544 | SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); | |||
11545 | else | |||
11546 | SrcExpr = Fixed; | |||
11547 | return true; | |||
11548 | } | |||
11549 | ||||
11550 | /// Given an expression that refers to an overloaded function, try to | |||
11551 | /// resolve that overloaded function expression down to a single function. | |||
11552 | /// | |||
11553 | /// This routine can only resolve template-ids that refer to a single function | |||
11554 | /// template, where that template-id refers to a single template whose template | |||
11555 | /// arguments are either provided by the template-id or have defaults, | |||
11556 | /// as described in C++0x [temp.arg.explicit]p3. | |||
11557 | /// | |||
11558 | /// If no template-ids are found, no diagnostics are emitted and NULL is | |||
11559 | /// returned. | |||
11560 | FunctionDecl * | |||
11561 | Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, | |||
11562 | bool Complain, | |||
11563 | DeclAccessPair *FoundResult) { | |||
11564 | // C++ [over.over]p1: | |||
11565 | // [...] [Note: any redundant set of parentheses surrounding the | |||
11566 | // overloaded function name is ignored (5.1). ] | |||
11567 | // C++ [over.over]p1: | |||
11568 | // [...] The overloaded function name can be preceded by the & | |||
11569 | // operator. | |||
11570 | ||||
11571 | // If we didn't actually find any template-ids, we're done. | |||
11572 | if (!ovl->hasExplicitTemplateArgs()) | |||
11573 | return nullptr; | |||
11574 | ||||
11575 | TemplateArgumentListInfo ExplicitTemplateArgs; | |||
11576 | ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); | |||
11577 | TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); | |||
11578 | ||||
11579 | // Look through all of the overloaded functions, searching for one | |||
11580 | // whose type matches exactly. | |||
11581 | FunctionDecl *Matched = nullptr; | |||
11582 | for (UnresolvedSetIterator I = ovl->decls_begin(), | |||
11583 | E = ovl->decls_end(); I != E; ++I) { | |||
11584 | // C++0x [temp.arg.explicit]p3: | |||
11585 | // [...] In contexts where deduction is done and fails, or in contexts | |||
11586 | // where deduction is not done, if a template argument list is | |||
11587 | // specified and it, along with any default template arguments, | |||
11588 | // identifies a single function template specialization, then the | |||
11589 | // template-id is an lvalue for the function template specialization. | |||
11590 | FunctionTemplateDecl *FunctionTemplate | |||
11591 | = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); | |||
11592 | ||||
11593 | // C++ [over.over]p2: | |||
11594 | // If the name is a function template, template argument deduction is | |||
11595 | // done (14.8.2.2), and if the argument deduction succeeds, the | |||
11596 | // resulting template argument list is used to generate a single | |||
11597 | // function template specialization, which is added to the set of | |||
11598 | // overloaded functions considered. | |||
11599 | FunctionDecl *Specialization = nullptr; | |||
11600 | TemplateDeductionInfo Info(FailedCandidates.getLocation()); | |||
11601 | if (TemplateDeductionResult Result | |||
11602 | = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, | |||
11603 | Specialization, Info, | |||
11604 | /*IsAddressOfFunction*/true)) { | |||
11605 | // Make a note of the failed deduction for diagnostics. | |||
11606 | // TODO: Actually use the failed-deduction info? | |||
11607 | FailedCandidates.addCandidate() | |||
11608 | .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), | |||
11609 | MakeDeductionFailureInfo(Context, Result, Info)); | |||
11610 | continue; | |||
11611 | } | |||
11612 | ||||
11613 | assert(Specialization && "no specialization and no error?")((Specialization && "no specialization and no error?" ) ? static_cast<void> (0) : __assert_fail ("Specialization && \"no specialization and no error?\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 11613, __PRETTY_FUNCTION__)); | |||
11614 | ||||
11615 | // Multiple matches; we can't resolve to a single declaration. | |||
11616 | if (Matched) { | |||
11617 | if (Complain) { | |||
11618 | Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) | |||
11619 | << ovl->getName(); | |||
11620 | NoteAllOverloadCandidates(ovl); | |||
11621 | } | |||
11622 | return nullptr; | |||
11623 | } | |||
11624 | ||||
11625 | Matched = Specialization; | |||
11626 | if (FoundResult) *FoundResult = I.getPair(); | |||
11627 | } | |||
11628 | ||||
11629 | if (Matched && | |||
11630 | completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) | |||
11631 | return nullptr; | |||
11632 | ||||
11633 | return Matched; | |||
11634 | } | |||
11635 | ||||
11636 | // Resolve and fix an overloaded expression that can be resolved | |||
11637 | // because it identifies a single function template specialization. | |||
11638 | // | |||
11639 | // Last three arguments should only be supplied if Complain = true | |||
11640 | // | |||
11641 | // Return true if it was logically possible to so resolve the | |||
11642 | // expression, regardless of whether or not it succeeded. Always | |||
11643 | // returns true if 'complain' is set. | |||
11644 | bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( | |||
11645 | ExprResult &SrcExpr, bool doFunctionPointerConverion, | |||
11646 | bool complain, SourceRange OpRangeForComplaining, | |||
11647 | QualType DestTypeForComplaining, | |||
11648 | unsigned DiagIDForComplaining) { | |||
11649 | assert(SrcExpr.get()->getType() == Context.OverloadTy)((SrcExpr.get()->getType() == Context.OverloadTy) ? static_cast <void> (0) : __assert_fail ("SrcExpr.get()->getType() == Context.OverloadTy" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 11649, __PRETTY_FUNCTION__)); | |||
11650 | ||||
11651 | OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); | |||
11652 | ||||
11653 | DeclAccessPair found; | |||
11654 | ExprResult SingleFunctionExpression; | |||
11655 | if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( | |||
11656 | ovl.Expression, /*complain*/ false, &found)) { | |||
11657 | if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { | |||
11658 | SrcExpr = ExprError(); | |||
11659 | return true; | |||
11660 | } | |||
11661 | ||||
11662 | // It is only correct to resolve to an instance method if we're | |||
11663 | // resolving a form that's permitted to be a pointer to member. | |||
11664 | // Otherwise we'll end up making a bound member expression, which | |||
11665 | // is illegal in all the contexts we resolve like this. | |||
11666 | if (!ovl.HasFormOfMemberPointer && | |||
11667 | isa<CXXMethodDecl>(fn) && | |||
11668 | cast<CXXMethodDecl>(fn)->isInstance()) { | |||
11669 | if (!complain) return false; | |||
11670 | ||||
11671 | Diag(ovl.Expression->getExprLoc(), | |||
11672 | diag::err_bound_member_function) | |||
11673 | << 0 << ovl.Expression->getSourceRange(); | |||
11674 | ||||
11675 | // TODO: I believe we only end up here if there's a mix of | |||
11676 | // static and non-static candidates (otherwise the expression | |||
11677 | // would have 'bound member' type, not 'overload' type). | |||
11678 | // Ideally we would note which candidate was chosen and why | |||
11679 | // the static candidates were rejected. | |||
11680 | SrcExpr = ExprError(); | |||
11681 | return true; | |||
11682 | } | |||
11683 | ||||
11684 | // Fix the expression to refer to 'fn'. | |||
11685 | SingleFunctionExpression = | |||
11686 | FixOverloadedFunctionReference(SrcExpr.get(), found, fn); | |||
11687 | ||||
11688 | // If desired, do function-to-pointer decay. | |||
11689 | if (doFunctionPointerConverion) { | |||
11690 | SingleFunctionExpression = | |||
11691 | DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); | |||
11692 | if (SingleFunctionExpression.isInvalid()) { | |||
11693 | SrcExpr = ExprError(); | |||
11694 | return true; | |||
11695 | } | |||
11696 | } | |||
11697 | } | |||
11698 | ||||
11699 | if (!SingleFunctionExpression.isUsable()) { | |||
11700 | if (complain) { | |||
11701 | Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) | |||
11702 | << ovl.Expression->getName() | |||
11703 | << DestTypeForComplaining | |||
11704 | << OpRangeForComplaining | |||
11705 | << ovl.Expression->getQualifierLoc().getSourceRange(); | |||
11706 | NoteAllOverloadCandidates(SrcExpr.get()); | |||
11707 | ||||
11708 | SrcExpr = ExprError(); | |||
11709 | return true; | |||
11710 | } | |||
11711 | ||||
11712 | return false; | |||
11713 | } | |||
11714 | ||||
11715 | SrcExpr = SingleFunctionExpression; | |||
11716 | return true; | |||
11717 | } | |||
11718 | ||||
11719 | /// Add a single candidate to the overload set. | |||
11720 | static void AddOverloadedCallCandidate(Sema &S, | |||
11721 | DeclAccessPair FoundDecl, | |||
11722 | TemplateArgumentListInfo *ExplicitTemplateArgs, | |||
11723 | ArrayRef<Expr *> Args, | |||
11724 | OverloadCandidateSet &CandidateSet, | |||
11725 | bool PartialOverloading, | |||
11726 | bool KnownValid) { | |||
11727 | NamedDecl *Callee = FoundDecl.getDecl(); | |||
11728 | if (isa<UsingShadowDecl>(Callee)) | |||
11729 | Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); | |||
11730 | ||||
11731 | if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { | |||
11732 | if (ExplicitTemplateArgs) { | |||
11733 | assert(!KnownValid && "Explicit template arguments?")((!KnownValid && "Explicit template arguments?") ? static_cast <void> (0) : __assert_fail ("!KnownValid && \"Explicit template arguments?\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 11733, __PRETTY_FUNCTION__)); | |||
11734 | return; | |||
11735 | } | |||
11736 | // Prevent ill-formed function decls to be added as overload candidates. | |||
11737 | if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) | |||
11738 | return; | |||
11739 | ||||
11740 | S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, | |||
11741 | /*SuppressUsedConversions=*/false, | |||
11742 | PartialOverloading); | |||
11743 | return; | |||
11744 | } | |||
11745 | ||||
11746 | if (FunctionTemplateDecl *FuncTemplate | |||
11747 | = dyn_cast<FunctionTemplateDecl>(Callee)) { | |||
11748 | S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, | |||
11749 | ExplicitTemplateArgs, Args, CandidateSet, | |||
11750 | /*SuppressUsedConversions=*/false, | |||
11751 | PartialOverloading); | |||
11752 | return; | |||
11753 | } | |||
11754 | ||||
11755 | assert(!KnownValid && "unhandled case in overloaded call candidate")((!KnownValid && "unhandled case in overloaded call candidate" ) ? static_cast<void> (0) : __assert_fail ("!KnownValid && \"unhandled case in overloaded call candidate\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 11755, __PRETTY_FUNCTION__)); | |||
11756 | } | |||
11757 | ||||
11758 | /// Add the overload candidates named by callee and/or found by argument | |||
11759 | /// dependent lookup to the given overload set. | |||
11760 | void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, | |||
11761 | ArrayRef<Expr *> Args, | |||
11762 | OverloadCandidateSet &CandidateSet, | |||
11763 | bool PartialOverloading) { | |||
11764 | ||||
11765 | #ifndef NDEBUG | |||
11766 | // Verify that ArgumentDependentLookup is consistent with the rules | |||
11767 | // in C++0x [basic.lookup.argdep]p3: | |||
11768 | // | |||
11769 | // Let X be the lookup set produced by unqualified lookup (3.4.1) | |||
11770 | // and let Y be the lookup set produced by argument dependent | |||
11771 | // lookup (defined as follows). If X contains | |||
11772 | // | |||
11773 | // -- a declaration of a class member, or | |||
11774 | // | |||
11775 | // -- a block-scope function declaration that is not a | |||
11776 | // using-declaration, or | |||
11777 | // | |||
11778 | // -- a declaration that is neither a function or a function | |||
11779 | // template | |||
11780 | // | |||
11781 | // then Y is empty. | |||
11782 | ||||
11783 | if (ULE->requiresADL()) { | |||
11784 | for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), | |||
11785 | E = ULE->decls_end(); I != E; ++I) { | |||
11786 | assert(!(*I)->getDeclContext()->isRecord())((!(*I)->getDeclContext()->isRecord()) ? static_cast< void> (0) : __assert_fail ("!(*I)->getDeclContext()->isRecord()" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 11786, __PRETTY_FUNCTION__)); | |||
11787 | assert(isa<UsingShadowDecl>(*I) ||((isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext( )->isFunctionOrMethod()) ? static_cast<void> (0) : __assert_fail ("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 11788, __PRETTY_FUNCTION__)) | |||
11788 | !(*I)->getDeclContext()->isFunctionOrMethod())((isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext( )->isFunctionOrMethod()) ? static_cast<void> (0) : __assert_fail ("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 11788, __PRETTY_FUNCTION__)); | |||
11789 | assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate())(((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate ()) ? static_cast<void> (0) : __assert_fail ("(*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 11789, __PRETTY_FUNCTION__)); | |||
11790 | } | |||
11791 | } | |||
11792 | #endif | |||
11793 | ||||
11794 | // It would be nice to avoid this copy. | |||
11795 | TemplateArgumentListInfo TABuffer; | |||
11796 | TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; | |||
11797 | if (ULE->hasExplicitTemplateArgs()) { | |||
11798 | ULE->copyTemplateArgumentsInto(TABuffer); | |||
11799 | ExplicitTemplateArgs = &TABuffer; | |||
11800 | } | |||
11801 | ||||
11802 | for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), | |||
11803 | E = ULE->decls_end(); I != E; ++I) | |||
11804 | AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, | |||
11805 | CandidateSet, PartialOverloading, | |||
11806 | /*KnownValid*/ true); | |||
11807 | ||||
11808 | if (ULE->requiresADL()) | |||
11809 | AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), | |||
11810 | Args, ExplicitTemplateArgs, | |||
11811 | CandidateSet, PartialOverloading); | |||
11812 | } | |||
11813 | ||||
11814 | /// Determine whether a declaration with the specified name could be moved into | |||
11815 | /// a different namespace. | |||
11816 | static bool canBeDeclaredInNamespace(const DeclarationName &Name) { | |||
11817 | switch (Name.getCXXOverloadedOperator()) { | |||
11818 | case OO_New: case OO_Array_New: | |||
11819 | case OO_Delete: case OO_Array_Delete: | |||
11820 | return false; | |||
11821 | ||||
11822 | default: | |||
11823 | return true; | |||
11824 | } | |||
11825 | } | |||
11826 | ||||
11827 | /// Attempt to recover from an ill-formed use of a non-dependent name in a | |||
11828 | /// template, where the non-dependent name was declared after the template | |||
11829 | /// was defined. This is common in code written for a compilers which do not | |||
11830 | /// correctly implement two-stage name lookup. | |||
11831 | /// | |||
11832 | /// Returns true if a viable candidate was found and a diagnostic was issued. | |||
11833 | static bool | |||
11834 | DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, | |||
11835 | const CXXScopeSpec &SS, LookupResult &R, | |||
11836 | OverloadCandidateSet::CandidateSetKind CSK, | |||
11837 | TemplateArgumentListInfo *ExplicitTemplateArgs, | |||
11838 | ArrayRef<Expr *> Args, | |||
11839 | bool *DoDiagnoseEmptyLookup = nullptr) { | |||
11840 | if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) | |||
11841 | return false; | |||
11842 | ||||
11843 | for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { | |||
11844 | if (DC->isTransparentContext()) | |||
11845 | continue; | |||
11846 | ||||
11847 | SemaRef.LookupQualifiedName(R, DC); | |||
11848 | ||||
11849 | if (!R.empty()) { | |||
11850 | R.suppressDiagnostics(); | |||
11851 | ||||
11852 | if (isa<CXXRecordDecl>(DC)) { | |||
11853 | // Don't diagnose names we find in classes; we get much better | |||
11854 | // diagnostics for these from DiagnoseEmptyLookup. | |||
11855 | R.clear(); | |||
11856 | if (DoDiagnoseEmptyLookup) | |||
11857 | *DoDiagnoseEmptyLookup = true; | |||
11858 | return false; | |||
11859 | } | |||
11860 | ||||
11861 | OverloadCandidateSet Candidates(FnLoc, CSK); | |||
11862 | for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) | |||
11863 | AddOverloadedCallCandidate(SemaRef, I.getPair(), | |||
11864 | ExplicitTemplateArgs, Args, | |||
11865 | Candidates, false, /*KnownValid*/ false); | |||
11866 | ||||
11867 | OverloadCandidateSet::iterator Best; | |||
11868 | if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { | |||
11869 | // No viable functions. Don't bother the user with notes for functions | |||
11870 | // which don't work and shouldn't be found anyway. | |||
11871 | R.clear(); | |||
11872 | return false; | |||
11873 | } | |||
11874 | ||||
11875 | // Find the namespaces where ADL would have looked, and suggest | |||
11876 | // declaring the function there instead. | |||
11877 | Sema::AssociatedNamespaceSet AssociatedNamespaces; | |||
11878 | Sema::AssociatedClassSet AssociatedClasses; | |||
11879 | SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, | |||
11880 | AssociatedNamespaces, | |||
11881 | AssociatedClasses); | |||
11882 | Sema::AssociatedNamespaceSet SuggestedNamespaces; | |||
11883 | if (canBeDeclaredInNamespace(R.getLookupName())) { | |||
11884 | DeclContext *Std = SemaRef.getStdNamespace(); | |||
11885 | for (Sema::AssociatedNamespaceSet::iterator | |||
11886 | it = AssociatedNamespaces.begin(), | |||
11887 | end = AssociatedNamespaces.end(); it != end; ++it) { | |||
11888 | // Never suggest declaring a function within namespace 'std'. | |||
11889 | if (Std && Std->Encloses(*it)) | |||
11890 | continue; | |||
11891 | ||||
11892 | // Never suggest declaring a function within a namespace with a | |||
11893 | // reserved name, like __gnu_cxx. | |||
11894 | NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); | |||
11895 | if (NS && | |||
11896 | NS->getQualifiedNameAsString().find("__") != std::string::npos) | |||
11897 | continue; | |||
11898 | ||||
11899 | SuggestedNamespaces.insert(*it); | |||
11900 | } | |||
11901 | } | |||
11902 | ||||
11903 | SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) | |||
11904 | << R.getLookupName(); | |||
11905 | if (SuggestedNamespaces.empty()) { | |||
11906 | SemaRef.Diag(Best->Function->getLocation(), | |||
11907 | diag::note_not_found_by_two_phase_lookup) | |||
11908 | << R.getLookupName() << 0; | |||
11909 | } else if (SuggestedNamespaces.size() == 1) { | |||
11910 | SemaRef.Diag(Best->Function->getLocation(), | |||
11911 | diag::note_not_found_by_two_phase_lookup) | |||
11912 | << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); | |||
11913 | } else { | |||
11914 | // FIXME: It would be useful to list the associated namespaces here, | |||
11915 | // but the diagnostics infrastructure doesn't provide a way to produce | |||
11916 | // a localized representation of a list of items. | |||
11917 | SemaRef.Diag(Best->Function->getLocation(), | |||
11918 | diag::note_not_found_by_two_phase_lookup) | |||
11919 | << R.getLookupName() << 2; | |||
11920 | } | |||
11921 | ||||
11922 | // Try to recover by calling this function. | |||
11923 | return true; | |||
11924 | } | |||
11925 | ||||
11926 | R.clear(); | |||
11927 | } | |||
11928 | ||||
11929 | return false; | |||
11930 | } | |||
11931 | ||||
11932 | /// Attempt to recover from ill-formed use of a non-dependent operator in a | |||
11933 | /// template, where the non-dependent operator was declared after the template | |||
11934 | /// was defined. | |||
11935 | /// | |||
11936 | /// Returns true if a viable candidate was found and a diagnostic was issued. | |||
11937 | static bool | |||
11938 | DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, | |||
11939 | SourceLocation OpLoc, | |||
11940 | ArrayRef<Expr *> Args) { | |||
11941 | DeclarationName OpName = | |||
11942 | SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); | |||
11943 | LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); | |||
11944 | return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, | |||
11945 | OverloadCandidateSet::CSK_Operator, | |||
11946 | /*ExplicitTemplateArgs=*/nullptr, Args); | |||
11947 | } | |||
11948 | ||||
11949 | namespace { | |||
11950 | class BuildRecoveryCallExprRAII { | |||
11951 | Sema &SemaRef; | |||
11952 | public: | |||
11953 | BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { | |||
11954 | assert(SemaRef.IsBuildingRecoveryCallExpr == false)((SemaRef.IsBuildingRecoveryCallExpr == false) ? static_cast< void> (0) : __assert_fail ("SemaRef.IsBuildingRecoveryCallExpr == false" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 11954, __PRETTY_FUNCTION__)); | |||
11955 | SemaRef.IsBuildingRecoveryCallExpr = true; | |||
11956 | } | |||
11957 | ||||
11958 | ~BuildRecoveryCallExprRAII() { | |||
11959 | SemaRef.IsBuildingRecoveryCallExpr = false; | |||
11960 | } | |||
11961 | }; | |||
11962 | ||||
11963 | } | |||
11964 | ||||
11965 | /// Attempts to recover from a call where no functions were found. | |||
11966 | /// | |||
11967 | /// Returns true if new candidates were found. | |||
11968 | static ExprResult | |||
11969 | BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, | |||
11970 | UnresolvedLookupExpr *ULE, | |||
11971 | SourceLocation LParenLoc, | |||
11972 | MutableArrayRef<Expr *> Args, | |||
11973 | SourceLocation RParenLoc, | |||
11974 | bool EmptyLookup, bool AllowTypoCorrection) { | |||
11975 | // Do not try to recover if it is already building a recovery call. | |||
11976 | // This stops infinite loops for template instantiations like | |||
11977 | // | |||
11978 | // template <typename T> auto foo(T t) -> decltype(foo(t)) {} | |||
11979 | // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} | |||
11980 | // | |||
11981 | if (SemaRef.IsBuildingRecoveryCallExpr) | |||
11982 | return ExprError(); | |||
11983 | BuildRecoveryCallExprRAII RCE(SemaRef); | |||
11984 | ||||
11985 | CXXScopeSpec SS; | |||
11986 | SS.Adopt(ULE->getQualifierLoc()); | |||
11987 | SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); | |||
11988 | ||||
11989 | TemplateArgumentListInfo TABuffer; | |||
11990 | TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; | |||
11991 | if (ULE->hasExplicitTemplateArgs()) { | |||
11992 | ULE->copyTemplateArgumentsInto(TABuffer); | |||
11993 | ExplicitTemplateArgs = &TABuffer; | |||
11994 | } | |||
11995 | ||||
11996 | LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), | |||
11997 | Sema::LookupOrdinaryName); | |||
11998 | bool DoDiagnoseEmptyLookup = EmptyLookup; | |||
11999 | if (!DiagnoseTwoPhaseLookup( | |||
12000 | SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal, | |||
12001 | ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) { | |||
12002 | NoTypoCorrectionCCC NoTypoValidator{}; | |||
12003 | FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), | |||
12004 | ExplicitTemplateArgs != nullptr, | |||
12005 | dyn_cast<MemberExpr>(Fn)); | |||
12006 | CorrectionCandidateCallback &Validator = | |||
12007 | AllowTypoCorrection | |||
12008 | ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) | |||
12009 | : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); | |||
12010 | if (!DoDiagnoseEmptyLookup || | |||
12011 | SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, | |||
12012 | Args)) | |||
12013 | return ExprError(); | |||
12014 | } | |||
12015 | ||||
12016 | assert(!R.empty() && "lookup results empty despite recovery")((!R.empty() && "lookup results empty despite recovery" ) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"lookup results empty despite recovery\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 12016, __PRETTY_FUNCTION__)); | |||
12017 | ||||
12018 | // If recovery created an ambiguity, just bail out. | |||
12019 | if (R.isAmbiguous()) { | |||
12020 | R.suppressDiagnostics(); | |||
12021 | return ExprError(); | |||
12022 | } | |||
12023 | ||||
12024 | // Build an implicit member call if appropriate. Just drop the | |||
12025 | // casts and such from the call, we don't really care. | |||
12026 | ExprResult NewFn = ExprError(); | |||
12027 | if ((*R.begin())->isCXXClassMember()) | |||
12028 | NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, | |||
12029 | ExplicitTemplateArgs, S); | |||
12030 | else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) | |||
12031 | NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, | |||
12032 | ExplicitTemplateArgs); | |||
12033 | else | |||
12034 | NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); | |||
12035 | ||||
12036 | if (NewFn.isInvalid()) | |||
12037 | return ExprError(); | |||
12038 | ||||
12039 | // This shouldn't cause an infinite loop because we're giving it | |||
12040 | // an expression with viable lookup results, which should never | |||
12041 | // end up here. | |||
12042 | return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, | |||
12043 | MultiExprArg(Args.data(), Args.size()), | |||
12044 | RParenLoc); | |||
12045 | } | |||
12046 | ||||
12047 | /// Constructs and populates an OverloadedCandidateSet from | |||
12048 | /// the given function. | |||
12049 | /// \returns true when an the ExprResult output parameter has been set. | |||
12050 | bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, | |||
12051 | UnresolvedLookupExpr *ULE, | |||
12052 | MultiExprArg Args, | |||
12053 | SourceLocation RParenLoc, | |||
12054 | OverloadCandidateSet *CandidateSet, | |||
12055 | ExprResult *Result) { | |||
12056 | #ifndef NDEBUG | |||
12057 | if (ULE->requiresADL()) { | |||
12058 | // To do ADL, we must have found an unqualified name. | |||
12059 | assert(!ULE->getQualifier() && "qualified name with ADL")((!ULE->getQualifier() && "qualified name with ADL" ) ? static_cast<void> (0) : __assert_fail ("!ULE->getQualifier() && \"qualified name with ADL\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 12059, __PRETTY_FUNCTION__)); | |||
12060 | ||||
12061 | // We don't perform ADL for implicit declarations of builtins. | |||
12062 | // Verify that this was correctly set up. | |||
12063 | FunctionDecl *F; | |||
12064 | if (ULE->decls_begin() != ULE->decls_end() && | |||
12065 | ULE->decls_begin() + 1 == ULE->decls_end() && | |||
12066 | (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && | |||
12067 | F->getBuiltinID() && F->isImplicit()) | |||
12068 | llvm_unreachable("performing ADL for builtin")::llvm::llvm_unreachable_internal("performing ADL for builtin" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 12068); | |||
12069 | ||||
12070 | // We don't perform ADL in C. | |||
12071 | assert(getLangOpts().CPlusPlus && "ADL enabled in C")((getLangOpts().CPlusPlus && "ADL enabled in C") ? static_cast <void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"ADL enabled in C\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 12071, __PRETTY_FUNCTION__)); | |||
12072 | } | |||
12073 | #endif | |||
12074 | ||||
12075 | UnbridgedCastsSet UnbridgedCasts; | |||
12076 | if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { | |||
12077 | *Result = ExprError(); | |||
12078 | return true; | |||
12079 | } | |||
12080 | ||||
12081 | // Add the functions denoted by the callee to the set of candidate | |||
12082 | // functions, including those from argument-dependent lookup. | |||
12083 | AddOverloadedCallCandidates(ULE, Args, *CandidateSet); | |||
12084 | ||||
12085 | if (getLangOpts().MSVCCompat && | |||
12086 | CurContext->isDependentContext() && !isSFINAEContext() && | |||
12087 | (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { | |||
12088 | ||||
12089 | OverloadCandidateSet::iterator Best; | |||
12090 | if (CandidateSet->empty() || | |||
12091 | CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == | |||
12092 | OR_No_Viable_Function) { | |||
12093 | // In Microsoft mode, if we are inside a template class member function | |||
12094 | // then create a type dependent CallExpr. The goal is to postpone name | |||
12095 | // lookup to instantiation time to be able to search into type dependent | |||
12096 | // base classes. | |||
12097 | CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy, | |||
12098 | VK_RValue, RParenLoc); | |||
12099 | CE->setTypeDependent(true); | |||
12100 | CE->setValueDependent(true); | |||
12101 | CE->setInstantiationDependent(true); | |||
12102 | *Result = CE; | |||
12103 | return true; | |||
12104 | } | |||
12105 | } | |||
12106 | ||||
12107 | if (CandidateSet->empty()) | |||
12108 | return false; | |||
12109 | ||||
12110 | UnbridgedCasts.restore(); | |||
12111 | return false; | |||
12112 | } | |||
12113 | ||||
12114 | /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns | |||
12115 | /// the completed call expression. If overload resolution fails, emits | |||
12116 | /// diagnostics and returns ExprError() | |||
12117 | static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, | |||
12118 | UnresolvedLookupExpr *ULE, | |||
12119 | SourceLocation LParenLoc, | |||
12120 | MultiExprArg Args, | |||
12121 | SourceLocation RParenLoc, | |||
12122 | Expr *ExecConfig, | |||
12123 | OverloadCandidateSet *CandidateSet, | |||
12124 | OverloadCandidateSet::iterator *Best, | |||
12125 | OverloadingResult OverloadResult, | |||
12126 | bool AllowTypoCorrection) { | |||
12127 | if (CandidateSet->empty()) | |||
12128 | return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, | |||
12129 | RParenLoc, /*EmptyLookup=*/true, | |||
12130 | AllowTypoCorrection); | |||
12131 | ||||
12132 | switch (OverloadResult) { | |||
12133 | case OR_Success: { | |||
12134 | FunctionDecl *FDecl = (*Best)->Function; | |||
12135 | SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); | |||
12136 | if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) | |||
12137 | return ExprError(); | |||
12138 | Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); | |||
12139 | return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, | |||
12140 | ExecConfig, /*IsExecConfig=*/false, | |||
12141 | (*Best)->IsADLCandidate); | |||
12142 | } | |||
12143 | ||||
12144 | case OR_No_Viable_Function: { | |||
12145 | // Try to recover by looking for viable functions which the user might | |||
12146 | // have meant to call. | |||
12147 | ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, | |||
12148 | Args, RParenLoc, | |||
12149 | /*EmptyLookup=*/false, | |||
12150 | AllowTypoCorrection); | |||
12151 | if (!Recovery.isInvalid()) | |||
12152 | return Recovery; | |||
12153 | ||||
12154 | // If the user passes in a function that we can't take the address of, we | |||
12155 | // generally end up emitting really bad error messages. Here, we attempt to | |||
12156 | // emit better ones. | |||
12157 | for (const Expr *Arg : Args) { | |||
12158 | if (!Arg->getType()->isFunctionType()) | |||
12159 | continue; | |||
12160 | if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { | |||
12161 | auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); | |||
12162 | if (FD && | |||
12163 | !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, | |||
12164 | Arg->getExprLoc())) | |||
12165 | return ExprError(); | |||
12166 | } | |||
12167 | } | |||
12168 | ||||
12169 | CandidateSet->NoteCandidates( | |||
12170 | PartialDiagnosticAt( | |||
12171 | Fn->getBeginLoc(), | |||
12172 | SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) | |||
12173 | << ULE->getName() << Fn->getSourceRange()), | |||
12174 | SemaRef, OCD_AllCandidates, Args); | |||
12175 | break; | |||
12176 | } | |||
12177 | ||||
12178 | case OR_Ambiguous: | |||
12179 | CandidateSet->NoteCandidates( | |||
12180 | PartialDiagnosticAt(Fn->getBeginLoc(), | |||
12181 | SemaRef.PDiag(diag::err_ovl_ambiguous_call) | |||
12182 | << ULE->getName() << Fn->getSourceRange()), | |||
12183 | SemaRef, OCD_ViableCandidates, Args); | |||
12184 | break; | |||
12185 | ||||
12186 | case OR_Deleted: { | |||
12187 | CandidateSet->NoteCandidates( | |||
12188 | PartialDiagnosticAt(Fn->getBeginLoc(), | |||
12189 | SemaRef.PDiag(diag::err_ovl_deleted_call) | |||
12190 | << ULE->getName() << Fn->getSourceRange()), | |||
12191 | SemaRef, OCD_AllCandidates, Args); | |||
12192 | ||||
12193 | // We emitted an error for the unavailable/deleted function call but keep | |||
12194 | // the call in the AST. | |||
12195 | FunctionDecl *FDecl = (*Best)->Function; | |||
12196 | Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); | |||
12197 | return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, | |||
12198 | ExecConfig, /*IsExecConfig=*/false, | |||
12199 | (*Best)->IsADLCandidate); | |||
12200 | } | |||
12201 | } | |||
12202 | ||||
12203 | // Overload resolution failed. | |||
12204 | return ExprError(); | |||
12205 | } | |||
12206 | ||||
12207 | static void markUnaddressableCandidatesUnviable(Sema &S, | |||
12208 | OverloadCandidateSet &CS) { | |||
12209 | for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { | |||
12210 | if (I->Viable && | |||
12211 | !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { | |||
12212 | I->Viable = false; | |||
12213 | I->FailureKind = ovl_fail_addr_not_available; | |||
12214 | } | |||
12215 | } | |||
12216 | } | |||
12217 | ||||
12218 | /// BuildOverloadedCallExpr - Given the call expression that calls Fn | |||
12219 | /// (which eventually refers to the declaration Func) and the call | |||
12220 | /// arguments Args/NumArgs, attempt to resolve the function call down | |||
12221 | /// to a specific function. If overload resolution succeeds, returns | |||
12222 | /// the call expression produced by overload resolution. | |||
12223 | /// Otherwise, emits diagnostics and returns ExprError. | |||
12224 | ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, | |||
12225 | UnresolvedLookupExpr *ULE, | |||
12226 | SourceLocation LParenLoc, | |||
12227 | MultiExprArg Args, | |||
12228 | SourceLocation RParenLoc, | |||
12229 | Expr *ExecConfig, | |||
12230 | bool AllowTypoCorrection, | |||
12231 | bool CalleesAddressIsTaken) { | |||
12232 | OverloadCandidateSet CandidateSet(Fn->getExprLoc(), | |||
12233 | OverloadCandidateSet::CSK_Normal); | |||
12234 | ExprResult result; | |||
12235 | ||||
12236 | if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, | |||
12237 | &result)) | |||
12238 | return result; | |||
12239 | ||||
12240 | // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that | |||
12241 | // functions that aren't addressible are considered unviable. | |||
12242 | if (CalleesAddressIsTaken) | |||
12243 | markUnaddressableCandidatesUnviable(*this, CandidateSet); | |||
12244 | ||||
12245 | OverloadCandidateSet::iterator Best; | |||
12246 | OverloadingResult OverloadResult = | |||
12247 | CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); | |||
12248 | ||||
12249 | return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, | |||
12250 | ExecConfig, &CandidateSet, &Best, | |||
12251 | OverloadResult, AllowTypoCorrection); | |||
12252 | } | |||
12253 | ||||
12254 | static bool IsOverloaded(const UnresolvedSetImpl &Functions) { | |||
12255 | return Functions.size() > 1 || | |||
12256 | (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); | |||
12257 | } | |||
12258 | ||||
12259 | /// Create a unary operation that may resolve to an overloaded | |||
12260 | /// operator. | |||
12261 | /// | |||
12262 | /// \param OpLoc The location of the operator itself (e.g., '*'). | |||
12263 | /// | |||
12264 | /// \param Opc The UnaryOperatorKind that describes this operator. | |||
12265 | /// | |||
12266 | /// \param Fns The set of non-member functions that will be | |||
12267 | /// considered by overload resolution. The caller needs to build this | |||
12268 | /// set based on the context using, e.g., | |||
12269 | /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This | |||
12270 | /// set should not contain any member functions; those will be added | |||
12271 | /// by CreateOverloadedUnaryOp(). | |||
12272 | /// | |||
12273 | /// \param Input The input argument. | |||
12274 | ExprResult | |||
12275 | Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, | |||
12276 | const UnresolvedSetImpl &Fns, | |||
12277 | Expr *Input, bool PerformADL) { | |||
12278 | OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); | |||
12279 | assert(Op != OO_None && "Invalid opcode for overloaded unary operator")((Op != OO_None && "Invalid opcode for overloaded unary operator" ) ? static_cast<void> (0) : __assert_fail ("Op != OO_None && \"Invalid opcode for overloaded unary operator\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 12279, __PRETTY_FUNCTION__)); | |||
12280 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); | |||
12281 | // TODO: provide better source location info. | |||
12282 | DeclarationNameInfo OpNameInfo(OpName, OpLoc); | |||
12283 | ||||
12284 | if (checkPlaceholderForOverload(*this, Input)) | |||
12285 | return ExprError(); | |||
12286 | ||||
12287 | Expr *Args[2] = { Input, nullptr }; | |||
12288 | unsigned NumArgs = 1; | |||
12289 | ||||
12290 | // For post-increment and post-decrement, add the implicit '0' as | |||
12291 | // the second argument, so that we know this is a post-increment or | |||
12292 | // post-decrement. | |||
12293 | if (Opc == UO_PostInc || Opc == UO_PostDec) { | |||
12294 | llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); | |||
12295 | Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, | |||
12296 | SourceLocation()); | |||
12297 | NumArgs = 2; | |||
12298 | } | |||
12299 | ||||
12300 | ArrayRef<Expr *> ArgsArray(Args, NumArgs); | |||
12301 | ||||
12302 | if (Input->isTypeDependent()) { | |||
12303 | if (Fns.empty()) | |||
12304 | return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, | |||
12305 | VK_RValue, OK_Ordinary, OpLoc, false); | |||
12306 | ||||
12307 | CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators | |||
12308 | UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( | |||
12309 | Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, | |||
12310 | /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end()); | |||
12311 | return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray, | |||
12312 | Context.DependentTy, VK_RValue, OpLoc, | |||
12313 | FPOptions()); | |||
12314 | } | |||
12315 | ||||
12316 | // Build an empty overload set. | |||
12317 | OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); | |||
12318 | ||||
12319 | // Add the candidates from the given function set. | |||
12320 | AddFunctionCandidates(Fns, ArgsArray, CandidateSet); | |||
12321 | ||||
12322 | // Add operator candidates that are member functions. | |||
12323 | AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); | |||
12324 | ||||
12325 | // Add candidates from ADL. | |||
12326 | if (PerformADL) { | |||
12327 | AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, | |||
12328 | /*ExplicitTemplateArgs*/nullptr, | |||
12329 | CandidateSet); | |||
12330 | } | |||
12331 | ||||
12332 | // Add builtin operator candidates. | |||
12333 | AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); | |||
12334 | ||||
12335 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | |||
12336 | ||||
12337 | // Perform overload resolution. | |||
12338 | OverloadCandidateSet::iterator Best; | |||
12339 | switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { | |||
12340 | case OR_Success: { | |||
12341 | // We found a built-in operator or an overloaded operator. | |||
12342 | FunctionDecl *FnDecl = Best->Function; | |||
12343 | ||||
12344 | if (FnDecl) { | |||
12345 | Expr *Base = nullptr; | |||
12346 | // We matched an overloaded operator. Build a call to that | |||
12347 | // operator. | |||
12348 | ||||
12349 | // Convert the arguments. | |||
12350 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { | |||
12351 | CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); | |||
12352 | ||||
12353 | ExprResult InputRes = | |||
12354 | PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, | |||
12355 | Best->FoundDecl, Method); | |||
12356 | if (InputRes.isInvalid()) | |||
12357 | return ExprError(); | |||
12358 | Base = Input = InputRes.get(); | |||
12359 | } else { | |||
12360 | // Convert the arguments. | |||
12361 | ExprResult InputInit | |||
12362 | = PerformCopyInitialization(InitializedEntity::InitializeParameter( | |||
12363 | Context, | |||
12364 | FnDecl->getParamDecl(0)), | |||
12365 | SourceLocation(), | |||
12366 | Input); | |||
12367 | if (InputInit.isInvalid()) | |||
12368 | return ExprError(); | |||
12369 | Input = InputInit.get(); | |||
12370 | } | |||
12371 | ||||
12372 | // Build the actual expression node. | |||
12373 | ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, | |||
12374 | Base, HadMultipleCandidates, | |||
12375 | OpLoc); | |||
12376 | if (FnExpr.isInvalid()) | |||
12377 | return ExprError(); | |||
12378 | ||||
12379 | // Determine the result type. | |||
12380 | QualType ResultTy = FnDecl->getReturnType(); | |||
12381 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); | |||
12382 | ResultTy = ResultTy.getNonLValueExprType(Context); | |||
12383 | ||||
12384 | Args[0] = Input; | |||
12385 | CallExpr *TheCall = CXXOperatorCallExpr::Create( | |||
12386 | Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, | |||
12387 | FPOptions(), Best->IsADLCandidate); | |||
12388 | ||||
12389 | if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) | |||
12390 | return ExprError(); | |||
12391 | ||||
12392 | if (CheckFunctionCall(FnDecl, TheCall, | |||
12393 | FnDecl->getType()->castAs<FunctionProtoType>())) | |||
12394 | return ExprError(); | |||
12395 | ||||
12396 | return MaybeBindToTemporary(TheCall); | |||
12397 | } else { | |||
12398 | // We matched a built-in operator. Convert the arguments, then | |||
12399 | // break out so that we will build the appropriate built-in | |||
12400 | // operator node. | |||
12401 | ExprResult InputRes = PerformImplicitConversion( | |||
12402 | Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, | |||
12403 | CCK_ForBuiltinOverloadedOp); | |||
12404 | if (InputRes.isInvalid()) | |||
12405 | return ExprError(); | |||
12406 | Input = InputRes.get(); | |||
12407 | break; | |||
12408 | } | |||
12409 | } | |||
12410 | ||||
12411 | case OR_No_Viable_Function: | |||
12412 | // This is an erroneous use of an operator which can be overloaded by | |||
12413 | // a non-member function. Check for non-member operators which were | |||
12414 | // defined too late to be candidates. | |||
12415 | if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) | |||
12416 | // FIXME: Recover by calling the found function. | |||
12417 | return ExprError(); | |||
12418 | ||||
12419 | // No viable function; fall through to handling this as a | |||
12420 | // built-in operator, which will produce an error message for us. | |||
12421 | break; | |||
12422 | ||||
12423 | case OR_Ambiguous: | |||
12424 | CandidateSet.NoteCandidates( | |||
12425 | PartialDiagnosticAt(OpLoc, | |||
12426 | PDiag(diag::err_ovl_ambiguous_oper_unary) | |||
12427 | << UnaryOperator::getOpcodeStr(Opc) | |||
12428 | << Input->getType() << Input->getSourceRange()), | |||
12429 | *this, OCD_ViableCandidates, ArgsArray, | |||
12430 | UnaryOperator::getOpcodeStr(Opc), OpLoc); | |||
12431 | return ExprError(); | |||
12432 | ||||
12433 | case OR_Deleted: | |||
12434 | CandidateSet.NoteCandidates( | |||
12435 | PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) | |||
12436 | << UnaryOperator::getOpcodeStr(Opc) | |||
12437 | << Input->getSourceRange()), | |||
12438 | *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), | |||
12439 | OpLoc); | |||
12440 | return ExprError(); | |||
12441 | } | |||
12442 | ||||
12443 | // Either we found no viable overloaded operator or we matched a | |||
12444 | // built-in operator. In either case, fall through to trying to | |||
12445 | // build a built-in operation. | |||
12446 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); | |||
12447 | } | |||
12448 | ||||
12449 | /// Create a binary operation that may resolve to an overloaded | |||
12450 | /// operator. | |||
12451 | /// | |||
12452 | /// \param OpLoc The location of the operator itself (e.g., '+'). | |||
12453 | /// | |||
12454 | /// \param Opc The BinaryOperatorKind that describes this operator. | |||
12455 | /// | |||
12456 | /// \param Fns The set of non-member functions that will be | |||
12457 | /// considered by overload resolution. The caller needs to build this | |||
12458 | /// set based on the context using, e.g., | |||
12459 | /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This | |||
12460 | /// set should not contain any member functions; those will be added | |||
12461 | /// by CreateOverloadedBinOp(). | |||
12462 | /// | |||
12463 | /// \param LHS Left-hand argument. | |||
12464 | /// \param RHS Right-hand argument. | |||
12465 | ExprResult | |||
12466 | Sema::CreateOverloadedBinOp(SourceLocation OpLoc, | |||
12467 | BinaryOperatorKind Opc, | |||
12468 | const UnresolvedSetImpl &Fns, | |||
12469 | Expr *LHS, Expr *RHS, bool PerformADL) { | |||
12470 | Expr *Args[2] = { LHS, RHS }; | |||
12471 | LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple | |||
12472 | ||||
12473 | OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); | |||
12474 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); | |||
12475 | ||||
12476 | // If either side is type-dependent, create an appropriate dependent | |||
12477 | // expression. | |||
12478 | if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { | |||
12479 | if (Fns.empty()) { | |||
12480 | // If there are no functions to store, just build a dependent | |||
12481 | // BinaryOperator or CompoundAssignment. | |||
12482 | if (Opc <= BO_Assign || Opc > BO_OrAssign) | |||
12483 | return new (Context) BinaryOperator( | |||
12484 | Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, | |||
12485 | OpLoc, FPFeatures); | |||
12486 | ||||
12487 | return new (Context) CompoundAssignOperator( | |||
12488 | Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, | |||
12489 | Context.DependentTy, Context.DependentTy, OpLoc, | |||
12490 | FPFeatures); | |||
12491 | } | |||
12492 | ||||
12493 | // FIXME: save results of ADL from here? | |||
12494 | CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators | |||
12495 | // TODO: provide better source location info in DNLoc component. | |||
12496 | DeclarationNameInfo OpNameInfo(OpName, OpLoc); | |||
12497 | UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( | |||
12498 | Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, | |||
12499 | /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end()); | |||
12500 | return CXXOperatorCallExpr::Create(Context, Op, Fn, Args, | |||
12501 | Context.DependentTy, VK_RValue, OpLoc, | |||
12502 | FPFeatures); | |||
12503 | } | |||
12504 | ||||
12505 | // Always do placeholder-like conversions on the RHS. | |||
12506 | if (checkPlaceholderForOverload(*this, Args[1])) | |||
12507 | return ExprError(); | |||
12508 | ||||
12509 | // Do placeholder-like conversion on the LHS; note that we should | |||
12510 | // not get here with a PseudoObject LHS. | |||
12511 | assert(Args[0]->getObjectKind() != OK_ObjCProperty)((Args[0]->getObjectKind() != OK_ObjCProperty) ? static_cast <void> (0) : __assert_fail ("Args[0]->getObjectKind() != OK_ObjCProperty" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 12511, __PRETTY_FUNCTION__)); | |||
12512 | if (checkPlaceholderForOverload(*this, Args[0])) | |||
12513 | return ExprError(); | |||
12514 | ||||
12515 | // If this is the assignment operator, we only perform overload resolution | |||
12516 | // if the left-hand side is a class or enumeration type. This is actually | |||
12517 | // a hack. The standard requires that we do overload resolution between the | |||
12518 | // various built-in candidates, but as DR507 points out, this can lead to | |||
12519 | // problems. So we do it this way, which pretty much follows what GCC does. | |||
12520 | // Note that we go the traditional code path for compound assignment forms. | |||
12521 | if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) | |||
12522 | return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); | |||
12523 | ||||
12524 | // If this is the .* operator, which is not overloadable, just | |||
12525 | // create a built-in binary operator. | |||
12526 | if (Opc == BO_PtrMemD) | |||
12527 | return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); | |||
12528 | ||||
12529 | // Build an empty overload set. | |||
12530 | OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); | |||
12531 | ||||
12532 | // Add the candidates from the given function set. | |||
12533 | AddFunctionCandidates(Fns, Args, CandidateSet); | |||
12534 | ||||
12535 | // Add operator candidates that are member functions. | |||
12536 | AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); | |||
12537 | ||||
12538 | // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not | |||
12539 | // performed for an assignment operator (nor for operator[] nor operator->, | |||
12540 | // which don't get here). | |||
12541 | if (Opc != BO_Assign && PerformADL) | |||
12542 | AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, | |||
12543 | /*ExplicitTemplateArgs*/ nullptr, | |||
12544 | CandidateSet); | |||
12545 | ||||
12546 | // Add builtin operator candidates. | |||
12547 | AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); | |||
12548 | ||||
12549 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | |||
12550 | ||||
12551 | // Perform overload resolution. | |||
12552 | OverloadCandidateSet::iterator Best; | |||
12553 | switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { | |||
12554 | case OR_Success: { | |||
12555 | // We found a built-in operator or an overloaded operator. | |||
12556 | FunctionDecl *FnDecl = Best->Function; | |||
12557 | ||||
12558 | if (FnDecl) { | |||
12559 | Expr *Base = nullptr; | |||
12560 | // We matched an overloaded operator. Build a call to that | |||
12561 | // operator. | |||
12562 | ||||
12563 | // Convert the arguments. | |||
12564 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { | |||
12565 | // Best->Access is only meaningful for class members. | |||
12566 | CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); | |||
12567 | ||||
12568 | ExprResult Arg1 = | |||
12569 | PerformCopyInitialization( | |||
12570 | InitializedEntity::InitializeParameter(Context, | |||
12571 | FnDecl->getParamDecl(0)), | |||
12572 | SourceLocation(), Args[1]); | |||
12573 | if (Arg1.isInvalid()) | |||
12574 | return ExprError(); | |||
12575 | ||||
12576 | ExprResult Arg0 = | |||
12577 | PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, | |||
12578 | Best->FoundDecl, Method); | |||
12579 | if (Arg0.isInvalid()) | |||
12580 | return ExprError(); | |||
12581 | Base = Args[0] = Arg0.getAs<Expr>(); | |||
12582 | Args[1] = RHS = Arg1.getAs<Expr>(); | |||
12583 | } else { | |||
12584 | // Convert the arguments. | |||
12585 | ExprResult Arg0 = PerformCopyInitialization( | |||
12586 | InitializedEntity::InitializeParameter(Context, | |||
12587 | FnDecl->getParamDecl(0)), | |||
12588 | SourceLocation(), Args[0]); | |||
12589 | if (Arg0.isInvalid()) | |||
12590 | return ExprError(); | |||
12591 | ||||
12592 | ExprResult Arg1 = | |||
12593 | PerformCopyInitialization( | |||
12594 | InitializedEntity::InitializeParameter(Context, | |||
12595 | FnDecl->getParamDecl(1)), | |||
12596 | SourceLocation(), Args[1]); | |||
12597 | if (Arg1.isInvalid()) | |||
12598 | return ExprError(); | |||
12599 | Args[0] = LHS = Arg0.getAs<Expr>(); | |||
12600 | Args[1] = RHS = Arg1.getAs<Expr>(); | |||
12601 | } | |||
12602 | ||||
12603 | // Build the actual expression node. | |||
12604 | ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, | |||
12605 | Best->FoundDecl, Base, | |||
12606 | HadMultipleCandidates, OpLoc); | |||
12607 | if (FnExpr.isInvalid()) | |||
12608 | return ExprError(); | |||
12609 | ||||
12610 | // Determine the result type. | |||
12611 | QualType ResultTy = FnDecl->getReturnType(); | |||
12612 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); | |||
12613 | ResultTy = ResultTy.getNonLValueExprType(Context); | |||
12614 | ||||
12615 | CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( | |||
12616 | Context, Op, FnExpr.get(), Args, ResultTy, VK, OpLoc, FPFeatures, | |||
12617 | Best->IsADLCandidate); | |||
12618 | ||||
12619 | if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, | |||
12620 | FnDecl)) | |||
12621 | return ExprError(); | |||
12622 | ||||
12623 | ArrayRef<const Expr *> ArgsArray(Args, 2); | |||
12624 | const Expr *ImplicitThis = nullptr; | |||
12625 | // Cut off the implicit 'this'. | |||
12626 | if (isa<CXXMethodDecl>(FnDecl)) { | |||
12627 | ImplicitThis = ArgsArray[0]; | |||
12628 | ArgsArray = ArgsArray.slice(1); | |||
12629 | } | |||
12630 | ||||
12631 | // Check for a self move. | |||
12632 | if (Op == OO_Equal) | |||
12633 | DiagnoseSelfMove(Args[0], Args[1], OpLoc); | |||
12634 | ||||
12635 | checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, | |||
12636 | isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), | |||
12637 | VariadicDoesNotApply); | |||
12638 | ||||
12639 | return MaybeBindToTemporary(TheCall); | |||
12640 | } else { | |||
12641 | // We matched a built-in operator. Convert the arguments, then | |||
12642 | // break out so that we will build the appropriate built-in | |||
12643 | // operator node. | |||
12644 | ExprResult ArgsRes0 = PerformImplicitConversion( | |||
12645 | Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], | |||
12646 | AA_Passing, CCK_ForBuiltinOverloadedOp); | |||
12647 | if (ArgsRes0.isInvalid()) | |||
12648 | return ExprError(); | |||
12649 | Args[0] = ArgsRes0.get(); | |||
12650 | ||||
12651 | ExprResult ArgsRes1 = PerformImplicitConversion( | |||
12652 | Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], | |||
12653 | AA_Passing, CCK_ForBuiltinOverloadedOp); | |||
12654 | if (ArgsRes1.isInvalid()) | |||
12655 | return ExprError(); | |||
12656 | Args[1] = ArgsRes1.get(); | |||
12657 | break; | |||
12658 | } | |||
12659 | } | |||
12660 | ||||
12661 | case OR_No_Viable_Function: { | |||
12662 | // C++ [over.match.oper]p9: | |||
12663 | // If the operator is the operator , [...] and there are no | |||
12664 | // viable functions, then the operator is assumed to be the | |||
12665 | // built-in operator and interpreted according to clause 5. | |||
12666 | if (Opc == BO_Comma) | |||
12667 | break; | |||
12668 | ||||
12669 | // For class as left operand for assignment or compound assignment | |||
12670 | // operator do not fall through to handling in built-in, but report that | |||
12671 | // no overloaded assignment operator found | |||
12672 | ExprResult Result = ExprError(); | |||
12673 | StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); | |||
12674 | auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, | |||
12675 | Args, OpLoc); | |||
12676 | if (Args[0]->getType()->isRecordType() && | |||
12677 | Opc >= BO_Assign && Opc <= BO_OrAssign) { | |||
12678 | Diag(OpLoc, diag::err_ovl_no_viable_oper) | |||
12679 | << BinaryOperator::getOpcodeStr(Opc) | |||
12680 | << Args[0]->getSourceRange() << Args[1]->getSourceRange(); | |||
12681 | if (Args[0]->getType()->isIncompleteType()) { | |||
12682 | Diag(OpLoc, diag::note_assign_lhs_incomplete) | |||
12683 | << Args[0]->getType() | |||
12684 | << Args[0]->getSourceRange() << Args[1]->getSourceRange(); | |||
12685 | } | |||
12686 | } else { | |||
12687 | // This is an erroneous use of an operator which can be overloaded by | |||
12688 | // a non-member function. Check for non-member operators which were | |||
12689 | // defined too late to be candidates. | |||
12690 | if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) | |||
12691 | // FIXME: Recover by calling the found function. | |||
12692 | return ExprError(); | |||
12693 | ||||
12694 | // No viable function; try to create a built-in operation, which will | |||
12695 | // produce an error. Then, show the non-viable candidates. | |||
12696 | Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); | |||
12697 | } | |||
12698 | assert(Result.isInvalid() &&((Result.isInvalid() && "C++ binary operator overloading is missing candidates!" ) ? static_cast<void> (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 12699, __PRETTY_FUNCTION__)) | |||
12699 | "C++ binary operator overloading is missing candidates!")((Result.isInvalid() && "C++ binary operator overloading is missing candidates!" ) ? static_cast<void> (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 12699, __PRETTY_FUNCTION__)); | |||
12700 | CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); | |||
12701 | return Result; | |||
12702 | } | |||
12703 | ||||
12704 | case OR_Ambiguous: | |||
12705 | CandidateSet.NoteCandidates( | |||
12706 | PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) | |||
12707 | << BinaryOperator::getOpcodeStr(Opc) | |||
12708 | << Args[0]->getType() | |||
12709 | << Args[1]->getType() | |||
12710 | << Args[0]->getSourceRange() | |||
12711 | << Args[1]->getSourceRange()), | |||
12712 | *this, OCD_ViableCandidates, Args, BinaryOperator::getOpcodeStr(Opc), | |||
12713 | OpLoc); | |||
12714 | return ExprError(); | |||
12715 | ||||
12716 | case OR_Deleted: | |||
12717 | if (isImplicitlyDeleted(Best->Function)) { | |||
12718 | CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); | |||
12719 | Diag(OpLoc, diag::err_ovl_deleted_special_oper) | |||
12720 | << Context.getRecordType(Method->getParent()) | |||
12721 | << getSpecialMember(Method); | |||
12722 | ||||
12723 | // The user probably meant to call this special member. Just | |||
12724 | // explain why it's deleted. | |||
12725 | NoteDeletedFunction(Method); | |||
12726 | return ExprError(); | |||
12727 | } | |||
12728 | CandidateSet.NoteCandidates( | |||
12729 | PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) | |||
12730 | << BinaryOperator::getOpcodeStr(Opc) | |||
12731 | << Args[0]->getSourceRange() | |||
12732 | << Args[1]->getSourceRange()), | |||
12733 | *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), | |||
12734 | OpLoc); | |||
12735 | return ExprError(); | |||
12736 | } | |||
12737 | ||||
12738 | // We matched a built-in operator; build it. | |||
12739 | return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); | |||
12740 | } | |||
12741 | ||||
12742 | ExprResult | |||
12743 | Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, | |||
12744 | SourceLocation RLoc, | |||
12745 | Expr *Base, Expr *Idx) { | |||
12746 | Expr *Args[2] = { Base, Idx }; | |||
12747 | DeclarationName OpName = | |||
12748 | Context.DeclarationNames.getCXXOperatorName(OO_Subscript); | |||
12749 | ||||
12750 | // If either side is type-dependent, create an appropriate dependent | |||
12751 | // expression. | |||
12752 | if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { | |||
12753 | ||||
12754 | CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators | |||
12755 | // CHECKME: no 'operator' keyword? | |||
12756 | DeclarationNameInfo OpNameInfo(OpName, LLoc); | |||
12757 | OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); | |||
12758 | UnresolvedLookupExpr *Fn | |||
12759 | = UnresolvedLookupExpr::Create(Context, NamingClass, | |||
12760 | NestedNameSpecifierLoc(), OpNameInfo, | |||
12761 | /*ADL*/ true, /*Overloaded*/ false, | |||
12762 | UnresolvedSetIterator(), | |||
12763 | UnresolvedSetIterator()); | |||
12764 | // Can't add any actual overloads yet | |||
12765 | ||||
12766 | return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args, | |||
12767 | Context.DependentTy, VK_RValue, RLoc, | |||
12768 | FPOptions()); | |||
12769 | } | |||
12770 | ||||
12771 | // Handle placeholders on both operands. | |||
12772 | if (checkPlaceholderForOverload(*this, Args[0])) | |||
12773 | return ExprError(); | |||
12774 | if (checkPlaceholderForOverload(*this, Args[1])) | |||
12775 | return ExprError(); | |||
12776 | ||||
12777 | // Build an empty overload set. | |||
12778 | OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); | |||
12779 | ||||
12780 | // Subscript can only be overloaded as a member function. | |||
12781 | ||||
12782 | // Add operator candidates that are member functions. | |||
12783 | AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); | |||
12784 | ||||
12785 | // Add builtin operator candidates. | |||
12786 | AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); | |||
12787 | ||||
12788 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | |||
12789 | ||||
12790 | // Perform overload resolution. | |||
12791 | OverloadCandidateSet::iterator Best; | |||
12792 | switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { | |||
12793 | case OR_Success: { | |||
12794 | // We found a built-in operator or an overloaded operator. | |||
12795 | FunctionDecl *FnDecl = Best->Function; | |||
12796 | ||||
12797 | if (FnDecl) { | |||
12798 | // We matched an overloaded operator. Build a call to that | |||
12799 | // operator. | |||
12800 | ||||
12801 | CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); | |||
12802 | ||||
12803 | // Convert the arguments. | |||
12804 | CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); | |||
12805 | ExprResult Arg0 = | |||
12806 | PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, | |||
12807 | Best->FoundDecl, Method); | |||
12808 | if (Arg0.isInvalid()) | |||
12809 | return ExprError(); | |||
12810 | Args[0] = Arg0.get(); | |||
12811 | ||||
12812 | // Convert the arguments. | |||
12813 | ExprResult InputInit | |||
12814 | = PerformCopyInitialization(InitializedEntity::InitializeParameter( | |||
12815 | Context, | |||
12816 | FnDecl->getParamDecl(0)), | |||
12817 | SourceLocation(), | |||
12818 | Args[1]); | |||
12819 | if (InputInit.isInvalid()) | |||
12820 | return ExprError(); | |||
12821 | ||||
12822 | Args[1] = InputInit.getAs<Expr>(); | |||
12823 | ||||
12824 | // Build the actual expression node. | |||
12825 | DeclarationNameInfo OpLocInfo(OpName, LLoc); | |||
12826 | OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); | |||
12827 | ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, | |||
12828 | Best->FoundDecl, | |||
12829 | Base, | |||
12830 | HadMultipleCandidates, | |||
12831 | OpLocInfo.getLoc(), | |||
12832 | OpLocInfo.getInfo()); | |||
12833 | if (FnExpr.isInvalid()) | |||
12834 | return ExprError(); | |||
12835 | ||||
12836 | // Determine the result type | |||
12837 | QualType ResultTy = FnDecl->getReturnType(); | |||
12838 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); | |||
12839 | ResultTy = ResultTy.getNonLValueExprType(Context); | |||
12840 | ||||
12841 | CXXOperatorCallExpr *TheCall = | |||
12842 | CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(), | |||
12843 | Args, ResultTy, VK, RLoc, FPOptions()); | |||
12844 | ||||
12845 | if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) | |||
12846 | return ExprError(); | |||
12847 | ||||
12848 | if (CheckFunctionCall(Method, TheCall, | |||
12849 | Method->getType()->castAs<FunctionProtoType>())) | |||
12850 | return ExprError(); | |||
12851 | ||||
12852 | return MaybeBindToTemporary(TheCall); | |||
12853 | } else { | |||
12854 | // We matched a built-in operator. Convert the arguments, then | |||
12855 | // break out so that we will build the appropriate built-in | |||
12856 | // operator node. | |||
12857 | ExprResult ArgsRes0 = PerformImplicitConversion( | |||
12858 | Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], | |||
12859 | AA_Passing, CCK_ForBuiltinOverloadedOp); | |||
12860 | if (ArgsRes0.isInvalid()) | |||
12861 | return ExprError(); | |||
12862 | Args[0] = ArgsRes0.get(); | |||
12863 | ||||
12864 | ExprResult ArgsRes1 = PerformImplicitConversion( | |||
12865 | Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], | |||
12866 | AA_Passing, CCK_ForBuiltinOverloadedOp); | |||
12867 | if (ArgsRes1.isInvalid()) | |||
12868 | return ExprError(); | |||
12869 | Args[1] = ArgsRes1.get(); | |||
12870 | ||||
12871 | break; | |||
12872 | } | |||
12873 | } | |||
12874 | ||||
12875 | case OR_No_Viable_Function: { | |||
12876 | PartialDiagnostic PD = CandidateSet.empty() | |||
12877 | ? (PDiag(diag::err_ovl_no_oper) | |||
12878 | << Args[0]->getType() << /*subscript*/ 0 | |||
12879 | << Args[0]->getSourceRange() << Args[1]->getSourceRange()) | |||
12880 | : (PDiag(diag::err_ovl_no_viable_subscript) | |||
12881 | << Args[0]->getType() << Args[0]->getSourceRange() | |||
12882 | << Args[1]->getSourceRange()); | |||
12883 | CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, | |||
12884 | OCD_AllCandidates, Args, "[]", LLoc); | |||
12885 | return ExprError(); | |||
12886 | } | |||
12887 | ||||
12888 | case OR_Ambiguous: | |||
12889 | CandidateSet.NoteCandidates( | |||
12890 | PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) | |||
12891 | << "[]" << Args[0]->getType() | |||
12892 | << Args[1]->getType() | |||
12893 | << Args[0]->getSourceRange() | |||
12894 | << Args[1]->getSourceRange()), | |||
12895 | *this, OCD_ViableCandidates, Args, "[]", LLoc); | |||
12896 | return ExprError(); | |||
12897 | ||||
12898 | case OR_Deleted: | |||
12899 | CandidateSet.NoteCandidates( | |||
12900 | PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) | |||
12901 | << "[]" << Args[0]->getSourceRange() | |||
12902 | << Args[1]->getSourceRange()), | |||
12903 | *this, OCD_AllCandidates, Args, "[]", LLoc); | |||
12904 | return ExprError(); | |||
12905 | } | |||
12906 | ||||
12907 | // We matched a built-in operator; build it. | |||
12908 | return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); | |||
12909 | } | |||
12910 | ||||
12911 | /// BuildCallToMemberFunction - Build a call to a member | |||
12912 | /// function. MemExpr is the expression that refers to the member | |||
12913 | /// function (and includes the object parameter), Args/NumArgs are the | |||
12914 | /// arguments to the function call (not including the object | |||
12915 | /// parameter). The caller needs to validate that the member | |||
12916 | /// expression refers to a non-static member function or an overloaded | |||
12917 | /// member function. | |||
12918 | ExprResult | |||
12919 | Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, | |||
12920 | SourceLocation LParenLoc, | |||
12921 | MultiExprArg Args, | |||
12922 | SourceLocation RParenLoc) { | |||
12923 | assert(MemExprE->getType() == Context.BoundMemberTy ||((MemExprE->getType() == Context.BoundMemberTy || MemExprE ->getType() == Context.OverloadTy) ? static_cast<void> (0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 12924, __PRETTY_FUNCTION__)) | |||
12924 | MemExprE->getType() == Context.OverloadTy)((MemExprE->getType() == Context.BoundMemberTy || MemExprE ->getType() == Context.OverloadTy) ? static_cast<void> (0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 12924, __PRETTY_FUNCTION__)); | |||
12925 | ||||
12926 | // Dig out the member expression. This holds both the object | |||
12927 | // argument and the member function we're referring to. | |||
12928 | Expr *NakedMemExpr = MemExprE->IgnoreParens(); | |||
12929 | ||||
12930 | // Determine whether this is a call to a pointer-to-member function. | |||
12931 | if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { | |||
12932 | assert(op->getType() == Context.BoundMemberTy)((op->getType() == Context.BoundMemberTy) ? static_cast< void> (0) : __assert_fail ("op->getType() == Context.BoundMemberTy" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 12932, __PRETTY_FUNCTION__)); | |||
12933 | assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI)((op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI ) ? static_cast<void> (0) : __assert_fail ("op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 12933, __PRETTY_FUNCTION__)); | |||
12934 | ||||
12935 | QualType fnType = | |||
12936 | op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); | |||
12937 | ||||
12938 | const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); | |||
12939 | QualType resultType = proto->getCallResultType(Context); | |||
12940 | ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); | |||
12941 | ||||
12942 | // Check that the object type isn't more qualified than the | |||
12943 | // member function we're calling. | |||
12944 | Qualifiers funcQuals = proto->getMethodQuals(); | |||
12945 | ||||
12946 | QualType objectType = op->getLHS()->getType(); | |||
12947 | if (op->getOpcode() == BO_PtrMemI) | |||
12948 | objectType = objectType->castAs<PointerType>()->getPointeeType(); | |||
12949 | Qualifiers objectQuals = objectType.getQualifiers(); | |||
12950 | ||||
12951 | Qualifiers difference = objectQuals - funcQuals; | |||
12952 | difference.removeObjCGCAttr(); | |||
12953 | difference.removeAddressSpace(); | |||
12954 | if (difference) { | |||
12955 | std::string qualsString = difference.getAsString(); | |||
12956 | Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) | |||
12957 | << fnType.getUnqualifiedType() | |||
12958 | << qualsString | |||
12959 | << (qualsString.find(' ') == std::string::npos ? 1 : 2); | |||
12960 | } | |||
12961 | ||||
12962 | CXXMemberCallExpr *call = | |||
12963 | CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType, | |||
12964 | valueKind, RParenLoc, proto->getNumParams()); | |||
12965 | ||||
12966 | if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), | |||
12967 | call, nullptr)) | |||
12968 | return ExprError(); | |||
12969 | ||||
12970 | if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) | |||
12971 | return ExprError(); | |||
12972 | ||||
12973 | if (CheckOtherCall(call, proto)) | |||
12974 | return ExprError(); | |||
12975 | ||||
12976 | return MaybeBindToTemporary(call); | |||
12977 | } | |||
12978 | ||||
12979 | if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) | |||
12980 | return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, | |||
12981 | RParenLoc); | |||
12982 | ||||
12983 | UnbridgedCastsSet UnbridgedCasts; | |||
12984 | if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) | |||
12985 | return ExprError(); | |||
12986 | ||||
12987 | MemberExpr *MemExpr; | |||
12988 | CXXMethodDecl *Method = nullptr; | |||
12989 | DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); | |||
12990 | NestedNameSpecifier *Qualifier = nullptr; | |||
12991 | if (isa<MemberExpr>(NakedMemExpr)) { | |||
12992 | MemExpr = cast<MemberExpr>(NakedMemExpr); | |||
12993 | Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); | |||
12994 | FoundDecl = MemExpr->getFoundDecl(); | |||
12995 | Qualifier = MemExpr->getQualifier(); | |||
12996 | UnbridgedCasts.restore(); | |||
12997 | } else { | |||
12998 | UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); | |||
12999 | Qualifier = UnresExpr->getQualifier(); | |||
13000 | ||||
13001 | QualType ObjectType = UnresExpr->getBaseType(); | |||
13002 | Expr::Classification ObjectClassification | |||
13003 | = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() | |||
13004 | : UnresExpr->getBase()->Classify(Context); | |||
13005 | ||||
13006 | // Add overload candidates | |||
13007 | OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), | |||
13008 | OverloadCandidateSet::CSK_Normal); | |||
13009 | ||||
13010 | // FIXME: avoid copy. | |||
13011 | TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; | |||
13012 | if (UnresExpr->hasExplicitTemplateArgs()) { | |||
13013 | UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); | |||
13014 | TemplateArgs = &TemplateArgsBuffer; | |||
13015 | } | |||
13016 | ||||
13017 | for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), | |||
13018 | E = UnresExpr->decls_end(); I != E; ++I) { | |||
13019 | ||||
13020 | NamedDecl *Func = *I; | |||
13021 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); | |||
13022 | if (isa<UsingShadowDecl>(Func)) | |||
13023 | Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); | |||
13024 | ||||
13025 | ||||
13026 | // Microsoft supports direct constructor calls. | |||
13027 | if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { | |||
13028 | AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, | |||
13029 | CandidateSet, | |||
13030 | /*SuppressUserConversions*/ false); | |||
13031 | } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { | |||
13032 | // If explicit template arguments were provided, we can't call a | |||
13033 | // non-template member function. | |||
13034 | if (TemplateArgs) | |||
13035 | continue; | |||
13036 | ||||
13037 | AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, | |||
13038 | ObjectClassification, Args, CandidateSet, | |||
13039 | /*SuppressUserConversions=*/false); | |||
13040 | } else { | |||
13041 | AddMethodTemplateCandidate( | |||
13042 | cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, | |||
13043 | TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, | |||
13044 | /*SuppressUsedConversions=*/false); | |||
13045 | } | |||
13046 | } | |||
13047 | ||||
13048 | DeclarationName DeclName = UnresExpr->getMemberName(); | |||
13049 | ||||
13050 | UnbridgedCasts.restore(); | |||
13051 | ||||
13052 | OverloadCandidateSet::iterator Best; | |||
13053 | switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), | |||
13054 | Best)) { | |||
13055 | case OR_Success: | |||
13056 | Method = cast<CXXMethodDecl>(Best->Function); | |||
13057 | FoundDecl = Best->FoundDecl; | |||
13058 | CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); | |||
13059 | if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) | |||
13060 | return ExprError(); | |||
13061 | // If FoundDecl is different from Method (such as if one is a template | |||
13062 | // and the other a specialization), make sure DiagnoseUseOfDecl is | |||
13063 | // called on both. | |||
13064 | // FIXME: This would be more comprehensively addressed by modifying | |||
13065 | // DiagnoseUseOfDecl to accept both the FoundDecl and the decl | |||
13066 | // being used. | |||
13067 | if (Method != FoundDecl.getDecl() && | |||
13068 | DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) | |||
13069 | return ExprError(); | |||
13070 | break; | |||
13071 | ||||
13072 | case OR_No_Viable_Function: | |||
13073 | CandidateSet.NoteCandidates( | |||
13074 | PartialDiagnosticAt( | |||
13075 | UnresExpr->getMemberLoc(), | |||
13076 | PDiag(diag::err_ovl_no_viable_member_function_in_call) | |||
13077 | << DeclName << MemExprE->getSourceRange()), | |||
13078 | *this, OCD_AllCandidates, Args); | |||
13079 | // FIXME: Leaking incoming expressions! | |||
13080 | return ExprError(); | |||
13081 | ||||
13082 | case OR_Ambiguous: | |||
13083 | CandidateSet.NoteCandidates( | |||
13084 | PartialDiagnosticAt(UnresExpr->getMemberLoc(), | |||
13085 | PDiag(diag::err_ovl_ambiguous_member_call) | |||
13086 | << DeclName << MemExprE->getSourceRange()), | |||
13087 | *this, OCD_AllCandidates, Args); | |||
13088 | // FIXME: Leaking incoming expressions! | |||
13089 | return ExprError(); | |||
13090 | ||||
13091 | case OR_Deleted: | |||
13092 | CandidateSet.NoteCandidates( | |||
13093 | PartialDiagnosticAt(UnresExpr->getMemberLoc(), | |||
13094 | PDiag(diag::err_ovl_deleted_member_call) | |||
13095 | << DeclName << MemExprE->getSourceRange()), | |||
13096 | *this, OCD_AllCandidates, Args); | |||
13097 | // FIXME: Leaking incoming expressions! | |||
13098 | return ExprError(); | |||
13099 | } | |||
13100 | ||||
13101 | MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); | |||
13102 | ||||
13103 | // If overload resolution picked a static member, build a | |||
13104 | // non-member call based on that function. | |||
13105 | if (Method->isStatic()) { | |||
13106 | return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, | |||
13107 | RParenLoc); | |||
13108 | } | |||
13109 | ||||
13110 | MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); | |||
13111 | } | |||
13112 | ||||
13113 | QualType ResultType = Method->getReturnType(); | |||
13114 | ExprValueKind VK = Expr::getValueKindForType(ResultType); | |||
13115 | ResultType = ResultType.getNonLValueExprType(Context); | |||
13116 | ||||
13117 | assert(Method && "Member call to something that isn't a method?")((Method && "Member call to something that isn't a method?" ) ? static_cast<void> (0) : __assert_fail ("Method && \"Member call to something that isn't a method?\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 13117, __PRETTY_FUNCTION__)); | |||
13118 | const auto *Proto = Method->getType()->getAs<FunctionProtoType>(); | |||
13119 | CXXMemberCallExpr *TheCall = | |||
13120 | CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK, | |||
13121 | RParenLoc, Proto->getNumParams()); | |||
13122 | ||||
13123 | // Check for a valid return type. | |||
13124 | if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), | |||
13125 | TheCall, Method)) | |||
13126 | return ExprError(); | |||
13127 | ||||
13128 | // Convert the object argument (for a non-static member function call). | |||
13129 | // We only need to do this if there was actually an overload; otherwise | |||
13130 | // it was done at lookup. | |||
13131 | if (!Method->isStatic()) { | |||
13132 | ExprResult ObjectArg = | |||
13133 | PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, | |||
13134 | FoundDecl, Method); | |||
13135 | if (ObjectArg.isInvalid()) | |||
13136 | return ExprError(); | |||
13137 | MemExpr->setBase(ObjectArg.get()); | |||
13138 | } | |||
13139 | ||||
13140 | // Convert the rest of the arguments | |||
13141 | if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, | |||
13142 | RParenLoc)) | |||
13143 | return ExprError(); | |||
13144 | ||||
13145 | DiagnoseSentinelCalls(Method, LParenLoc, Args); | |||
13146 | ||||
13147 | if (CheckFunctionCall(Method, TheCall, Proto)) | |||
13148 | return ExprError(); | |||
13149 | ||||
13150 | // In the case the method to call was not selected by the overloading | |||
13151 | // resolution process, we still need to handle the enable_if attribute. Do | |||
13152 | // that here, so it will not hide previous -- and more relevant -- errors. | |||
13153 | if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { | |||
13154 | if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { | |||
13155 | Diag(MemE->getMemberLoc(), | |||
13156 | diag::err_ovl_no_viable_member_function_in_call) | |||
13157 | << Method << Method->getSourceRange(); | |||
13158 | Diag(Method->getLocation(), | |||
13159 | diag::note_ovl_candidate_disabled_by_function_cond_attr) | |||
13160 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); | |||
13161 | return ExprError(); | |||
13162 | } | |||
13163 | } | |||
13164 | ||||
13165 | if ((isa<CXXConstructorDecl>(CurContext) || | |||
13166 | isa<CXXDestructorDecl>(CurContext)) && | |||
13167 | TheCall->getMethodDecl()->isPure()) { | |||
13168 | const CXXMethodDecl *MD = TheCall->getMethodDecl(); | |||
13169 | ||||
13170 | if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && | |||
13171 | MemExpr->performsVirtualDispatch(getLangOpts())) { | |||
13172 | Diag(MemExpr->getBeginLoc(), | |||
13173 | diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) | |||
13174 | << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) | |||
13175 | << MD->getParent()->getDeclName(); | |||
13176 | ||||
13177 | Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); | |||
13178 | if (getLangOpts().AppleKext) | |||
13179 | Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) | |||
13180 | << MD->getParent()->getDeclName() << MD->getDeclName(); | |||
13181 | } | |||
13182 | } | |||
13183 | ||||
13184 | if (CXXDestructorDecl *DD = | |||
13185 | dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { | |||
13186 | // a->A::f() doesn't go through the vtable, except in AppleKext mode. | |||
13187 | bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; | |||
13188 | CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, | |||
13189 | CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, | |||
13190 | MemExpr->getMemberLoc()); | |||
13191 | } | |||
13192 | ||||
13193 | return MaybeBindToTemporary(TheCall); | |||
13194 | } | |||
13195 | ||||
13196 | /// BuildCallToObjectOfClassType - Build a call to an object of class | |||
13197 | /// type (C++ [over.call.object]), which can end up invoking an | |||
13198 | /// overloaded function call operator (@c operator()) or performing a | |||
13199 | /// user-defined conversion on the object argument. | |||
13200 | ExprResult | |||
13201 | Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, | |||
13202 | SourceLocation LParenLoc, | |||
13203 | MultiExprArg Args, | |||
13204 | SourceLocation RParenLoc) { | |||
13205 | if (checkPlaceholderForOverload(*this, Obj)) | |||
13206 | return ExprError(); | |||
13207 | ExprResult Object = Obj; | |||
13208 | ||||
13209 | UnbridgedCastsSet UnbridgedCasts; | |||
13210 | if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) | |||
13211 | return ExprError(); | |||
13212 | ||||
13213 | assert(Object.get()->getType()->isRecordType() &&((Object.get()->getType()->isRecordType() && "Requires object type argument" ) ? static_cast<void> (0) : __assert_fail ("Object.get()->getType()->isRecordType() && \"Requires object type argument\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 13214, __PRETTY_FUNCTION__)) | |||
13214 | "Requires object type argument")((Object.get()->getType()->isRecordType() && "Requires object type argument" ) ? static_cast<void> (0) : __assert_fail ("Object.get()->getType()->isRecordType() && \"Requires object type argument\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 13214, __PRETTY_FUNCTION__)); | |||
13215 | const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); | |||
13216 | ||||
13217 | // C++ [over.call.object]p1: | |||
13218 | // If the primary-expression E in the function call syntax | |||
13219 | // evaluates to a class object of type "cv T", then the set of | |||
13220 | // candidate functions includes at least the function call | |||
13221 | // operators of T. The function call operators of T are obtained by | |||
13222 | // ordinary lookup of the name operator() in the context of | |||
13223 | // (E).operator(). | |||
13224 | OverloadCandidateSet CandidateSet(LParenLoc, | |||
13225 | OverloadCandidateSet::CSK_Operator); | |||
13226 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); | |||
13227 | ||||
13228 | if (RequireCompleteType(LParenLoc, Object.get()->getType(), | |||
13229 | diag::err_incomplete_object_call, Object.get())) | |||
13230 | return true; | |||
13231 | ||||
13232 | LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); | |||
13233 | LookupQualifiedName(R, Record->getDecl()); | |||
13234 | R.suppressDiagnostics(); | |||
13235 | ||||
13236 | for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); | |||
13237 | Oper != OperEnd; ++Oper) { | |||
13238 | AddMethodCandidate(Oper.getPair(), Object.get()->getType(), | |||
13239 | Object.get()->Classify(Context), Args, CandidateSet, | |||
13240 | /*SuppressUserConversions=*/false); | |||
13241 | } | |||
13242 | ||||
13243 | // C++ [over.call.object]p2: | |||
13244 | // In addition, for each (non-explicit in C++0x) conversion function | |||
13245 | // declared in T of the form | |||
13246 | // | |||
13247 | // operator conversion-type-id () cv-qualifier; | |||
13248 | // | |||
13249 | // where cv-qualifier is the same cv-qualification as, or a | |||
13250 | // greater cv-qualification than, cv, and where conversion-type-id | |||
13251 | // denotes the type "pointer to function of (P1,...,Pn) returning | |||
13252 | // R", or the type "reference to pointer to function of | |||
13253 | // (P1,...,Pn) returning R", or the type "reference to function | |||
13254 | // of (P1,...,Pn) returning R", a surrogate call function [...] | |||
13255 | // is also considered as a candidate function. Similarly, | |||
13256 | // surrogate call functions are added to the set of candidate | |||
13257 | // functions for each conversion function declared in an | |||
13258 | // accessible base class provided the function is not hidden | |||
13259 | // within T by another intervening declaration. | |||
13260 | const auto &Conversions = | |||
13261 | cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); | |||
13262 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { | |||
13263 | NamedDecl *D = *I; | |||
13264 | CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); | |||
13265 | if (isa<UsingShadowDecl>(D)) | |||
13266 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | |||
13267 | ||||
13268 | // Skip over templated conversion functions; they aren't | |||
13269 | // surrogates. | |||
13270 | if (isa<FunctionTemplateDecl>(D)) | |||
13271 | continue; | |||
13272 | ||||
13273 | CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); | |||
13274 | if (!Conv->isExplicit()) { | |||
13275 | // Strip the reference type (if any) and then the pointer type (if | |||
13276 | // any) to get down to what might be a function type. | |||
13277 | QualType ConvType = Conv->getConversionType().getNonReferenceType(); | |||
13278 | if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) | |||
13279 | ConvType = ConvPtrType->getPointeeType(); | |||
13280 | ||||
13281 | if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) | |||
13282 | { | |||
13283 | AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, | |||
13284 | Object.get(), Args, CandidateSet); | |||
13285 | } | |||
13286 | } | |||
13287 | } | |||
13288 | ||||
13289 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | |||
13290 | ||||
13291 | // Perform overload resolution. | |||
13292 | OverloadCandidateSet::iterator Best; | |||
13293 | switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), | |||
13294 | Best)) { | |||
13295 | case OR_Success: | |||
13296 | // Overload resolution succeeded; we'll build the appropriate call | |||
13297 | // below. | |||
13298 | break; | |||
13299 | ||||
13300 | case OR_No_Viable_Function: { | |||
13301 | PartialDiagnostic PD = | |||
13302 | CandidateSet.empty() | |||
13303 | ? (PDiag(diag::err_ovl_no_oper) | |||
13304 | << Object.get()->getType() << /*call*/ 1 | |||
13305 | << Object.get()->getSourceRange()) | |||
13306 | : (PDiag(diag::err_ovl_no_viable_object_call) | |||
13307 | << Object.get()->getType() << Object.get()->getSourceRange()); | |||
13308 | CandidateSet.NoteCandidates( | |||
13309 | PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, | |||
13310 | OCD_AllCandidates, Args); | |||
13311 | break; | |||
13312 | } | |||
13313 | case OR_Ambiguous: | |||
13314 | CandidateSet.NoteCandidates( | |||
13315 | PartialDiagnosticAt(Object.get()->getBeginLoc(), | |||
13316 | PDiag(diag::err_ovl_ambiguous_object_call) | |||
13317 | << Object.get()->getType() | |||
13318 | << Object.get()->getSourceRange()), | |||
13319 | *this, OCD_ViableCandidates, Args); | |||
13320 | break; | |||
13321 | ||||
13322 | case OR_Deleted: | |||
13323 | CandidateSet.NoteCandidates( | |||
13324 | PartialDiagnosticAt(Object.get()->getBeginLoc(), | |||
13325 | PDiag(diag::err_ovl_deleted_object_call) | |||
13326 | << Object.get()->getType() | |||
13327 | << Object.get()->getSourceRange()), | |||
13328 | *this, OCD_AllCandidates, Args); | |||
13329 | break; | |||
13330 | } | |||
13331 | ||||
13332 | if (Best == CandidateSet.end()) | |||
13333 | return true; | |||
13334 | ||||
13335 | UnbridgedCasts.restore(); | |||
13336 | ||||
13337 | if (Best->Function == nullptr) { | |||
13338 | // Since there is no function declaration, this is one of the | |||
13339 | // surrogate candidates. Dig out the conversion function. | |||
13340 | CXXConversionDecl *Conv | |||
13341 | = cast<CXXConversionDecl>( | |||
13342 | Best->Conversions[0].UserDefined.ConversionFunction); | |||
13343 | ||||
13344 | CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, | |||
13345 | Best->FoundDecl); | |||
13346 | if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) | |||
13347 | return ExprError(); | |||
13348 | assert(Conv == Best->FoundDecl.getDecl() &&((Conv == Best->FoundDecl.getDecl() && "Found Decl & conversion-to-functionptr should be same, right?!" ) ? static_cast<void> (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 13349, __PRETTY_FUNCTION__)) | |||
13349 | "Found Decl & conversion-to-functionptr should be same, right?!")((Conv == Best->FoundDecl.getDecl() && "Found Decl & conversion-to-functionptr should be same, right?!" ) ? static_cast<void> (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 13349, __PRETTY_FUNCTION__)); | |||
13350 | // We selected one of the surrogate functions that converts the | |||
13351 | // object parameter to a function pointer. Perform the conversion | |||
13352 | // on the object argument, then let BuildCallExpr finish the job. | |||
13353 | ||||
13354 | // Create an implicit member expr to refer to the conversion operator. | |||
13355 | // and then call it. | |||
13356 | ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, | |||
13357 | Conv, HadMultipleCandidates); | |||
13358 | if (Call.isInvalid()) | |||
13359 | return ExprError(); | |||
13360 | // Record usage of conversion in an implicit cast. | |||
13361 | Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), | |||
13362 | CK_UserDefinedConversion, Call.get(), | |||
13363 | nullptr, VK_RValue); | |||
13364 | ||||
13365 | return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); | |||
13366 | } | |||
13367 | ||||
13368 | CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); | |||
13369 | ||||
13370 | // We found an overloaded operator(). Build a CXXOperatorCallExpr | |||
13371 | // that calls this method, using Object for the implicit object | |||
13372 | // parameter and passing along the remaining arguments. | |||
13373 | CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); | |||
13374 | ||||
13375 | // An error diagnostic has already been printed when parsing the declaration. | |||
13376 | if (Method->isInvalidDecl()) | |||
13377 | return ExprError(); | |||
13378 | ||||
13379 | const FunctionProtoType *Proto = | |||
13380 | Method->getType()->getAs<FunctionProtoType>(); | |||
13381 | ||||
13382 | unsigned NumParams = Proto->getNumParams(); | |||
13383 | ||||
13384 | DeclarationNameInfo OpLocInfo( | |||
13385 | Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); | |||
13386 | OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); | |||
13387 | ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, | |||
13388 | Obj, HadMultipleCandidates, | |||
13389 | OpLocInfo.getLoc(), | |||
13390 | OpLocInfo.getInfo()); | |||
13391 | if (NewFn.isInvalid()) | |||
13392 | return true; | |||
13393 | ||||
13394 | // The number of argument slots to allocate in the call. If we have default | |||
13395 | // arguments we need to allocate space for them as well. We additionally | |||
13396 | // need one more slot for the object parameter. | |||
13397 | unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); | |||
13398 | ||||
13399 | // Build the full argument list for the method call (the implicit object | |||
13400 | // parameter is placed at the beginning of the list). | |||
13401 | SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); | |||
13402 | ||||
13403 | bool IsError = false; | |||
13404 | ||||
13405 | // Initialize the implicit object parameter. | |||
13406 | ExprResult ObjRes = | |||
13407 | PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, | |||
13408 | Best->FoundDecl, Method); | |||
13409 | if (ObjRes.isInvalid()) | |||
13410 | IsError = true; | |||
13411 | else | |||
13412 | Object = ObjRes; | |||
13413 | MethodArgs[0] = Object.get(); | |||
13414 | ||||
13415 | // Check the argument types. | |||
13416 | for (unsigned i = 0; i != NumParams; i++) { | |||
13417 | Expr *Arg; | |||
13418 | if (i < Args.size()) { | |||
13419 | Arg = Args[i]; | |||
13420 | ||||
13421 | // Pass the argument. | |||
13422 | ||||
13423 | ExprResult InputInit | |||
13424 | = PerformCopyInitialization(InitializedEntity::InitializeParameter( | |||
13425 | Context, | |||
13426 | Method->getParamDecl(i)), | |||
13427 | SourceLocation(), Arg); | |||
13428 | ||||
13429 | IsError |= InputInit.isInvalid(); | |||
13430 | Arg = InputInit.getAs<Expr>(); | |||
13431 | } else { | |||
13432 | ExprResult DefArg | |||
13433 | = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); | |||
13434 | if (DefArg.isInvalid()) { | |||
13435 | IsError = true; | |||
13436 | break; | |||
13437 | } | |||
13438 | ||||
13439 | Arg = DefArg.getAs<Expr>(); | |||
13440 | } | |||
13441 | ||||
13442 | MethodArgs[i + 1] = Arg; | |||
13443 | } | |||
13444 | ||||
13445 | // If this is a variadic call, handle args passed through "...". | |||
13446 | if (Proto->isVariadic()) { | |||
13447 | // Promote the arguments (C99 6.5.2.2p7). | |||
13448 | for (unsigned i = NumParams, e = Args.size(); i < e; i++) { | |||
13449 | ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, | |||
13450 | nullptr); | |||
13451 | IsError |= Arg.isInvalid(); | |||
13452 | MethodArgs[i + 1] = Arg.get(); | |||
13453 | } | |||
13454 | } | |||
13455 | ||||
13456 | if (IsError) | |||
13457 | return true; | |||
13458 | ||||
13459 | DiagnoseSentinelCalls(Method, LParenLoc, Args); | |||
13460 | ||||
13461 | // Once we've built TheCall, all of the expressions are properly owned. | |||
13462 | QualType ResultTy = Method->getReturnType(); | |||
13463 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); | |||
13464 | ResultTy = ResultTy.getNonLValueExprType(Context); | |||
13465 | ||||
13466 | CXXOperatorCallExpr *TheCall = | |||
13467 | CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs, | |||
13468 | ResultTy, VK, RParenLoc, FPOptions()); | |||
13469 | ||||
13470 | if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) | |||
13471 | return true; | |||
13472 | ||||
13473 | if (CheckFunctionCall(Method, TheCall, Proto)) | |||
13474 | return true; | |||
13475 | ||||
13476 | return MaybeBindToTemporary(TheCall); | |||
13477 | } | |||
13478 | ||||
13479 | /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> | |||
13480 | /// (if one exists), where @c Base is an expression of class type and | |||
13481 | /// @c Member is the name of the member we're trying to find. | |||
13482 | ExprResult | |||
13483 | Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, | |||
13484 | bool *NoArrowOperatorFound) { | |||
13485 | assert(Base->getType()->isRecordType() &&((Base->getType()->isRecordType() && "left-hand side must have class type" ) ? static_cast<void> (0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 13486, __PRETTY_FUNCTION__)) | |||
13486 | "left-hand side must have class type")((Base->getType()->isRecordType() && "left-hand side must have class type" ) ? static_cast<void> (0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 13486, __PRETTY_FUNCTION__)); | |||
13487 | ||||
13488 | if (checkPlaceholderForOverload(*this, Base)) | |||
13489 | return ExprError(); | |||
13490 | ||||
13491 | SourceLocation Loc = Base->getExprLoc(); | |||
13492 | ||||
13493 | // C++ [over.ref]p1: | |||
13494 | // | |||
13495 | // [...] An expression x->m is interpreted as (x.operator->())->m | |||
13496 | // for a class object x of type T if T::operator->() exists and if | |||
13497 | // the operator is selected as the best match function by the | |||
13498 | // overload resolution mechanism (13.3). | |||
13499 | DeclarationName OpName = | |||
13500 | Context.DeclarationNames.getCXXOperatorName(OO_Arrow); | |||
13501 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); | |||
13502 | const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); | |||
13503 | ||||
13504 | if (RequireCompleteType(Loc, Base->getType(), | |||
13505 | diag::err_typecheck_incomplete_tag, Base)) | |||
13506 | return ExprError(); | |||
13507 | ||||
13508 | LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); | |||
13509 | LookupQualifiedName(R, BaseRecord->getDecl()); | |||
13510 | R.suppressDiagnostics(); | |||
13511 | ||||
13512 | for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); | |||
13513 | Oper != OperEnd; ++Oper) { | |||
13514 | AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), | |||
13515 | None, CandidateSet, /*SuppressUserConversions=*/false); | |||
13516 | } | |||
13517 | ||||
13518 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | |||
13519 | ||||
13520 | // Perform overload resolution. | |||
13521 | OverloadCandidateSet::iterator Best; | |||
13522 | switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { | |||
13523 | case OR_Success: | |||
13524 | // Overload resolution succeeded; we'll build the call below. | |||
13525 | break; | |||
13526 | ||||
13527 | case OR_No_Viable_Function: { | |||
13528 | auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); | |||
13529 | if (CandidateSet.empty()) { | |||
13530 | QualType BaseType = Base->getType(); | |||
13531 | if (NoArrowOperatorFound) { | |||
13532 | // Report this specific error to the caller instead of emitting a | |||
13533 | // diagnostic, as requested. | |||
13534 | *NoArrowOperatorFound = true; | |||
13535 | return ExprError(); | |||
13536 | } | |||
13537 | Diag(OpLoc, diag::err_typecheck_member_reference_arrow) | |||
13538 | << BaseType << Base->getSourceRange(); | |||
13539 | if (BaseType->isRecordType() && !BaseType->isPointerType()) { | |||
13540 | Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) | |||
13541 | << FixItHint::CreateReplacement(OpLoc, "."); | |||
13542 | } | |||
13543 | } else | |||
13544 | Diag(OpLoc, diag::err_ovl_no_viable_oper) | |||
13545 | << "operator->" << Base->getSourceRange(); | |||
13546 | CandidateSet.NoteCandidates(*this, Base, Cands); | |||
13547 | return ExprError(); | |||
13548 | } | |||
13549 | case OR_Ambiguous: | |||
13550 | CandidateSet.NoteCandidates( | |||
13551 | PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) | |||
13552 | << "->" << Base->getType() | |||
13553 | << Base->getSourceRange()), | |||
13554 | *this, OCD_ViableCandidates, Base); | |||
13555 | return ExprError(); | |||
13556 | ||||
13557 | case OR_Deleted: | |||
13558 | CandidateSet.NoteCandidates( | |||
13559 | PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) | |||
13560 | << "->" << Base->getSourceRange()), | |||
13561 | *this, OCD_AllCandidates, Base); | |||
13562 | return ExprError(); | |||
13563 | } | |||
13564 | ||||
13565 | CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); | |||
13566 | ||||
13567 | // Convert the object parameter. | |||
13568 | CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); | |||
13569 | ExprResult BaseResult = | |||
13570 | PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, | |||
13571 | Best->FoundDecl, Method); | |||
13572 | if (BaseResult.isInvalid()) | |||
13573 | return ExprError(); | |||
13574 | Base = BaseResult.get(); | |||
13575 | ||||
13576 | // Build the operator call. | |||
13577 | ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, | |||
13578 | Base, HadMultipleCandidates, OpLoc); | |||
13579 | if (FnExpr.isInvalid()) | |||
13580 | return ExprError(); | |||
13581 | ||||
13582 | QualType ResultTy = Method->getReturnType(); | |||
13583 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); | |||
13584 | ResultTy = ResultTy.getNonLValueExprType(Context); | |||
13585 | CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( | |||
13586 | Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions()); | |||
13587 | ||||
13588 | if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) | |||
13589 | return ExprError(); | |||
13590 | ||||
13591 | if (CheckFunctionCall(Method, TheCall, | |||
13592 | Method->getType()->castAs<FunctionProtoType>())) | |||
13593 | return ExprError(); | |||
13594 | ||||
13595 | return MaybeBindToTemporary(TheCall); | |||
13596 | } | |||
13597 | ||||
13598 | /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to | |||
13599 | /// a literal operator described by the provided lookup results. | |||
13600 | ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, | |||
13601 | DeclarationNameInfo &SuffixInfo, | |||
13602 | ArrayRef<Expr*> Args, | |||
13603 | SourceLocation LitEndLoc, | |||
13604 | TemplateArgumentListInfo *TemplateArgs) { | |||
13605 | SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); | |||
13606 | ||||
13607 | OverloadCandidateSet CandidateSet(UDSuffixLoc, | |||
13608 | OverloadCandidateSet::CSK_Normal); | |||
13609 | AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, | |||
13610 | /*SuppressUserConversions=*/true); | |||
13611 | ||||
13612 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | |||
13613 | ||||
13614 | // Perform overload resolution. This will usually be trivial, but might need | |||
13615 | // to perform substitutions for a literal operator template. | |||
13616 | OverloadCandidateSet::iterator Best; | |||
13617 | switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { | |||
13618 | case OR_Success: | |||
13619 | case OR_Deleted: | |||
13620 | break; | |||
13621 | ||||
13622 | case OR_No_Viable_Function: | |||
13623 | CandidateSet.NoteCandidates( | |||
13624 | PartialDiagnosticAt(UDSuffixLoc, | |||
13625 | PDiag(diag::err_ovl_no_viable_function_in_call) | |||
13626 | << R.getLookupName()), | |||
13627 | *this, OCD_AllCandidates, Args); | |||
13628 | return ExprError(); | |||
13629 | ||||
13630 | case OR_Ambiguous: | |||
13631 | CandidateSet.NoteCandidates( | |||
13632 | PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) | |||
13633 | << R.getLookupName()), | |||
13634 | *this, OCD_ViableCandidates, Args); | |||
13635 | return ExprError(); | |||
13636 | } | |||
13637 | ||||
13638 | FunctionDecl *FD = Best->Function; | |||
13639 | ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, | |||
13640 | nullptr, HadMultipleCandidates, | |||
13641 | SuffixInfo.getLoc(), | |||
13642 | SuffixInfo.getInfo()); | |||
13643 | if (Fn.isInvalid()) | |||
13644 | return true; | |||
13645 | ||||
13646 | // Check the argument types. This should almost always be a no-op, except | |||
13647 | // that array-to-pointer decay is applied to string literals. | |||
13648 | Expr *ConvArgs[2]; | |||
13649 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { | |||
13650 | ExprResult InputInit = PerformCopyInitialization( | |||
13651 | InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), | |||
13652 | SourceLocation(), Args[ArgIdx]); | |||
13653 | if (InputInit.isInvalid()) | |||
13654 | return true; | |||
13655 | ConvArgs[ArgIdx] = InputInit.get(); | |||
13656 | } | |||
13657 | ||||
13658 | QualType ResultTy = FD->getReturnType(); | |||
13659 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); | |||
13660 | ResultTy = ResultTy.getNonLValueExprType(Context); | |||
13661 | ||||
13662 | UserDefinedLiteral *UDL = UserDefinedLiteral::Create( | |||
13663 | Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, | |||
13664 | VK, LitEndLoc, UDSuffixLoc); | |||
13665 | ||||
13666 | if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) | |||
13667 | return ExprError(); | |||
13668 | ||||
13669 | if (CheckFunctionCall(FD, UDL, nullptr)) | |||
13670 | return ExprError(); | |||
13671 | ||||
13672 | return MaybeBindToTemporary(UDL); | |||
13673 | } | |||
13674 | ||||
13675 | /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the | |||
13676 | /// given LookupResult is non-empty, it is assumed to describe a member which | |||
13677 | /// will be invoked. Otherwise, the function will be found via argument | |||
13678 | /// dependent lookup. | |||
13679 | /// CallExpr is set to a valid expression and FRS_Success returned on success, | |||
13680 | /// otherwise CallExpr is set to ExprError() and some non-success value | |||
13681 | /// is returned. | |||
13682 | Sema::ForRangeStatus | |||
13683 | Sema::BuildForRangeBeginEndCall(SourceLocation Loc, | |||
13684 | SourceLocation RangeLoc, | |||
13685 | const DeclarationNameInfo &NameInfo, | |||
13686 | LookupResult &MemberLookup, | |||
13687 | OverloadCandidateSet *CandidateSet, | |||
13688 | Expr *Range, ExprResult *CallExpr) { | |||
13689 | Scope *S = nullptr; | |||
13690 | ||||
13691 | CandidateSet->clear(OverloadCandidateSet::CSK_Normal); | |||
13692 | if (!MemberLookup.empty()) { | |||
13693 | ExprResult MemberRef = | |||
13694 | BuildMemberReferenceExpr(Range, Range->getType(), Loc, | |||
13695 | /*IsPtr=*/false, CXXScopeSpec(), | |||
13696 | /*TemplateKWLoc=*/SourceLocation(), | |||
13697 | /*FirstQualifierInScope=*/nullptr, | |||
13698 | MemberLookup, | |||
13699 | /*TemplateArgs=*/nullptr, S); | |||
13700 | if (MemberRef.isInvalid()) { | |||
13701 | *CallExpr = ExprError(); | |||
13702 | return FRS_DiagnosticIssued; | |||
13703 | } | |||
13704 | *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); | |||
13705 | if (CallExpr->isInvalid()) { | |||
13706 | *CallExpr = ExprError(); | |||
13707 | return FRS_DiagnosticIssued; | |||
13708 | } | |||
13709 | } else { | |||
13710 | UnresolvedSet<0> FoundNames; | |||
13711 | UnresolvedLookupExpr *Fn = | |||
13712 | UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, | |||
13713 | NestedNameSpecifierLoc(), NameInfo, | |||
13714 | /*NeedsADL=*/true, /*Overloaded=*/false, | |||
13715 | FoundNames.begin(), FoundNames.end()); | |||
13716 | ||||
13717 | bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, | |||
13718 | CandidateSet, CallExpr); | |||
13719 | if (CandidateSet->empty() || CandidateSetError) { | |||
13720 | *CallExpr = ExprError(); | |||
13721 | return FRS_NoViableFunction; | |||
13722 | } | |||
13723 | OverloadCandidateSet::iterator Best; | |||
13724 | OverloadingResult OverloadResult = | |||
13725 | CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); | |||
13726 | ||||
13727 | if (OverloadResult == OR_No_Viable_Function) { | |||
13728 | *CallExpr = ExprError(); | |||
13729 | return FRS_NoViableFunction; | |||
13730 | } | |||
13731 | *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, | |||
13732 | Loc, nullptr, CandidateSet, &Best, | |||
13733 | OverloadResult, | |||
13734 | /*AllowTypoCorrection=*/false); | |||
13735 | if (CallExpr->isInvalid() || OverloadResult != OR_Success) { | |||
13736 | *CallExpr = ExprError(); | |||
13737 | return FRS_DiagnosticIssued; | |||
13738 | } | |||
13739 | } | |||
13740 | return FRS_Success; | |||
13741 | } | |||
13742 | ||||
13743 | ||||
13744 | /// FixOverloadedFunctionReference - E is an expression that refers to | |||
13745 | /// a C++ overloaded function (possibly with some parentheses and | |||
13746 | /// perhaps a '&' around it). We have resolved the overloaded function | |||
13747 | /// to the function declaration Fn, so patch up the expression E to | |||
13748 | /// refer (possibly indirectly) to Fn. Returns the new expr. | |||
13749 | Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, | |||
13750 | FunctionDecl *Fn) { | |||
13751 | if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { | |||
13752 | Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), | |||
13753 | Found, Fn); | |||
13754 | if (SubExpr == PE->getSubExpr()) | |||
13755 | return PE; | |||
13756 | ||||
13757 | return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); | |||
13758 | } | |||
13759 | ||||
13760 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { | |||
13761 | Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), | |||
13762 | Found, Fn); | |||
13763 | assert(Context.hasSameType(ICE->getSubExpr()->getType(),((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr ->getType()) && "Implicit cast type cannot be determined from overload" ) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 13765, __PRETTY_FUNCTION__)) | |||
13764 | SubExpr->getType()) &&((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr ->getType()) && "Implicit cast type cannot be determined from overload" ) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 13765, __PRETTY_FUNCTION__)) | |||
13765 | "Implicit cast type cannot be determined from overload")((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr ->getType()) && "Implicit cast type cannot be determined from overload" ) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 13765, __PRETTY_FUNCTION__)); | |||
13766 | assert(ICE->path_empty() && "fixing up hierarchy conversion?")((ICE->path_empty() && "fixing up hierarchy conversion?" ) ? static_cast<void> (0) : __assert_fail ("ICE->path_empty() && \"fixing up hierarchy conversion?\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 13766, __PRETTY_FUNCTION__)); | |||
13767 | if (SubExpr == ICE->getSubExpr()) | |||
13768 | return ICE; | |||
13769 | ||||
13770 | return ImplicitCastExpr::Create(Context, ICE->getType(), | |||
13771 | ICE->getCastKind(), | |||
13772 | SubExpr, nullptr, | |||
13773 | ICE->getValueKind()); | |||
13774 | } | |||
13775 | ||||
13776 | if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { | |||
13777 | if (!GSE->isResultDependent()) { | |||
13778 | Expr *SubExpr = | |||
13779 | FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); | |||
13780 | if (SubExpr == GSE->getResultExpr()) | |||
13781 | return GSE; | |||
13782 | ||||
13783 | // Replace the resulting type information before rebuilding the generic | |||
13784 | // selection expression. | |||
13785 | ArrayRef<Expr *> A = GSE->getAssocExprs(); | |||
13786 | SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); | |||
13787 | unsigned ResultIdx = GSE->getResultIndex(); | |||
13788 | AssocExprs[ResultIdx] = SubExpr; | |||
13789 | ||||
13790 | return GenericSelectionExpr::Create( | |||
13791 | Context, GSE->getGenericLoc(), GSE->getControllingExpr(), | |||
13792 | GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), | |||
13793 | GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), | |||
13794 | ResultIdx); | |||
13795 | } | |||
13796 | // Rather than fall through to the unreachable, return the original generic | |||
13797 | // selection expression. | |||
13798 | return GSE; | |||
13799 | } | |||
13800 | ||||
13801 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { | |||
13802 | assert(UnOp->getOpcode() == UO_AddrOf &&((UnOp->getOpcode() == UO_AddrOf && "Can only take the address of an overloaded function" ) ? static_cast<void> (0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 13803, __PRETTY_FUNCTION__)) | |||
13803 | "Can only take the address of an overloaded function")((UnOp->getOpcode() == UO_AddrOf && "Can only take the address of an overloaded function" ) ? static_cast<void> (0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 13803, __PRETTY_FUNCTION__)); | |||
13804 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { | |||
13805 | if (Method->isStatic()) { | |||
13806 | // Do nothing: static member functions aren't any different | |||
13807 | // from non-member functions. | |||
13808 | } else { | |||
13809 | // Fix the subexpression, which really has to be an | |||
13810 | // UnresolvedLookupExpr holding an overloaded member function | |||
13811 | // or template. | |||
13812 | Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), | |||
13813 | Found, Fn); | |||
13814 | if (SubExpr == UnOp->getSubExpr()) | |||
13815 | return UnOp; | |||
13816 | ||||
13817 | assert(isa<DeclRefExpr>(SubExpr)((isa<DeclRefExpr>(SubExpr) && "fixed to something other than a decl ref" ) ? static_cast<void> (0) : __assert_fail ("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 13818, __PRETTY_FUNCTION__)) | |||
13818 | && "fixed to something other than a decl ref")((isa<DeclRefExpr>(SubExpr) && "fixed to something other than a decl ref" ) ? static_cast<void> (0) : __assert_fail ("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 13818, __PRETTY_FUNCTION__)); | |||
13819 | assert(cast<DeclRefExpr>(SubExpr)->getQualifier()((cast<DeclRefExpr>(SubExpr)->getQualifier() && "fixed to a member ref with no nested name qualifier") ? static_cast <void> (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 13820, __PRETTY_FUNCTION__)) | |||
13820 | && "fixed to a member ref with no nested name qualifier")((cast<DeclRefExpr>(SubExpr)->getQualifier() && "fixed to a member ref with no nested name qualifier") ? static_cast <void> (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\"" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 13820, __PRETTY_FUNCTION__)); | |||
13821 | ||||
13822 | // We have taken the address of a pointer to member | |||
13823 | // function. Perform the computation here so that we get the | |||
13824 | // appropriate pointer to member type. | |||
13825 | QualType ClassType | |||
13826 | = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); | |||
13827 | QualType MemPtrType | |||
13828 | = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); | |||
13829 | // Under the MS ABI, lock down the inheritance model now. | |||
13830 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) | |||
13831 | (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); | |||
13832 | ||||
13833 | return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, | |||
13834 | VK_RValue, OK_Ordinary, | |||
13835 | UnOp->getOperatorLoc(), false); | |||
13836 | } | |||
13837 | } | |||
13838 | Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), | |||
13839 | Found, Fn); | |||
13840 | if (SubExpr == UnOp->getSubExpr()) | |||
13841 | return UnOp; | |||
13842 | ||||
13843 | return new (Context) UnaryOperator(SubExpr, UO_AddrOf, | |||
13844 | Context.getPointerType(SubExpr->getType()), | |||
13845 | VK_RValue, OK_Ordinary, | |||
13846 | UnOp->getOperatorLoc(), false); | |||
13847 | } | |||
13848 | ||||
13849 | // C++ [except.spec]p17: | |||
13850 | // An exception-specification is considered to be needed when: | |||
13851 | // - in an expression the function is the unique lookup result or the | |||
13852 | // selected member of a set of overloaded functions | |||
13853 | if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) | |||
13854 | ResolveExceptionSpec(E->getExprLoc(), FPT); | |||
13855 | ||||
13856 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { | |||
13857 | // FIXME: avoid copy. | |||
13858 | TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; | |||
13859 | if (ULE->hasExplicitTemplateArgs()) { | |||
13860 | ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); | |||
13861 | TemplateArgs = &TemplateArgsBuffer; | |||
13862 | } | |||
13863 | ||||
13864 | DeclRefExpr *DRE = DeclRefExpr::Create(Context, | |||
13865 | ULE->getQualifierLoc(), | |||
13866 | ULE->getTemplateKeywordLoc(), | |||
13867 | Fn, | |||
13868 | /*enclosing*/ false, // FIXME? | |||
13869 | ULE->getNameLoc(), | |||
13870 | Fn->getType(), | |||
13871 | VK_LValue, | |||
13872 | Found.getDecl(), | |||
13873 | TemplateArgs); | |||
13874 | MarkDeclRefReferenced(DRE); | |||
13875 | DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); | |||
13876 | return DRE; | |||
13877 | } | |||
13878 | ||||
13879 | if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { | |||
13880 | // FIXME: avoid copy. | |||
13881 | TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; | |||
13882 | if (MemExpr->hasExplicitTemplateArgs()) { | |||
13883 | MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); | |||
13884 | TemplateArgs = &TemplateArgsBuffer; | |||
13885 | } | |||
13886 | ||||
13887 | Expr *Base; | |||
13888 | ||||
13889 | // If we're filling in a static method where we used to have an | |||
13890 | // implicit member access, rewrite to a simple decl ref. | |||
13891 | if (MemExpr->isImplicitAccess()) { | |||
13892 | if (cast<CXXMethodDecl>(Fn)->isStatic()) { | |||
13893 | DeclRefExpr *DRE = DeclRefExpr::Create(Context, | |||
13894 | MemExpr->getQualifierLoc(), | |||
13895 | MemExpr->getTemplateKeywordLoc(), | |||
13896 | Fn, | |||
13897 | /*enclosing*/ false, | |||
13898 | MemExpr->getMemberLoc(), | |||
13899 | Fn->getType(), | |||
13900 | VK_LValue, | |||
13901 | Found.getDecl(), | |||
13902 | TemplateArgs); | |||
13903 | MarkDeclRefReferenced(DRE); | |||
13904 | DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); | |||
13905 | return DRE; | |||
13906 | } else { | |||
13907 | SourceLocation Loc = MemExpr->getMemberLoc(); | |||
13908 | if (MemExpr->getQualifier()) | |||
13909 | Loc = MemExpr->getQualifierLoc().getBeginLoc(); | |||
13910 | CheckCXXThisCapture(Loc); | |||
13911 | Base = new (Context) CXXThisExpr(Loc, | |||
13912 | MemExpr->getBaseType(), | |||
13913 | /*isImplicit=*/true); | |||
13914 | } | |||
13915 | } else | |||
13916 | Base = MemExpr->getBase(); | |||
13917 | ||||
13918 | ExprValueKind valueKind; | |||
13919 | QualType type; | |||
13920 | if (cast<CXXMethodDecl>(Fn)->isStatic()) { | |||
13921 | valueKind = VK_LValue; | |||
13922 | type = Fn->getType(); | |||
13923 | } else { | |||
13924 | valueKind = VK_RValue; | |||
13925 | type = Context.BoundMemberTy; | |||
13926 | } | |||
13927 | ||||
13928 | MemberExpr *ME = MemberExpr::Create( | |||
13929 | Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), | |||
13930 | MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, | |||
13931 | MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, | |||
13932 | OK_Ordinary); | |||
13933 | ME->setHadMultipleCandidates(true); | |||
13934 | MarkMemberReferenced(ME); | |||
13935 | return ME; | |||
13936 | } | |||
13937 | ||||
13938 | llvm_unreachable("Invalid reference to overloaded function")::llvm::llvm_unreachable_internal("Invalid reference to overloaded function" , "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOverload.cpp" , 13938); | |||
13939 | } | |||
13940 | ||||
13941 | ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, | |||
13942 | DeclAccessPair Found, | |||
13943 | FunctionDecl *Fn) { | |||
13944 | return FixOverloadedFunctionReference(E.get(), Found, Fn); | |||
13945 | } |