/src/llvm-project/clang/lib/Sema/SemaOverload.cpp
Line | Count | Source (jump to first uncovered line) |
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/AST/ASTContext.h" |
14 | | #include "clang/AST/ASTLambda.h" |
15 | | #include "clang/AST/CXXInheritance.h" |
16 | | #include "clang/AST/DeclCXX.h" |
17 | | #include "clang/AST/DeclObjC.h" |
18 | | #include "clang/AST/DependenceFlags.h" |
19 | | #include "clang/AST/Expr.h" |
20 | | #include "clang/AST/ExprCXX.h" |
21 | | #include "clang/AST/ExprObjC.h" |
22 | | #include "clang/AST/Type.h" |
23 | | #include "clang/AST/TypeOrdering.h" |
24 | | #include "clang/Basic/Diagnostic.h" |
25 | | #include "clang/Basic/DiagnosticOptions.h" |
26 | | #include "clang/Basic/OperatorKinds.h" |
27 | | #include "clang/Basic/PartialDiagnostic.h" |
28 | | #include "clang/Basic/SourceManager.h" |
29 | | #include "clang/Basic/TargetInfo.h" |
30 | | #include "clang/Sema/EnterExpressionEvaluationContext.h" |
31 | | #include "clang/Sema/Initialization.h" |
32 | | #include "clang/Sema/Lookup.h" |
33 | | #include "clang/Sema/Overload.h" |
34 | | #include "clang/Sema/SemaInternal.h" |
35 | | #include "clang/Sema/Template.h" |
36 | | #include "clang/Sema/TemplateDeduction.h" |
37 | | #include "llvm/ADT/DenseSet.h" |
38 | | #include "llvm/ADT/STLExtras.h" |
39 | | #include "llvm/ADT/SmallPtrSet.h" |
40 | | #include "llvm/ADT/SmallString.h" |
41 | | #include "llvm/ADT/SmallVector.h" |
42 | | #include "llvm/Support/Casting.h" |
43 | | #include <algorithm> |
44 | | #include <cstddef> |
45 | | #include <cstdlib> |
46 | | #include <optional> |
47 | | |
48 | | using namespace clang; |
49 | | using namespace sema; |
50 | | |
51 | | using AllowedExplicit = Sema::AllowedExplicit; |
52 | | |
53 | 0 | static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { |
54 | 0 | return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { |
55 | 0 | return P->hasAttr<PassObjectSizeAttr>(); |
56 | 0 | }); |
57 | 0 | } |
58 | | |
59 | | /// A convenience routine for creating a decayed reference to a function. |
60 | | static ExprResult CreateFunctionRefExpr( |
61 | | Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, |
62 | | bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(), |
63 | 0 | const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) { |
64 | 0 | if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) |
65 | 0 | return ExprError(); |
66 | | // If FoundDecl is different from Fn (such as if one is a template |
67 | | // and the other a specialization), make sure DiagnoseUseOfDecl is |
68 | | // called on both. |
69 | | // FIXME: This would be more comprehensively addressed by modifying |
70 | | // DiagnoseUseOfDecl to accept both the FoundDecl and the decl |
71 | | // being used. |
72 | 0 | if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) |
73 | 0 | return ExprError(); |
74 | 0 | DeclRefExpr *DRE = new (S.Context) |
75 | 0 | DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); |
76 | 0 | if (HadMultipleCandidates) |
77 | 0 | DRE->setHadMultipleCandidates(true); |
78 | |
|
79 | 0 | S.MarkDeclRefReferenced(DRE, Base); |
80 | 0 | if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) { |
81 | 0 | if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { |
82 | 0 | S.ResolveExceptionSpec(Loc, FPT); |
83 | 0 | DRE->setType(Fn->getType()); |
84 | 0 | } |
85 | 0 | } |
86 | 0 | return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), |
87 | 0 | CK_FunctionToPointerDecay); |
88 | 0 | } |
89 | | |
90 | | static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, |
91 | | bool InOverloadResolution, |
92 | | StandardConversionSequence &SCS, |
93 | | bool CStyle, |
94 | | bool AllowObjCWritebackConversion); |
95 | | |
96 | | static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, |
97 | | QualType &ToType, |
98 | | bool InOverloadResolution, |
99 | | StandardConversionSequence &SCS, |
100 | | bool CStyle); |
101 | | static OverloadingResult |
102 | | IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, |
103 | | UserDefinedConversionSequence& User, |
104 | | OverloadCandidateSet& Conversions, |
105 | | AllowedExplicit AllowExplicit, |
106 | | bool AllowObjCConversionOnExplicit); |
107 | | |
108 | | static ImplicitConversionSequence::CompareKind |
109 | | CompareStandardConversionSequences(Sema &S, SourceLocation Loc, |
110 | | const StandardConversionSequence& SCS1, |
111 | | const StandardConversionSequence& SCS2); |
112 | | |
113 | | static ImplicitConversionSequence::CompareKind |
114 | | CompareQualificationConversions(Sema &S, |
115 | | const StandardConversionSequence& SCS1, |
116 | | const StandardConversionSequence& SCS2); |
117 | | |
118 | | static ImplicitConversionSequence::CompareKind |
119 | | CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, |
120 | | const StandardConversionSequence& SCS1, |
121 | | const StandardConversionSequence& SCS2); |
122 | | |
123 | | /// GetConversionRank - Retrieve the implicit conversion rank |
124 | | /// corresponding to the given implicit conversion kind. |
125 | 0 | ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { |
126 | 0 | static const ImplicitConversionRank |
127 | 0 | Rank[] = { |
128 | 0 | ICR_Exact_Match, |
129 | 0 | ICR_Exact_Match, |
130 | 0 | ICR_Exact_Match, |
131 | 0 | ICR_Exact_Match, |
132 | 0 | ICR_Exact_Match, |
133 | 0 | ICR_Exact_Match, |
134 | 0 | ICR_Promotion, |
135 | 0 | ICR_Promotion, |
136 | 0 | ICR_Promotion, |
137 | 0 | ICR_Conversion, |
138 | 0 | ICR_Conversion, |
139 | 0 | ICR_Conversion, |
140 | 0 | ICR_Conversion, |
141 | 0 | ICR_Conversion, |
142 | 0 | ICR_Conversion, |
143 | 0 | ICR_Conversion, |
144 | 0 | ICR_Conversion, |
145 | 0 | ICR_Conversion, |
146 | 0 | ICR_Conversion, |
147 | 0 | ICR_Conversion, |
148 | 0 | ICR_Conversion, |
149 | 0 | ICR_OCL_Scalar_Widening, |
150 | 0 | ICR_Complex_Real_Conversion, |
151 | 0 | ICR_Conversion, |
152 | 0 | ICR_Conversion, |
153 | 0 | ICR_Writeback_Conversion, |
154 | 0 | ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- |
155 | | // it was omitted by the patch that added |
156 | | // ICK_Zero_Event_Conversion |
157 | 0 | ICR_Exact_Match, // NOTE(ctopper): This may not be completely right -- |
158 | | // it was omitted by the patch that added |
159 | | // ICK_Zero_Queue_Conversion |
160 | 0 | ICR_C_Conversion, |
161 | 0 | ICR_C_Conversion_Extension, |
162 | 0 | ICR_Conversion, |
163 | 0 | }; |
164 | 0 | static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds); |
165 | 0 | return Rank[(int)Kind]; |
166 | 0 | } |
167 | | |
168 | | /// GetImplicitConversionName - Return the name of this kind of |
169 | | /// implicit conversion. |
170 | 0 | static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { |
171 | 0 | static const char* const Name[] = { |
172 | 0 | "No conversion", |
173 | 0 | "Lvalue-to-rvalue", |
174 | 0 | "Array-to-pointer", |
175 | 0 | "Function-to-pointer", |
176 | 0 | "Function pointer conversion", |
177 | 0 | "Qualification", |
178 | 0 | "Integral promotion", |
179 | 0 | "Floating point promotion", |
180 | 0 | "Complex promotion", |
181 | 0 | "Integral conversion", |
182 | 0 | "Floating conversion", |
183 | 0 | "Complex conversion", |
184 | 0 | "Floating-integral conversion", |
185 | 0 | "Pointer conversion", |
186 | 0 | "Pointer-to-member conversion", |
187 | 0 | "Boolean conversion", |
188 | 0 | "Compatible-types conversion", |
189 | 0 | "Derived-to-base conversion", |
190 | 0 | "Vector conversion", |
191 | 0 | "SVE Vector conversion", |
192 | 0 | "RVV Vector conversion", |
193 | 0 | "Vector splat", |
194 | 0 | "Complex-real conversion", |
195 | 0 | "Block Pointer conversion", |
196 | 0 | "Transparent Union Conversion", |
197 | 0 | "Writeback conversion", |
198 | 0 | "OpenCL Zero Event Conversion", |
199 | 0 | "OpenCL Zero Queue Conversion", |
200 | 0 | "C specific type conversion", |
201 | 0 | "Incompatible pointer conversion", |
202 | 0 | "Fixed point conversion", |
203 | 0 | }; |
204 | 0 | static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds); |
205 | 0 | return Name[Kind]; |
206 | 0 | } |
207 | | |
208 | | /// StandardConversionSequence - Set the standard conversion |
209 | | /// sequence to the identity conversion. |
210 | 4 | void StandardConversionSequence::setAsIdentityConversion() { |
211 | 4 | First = ICK_Identity; |
212 | 4 | Second = ICK_Identity; |
213 | 4 | Third = ICK_Identity; |
214 | 4 | DeprecatedStringLiteralToCharPtr = false; |
215 | 4 | QualificationIncludesObjCLifetime = false; |
216 | 4 | ReferenceBinding = false; |
217 | 4 | DirectBinding = false; |
218 | 4 | IsLvalueReference = true; |
219 | 4 | BindsToFunctionLvalue = false; |
220 | 4 | BindsToRvalue = false; |
221 | 4 | BindsImplicitObjectArgumentWithoutRefQualifier = false; |
222 | 4 | ObjCLifetimeConversionBinding = false; |
223 | 4 | CopyConstructor = nullptr; |
224 | 4 | } |
225 | | |
226 | | /// getRank - Retrieve the rank of this standard conversion sequence |
227 | | /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the |
228 | | /// implicit conversions. |
229 | 0 | ImplicitConversionRank StandardConversionSequence::getRank() const { |
230 | 0 | ImplicitConversionRank Rank = ICR_Exact_Match; |
231 | 0 | if (GetConversionRank(First) > Rank) |
232 | 0 | Rank = GetConversionRank(First); |
233 | 0 | if (GetConversionRank(Second) > Rank) |
234 | 0 | Rank = GetConversionRank(Second); |
235 | 0 | if (GetConversionRank(Third) > Rank) |
236 | 0 | Rank = GetConversionRank(Third); |
237 | 0 | return Rank; |
238 | 0 | } |
239 | | |
240 | | /// isPointerConversionToBool - Determines whether this conversion is |
241 | | /// a conversion of a pointer or pointer-to-member to bool. This is |
242 | | /// used as part of the ranking of standard conversion sequences |
243 | | /// (C++ 13.3.3.2p4). |
244 | 0 | bool StandardConversionSequence::isPointerConversionToBool() const { |
245 | | // Note that FromType has not necessarily been transformed by the |
246 | | // array-to-pointer or function-to-pointer implicit conversions, so |
247 | | // check for their presence as well as checking whether FromType is |
248 | | // a pointer. |
249 | 0 | if (getToType(1)->isBooleanType() && |
250 | 0 | (getFromType()->isPointerType() || |
251 | 0 | getFromType()->isMemberPointerType() || |
252 | 0 | getFromType()->isObjCObjectPointerType() || |
253 | 0 | getFromType()->isBlockPointerType() || |
254 | 0 | First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) |
255 | 0 | return true; |
256 | | |
257 | 0 | return false; |
258 | 0 | } |
259 | | |
260 | | /// isPointerConversionToVoidPointer - Determines whether this |
261 | | /// conversion is a conversion of a pointer to a void pointer. This is |
262 | | /// used as part of the ranking of standard conversion sequences (C++ |
263 | | /// 13.3.3.2p4). |
264 | | bool |
265 | | StandardConversionSequence:: |
266 | 0 | isPointerConversionToVoidPointer(ASTContext& Context) const { |
267 | 0 | QualType FromType = getFromType(); |
268 | 0 | QualType ToType = getToType(1); |
269 | | |
270 | | // Note that FromType has not necessarily been transformed by the |
271 | | // array-to-pointer implicit conversion, so check for its presence |
272 | | // and redo the conversion to get a pointer. |
273 | 0 | if (First == ICK_Array_To_Pointer) |
274 | 0 | FromType = Context.getArrayDecayedType(FromType); |
275 | |
|
276 | 0 | if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) |
277 | 0 | if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) |
278 | 0 | return ToPtrType->getPointeeType()->isVoidType(); |
279 | | |
280 | 0 | return false; |
281 | 0 | } |
282 | | |
283 | | /// Skip any implicit casts which could be either part of a narrowing conversion |
284 | | /// or after one in an implicit conversion. |
285 | | static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx, |
286 | 0 | const Expr *Converted) { |
287 | | // We can have cleanups wrapping the converted expression; these need to be |
288 | | // preserved so that destructors run if necessary. |
289 | 0 | if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) { |
290 | 0 | Expr *Inner = |
291 | 0 | const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr())); |
292 | 0 | return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(), |
293 | 0 | EWC->getObjects()); |
294 | 0 | } |
295 | | |
296 | 0 | while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { |
297 | 0 | switch (ICE->getCastKind()) { |
298 | 0 | case CK_NoOp: |
299 | 0 | case CK_IntegralCast: |
300 | 0 | case CK_IntegralToBoolean: |
301 | 0 | case CK_IntegralToFloating: |
302 | 0 | case CK_BooleanToSignedIntegral: |
303 | 0 | case CK_FloatingToIntegral: |
304 | 0 | case CK_FloatingToBoolean: |
305 | 0 | case CK_FloatingCast: |
306 | 0 | Converted = ICE->getSubExpr(); |
307 | 0 | continue; |
308 | | |
309 | 0 | default: |
310 | 0 | return Converted; |
311 | 0 | } |
312 | 0 | } |
313 | | |
314 | 0 | return Converted; |
315 | 0 | } |
316 | | |
317 | | /// Check if this standard conversion sequence represents a narrowing |
318 | | /// conversion, according to C++11 [dcl.init.list]p7. |
319 | | /// |
320 | | /// \param Ctx The AST context. |
321 | | /// \param Converted The result of applying this standard conversion sequence. |
322 | | /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the |
323 | | /// value of the expression prior to the narrowing conversion. |
324 | | /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the |
325 | | /// type of the expression prior to the narrowing conversion. |
326 | | /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions |
327 | | /// from floating point types to integral types should be ignored. |
328 | | NarrowingKind StandardConversionSequence::getNarrowingKind( |
329 | | ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, |
330 | 0 | QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { |
331 | 0 | assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); |
332 | | |
333 | | // C++11 [dcl.init.list]p7: |
334 | | // A narrowing conversion is an implicit conversion ... |
335 | 0 | QualType FromType = getToType(0); |
336 | 0 | QualType ToType = getToType(1); |
337 | | |
338 | | // A conversion to an enumeration type is narrowing if the conversion to |
339 | | // the underlying type is narrowing. This only arises for expressions of |
340 | | // the form 'Enum{init}'. |
341 | 0 | if (auto *ET = ToType->getAs<EnumType>()) |
342 | 0 | ToType = ET->getDecl()->getIntegerType(); |
343 | |
|
344 | 0 | switch (Second) { |
345 | | // 'bool' is an integral type; dispatch to the right place to handle it. |
346 | 0 | case ICK_Boolean_Conversion: |
347 | 0 | if (FromType->isRealFloatingType()) |
348 | 0 | goto FloatingIntegralConversion; |
349 | 0 | if (FromType->isIntegralOrUnscopedEnumerationType()) |
350 | 0 | goto IntegralConversion; |
351 | | // -- from a pointer type or pointer-to-member type to bool, or |
352 | 0 | return NK_Type_Narrowing; |
353 | | |
354 | | // -- from a floating-point type to an integer type, or |
355 | | // |
356 | | // -- from an integer type or unscoped enumeration type to a floating-point |
357 | | // type, except where the source is a constant expression and the actual |
358 | | // value after conversion will fit into the target type and will produce |
359 | | // the original value when converted back to the original type, or |
360 | 0 | case ICK_Floating_Integral: |
361 | 0 | FloatingIntegralConversion: |
362 | 0 | if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { |
363 | 0 | return NK_Type_Narrowing; |
364 | 0 | } else if (FromType->isIntegralOrUnscopedEnumerationType() && |
365 | 0 | ToType->isRealFloatingType()) { |
366 | 0 | if (IgnoreFloatToIntegralConversion) |
367 | 0 | return NK_Not_Narrowing; |
368 | 0 | const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); |
369 | 0 | assert(Initializer && "Unknown conversion expression"); |
370 | | |
371 | | // If it's value-dependent, we can't tell whether it's narrowing. |
372 | 0 | if (Initializer->isValueDependent()) |
373 | 0 | return NK_Dependent_Narrowing; |
374 | | |
375 | 0 | if (std::optional<llvm::APSInt> IntConstantValue = |
376 | 0 | Initializer->getIntegerConstantExpr(Ctx)) { |
377 | | // Convert the integer to the floating type. |
378 | 0 | llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); |
379 | 0 | Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(), |
380 | 0 | llvm::APFloat::rmNearestTiesToEven); |
381 | | // And back. |
382 | 0 | llvm::APSInt ConvertedValue = *IntConstantValue; |
383 | 0 | bool ignored; |
384 | 0 | Result.convertToInteger(ConvertedValue, |
385 | 0 | llvm::APFloat::rmTowardZero, &ignored); |
386 | | // If the resulting value is different, this was a narrowing conversion. |
387 | 0 | if (*IntConstantValue != ConvertedValue) { |
388 | 0 | ConstantValue = APValue(*IntConstantValue); |
389 | 0 | ConstantType = Initializer->getType(); |
390 | 0 | return NK_Constant_Narrowing; |
391 | 0 | } |
392 | 0 | } else { |
393 | | // Variables are always narrowings. |
394 | 0 | return NK_Variable_Narrowing; |
395 | 0 | } |
396 | 0 | } |
397 | 0 | return NK_Not_Narrowing; |
398 | | |
399 | | // -- from long double to double or float, or from double to float, except |
400 | | // where the source is a constant expression and the actual value after |
401 | | // conversion is within the range of values that can be represented (even |
402 | | // if it cannot be represented exactly), or |
403 | 0 | case ICK_Floating_Conversion: |
404 | 0 | if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && |
405 | 0 | Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { |
406 | | // FromType is larger than ToType. |
407 | 0 | const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); |
408 | | |
409 | | // If it's value-dependent, we can't tell whether it's narrowing. |
410 | 0 | if (Initializer->isValueDependent()) |
411 | 0 | return NK_Dependent_Narrowing; |
412 | | |
413 | 0 | if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { |
414 | | // Constant! |
415 | 0 | assert(ConstantValue.isFloat()); |
416 | 0 | llvm::APFloat FloatVal = ConstantValue.getFloat(); |
417 | | // Convert the source value into the target type. |
418 | 0 | bool ignored; |
419 | 0 | llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( |
420 | 0 | Ctx.getFloatTypeSemantics(ToType), |
421 | 0 | llvm::APFloat::rmNearestTiesToEven, &ignored); |
422 | | // If there was no overflow, the source value is within the range of |
423 | | // values that can be represented. |
424 | 0 | if (ConvertStatus & llvm::APFloat::opOverflow) { |
425 | 0 | ConstantType = Initializer->getType(); |
426 | 0 | return NK_Constant_Narrowing; |
427 | 0 | } |
428 | 0 | } else { |
429 | 0 | return NK_Variable_Narrowing; |
430 | 0 | } |
431 | 0 | } |
432 | 0 | return NK_Not_Narrowing; |
433 | | |
434 | | // -- from an integer type or unscoped enumeration type to an integer type |
435 | | // that cannot represent all the values of the original type, except where |
436 | | // the source is a constant expression and the actual value after |
437 | | // conversion will fit into the target type and will produce the original |
438 | | // value when converted back to the original type. |
439 | 0 | case ICK_Integral_Conversion: |
440 | 0 | IntegralConversion: { |
441 | 0 | assert(FromType->isIntegralOrUnscopedEnumerationType()); |
442 | 0 | assert(ToType->isIntegralOrUnscopedEnumerationType()); |
443 | 0 | const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); |
444 | 0 | const unsigned FromWidth = Ctx.getIntWidth(FromType); |
445 | 0 | const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); |
446 | 0 | const unsigned ToWidth = Ctx.getIntWidth(ToType); |
447 | |
|
448 | 0 | if (FromWidth > ToWidth || |
449 | 0 | (FromWidth == ToWidth && FromSigned != ToSigned) || |
450 | 0 | (FromSigned && !ToSigned)) { |
451 | | // Not all values of FromType can be represented in ToType. |
452 | 0 | const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); |
453 | | |
454 | | // If it's value-dependent, we can't tell whether it's narrowing. |
455 | 0 | if (Initializer->isValueDependent()) |
456 | 0 | return NK_Dependent_Narrowing; |
457 | | |
458 | 0 | std::optional<llvm::APSInt> OptInitializerValue; |
459 | 0 | if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) { |
460 | | // Such conversions on variables are always narrowing. |
461 | 0 | return NK_Variable_Narrowing; |
462 | 0 | } |
463 | 0 | llvm::APSInt &InitializerValue = *OptInitializerValue; |
464 | 0 | bool Narrowing = false; |
465 | 0 | if (FromWidth < ToWidth) { |
466 | | // Negative -> unsigned is narrowing. Otherwise, more bits is never |
467 | | // narrowing. |
468 | 0 | if (InitializerValue.isSigned() && InitializerValue.isNegative()) |
469 | 0 | Narrowing = true; |
470 | 0 | } else { |
471 | | // Add a bit to the InitializerValue so we don't have to worry about |
472 | | // signed vs. unsigned comparisons. |
473 | 0 | InitializerValue = InitializerValue.extend( |
474 | 0 | InitializerValue.getBitWidth() + 1); |
475 | | // Convert the initializer to and from the target width and signed-ness. |
476 | 0 | llvm::APSInt ConvertedValue = InitializerValue; |
477 | 0 | ConvertedValue = ConvertedValue.trunc(ToWidth); |
478 | 0 | ConvertedValue.setIsSigned(ToSigned); |
479 | 0 | ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); |
480 | 0 | ConvertedValue.setIsSigned(InitializerValue.isSigned()); |
481 | | // If the result is different, this was a narrowing conversion. |
482 | 0 | if (ConvertedValue != InitializerValue) |
483 | 0 | Narrowing = true; |
484 | 0 | } |
485 | 0 | if (Narrowing) { |
486 | 0 | ConstantType = Initializer->getType(); |
487 | 0 | ConstantValue = APValue(InitializerValue); |
488 | 0 | return NK_Constant_Narrowing; |
489 | 0 | } |
490 | 0 | } |
491 | 0 | return NK_Not_Narrowing; |
492 | 0 | } |
493 | | |
494 | 0 | default: |
495 | | // Other kinds of conversions are not narrowings. |
496 | 0 | return NK_Not_Narrowing; |
497 | 0 | } |
498 | 0 | } |
499 | | |
500 | | /// dump - Print this standard conversion sequence to standard |
501 | | /// error. Useful for debugging overloading issues. |
502 | 0 | LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { |
503 | 0 | raw_ostream &OS = llvm::errs(); |
504 | 0 | bool PrintedSomething = false; |
505 | 0 | if (First != ICK_Identity) { |
506 | 0 | OS << GetImplicitConversionName(First); |
507 | 0 | PrintedSomething = true; |
508 | 0 | } |
509 | |
|
510 | 0 | if (Second != ICK_Identity) { |
511 | 0 | if (PrintedSomething) { |
512 | 0 | OS << " -> "; |
513 | 0 | } |
514 | 0 | OS << GetImplicitConversionName(Second); |
515 | |
|
516 | 0 | if (CopyConstructor) { |
517 | 0 | OS << " (by copy constructor)"; |
518 | 0 | } else if (DirectBinding) { |
519 | 0 | OS << " (direct reference binding)"; |
520 | 0 | } else if (ReferenceBinding) { |
521 | 0 | OS << " (reference binding)"; |
522 | 0 | } |
523 | 0 | PrintedSomething = true; |
524 | 0 | } |
525 | |
|
526 | 0 | if (Third != ICK_Identity) { |
527 | 0 | if (PrintedSomething) { |
528 | 0 | OS << " -> "; |
529 | 0 | } |
530 | 0 | OS << GetImplicitConversionName(Third); |
531 | 0 | PrintedSomething = true; |
532 | 0 | } |
533 | |
|
534 | 0 | if (!PrintedSomething) { |
535 | 0 | OS << "No conversions required"; |
536 | 0 | } |
537 | 0 | } |
538 | | |
539 | | /// dump - Print this user-defined conversion sequence to standard |
540 | | /// error. Useful for debugging overloading issues. |
541 | 0 | void UserDefinedConversionSequence::dump() const { |
542 | 0 | raw_ostream &OS = llvm::errs(); |
543 | 0 | if (Before.First || Before.Second || Before.Third) { |
544 | 0 | Before.dump(); |
545 | 0 | OS << " -> "; |
546 | 0 | } |
547 | 0 | if (ConversionFunction) |
548 | 0 | OS << '\'' << *ConversionFunction << '\''; |
549 | 0 | else |
550 | 0 | OS << "aggregate initialization"; |
551 | 0 | if (After.First || After.Second || After.Third) { |
552 | 0 | OS << " -> "; |
553 | 0 | After.dump(); |
554 | 0 | } |
555 | 0 | } |
556 | | |
557 | | /// dump - Print this implicit conversion sequence to standard |
558 | | /// error. Useful for debugging overloading issues. |
559 | 0 | void ImplicitConversionSequence::dump() const { |
560 | 0 | raw_ostream &OS = llvm::errs(); |
561 | 0 | if (hasInitializerListContainerType()) |
562 | 0 | OS << "Worst list element conversion: "; |
563 | 0 | switch (ConversionKind) { |
564 | 0 | case StandardConversion: |
565 | 0 | OS << "Standard conversion: "; |
566 | 0 | Standard.dump(); |
567 | 0 | break; |
568 | 0 | case UserDefinedConversion: |
569 | 0 | OS << "User-defined conversion: "; |
570 | 0 | UserDefined.dump(); |
571 | 0 | break; |
572 | 0 | case EllipsisConversion: |
573 | 0 | OS << "Ellipsis conversion"; |
574 | 0 | break; |
575 | 0 | case AmbiguousConversion: |
576 | 0 | OS << "Ambiguous conversion"; |
577 | 0 | break; |
578 | 0 | case BadConversion: |
579 | 0 | OS << "Bad conversion"; |
580 | 0 | break; |
581 | 0 | } |
582 | | |
583 | 0 | OS << "\n"; |
584 | 0 | } |
585 | | |
586 | 0 | void AmbiguousConversionSequence::construct() { |
587 | 0 | new (&conversions()) ConversionSet(); |
588 | 0 | } |
589 | | |
590 | 0 | void AmbiguousConversionSequence::destruct() { |
591 | 0 | conversions().~ConversionSet(); |
592 | 0 | } |
593 | | |
594 | | void |
595 | 0 | AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { |
596 | 0 | FromTypePtr = O.FromTypePtr; |
597 | 0 | ToTypePtr = O.ToTypePtr; |
598 | 0 | new (&conversions()) ConversionSet(O.conversions()); |
599 | 0 | } |
600 | | |
601 | | namespace { |
602 | | // Structure used by DeductionFailureInfo to store |
603 | | // template argument information. |
604 | | struct DFIArguments { |
605 | | TemplateArgument FirstArg; |
606 | | TemplateArgument SecondArg; |
607 | | }; |
608 | | // Structure used by DeductionFailureInfo to store |
609 | | // template parameter and template argument information. |
610 | | struct DFIParamWithArguments : DFIArguments { |
611 | | TemplateParameter Param; |
612 | | }; |
613 | | // Structure used by DeductionFailureInfo to store template argument |
614 | | // information and the index of the problematic call argument. |
615 | | struct DFIDeducedMismatchArgs : DFIArguments { |
616 | | TemplateArgumentList *TemplateArgs; |
617 | | unsigned CallArgIndex; |
618 | | }; |
619 | | // Structure used by DeductionFailureInfo to store information about |
620 | | // unsatisfied constraints. |
621 | | struct CNSInfo { |
622 | | TemplateArgumentList *TemplateArgs; |
623 | | ConstraintSatisfaction Satisfaction; |
624 | | }; |
625 | | } |
626 | | |
627 | | /// Convert from Sema's representation of template deduction information |
628 | | /// to the form used in overload-candidate information. |
629 | | DeductionFailureInfo |
630 | | clang::MakeDeductionFailureInfo(ASTContext &Context, |
631 | | Sema::TemplateDeductionResult TDK, |
632 | 0 | TemplateDeductionInfo &Info) { |
633 | 0 | DeductionFailureInfo Result; |
634 | 0 | Result.Result = static_cast<unsigned>(TDK); |
635 | 0 | Result.HasDiagnostic = false; |
636 | 0 | switch (TDK) { |
637 | 0 | case Sema::TDK_Invalid: |
638 | 0 | case Sema::TDK_InstantiationDepth: |
639 | 0 | case Sema::TDK_TooManyArguments: |
640 | 0 | case Sema::TDK_TooFewArguments: |
641 | 0 | case Sema::TDK_MiscellaneousDeductionFailure: |
642 | 0 | case Sema::TDK_CUDATargetMismatch: |
643 | 0 | Result.Data = nullptr; |
644 | 0 | break; |
645 | | |
646 | 0 | case Sema::TDK_Incomplete: |
647 | 0 | case Sema::TDK_InvalidExplicitArguments: |
648 | 0 | Result.Data = Info.Param.getOpaqueValue(); |
649 | 0 | break; |
650 | | |
651 | 0 | case Sema::TDK_DeducedMismatch: |
652 | 0 | case Sema::TDK_DeducedMismatchNested: { |
653 | | // FIXME: Should allocate from normal heap so that we can free this later. |
654 | 0 | auto *Saved = new (Context) DFIDeducedMismatchArgs; |
655 | 0 | Saved->FirstArg = Info.FirstArg; |
656 | 0 | Saved->SecondArg = Info.SecondArg; |
657 | 0 | Saved->TemplateArgs = Info.takeSugared(); |
658 | 0 | Saved->CallArgIndex = Info.CallArgIndex; |
659 | 0 | Result.Data = Saved; |
660 | 0 | break; |
661 | 0 | } |
662 | | |
663 | 0 | case Sema::TDK_NonDeducedMismatch: { |
664 | | // FIXME: Should allocate from normal heap so that we can free this later. |
665 | 0 | DFIArguments *Saved = new (Context) DFIArguments; |
666 | 0 | Saved->FirstArg = Info.FirstArg; |
667 | 0 | Saved->SecondArg = Info.SecondArg; |
668 | 0 | Result.Data = Saved; |
669 | 0 | break; |
670 | 0 | } |
671 | | |
672 | 0 | case Sema::TDK_IncompletePack: |
673 | | // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. |
674 | 0 | case Sema::TDK_Inconsistent: |
675 | 0 | case Sema::TDK_Underqualified: { |
676 | | // FIXME: Should allocate from normal heap so that we can free this later. |
677 | 0 | DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; |
678 | 0 | Saved->Param = Info.Param; |
679 | 0 | Saved->FirstArg = Info.FirstArg; |
680 | 0 | Saved->SecondArg = Info.SecondArg; |
681 | 0 | Result.Data = Saved; |
682 | 0 | break; |
683 | 0 | } |
684 | | |
685 | 0 | case Sema::TDK_SubstitutionFailure: |
686 | 0 | Result.Data = Info.takeSugared(); |
687 | 0 | if (Info.hasSFINAEDiagnostic()) { |
688 | 0 | PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( |
689 | 0 | SourceLocation(), PartialDiagnostic::NullDiagnostic()); |
690 | 0 | Info.takeSFINAEDiagnostic(*Diag); |
691 | 0 | Result.HasDiagnostic = true; |
692 | 0 | } |
693 | 0 | break; |
694 | | |
695 | 0 | case Sema::TDK_ConstraintsNotSatisfied: { |
696 | 0 | CNSInfo *Saved = new (Context) CNSInfo; |
697 | 0 | Saved->TemplateArgs = Info.takeSugared(); |
698 | 0 | Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction; |
699 | 0 | Result.Data = Saved; |
700 | 0 | break; |
701 | 0 | } |
702 | | |
703 | 0 | case Sema::TDK_Success: |
704 | 0 | case Sema::TDK_NonDependentConversionFailure: |
705 | 0 | case Sema::TDK_AlreadyDiagnosed: |
706 | 0 | llvm_unreachable("not a deduction failure"); |
707 | 0 | } |
708 | | |
709 | 0 | return Result; |
710 | 0 | } |
711 | | |
712 | 0 | void DeductionFailureInfo::Destroy() { |
713 | 0 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { |
714 | 0 | case Sema::TDK_Success: |
715 | 0 | case Sema::TDK_Invalid: |
716 | 0 | case Sema::TDK_InstantiationDepth: |
717 | 0 | case Sema::TDK_Incomplete: |
718 | 0 | case Sema::TDK_TooManyArguments: |
719 | 0 | case Sema::TDK_TooFewArguments: |
720 | 0 | case Sema::TDK_InvalidExplicitArguments: |
721 | 0 | case Sema::TDK_CUDATargetMismatch: |
722 | 0 | case Sema::TDK_NonDependentConversionFailure: |
723 | 0 | break; |
724 | | |
725 | 0 | case Sema::TDK_IncompletePack: |
726 | 0 | case Sema::TDK_Inconsistent: |
727 | 0 | case Sema::TDK_Underqualified: |
728 | 0 | case Sema::TDK_DeducedMismatch: |
729 | 0 | case Sema::TDK_DeducedMismatchNested: |
730 | 0 | case Sema::TDK_NonDeducedMismatch: |
731 | | // FIXME: Destroy the data? |
732 | 0 | Data = nullptr; |
733 | 0 | break; |
734 | | |
735 | 0 | case Sema::TDK_SubstitutionFailure: |
736 | | // FIXME: Destroy the template argument list? |
737 | 0 | Data = nullptr; |
738 | 0 | if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { |
739 | 0 | Diag->~PartialDiagnosticAt(); |
740 | 0 | HasDiagnostic = false; |
741 | 0 | } |
742 | 0 | break; |
743 | | |
744 | 0 | case Sema::TDK_ConstraintsNotSatisfied: |
745 | | // FIXME: Destroy the template argument list? |
746 | 0 | Data = nullptr; |
747 | 0 | if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { |
748 | 0 | Diag->~PartialDiagnosticAt(); |
749 | 0 | HasDiagnostic = false; |
750 | 0 | } |
751 | 0 | break; |
752 | | |
753 | | // Unhandled |
754 | 0 | case Sema::TDK_MiscellaneousDeductionFailure: |
755 | 0 | case Sema::TDK_AlreadyDiagnosed: |
756 | 0 | break; |
757 | 0 | } |
758 | 0 | } |
759 | | |
760 | 0 | PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { |
761 | 0 | if (HasDiagnostic) |
762 | 0 | return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); |
763 | 0 | return nullptr; |
764 | 0 | } |
765 | | |
766 | 0 | TemplateParameter DeductionFailureInfo::getTemplateParameter() { |
767 | 0 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { |
768 | 0 | case Sema::TDK_Success: |
769 | 0 | case Sema::TDK_Invalid: |
770 | 0 | case Sema::TDK_InstantiationDepth: |
771 | 0 | case Sema::TDK_TooManyArguments: |
772 | 0 | case Sema::TDK_TooFewArguments: |
773 | 0 | case Sema::TDK_SubstitutionFailure: |
774 | 0 | case Sema::TDK_DeducedMismatch: |
775 | 0 | case Sema::TDK_DeducedMismatchNested: |
776 | 0 | case Sema::TDK_NonDeducedMismatch: |
777 | 0 | case Sema::TDK_CUDATargetMismatch: |
778 | 0 | case Sema::TDK_NonDependentConversionFailure: |
779 | 0 | case Sema::TDK_ConstraintsNotSatisfied: |
780 | 0 | return TemplateParameter(); |
781 | | |
782 | 0 | case Sema::TDK_Incomplete: |
783 | 0 | case Sema::TDK_InvalidExplicitArguments: |
784 | 0 | return TemplateParameter::getFromOpaqueValue(Data); |
785 | | |
786 | 0 | case Sema::TDK_IncompletePack: |
787 | 0 | case Sema::TDK_Inconsistent: |
788 | 0 | case Sema::TDK_Underqualified: |
789 | 0 | return static_cast<DFIParamWithArguments*>(Data)->Param; |
790 | | |
791 | | // Unhandled |
792 | 0 | case Sema::TDK_MiscellaneousDeductionFailure: |
793 | 0 | case Sema::TDK_AlreadyDiagnosed: |
794 | 0 | break; |
795 | 0 | } |
796 | | |
797 | 0 | return TemplateParameter(); |
798 | 0 | } |
799 | | |
800 | 0 | TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { |
801 | 0 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { |
802 | 0 | case Sema::TDK_Success: |
803 | 0 | case Sema::TDK_Invalid: |
804 | 0 | case Sema::TDK_InstantiationDepth: |
805 | 0 | case Sema::TDK_TooManyArguments: |
806 | 0 | case Sema::TDK_TooFewArguments: |
807 | 0 | case Sema::TDK_Incomplete: |
808 | 0 | case Sema::TDK_IncompletePack: |
809 | 0 | case Sema::TDK_InvalidExplicitArguments: |
810 | 0 | case Sema::TDK_Inconsistent: |
811 | 0 | case Sema::TDK_Underqualified: |
812 | 0 | case Sema::TDK_NonDeducedMismatch: |
813 | 0 | case Sema::TDK_CUDATargetMismatch: |
814 | 0 | case Sema::TDK_NonDependentConversionFailure: |
815 | 0 | return nullptr; |
816 | | |
817 | 0 | case Sema::TDK_DeducedMismatch: |
818 | 0 | case Sema::TDK_DeducedMismatchNested: |
819 | 0 | return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; |
820 | | |
821 | 0 | case Sema::TDK_SubstitutionFailure: |
822 | 0 | return static_cast<TemplateArgumentList*>(Data); |
823 | | |
824 | 0 | case Sema::TDK_ConstraintsNotSatisfied: |
825 | 0 | return static_cast<CNSInfo*>(Data)->TemplateArgs; |
826 | | |
827 | | // Unhandled |
828 | 0 | case Sema::TDK_MiscellaneousDeductionFailure: |
829 | 0 | case Sema::TDK_AlreadyDiagnosed: |
830 | 0 | break; |
831 | 0 | } |
832 | | |
833 | 0 | return nullptr; |
834 | 0 | } |
835 | | |
836 | 0 | const TemplateArgument *DeductionFailureInfo::getFirstArg() { |
837 | 0 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { |
838 | 0 | case Sema::TDK_Success: |
839 | 0 | case Sema::TDK_Invalid: |
840 | 0 | case Sema::TDK_InstantiationDepth: |
841 | 0 | case Sema::TDK_Incomplete: |
842 | 0 | case Sema::TDK_TooManyArguments: |
843 | 0 | case Sema::TDK_TooFewArguments: |
844 | 0 | case Sema::TDK_InvalidExplicitArguments: |
845 | 0 | case Sema::TDK_SubstitutionFailure: |
846 | 0 | case Sema::TDK_CUDATargetMismatch: |
847 | 0 | case Sema::TDK_NonDependentConversionFailure: |
848 | 0 | case Sema::TDK_ConstraintsNotSatisfied: |
849 | 0 | return nullptr; |
850 | | |
851 | 0 | case Sema::TDK_IncompletePack: |
852 | 0 | case Sema::TDK_Inconsistent: |
853 | 0 | case Sema::TDK_Underqualified: |
854 | 0 | case Sema::TDK_DeducedMismatch: |
855 | 0 | case Sema::TDK_DeducedMismatchNested: |
856 | 0 | case Sema::TDK_NonDeducedMismatch: |
857 | 0 | return &static_cast<DFIArguments*>(Data)->FirstArg; |
858 | | |
859 | | // Unhandled |
860 | 0 | case Sema::TDK_MiscellaneousDeductionFailure: |
861 | 0 | case Sema::TDK_AlreadyDiagnosed: |
862 | 0 | break; |
863 | 0 | } |
864 | | |
865 | 0 | return nullptr; |
866 | 0 | } |
867 | | |
868 | 0 | const TemplateArgument *DeductionFailureInfo::getSecondArg() { |
869 | 0 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { |
870 | 0 | case Sema::TDK_Success: |
871 | 0 | case Sema::TDK_Invalid: |
872 | 0 | case Sema::TDK_InstantiationDepth: |
873 | 0 | case Sema::TDK_Incomplete: |
874 | 0 | case Sema::TDK_IncompletePack: |
875 | 0 | case Sema::TDK_TooManyArguments: |
876 | 0 | case Sema::TDK_TooFewArguments: |
877 | 0 | case Sema::TDK_InvalidExplicitArguments: |
878 | 0 | case Sema::TDK_SubstitutionFailure: |
879 | 0 | case Sema::TDK_CUDATargetMismatch: |
880 | 0 | case Sema::TDK_NonDependentConversionFailure: |
881 | 0 | case Sema::TDK_ConstraintsNotSatisfied: |
882 | 0 | return nullptr; |
883 | | |
884 | 0 | case Sema::TDK_Inconsistent: |
885 | 0 | case Sema::TDK_Underqualified: |
886 | 0 | case Sema::TDK_DeducedMismatch: |
887 | 0 | case Sema::TDK_DeducedMismatchNested: |
888 | 0 | case Sema::TDK_NonDeducedMismatch: |
889 | 0 | return &static_cast<DFIArguments*>(Data)->SecondArg; |
890 | | |
891 | | // Unhandled |
892 | 0 | case Sema::TDK_MiscellaneousDeductionFailure: |
893 | 0 | case Sema::TDK_AlreadyDiagnosed: |
894 | 0 | break; |
895 | 0 | } |
896 | | |
897 | 0 | return nullptr; |
898 | 0 | } |
899 | | |
900 | 0 | std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() { |
901 | 0 | switch (static_cast<Sema::TemplateDeductionResult>(Result)) { |
902 | 0 | case Sema::TDK_DeducedMismatch: |
903 | 0 | case Sema::TDK_DeducedMismatchNested: |
904 | 0 | return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; |
905 | | |
906 | 0 | default: |
907 | 0 | return std::nullopt; |
908 | 0 | } |
909 | 0 | } |
910 | | |
911 | | static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X, |
912 | 0 | const FunctionDecl *Y) { |
913 | 0 | if (!X || !Y) |
914 | 0 | return false; |
915 | 0 | if (X->getNumParams() != Y->getNumParams()) |
916 | 0 | return false; |
917 | | // FIXME: when do rewritten comparison operators |
918 | | // with explicit object parameters correspond? |
919 | | // https://cplusplus.github.io/CWG/issues/2797.html |
920 | 0 | for (unsigned I = 0; I < X->getNumParams(); ++I) |
921 | 0 | if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(), |
922 | 0 | Y->getParamDecl(I)->getType())) |
923 | 0 | return false; |
924 | 0 | if (auto *FTX = X->getDescribedFunctionTemplate()) { |
925 | 0 | auto *FTY = Y->getDescribedFunctionTemplate(); |
926 | 0 | if (!FTY) |
927 | 0 | return false; |
928 | 0 | if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(), |
929 | 0 | FTY->getTemplateParameters())) |
930 | 0 | return false; |
931 | 0 | } |
932 | 0 | return true; |
933 | 0 | } |
934 | | |
935 | | static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc, |
936 | 0 | Expr *FirstOperand, FunctionDecl *EqFD) { |
937 | 0 | assert(EqFD->getOverloadedOperator() == |
938 | 0 | OverloadedOperatorKind::OO_EqualEqual); |
939 | | // C++2a [over.match.oper]p4: |
940 | | // A non-template function or function template F named operator== is a |
941 | | // rewrite target with first operand o unless a search for the name operator!= |
942 | | // in the scope S from the instantiation context of the operator expression |
943 | | // finds a function or function template that would correspond |
944 | | // ([basic.scope.scope]) to F if its name were operator==, where S is the |
945 | | // scope of the class type of o if F is a class member, and the namespace |
946 | | // scope of which F is a member otherwise. A function template specialization |
947 | | // named operator== is a rewrite target if its function template is a rewrite |
948 | | // target. |
949 | 0 | DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName( |
950 | 0 | OverloadedOperatorKind::OO_ExclaimEqual); |
951 | 0 | if (isa<CXXMethodDecl>(EqFD)) { |
952 | | // If F is a class member, search scope is class type of first operand. |
953 | 0 | QualType RHS = FirstOperand->getType(); |
954 | 0 | auto *RHSRec = RHS->getAs<RecordType>(); |
955 | 0 | if (!RHSRec) |
956 | 0 | return true; |
957 | 0 | LookupResult Members(S, NotEqOp, OpLoc, |
958 | 0 | Sema::LookupNameKind::LookupMemberName); |
959 | 0 | S.LookupQualifiedName(Members, RHSRec->getDecl()); |
960 | 0 | Members.suppressAccessDiagnostics(); |
961 | 0 | for (NamedDecl *Op : Members) |
962 | 0 | if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction())) |
963 | 0 | return false; |
964 | 0 | return true; |
965 | 0 | } |
966 | | // Otherwise the search scope is the namespace scope of which F is a member. |
967 | 0 | for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) { |
968 | 0 | auto *NotEqFD = Op->getAsFunction(); |
969 | 0 | if (auto *UD = dyn_cast<UsingShadowDecl>(Op)) |
970 | 0 | NotEqFD = UD->getUnderlyingDecl()->getAsFunction(); |
971 | 0 | if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) && |
972 | 0 | declaresSameEntity(cast<Decl>(EqFD->getEnclosingNamespaceContext()), |
973 | 0 | cast<Decl>(Op->getLexicalDeclContext()))) |
974 | 0 | return false; |
975 | 0 | } |
976 | 0 | return true; |
977 | 0 | } |
978 | | |
979 | | bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed( |
980 | 0 | OverloadedOperatorKind Op) { |
981 | 0 | if (!AllowRewrittenCandidates) |
982 | 0 | return false; |
983 | 0 | return Op == OO_EqualEqual || Op == OO_Spaceship; |
984 | 0 | } |
985 | | |
986 | | bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( |
987 | 0 | Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) { |
988 | 0 | auto Op = FD->getOverloadedOperator(); |
989 | 0 | if (!allowsReversed(Op)) |
990 | 0 | return false; |
991 | 0 | if (Op == OverloadedOperatorKind::OO_EqualEqual) { |
992 | 0 | assert(OriginalArgs.size() == 2); |
993 | 0 | if (!shouldAddReversedEqEq( |
994 | 0 | S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD)) |
995 | 0 | return false; |
996 | 0 | } |
997 | | // Don't bother adding a reversed candidate that can never be a better |
998 | | // match than the non-reversed version. |
999 | 0 | return FD->getNumNonObjectParams() != 2 || |
1000 | 0 | !S.Context.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(), |
1001 | 0 | FD->getParamDecl(1)->getType()) || |
1002 | 0 | FD->hasAttr<EnableIfAttr>(); |
1003 | 0 | } |
1004 | | |
1005 | 24 | void OverloadCandidateSet::destroyCandidates() { |
1006 | 24 | for (iterator i = begin(), e = end(); i != e; ++i) { |
1007 | 0 | for (auto &C : i->Conversions) |
1008 | 0 | C.~ImplicitConversionSequence(); |
1009 | 0 | if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) |
1010 | 0 | i->DeductionFailure.Destroy(); |
1011 | 0 | } |
1012 | 24 | } |
1013 | | |
1014 | 2 | void OverloadCandidateSet::clear(CandidateSetKind CSK) { |
1015 | 2 | destroyCandidates(); |
1016 | 2 | SlabAllocator.Reset(); |
1017 | 2 | NumInlineBytesUsed = 0; |
1018 | 2 | Candidates.clear(); |
1019 | 2 | Functions.clear(); |
1020 | 2 | Kind = CSK; |
1021 | 2 | } |
1022 | | |
1023 | | namespace { |
1024 | | class UnbridgedCastsSet { |
1025 | | struct Entry { |
1026 | | Expr **Addr; |
1027 | | Expr *Saved; |
1028 | | }; |
1029 | | SmallVector<Entry, 2> Entries; |
1030 | | |
1031 | | public: |
1032 | 0 | void save(Sema &S, Expr *&E) { |
1033 | 0 | assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); |
1034 | 0 | Entry entry = { &E, E }; |
1035 | 0 | Entries.push_back(entry); |
1036 | 0 | E = S.stripARCUnbridgedCast(E); |
1037 | 0 | } |
1038 | | |
1039 | 0 | void restore() { |
1040 | 0 | for (SmallVectorImpl<Entry>::iterator |
1041 | 0 | i = Entries.begin(), e = Entries.end(); i != e; ++i) |
1042 | 0 | *i->Addr = i->Saved; |
1043 | 0 | } |
1044 | | }; |
1045 | | } |
1046 | | |
1047 | | /// checkPlaceholderForOverload - Do any interesting placeholder-like |
1048 | | /// preprocessing on the given expression. |
1049 | | /// |
1050 | | /// \param unbridgedCasts a collection to which to add unbridged casts; |
1051 | | /// without this, they will be immediately diagnosed as errors |
1052 | | /// |
1053 | | /// Return true on unrecoverable error. |
1054 | | static bool |
1055 | | checkPlaceholderForOverload(Sema &S, Expr *&E, |
1056 | 7 | UnbridgedCastsSet *unbridgedCasts = nullptr) { |
1057 | 7 | if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { |
1058 | | // We can't handle overloaded expressions here because overload |
1059 | | // resolution might reasonably tweak them. |
1060 | 0 | if (placeholder->getKind() == BuiltinType::Overload) return false; |
1061 | | |
1062 | | // If the context potentially accepts unbridged ARC casts, strip |
1063 | | // the unbridged cast and add it to the collection for later restoration. |
1064 | 0 | if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && |
1065 | 0 | unbridgedCasts) { |
1066 | 0 | unbridgedCasts->save(S, E); |
1067 | 0 | return false; |
1068 | 0 | } |
1069 | | |
1070 | | // Go ahead and check everything else. |
1071 | 0 | ExprResult result = S.CheckPlaceholderExpr(E); |
1072 | 0 | if (result.isInvalid()) |
1073 | 0 | return true; |
1074 | | |
1075 | 0 | E = result.get(); |
1076 | 0 | return false; |
1077 | 0 | } |
1078 | | |
1079 | | // Nothing to do. |
1080 | 7 | return false; |
1081 | 7 | } |
1082 | | |
1083 | | /// checkArgPlaceholdersForOverload - Check a set of call operands for |
1084 | | /// placeholders. |
1085 | | static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, |
1086 | 0 | UnbridgedCastsSet &unbridged) { |
1087 | 0 | for (unsigned i = 0, e = Args.size(); i != e; ++i) |
1088 | 0 | if (checkPlaceholderForOverload(S, Args[i], &unbridged)) |
1089 | 0 | return true; |
1090 | | |
1091 | 0 | return false; |
1092 | 0 | } |
1093 | | |
1094 | | /// Determine whether the given New declaration is an overload of the |
1095 | | /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if |
1096 | | /// New and Old cannot be overloaded, e.g., if New has the same signature as |
1097 | | /// some function in Old (C++ 1.3.10) or if the Old declarations aren't |
1098 | | /// functions (or function templates) at all. When it does return Ovl_Match or |
1099 | | /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be |
1100 | | /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying |
1101 | | /// declaration. |
1102 | | /// |
1103 | | /// Example: Given the following input: |
1104 | | /// |
1105 | | /// void f(int, float); // #1 |
1106 | | /// void f(int, int); // #2 |
1107 | | /// int f(int, int); // #3 |
1108 | | /// |
1109 | | /// When we process #1, there is no previous declaration of "f", so IsOverload |
1110 | | /// will not be used. |
1111 | | /// |
1112 | | /// When we process #2, Old contains only the FunctionDecl for #1. By comparing |
1113 | | /// the parameter types, we see that #1 and #2 are overloaded (since they have |
1114 | | /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is |
1115 | | /// unchanged. |
1116 | | /// |
1117 | | /// When we process #3, Old is an overload set containing #1 and #2. We compare |
1118 | | /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then |
1119 | | /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of |
1120 | | /// functions are not part of the signature), IsOverload returns Ovl_Match and |
1121 | | /// MatchedDecl will be set to point to the FunctionDecl for #2. |
1122 | | /// |
1123 | | /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class |
1124 | | /// by a using declaration. The rules for whether to hide shadow declarations |
1125 | | /// ignore some properties which otherwise figure into a function template's |
1126 | | /// signature. |
1127 | | Sema::OverloadKind |
1128 | | Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, |
1129 | 0 | NamedDecl *&Match, bool NewIsUsingDecl) { |
1130 | 0 | for (LookupResult::iterator I = Old.begin(), E = Old.end(); |
1131 | 0 | I != E; ++I) { |
1132 | 0 | NamedDecl *OldD = *I; |
1133 | |
|
1134 | 0 | bool OldIsUsingDecl = false; |
1135 | 0 | if (isa<UsingShadowDecl>(OldD)) { |
1136 | 0 | OldIsUsingDecl = true; |
1137 | | |
1138 | | // We can always introduce two using declarations into the same |
1139 | | // context, even if they have identical signatures. |
1140 | 0 | if (NewIsUsingDecl) continue; |
1141 | | |
1142 | 0 | OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); |
1143 | 0 | } |
1144 | | |
1145 | | // A using-declaration does not conflict with another declaration |
1146 | | // if one of them is hidden. |
1147 | 0 | if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) |
1148 | 0 | continue; |
1149 | | |
1150 | | // If either declaration was introduced by a using declaration, |
1151 | | // we'll need to use slightly different rules for matching. |
1152 | | // Essentially, these rules are the normal rules, except that |
1153 | | // function templates hide function templates with different |
1154 | | // return types or template parameter lists. |
1155 | 0 | bool UseMemberUsingDeclRules = |
1156 | 0 | (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && |
1157 | 0 | !New->getFriendObjectKind(); |
1158 | |
|
1159 | 0 | if (FunctionDecl *OldF = OldD->getAsFunction()) { |
1160 | 0 | if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { |
1161 | 0 | if (UseMemberUsingDeclRules && OldIsUsingDecl) { |
1162 | 0 | HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); |
1163 | 0 | continue; |
1164 | 0 | } |
1165 | | |
1166 | 0 | if (!isa<FunctionTemplateDecl>(OldD) && |
1167 | 0 | !shouldLinkPossiblyHiddenDecl(*I, New)) |
1168 | 0 | continue; |
1169 | | |
1170 | 0 | Match = *I; |
1171 | 0 | return Ovl_Match; |
1172 | 0 | } |
1173 | | |
1174 | | // Builtins that have custom typechecking or have a reference should |
1175 | | // not be overloadable or redeclarable. |
1176 | 0 | if (!getASTContext().canBuiltinBeRedeclared(OldF)) { |
1177 | 0 | Match = *I; |
1178 | 0 | return Ovl_NonFunction; |
1179 | 0 | } |
1180 | 0 | } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { |
1181 | | // We can overload with these, which can show up when doing |
1182 | | // redeclaration checks for UsingDecls. |
1183 | 0 | assert(Old.getLookupKind() == LookupUsingDeclName); |
1184 | 0 | } else if (isa<TagDecl>(OldD)) { |
1185 | | // We can always overload with tags by hiding them. |
1186 | 0 | } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { |
1187 | | // Optimistically assume that an unresolved using decl will |
1188 | | // overload; if it doesn't, we'll have to diagnose during |
1189 | | // template instantiation. |
1190 | | // |
1191 | | // Exception: if the scope is dependent and this is not a class |
1192 | | // member, the using declaration can only introduce an enumerator. |
1193 | 0 | if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { |
1194 | 0 | Match = *I; |
1195 | 0 | return Ovl_NonFunction; |
1196 | 0 | } |
1197 | 0 | } else { |
1198 | | // (C++ 13p1): |
1199 | | // Only function declarations can be overloaded; object and type |
1200 | | // declarations cannot be overloaded. |
1201 | 0 | Match = *I; |
1202 | 0 | return Ovl_NonFunction; |
1203 | 0 | } |
1204 | 0 | } |
1205 | | |
1206 | | // C++ [temp.friend]p1: |
1207 | | // For a friend function declaration that is not a template declaration: |
1208 | | // -- if the name of the friend is a qualified or unqualified template-id, |
1209 | | // [...], otherwise |
1210 | | // -- if the name of the friend is a qualified-id and a matching |
1211 | | // non-template function is found in the specified class or namespace, |
1212 | | // the friend declaration refers to that function, otherwise, |
1213 | | // -- if the name of the friend is a qualified-id and a matching function |
1214 | | // template is found in the specified class or namespace, the friend |
1215 | | // declaration refers to the deduced specialization of that function |
1216 | | // template, otherwise |
1217 | | // -- the name shall be an unqualified-id [...] |
1218 | | // If we get here for a qualified friend declaration, we've just reached the |
1219 | | // third bullet. If the type of the friend is dependent, skip this lookup |
1220 | | // until instantiation. |
1221 | 0 | if (New->getFriendObjectKind() && New->getQualifier() && |
1222 | 0 | !New->getDescribedFunctionTemplate() && |
1223 | 0 | !New->getDependentSpecializationInfo() && |
1224 | 0 | !New->getType()->isDependentType()) { |
1225 | 0 | LookupResult TemplateSpecResult(LookupResult::Temporary, Old); |
1226 | 0 | TemplateSpecResult.addAllDecls(Old); |
1227 | 0 | if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, |
1228 | 0 | /*QualifiedFriend*/true)) { |
1229 | 0 | New->setInvalidDecl(); |
1230 | 0 | return Ovl_Overload; |
1231 | 0 | } |
1232 | | |
1233 | 0 | Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); |
1234 | 0 | return Ovl_Match; |
1235 | 0 | } |
1236 | | |
1237 | 0 | return Ovl_Overload; |
1238 | 0 | } |
1239 | | |
1240 | | static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New, |
1241 | | FunctionDecl *Old, |
1242 | | bool UseMemberUsingDeclRules, |
1243 | | bool ConsiderCudaAttrs, |
1244 | 0 | bool UseOverrideRules = false) { |
1245 | | // C++ [basic.start.main]p2: This function shall not be overloaded. |
1246 | 0 | if (New->isMain()) |
1247 | 0 | return false; |
1248 | | |
1249 | | // MSVCRT user defined entry points cannot be overloaded. |
1250 | 0 | if (New->isMSVCRTEntryPoint()) |
1251 | 0 | return false; |
1252 | | |
1253 | 0 | FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); |
1254 | 0 | FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); |
1255 | | |
1256 | | // C++ [temp.fct]p2: |
1257 | | // A function template can be overloaded with other function templates |
1258 | | // and with normal (non-template) functions. |
1259 | 0 | if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) |
1260 | 0 | return true; |
1261 | | |
1262 | | // Is the function New an overload of the function Old? |
1263 | 0 | QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType()); |
1264 | 0 | QualType NewQType = SemaRef.Context.getCanonicalType(New->getType()); |
1265 | | |
1266 | | // Compare the signatures (C++ 1.3.10) of the two functions to |
1267 | | // determine whether they are overloads. If we find any mismatch |
1268 | | // in the signature, they are overloads. |
1269 | | |
1270 | | // If either of these functions is a K&R-style function (no |
1271 | | // prototype), then we consider them to have matching signatures. |
1272 | 0 | if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || |
1273 | 0 | isa<FunctionNoProtoType>(NewQType.getTypePtr())) |
1274 | 0 | return false; |
1275 | | |
1276 | 0 | const auto *OldType = cast<FunctionProtoType>(OldQType); |
1277 | 0 | const auto *NewType = cast<FunctionProtoType>(NewQType); |
1278 | | |
1279 | | // The signature of a function includes the types of its |
1280 | | // parameters (C++ 1.3.10), which includes the presence or absence |
1281 | | // of the ellipsis; see C++ DR 357). |
1282 | 0 | if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic()) |
1283 | 0 | return true; |
1284 | | |
1285 | | // For member-like friends, the enclosing class is part of the signature. |
1286 | 0 | if ((New->isMemberLikeConstrainedFriend() || |
1287 | 0 | Old->isMemberLikeConstrainedFriend()) && |
1288 | 0 | !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext())) |
1289 | 0 | return true; |
1290 | | |
1291 | | // Compare the parameter lists. |
1292 | | // This can only be done once we have establish that friend functions |
1293 | | // inhabit the same context, otherwise we might tried to instantiate |
1294 | | // references to non-instantiated entities during constraint substitution. |
1295 | | // GH78101. |
1296 | 0 | if (NewTemplate) { |
1297 | | // C++ [temp.over.link]p4: |
1298 | | // The signature of a function template consists of its function |
1299 | | // signature, its return type and its template parameter list. The names |
1300 | | // of the template parameters are significant only for establishing the |
1301 | | // relationship between the template parameters and the rest of the |
1302 | | // signature. |
1303 | | // |
1304 | | // We check the return type and template parameter lists for function |
1305 | | // templates first; the remaining checks follow. |
1306 | 0 | bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual( |
1307 | 0 | NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate, |
1308 | 0 | OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch); |
1309 | 0 | bool SameReturnType = SemaRef.Context.hasSameType( |
1310 | 0 | Old->getDeclaredReturnType(), New->getDeclaredReturnType()); |
1311 | | // FIXME(GH58571): Match template parameter list even for non-constrained |
1312 | | // template heads. This currently ensures that the code prior to C++20 is |
1313 | | // not newly broken. |
1314 | 0 | bool ConstraintsInTemplateHead = |
1315 | 0 | NewTemplate->getTemplateParameters()->hasAssociatedConstraints() || |
1316 | 0 | OldTemplate->getTemplateParameters()->hasAssociatedConstraints(); |
1317 | | // C++ [namespace.udecl]p11: |
1318 | | // The set of declarations named by a using-declarator that inhabits a |
1319 | | // class C does not include member functions and member function |
1320 | | // templates of a base class that "correspond" to (and thus would |
1321 | | // conflict with) a declaration of a function or function template in |
1322 | | // C. |
1323 | | // Comparing return types is not required for the "correspond" check to |
1324 | | // decide whether a member introduced by a shadow declaration is hidden. |
1325 | 0 | if (UseMemberUsingDeclRules && ConstraintsInTemplateHead && |
1326 | 0 | !SameTemplateParameterList) |
1327 | 0 | return true; |
1328 | 0 | if (!UseMemberUsingDeclRules && |
1329 | 0 | (!SameTemplateParameterList || !SameReturnType)) |
1330 | 0 | return true; |
1331 | 0 | } |
1332 | | |
1333 | 0 | const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old); |
1334 | 0 | const auto *NewMethod = dyn_cast<CXXMethodDecl>(New); |
1335 | |
|
1336 | 0 | int OldParamsOffset = 0; |
1337 | 0 | int NewParamsOffset = 0; |
1338 | | |
1339 | | // When determining if a method is an overload from a base class, act as if |
1340 | | // the implicit object parameter are of the same type. |
1341 | |
|
1342 | 0 | auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) { |
1343 | 0 | if (M->isExplicitObjectMemberFunction()) |
1344 | 0 | return Q; |
1345 | | |
1346 | | // We do not allow overloading based off of '__restrict'. |
1347 | 0 | Q.removeRestrict(); |
1348 | | |
1349 | | // We may not have applied the implicit const for a constexpr member |
1350 | | // function yet (because we haven't yet resolved whether this is a static |
1351 | | // or non-static member function). Add it now, on the assumption that this |
1352 | | // is a redeclaration of OldMethod. |
1353 | 0 | if (!SemaRef.getLangOpts().CPlusPlus14 && |
1354 | 0 | (M->isConstexpr() || M->isConsteval()) && |
1355 | 0 | !isa<CXXConstructorDecl>(NewMethod)) |
1356 | 0 | Q.addConst(); |
1357 | 0 | return Q; |
1358 | 0 | }; |
1359 | |
|
1360 | 0 | auto CompareType = [&](QualType Base, QualType D) { |
1361 | 0 | auto BS = Base.getNonReferenceType().getCanonicalType().split(); |
1362 | 0 | BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals); |
1363 | |
|
1364 | 0 | auto DS = D.getNonReferenceType().getCanonicalType().split(); |
1365 | 0 | DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals); |
1366 | |
|
1367 | 0 | if (BS.Quals != DS.Quals) |
1368 | 0 | return false; |
1369 | | |
1370 | 0 | if (OldMethod->isImplicitObjectMemberFunction() && |
1371 | 0 | OldMethod->getParent() != NewMethod->getParent()) { |
1372 | 0 | QualType ParentType = |
1373 | 0 | SemaRef.Context.getTypeDeclType(OldMethod->getParent()) |
1374 | 0 | .getCanonicalType(); |
1375 | 0 | if (ParentType.getTypePtr() != BS.Ty) |
1376 | 0 | return false; |
1377 | 0 | BS.Ty = DS.Ty; |
1378 | 0 | } |
1379 | | |
1380 | | // FIXME: should we ignore some type attributes here? |
1381 | 0 | if (BS.Ty != DS.Ty) |
1382 | 0 | return false; |
1383 | | |
1384 | 0 | if (Base->isLValueReferenceType()) |
1385 | 0 | return D->isLValueReferenceType(); |
1386 | 0 | return Base->isRValueReferenceType() == D->isRValueReferenceType(); |
1387 | 0 | }; |
1388 | | |
1389 | | // If the function is a class member, its signature includes the |
1390 | | // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. |
1391 | 0 | auto DiagnoseInconsistentRefQualifiers = [&]() { |
1392 | 0 | if (SemaRef.LangOpts.CPlusPlus23) |
1393 | 0 | return false; |
1394 | 0 | if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier()) |
1395 | 0 | return false; |
1396 | 0 | if (OldMethod->isExplicitObjectMemberFunction() || |
1397 | 0 | NewMethod->isExplicitObjectMemberFunction()) |
1398 | 0 | return false; |
1399 | 0 | if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None || |
1400 | 0 | NewMethod->getRefQualifier() == RQ_None)) { |
1401 | 0 | SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) |
1402 | 0 | << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); |
1403 | 0 | SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration); |
1404 | 0 | return true; |
1405 | 0 | } |
1406 | 0 | return false; |
1407 | 0 | }; |
1408 | |
|
1409 | 0 | if (OldMethod && OldMethod->isExplicitObjectMemberFunction()) |
1410 | 0 | OldParamsOffset++; |
1411 | 0 | if (NewMethod && NewMethod->isExplicitObjectMemberFunction()) |
1412 | 0 | NewParamsOffset++; |
1413 | |
|
1414 | 0 | if (OldType->getNumParams() - OldParamsOffset != |
1415 | 0 | NewType->getNumParams() - NewParamsOffset || |
1416 | 0 | !SemaRef.FunctionParamTypesAreEqual( |
1417 | 0 | {OldType->param_type_begin() + OldParamsOffset, |
1418 | 0 | OldType->param_type_end()}, |
1419 | 0 | {NewType->param_type_begin() + NewParamsOffset, |
1420 | 0 | NewType->param_type_end()}, |
1421 | 0 | nullptr)) { |
1422 | 0 | return true; |
1423 | 0 | } |
1424 | | |
1425 | 0 | if (OldMethod && NewMethod && !OldMethod->isStatic() && |
1426 | 0 | !OldMethod->isStatic()) { |
1427 | 0 | bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old, |
1428 | 0 | const CXXMethodDecl *New) { |
1429 | 0 | auto NewObjectType = New->getFunctionObjectParameterReferenceType(); |
1430 | 0 | auto OldObjectType = Old->getFunctionObjectParameterReferenceType(); |
1431 | |
|
1432 | 0 | auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) { |
1433 | 0 | return F->getRefQualifier() == RQ_None && |
1434 | 0 | !F->isExplicitObjectMemberFunction(); |
1435 | 0 | }; |
1436 | |
|
1437 | 0 | if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) && |
1438 | 0 | CompareType(OldObjectType.getNonReferenceType(), |
1439 | 0 | NewObjectType.getNonReferenceType())) |
1440 | 0 | return true; |
1441 | 0 | return CompareType(OldObjectType, NewObjectType); |
1442 | 0 | }(OldMethod, NewMethod); |
1443 | |
|
1444 | 0 | if (!HaveCorrespondingObjectParameters) { |
1445 | 0 | if (DiagnoseInconsistentRefQualifiers()) |
1446 | 0 | return true; |
1447 | | // CWG2554 |
1448 | | // and, if at least one is an explicit object member function, ignoring |
1449 | | // object parameters |
1450 | 0 | if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() && |
1451 | 0 | !OldMethod->isExplicitObjectMemberFunction())) |
1452 | 0 | return true; |
1453 | 0 | } |
1454 | 0 | } |
1455 | | |
1456 | 0 | if (!UseOverrideRules) { |
1457 | 0 | Expr *NewRC = New->getTrailingRequiresClause(), |
1458 | 0 | *OldRC = Old->getTrailingRequiresClause(); |
1459 | 0 | if ((NewRC != nullptr) != (OldRC != nullptr)) |
1460 | 0 | return true; |
1461 | | |
1462 | 0 | if (NewRC && !SemaRef.AreConstraintExpressionsEqual(Old, OldRC, New, NewRC)) |
1463 | 0 | return true; |
1464 | 0 | } |
1465 | | |
1466 | 0 | if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() && |
1467 | 0 | NewMethod->isImplicitObjectMemberFunction()) { |
1468 | 0 | if (DiagnoseInconsistentRefQualifiers()) |
1469 | 0 | return true; |
1470 | 0 | } |
1471 | | |
1472 | | // Though pass_object_size is placed on parameters and takes an argument, we |
1473 | | // consider it to be a function-level modifier for the sake of function |
1474 | | // identity. Either the function has one or more parameters with |
1475 | | // pass_object_size or it doesn't. |
1476 | 0 | if (functionHasPassObjectSizeParams(New) != |
1477 | 0 | functionHasPassObjectSizeParams(Old)) |
1478 | 0 | return true; |
1479 | | |
1480 | | // enable_if attributes are an order-sensitive part of the signature. |
1481 | 0 | for (specific_attr_iterator<EnableIfAttr> |
1482 | 0 | NewI = New->specific_attr_begin<EnableIfAttr>(), |
1483 | 0 | NewE = New->specific_attr_end<EnableIfAttr>(), |
1484 | 0 | OldI = Old->specific_attr_begin<EnableIfAttr>(), |
1485 | 0 | OldE = Old->specific_attr_end<EnableIfAttr>(); |
1486 | 0 | NewI != NewE || OldI != OldE; ++NewI, ++OldI) { |
1487 | 0 | if (NewI == NewE || OldI == OldE) |
1488 | 0 | return true; |
1489 | 0 | llvm::FoldingSetNodeID NewID, OldID; |
1490 | 0 | NewI->getCond()->Profile(NewID, SemaRef.Context, true); |
1491 | 0 | OldI->getCond()->Profile(OldID, SemaRef.Context, true); |
1492 | 0 | if (NewID != OldID) |
1493 | 0 | return true; |
1494 | 0 | } |
1495 | | |
1496 | 0 | if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) { |
1497 | | // Don't allow overloading of destructors. (In theory we could, but it |
1498 | | // would be a giant change to clang.) |
1499 | 0 | if (!isa<CXXDestructorDecl>(New)) { |
1500 | 0 | Sema::CUDAFunctionTarget NewTarget = SemaRef.IdentifyCUDATarget(New), |
1501 | 0 | OldTarget = SemaRef.IdentifyCUDATarget(Old); |
1502 | 0 | if (NewTarget != Sema::CFT_InvalidTarget) { |
1503 | 0 | assert((OldTarget != Sema::CFT_InvalidTarget) && |
1504 | 0 | "Unexpected invalid target."); |
1505 | | |
1506 | | // Allow overloading of functions with same signature and different CUDA |
1507 | | // target attributes. |
1508 | 0 | if (NewTarget != OldTarget) |
1509 | 0 | return true; |
1510 | 0 | } |
1511 | 0 | } |
1512 | 0 | } |
1513 | | |
1514 | | // The signatures match; this is not an overload. |
1515 | 0 | return false; |
1516 | 0 | } |
1517 | | |
1518 | | bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, |
1519 | 0 | bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { |
1520 | 0 | return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules, |
1521 | 0 | ConsiderCudaAttrs); |
1522 | 0 | } |
1523 | | |
1524 | | bool Sema::IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, |
1525 | 0 | bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { |
1526 | 0 | return IsOverloadOrOverrideImpl(*this, MD, BaseMD, |
1527 | 0 | /*UseMemberUsingDeclRules=*/false, |
1528 | 0 | /*ConsiderCudaAttrs=*/true, |
1529 | 0 | /*UseOverrideRules=*/true); |
1530 | 0 | } |
1531 | | |
1532 | | /// Tries a user-defined conversion from From to ToType. |
1533 | | /// |
1534 | | /// Produces an implicit conversion sequence for when a standard conversion |
1535 | | /// is not an option. See TryImplicitConversion for more information. |
1536 | | static ImplicitConversionSequence |
1537 | | TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, |
1538 | | bool SuppressUserConversions, |
1539 | | AllowedExplicit AllowExplicit, |
1540 | | bool InOverloadResolution, |
1541 | | bool CStyle, |
1542 | | bool AllowObjCWritebackConversion, |
1543 | 1 | bool AllowObjCConversionOnExplicit) { |
1544 | 1 | ImplicitConversionSequence ICS; |
1545 | | |
1546 | 1 | if (SuppressUserConversions) { |
1547 | | // We're not in the case above, so there is no conversion that |
1548 | | // we can perform. |
1549 | 0 | ICS.setBad(BadConversionSequence::no_conversion, From, ToType); |
1550 | 0 | return ICS; |
1551 | 0 | } |
1552 | | |
1553 | | // Attempt user-defined conversion. |
1554 | 1 | OverloadCandidateSet Conversions(From->getExprLoc(), |
1555 | 1 | OverloadCandidateSet::CSK_Normal); |
1556 | 1 | switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, |
1557 | 1 | Conversions, AllowExplicit, |
1558 | 1 | AllowObjCConversionOnExplicit)) { |
1559 | 0 | case OR_Success: |
1560 | 0 | case OR_Deleted: |
1561 | 0 | ICS.setUserDefined(); |
1562 | | // C++ [over.ics.user]p4: |
1563 | | // A conversion of an expression of class type to the same class |
1564 | | // type is given Exact Match rank, and a conversion of an |
1565 | | // expression of class type to a base class of that type is |
1566 | | // given Conversion rank, in spite of the fact that a copy |
1567 | | // constructor (i.e., a user-defined conversion function) is |
1568 | | // called for those cases. |
1569 | 0 | if (CXXConstructorDecl *Constructor |
1570 | 0 | = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { |
1571 | 0 | QualType FromCanon |
1572 | 0 | = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); |
1573 | 0 | QualType ToCanon |
1574 | 0 | = S.Context.getCanonicalType(ToType).getUnqualifiedType(); |
1575 | 0 | if (Constructor->isCopyConstructor() && |
1576 | 0 | (FromCanon == ToCanon || |
1577 | 0 | S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { |
1578 | | // Turn this into a "standard" conversion sequence, so that it |
1579 | | // gets ranked with standard conversion sequences. |
1580 | 0 | DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; |
1581 | 0 | ICS.setStandard(); |
1582 | 0 | ICS.Standard.setAsIdentityConversion(); |
1583 | 0 | ICS.Standard.setFromType(From->getType()); |
1584 | 0 | ICS.Standard.setAllToTypes(ToType); |
1585 | 0 | ICS.Standard.CopyConstructor = Constructor; |
1586 | 0 | ICS.Standard.FoundCopyConstructor = Found; |
1587 | 0 | if (ToCanon != FromCanon) |
1588 | 0 | ICS.Standard.Second = ICK_Derived_To_Base; |
1589 | 0 | } |
1590 | 0 | } |
1591 | 0 | break; |
1592 | | |
1593 | 0 | case OR_Ambiguous: |
1594 | 0 | ICS.setAmbiguous(); |
1595 | 0 | ICS.Ambiguous.setFromType(From->getType()); |
1596 | 0 | ICS.Ambiguous.setToType(ToType); |
1597 | 0 | for (OverloadCandidateSet::iterator Cand = Conversions.begin(); |
1598 | 0 | Cand != Conversions.end(); ++Cand) |
1599 | 0 | if (Cand->Best) |
1600 | 0 | ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); |
1601 | 0 | break; |
1602 | | |
1603 | | // Fall through. |
1604 | 1 | case OR_No_Viable_Function: |
1605 | 1 | ICS.setBad(BadConversionSequence::no_conversion, From, ToType); |
1606 | 1 | break; |
1607 | 1 | } |
1608 | | |
1609 | 1 | return ICS; |
1610 | 1 | } |
1611 | | |
1612 | | /// TryImplicitConversion - Attempt to perform an implicit conversion |
1613 | | /// from the given expression (Expr) to the given type (ToType). This |
1614 | | /// function returns an implicit conversion sequence that can be used |
1615 | | /// to perform the initialization. Given |
1616 | | /// |
1617 | | /// void f(float f); |
1618 | | /// void g(int i) { f(i); } |
1619 | | /// |
1620 | | /// this routine would produce an implicit conversion sequence to |
1621 | | /// describe the initialization of f from i, which will be a standard |
1622 | | /// conversion sequence containing an lvalue-to-rvalue conversion (C++ |
1623 | | /// 4.1) followed by a floating-integral conversion (C++ 4.9). |
1624 | | // |
1625 | | /// Note that this routine only determines how the conversion can be |
1626 | | /// performed; it does not actually perform the conversion. As such, |
1627 | | /// it will not produce any diagnostics if no conversion is available, |
1628 | | /// but will instead return an implicit conversion sequence of kind |
1629 | | /// "BadConversion". |
1630 | | /// |
1631 | | /// If @p SuppressUserConversions, then user-defined conversions are |
1632 | | /// not permitted. |
1633 | | /// If @p AllowExplicit, then explicit user-defined conversions are |
1634 | | /// permitted. |
1635 | | /// |
1636 | | /// \param AllowObjCWritebackConversion Whether we allow the Objective-C |
1637 | | /// writeback conversion, which allows __autoreleasing id* parameters to |
1638 | | /// be initialized with __strong id* or __weak id* arguments. |
1639 | | static ImplicitConversionSequence |
1640 | | TryImplicitConversion(Sema &S, Expr *From, QualType ToType, |
1641 | | bool SuppressUserConversions, |
1642 | | AllowedExplicit AllowExplicit, |
1643 | | bool InOverloadResolution, |
1644 | | bool CStyle, |
1645 | | bool AllowObjCWritebackConversion, |
1646 | 1 | bool AllowObjCConversionOnExplicit) { |
1647 | 1 | ImplicitConversionSequence ICS; |
1648 | 1 | if (IsStandardConversion(S, From, ToType, InOverloadResolution, |
1649 | 1 | ICS.Standard, CStyle, AllowObjCWritebackConversion)){ |
1650 | 0 | ICS.setStandard(); |
1651 | 0 | return ICS; |
1652 | 0 | } |
1653 | | |
1654 | 1 | if (!S.getLangOpts().CPlusPlus) { |
1655 | 0 | ICS.setBad(BadConversionSequence::no_conversion, From, ToType); |
1656 | 0 | return ICS; |
1657 | 0 | } |
1658 | | |
1659 | | // C++ [over.ics.user]p4: |
1660 | | // A conversion of an expression of class type to the same class |
1661 | | // type is given Exact Match rank, and a conversion of an |
1662 | | // expression of class type to a base class of that type is |
1663 | | // given Conversion rank, in spite of the fact that a copy/move |
1664 | | // constructor (i.e., a user-defined conversion function) is |
1665 | | // called for those cases. |
1666 | 1 | QualType FromType = From->getType(); |
1667 | 1 | if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && |
1668 | 1 | (S.Context.hasSameUnqualifiedType(FromType, ToType) || |
1669 | 0 | S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { |
1670 | 0 | ICS.setStandard(); |
1671 | 0 | ICS.Standard.setAsIdentityConversion(); |
1672 | 0 | ICS.Standard.setFromType(FromType); |
1673 | 0 | ICS.Standard.setAllToTypes(ToType); |
1674 | | |
1675 | | // We don't actually check at this point whether there is a valid |
1676 | | // copy/move constructor, since overloading just assumes that it |
1677 | | // exists. When we actually perform initialization, we'll find the |
1678 | | // appropriate constructor to copy the returned object, if needed. |
1679 | 0 | ICS.Standard.CopyConstructor = nullptr; |
1680 | | |
1681 | | // Determine whether this is considered a derived-to-base conversion. |
1682 | 0 | if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) |
1683 | 0 | ICS.Standard.Second = ICK_Derived_To_Base; |
1684 | |
|
1685 | 0 | return ICS; |
1686 | 0 | } |
1687 | | |
1688 | 1 | return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, |
1689 | 1 | AllowExplicit, InOverloadResolution, CStyle, |
1690 | 1 | AllowObjCWritebackConversion, |
1691 | 1 | AllowObjCConversionOnExplicit); |
1692 | 1 | } |
1693 | | |
1694 | | ImplicitConversionSequence |
1695 | | Sema::TryImplicitConversion(Expr *From, QualType ToType, |
1696 | | bool SuppressUserConversions, |
1697 | | AllowedExplicit AllowExplicit, |
1698 | | bool InOverloadResolution, |
1699 | | bool CStyle, |
1700 | 0 | bool AllowObjCWritebackConversion) { |
1701 | 0 | return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions, |
1702 | 0 | AllowExplicit, InOverloadResolution, CStyle, |
1703 | 0 | AllowObjCWritebackConversion, |
1704 | 0 | /*AllowObjCConversionOnExplicit=*/false); |
1705 | 0 | } |
1706 | | |
1707 | | /// PerformImplicitConversion - Perform an implicit conversion of the |
1708 | | /// expression From to the type ToType. Returns the |
1709 | | /// converted expression. Flavor is the kind of conversion we're |
1710 | | /// performing, used in the error message. If @p AllowExplicit, |
1711 | | /// explicit user-defined conversions are permitted. |
1712 | | ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType, |
1713 | | AssignmentAction Action, |
1714 | 0 | bool AllowExplicit) { |
1715 | 0 | if (checkPlaceholderForOverload(*this, From)) |
1716 | 0 | return ExprError(); |
1717 | | |
1718 | | // Objective-C ARC: Determine whether we will allow the writeback conversion. |
1719 | 0 | bool AllowObjCWritebackConversion |
1720 | 0 | = getLangOpts().ObjCAutoRefCount && |
1721 | 0 | (Action == AA_Passing || Action == AA_Sending); |
1722 | 0 | if (getLangOpts().ObjC) |
1723 | 0 | CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, |
1724 | 0 | From->getType(), From); |
1725 | 0 | ImplicitConversionSequence ICS = ::TryImplicitConversion( |
1726 | 0 | *this, From, ToType, |
1727 | 0 | /*SuppressUserConversions=*/false, |
1728 | 0 | AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None, |
1729 | 0 | /*InOverloadResolution=*/false, |
1730 | 0 | /*CStyle=*/false, AllowObjCWritebackConversion, |
1731 | 0 | /*AllowObjCConversionOnExplicit=*/false); |
1732 | 0 | return PerformImplicitConversion(From, ToType, ICS, Action); |
1733 | 0 | } |
1734 | | |
1735 | | /// Determine whether the conversion from FromType to ToType is a valid |
1736 | | /// conversion that strips "noexcept" or "noreturn" off the nested function |
1737 | | /// type. |
1738 | | bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, |
1739 | 1 | QualType &ResultTy) { |
1740 | 1 | if (Context.hasSameUnqualifiedType(FromType, ToType)) |
1741 | 0 | return false; |
1742 | | |
1743 | | // Permit the conversion F(t __attribute__((noreturn))) -> F(t) |
1744 | | // or F(t noexcept) -> F(t) |
1745 | | // where F adds one of the following at most once: |
1746 | | // - a pointer |
1747 | | // - a member pointer |
1748 | | // - a block pointer |
1749 | | // Changes here need matching changes in FindCompositePointerType. |
1750 | 1 | CanQualType CanTo = Context.getCanonicalType(ToType); |
1751 | 1 | CanQualType CanFrom = Context.getCanonicalType(FromType); |
1752 | 1 | Type::TypeClass TyClass = CanTo->getTypeClass(); |
1753 | 1 | if (TyClass != CanFrom->getTypeClass()) return false; |
1754 | 0 | if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { |
1755 | 0 | if (TyClass == Type::Pointer) { |
1756 | 0 | CanTo = CanTo.castAs<PointerType>()->getPointeeType(); |
1757 | 0 | CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); |
1758 | 0 | } else if (TyClass == Type::BlockPointer) { |
1759 | 0 | CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); |
1760 | 0 | CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); |
1761 | 0 | } else if (TyClass == Type::MemberPointer) { |
1762 | 0 | auto ToMPT = CanTo.castAs<MemberPointerType>(); |
1763 | 0 | auto FromMPT = CanFrom.castAs<MemberPointerType>(); |
1764 | | // A function pointer conversion cannot change the class of the function. |
1765 | 0 | if (ToMPT->getClass() != FromMPT->getClass()) |
1766 | 0 | return false; |
1767 | 0 | CanTo = ToMPT->getPointeeType(); |
1768 | 0 | CanFrom = FromMPT->getPointeeType(); |
1769 | 0 | } else { |
1770 | 0 | return false; |
1771 | 0 | } |
1772 | | |
1773 | 0 | TyClass = CanTo->getTypeClass(); |
1774 | 0 | if (TyClass != CanFrom->getTypeClass()) return false; |
1775 | 0 | if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) |
1776 | 0 | return false; |
1777 | 0 | } |
1778 | | |
1779 | 0 | const auto *FromFn = cast<FunctionType>(CanFrom); |
1780 | 0 | FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); |
1781 | |
|
1782 | 0 | const auto *ToFn = cast<FunctionType>(CanTo); |
1783 | 0 | FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); |
1784 | |
|
1785 | 0 | bool Changed = false; |
1786 | | |
1787 | | // Drop 'noreturn' if not present in target type. |
1788 | 0 | if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { |
1789 | 0 | FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); |
1790 | 0 | Changed = true; |
1791 | 0 | } |
1792 | | |
1793 | | // Drop 'noexcept' if not present in target type. |
1794 | 0 | if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { |
1795 | 0 | const auto *ToFPT = cast<FunctionProtoType>(ToFn); |
1796 | 0 | if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { |
1797 | 0 | FromFn = cast<FunctionType>( |
1798 | 0 | Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), |
1799 | 0 | EST_None) |
1800 | 0 | .getTypePtr()); |
1801 | 0 | Changed = true; |
1802 | 0 | } |
1803 | | |
1804 | | // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid |
1805 | | // only if the ExtParameterInfo lists of the two function prototypes can be |
1806 | | // merged and the merged list is identical to ToFPT's ExtParameterInfo list. |
1807 | 0 | SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; |
1808 | 0 | bool CanUseToFPT, CanUseFromFPT; |
1809 | 0 | if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, |
1810 | 0 | CanUseFromFPT, NewParamInfos) && |
1811 | 0 | CanUseToFPT && !CanUseFromFPT) { |
1812 | 0 | FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); |
1813 | 0 | ExtInfo.ExtParameterInfos = |
1814 | 0 | NewParamInfos.empty() ? nullptr : NewParamInfos.data(); |
1815 | 0 | QualType QT = Context.getFunctionType(FromFPT->getReturnType(), |
1816 | 0 | FromFPT->getParamTypes(), ExtInfo); |
1817 | 0 | FromFn = QT->getAs<FunctionType>(); |
1818 | 0 | Changed = true; |
1819 | 0 | } |
1820 | 0 | } |
1821 | |
|
1822 | 0 | if (!Changed) |
1823 | 0 | return false; |
1824 | | |
1825 | 0 | assert(QualType(FromFn, 0).isCanonical()); |
1826 | 0 | if (QualType(FromFn, 0) != CanTo) return false; |
1827 | | |
1828 | 0 | ResultTy = ToType; |
1829 | 0 | return true; |
1830 | 0 | } |
1831 | | |
1832 | | /// Determine whether the conversion from FromType to ToType is a valid |
1833 | | /// vector conversion. |
1834 | | /// |
1835 | | /// \param ICK Will be set to the vector conversion kind, if this is a vector |
1836 | | /// conversion. |
1837 | | static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType, |
1838 | | ImplicitConversionKind &ICK, Expr *From, |
1839 | 1 | bool InOverloadResolution, bool CStyle) { |
1840 | | // We need at least one of these types to be a vector type to have a vector |
1841 | | // conversion. |
1842 | 1 | if (!ToType->isVectorType() && !FromType->isVectorType()) |
1843 | 1 | return false; |
1844 | | |
1845 | | // Identical types require no conversions. |
1846 | 0 | if (S.Context.hasSameUnqualifiedType(FromType, ToType)) |
1847 | 0 | return false; |
1848 | | |
1849 | | // There are no conversions between extended vector types, only identity. |
1850 | 0 | if (ToType->isExtVectorType()) { |
1851 | | // There are no conversions between extended vector types other than the |
1852 | | // identity conversion. |
1853 | 0 | if (FromType->isExtVectorType()) |
1854 | 0 | return false; |
1855 | | |
1856 | | // Vector splat from any arithmetic type to a vector. |
1857 | 0 | if (FromType->isArithmeticType()) { |
1858 | 0 | ICK = ICK_Vector_Splat; |
1859 | 0 | return true; |
1860 | 0 | } |
1861 | 0 | } |
1862 | | |
1863 | 0 | if (ToType->isSVESizelessBuiltinType() || |
1864 | 0 | FromType->isSVESizelessBuiltinType()) |
1865 | 0 | if (S.Context.areCompatibleSveTypes(FromType, ToType) || |
1866 | 0 | S.Context.areLaxCompatibleSveTypes(FromType, ToType)) { |
1867 | 0 | ICK = ICK_SVE_Vector_Conversion; |
1868 | 0 | return true; |
1869 | 0 | } |
1870 | | |
1871 | 0 | if (ToType->isRVVSizelessBuiltinType() || |
1872 | 0 | FromType->isRVVSizelessBuiltinType()) |
1873 | 0 | if (S.Context.areCompatibleRVVTypes(FromType, ToType) || |
1874 | 0 | S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) { |
1875 | 0 | ICK = ICK_RVV_Vector_Conversion; |
1876 | 0 | return true; |
1877 | 0 | } |
1878 | | |
1879 | | // We can perform the conversion between vector types in the following cases: |
1880 | | // 1)vector types are equivalent AltiVec and GCC vector types |
1881 | | // 2)lax vector conversions are permitted and the vector types are of the |
1882 | | // same size |
1883 | | // 3)the destination type does not have the ARM MVE strict-polymorphism |
1884 | | // attribute, which inhibits lax vector conversion for overload resolution |
1885 | | // only |
1886 | 0 | if (ToType->isVectorType() && FromType->isVectorType()) { |
1887 | 0 | if (S.Context.areCompatibleVectorTypes(FromType, ToType) || |
1888 | 0 | (S.isLaxVectorConversion(FromType, ToType) && |
1889 | 0 | !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) { |
1890 | 0 | if (S.getASTContext().getTargetInfo().getTriple().isPPC() && |
1891 | 0 | S.isLaxVectorConversion(FromType, ToType) && |
1892 | 0 | S.anyAltivecTypes(FromType, ToType) && |
1893 | 0 | !S.Context.areCompatibleVectorTypes(FromType, ToType) && |
1894 | 0 | !InOverloadResolution && !CStyle) { |
1895 | 0 | S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all) |
1896 | 0 | << FromType << ToType; |
1897 | 0 | } |
1898 | 0 | ICK = ICK_Vector_Conversion; |
1899 | 0 | return true; |
1900 | 0 | } |
1901 | 0 | } |
1902 | | |
1903 | 0 | return false; |
1904 | 0 | } |
1905 | | |
1906 | | static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, |
1907 | | bool InOverloadResolution, |
1908 | | StandardConversionSequence &SCS, |
1909 | | bool CStyle); |
1910 | | |
1911 | | /// IsStandardConversion - Determines whether there is a standard |
1912 | | /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the |
1913 | | /// expression From to the type ToType. Standard conversion sequences |
1914 | | /// only consider non-class types; for conversions that involve class |
1915 | | /// types, use TryImplicitConversion. If a conversion exists, SCS will |
1916 | | /// contain the standard conversion sequence required to perform this |
1917 | | /// conversion and this routine will return true. Otherwise, this |
1918 | | /// routine will return false and the value of SCS is unspecified. |
1919 | | static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, |
1920 | | bool InOverloadResolution, |
1921 | | StandardConversionSequence &SCS, |
1922 | | bool CStyle, |
1923 | 1 | bool AllowObjCWritebackConversion) { |
1924 | 1 | QualType FromType = From->getType(); |
1925 | | |
1926 | | // Standard conversions (C++ [conv]) |
1927 | 1 | SCS.setAsIdentityConversion(); |
1928 | 1 | SCS.IncompatibleObjC = false; |
1929 | 1 | SCS.setFromType(FromType); |
1930 | 1 | SCS.CopyConstructor = nullptr; |
1931 | | |
1932 | | // There are no standard conversions for class types in C++, so |
1933 | | // abort early. When overloading in C, however, we do permit them. |
1934 | 1 | if (S.getLangOpts().CPlusPlus && |
1935 | 1 | (FromType->isRecordType() || ToType->isRecordType())) |
1936 | 0 | return false; |
1937 | | |
1938 | | // The first conversion can be an lvalue-to-rvalue conversion, |
1939 | | // array-to-pointer conversion, or function-to-pointer conversion |
1940 | | // (C++ 4p1). |
1941 | | |
1942 | 1 | if (FromType == S.Context.OverloadTy) { |
1943 | 0 | DeclAccessPair AccessPair; |
1944 | 0 | if (FunctionDecl *Fn |
1945 | 0 | = S.ResolveAddressOfOverloadedFunction(From, ToType, false, |
1946 | 0 | AccessPair)) { |
1947 | | // We were able to resolve the address of the overloaded function, |
1948 | | // so we can convert to the type of that function. |
1949 | 0 | FromType = Fn->getType(); |
1950 | 0 | SCS.setFromType(FromType); |
1951 | | |
1952 | | // we can sometimes resolve &foo<int> regardless of ToType, so check |
1953 | | // if the type matches (identity) or we are converting to bool |
1954 | 0 | if (!S.Context.hasSameUnqualifiedType( |
1955 | 0 | S.ExtractUnqualifiedFunctionType(ToType), FromType)) { |
1956 | 0 | QualType resultTy; |
1957 | | // if the function type matches except for [[noreturn]], it's ok |
1958 | 0 | if (!S.IsFunctionConversion(FromType, |
1959 | 0 | S.ExtractUnqualifiedFunctionType(ToType), resultTy)) |
1960 | | // otherwise, only a boolean conversion is standard |
1961 | 0 | if (!ToType->isBooleanType()) |
1962 | 0 | return false; |
1963 | 0 | } |
1964 | | |
1965 | | // Check if the "from" expression is taking the address of an overloaded |
1966 | | // function and recompute the FromType accordingly. Take advantage of the |
1967 | | // fact that non-static member functions *must* have such an address-of |
1968 | | // expression. |
1969 | 0 | CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); |
1970 | 0 | if (Method && !Method->isStatic() && |
1971 | 0 | !Method->isExplicitObjectMemberFunction()) { |
1972 | 0 | assert(isa<UnaryOperator>(From->IgnoreParens()) && |
1973 | 0 | "Non-unary operator on non-static member address"); |
1974 | 0 | assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() |
1975 | 0 | == UO_AddrOf && |
1976 | 0 | "Non-address-of operator on non-static member address"); |
1977 | 0 | const Type *ClassType |
1978 | 0 | = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); |
1979 | 0 | FromType = S.Context.getMemberPointerType(FromType, ClassType); |
1980 | 0 | } else if (isa<UnaryOperator>(From->IgnoreParens())) { |
1981 | 0 | assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == |
1982 | 0 | UO_AddrOf && |
1983 | 0 | "Non-address-of operator for overloaded function expression"); |
1984 | 0 | FromType = S.Context.getPointerType(FromType); |
1985 | 0 | } |
1986 | 0 | } else { |
1987 | 0 | return false; |
1988 | 0 | } |
1989 | 0 | } |
1990 | | // Lvalue-to-rvalue conversion (C++11 4.1): |
1991 | | // A glvalue (3.10) of a non-function, non-array type T can |
1992 | | // be converted to a prvalue. |
1993 | 1 | bool argIsLValue = From->isGLValue(); |
1994 | 1 | if (argIsLValue && |
1995 | 1 | !FromType->isFunctionType() && !FromType->isArrayType() && |
1996 | 1 | S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { |
1997 | 0 | SCS.First = ICK_Lvalue_To_Rvalue; |
1998 | | |
1999 | | // C11 6.3.2.1p2: |
2000 | | // ... if the lvalue has atomic type, the value has the non-atomic version |
2001 | | // of the type of the lvalue ... |
2002 | 0 | if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) |
2003 | 0 | FromType = Atomic->getValueType(); |
2004 | | |
2005 | | // If T is a non-class type, the type of the rvalue is the |
2006 | | // cv-unqualified version of T. Otherwise, the type of the rvalue |
2007 | | // is T (C++ 4.1p1). C++ can't get here with class types; in C, we |
2008 | | // just strip the qualifiers because they don't matter. |
2009 | 0 | FromType = FromType.getUnqualifiedType(); |
2010 | 1 | } else if (FromType->isArrayType()) { |
2011 | | // Array-to-pointer conversion (C++ 4.2) |
2012 | 0 | SCS.First = ICK_Array_To_Pointer; |
2013 | | |
2014 | | // An lvalue or rvalue of type "array of N T" or "array of unknown |
2015 | | // bound of T" can be converted to an rvalue of type "pointer to |
2016 | | // T" (C++ 4.2p1). |
2017 | 0 | FromType = S.Context.getArrayDecayedType(FromType); |
2018 | |
|
2019 | 0 | if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { |
2020 | | // This conversion is deprecated in C++03 (D.4) |
2021 | 0 | SCS.DeprecatedStringLiteralToCharPtr = true; |
2022 | | |
2023 | | // For the purpose of ranking in overload resolution |
2024 | | // (13.3.3.1.1), this conversion is considered an |
2025 | | // array-to-pointer conversion followed by a qualification |
2026 | | // conversion (4.4). (C++ 4.2p2) |
2027 | 0 | SCS.Second = ICK_Identity; |
2028 | 0 | SCS.Third = ICK_Qualification; |
2029 | 0 | SCS.QualificationIncludesObjCLifetime = false; |
2030 | 0 | SCS.setAllToTypes(FromType); |
2031 | 0 | return true; |
2032 | 0 | } |
2033 | 1 | } else if (FromType->isFunctionType() && argIsLValue) { |
2034 | | // Function-to-pointer conversion (C++ 4.3). |
2035 | 0 | SCS.First = ICK_Function_To_Pointer; |
2036 | |
|
2037 | 0 | if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) |
2038 | 0 | if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) |
2039 | 0 | if (!S.checkAddressOfFunctionIsAvailable(FD)) |
2040 | 0 | return false; |
2041 | | |
2042 | | // An lvalue of function type T can be converted to an rvalue of |
2043 | | // type "pointer to T." The result is a pointer to the |
2044 | | // function. (C++ 4.3p1). |
2045 | 0 | FromType = S.Context.getPointerType(FromType); |
2046 | 1 | } else { |
2047 | | // We don't require any conversions for the first step. |
2048 | 1 | SCS.First = ICK_Identity; |
2049 | 1 | } |
2050 | 1 | SCS.setToType(0, FromType); |
2051 | | |
2052 | | // The second conversion can be an integral promotion, floating |
2053 | | // point promotion, integral conversion, floating point conversion, |
2054 | | // floating-integral conversion, pointer conversion, |
2055 | | // pointer-to-member conversion, or boolean conversion (C++ 4p1). |
2056 | | // For overloading in C, this can also be a "compatible-type" |
2057 | | // conversion. |
2058 | 1 | bool IncompatibleObjC = false; |
2059 | 1 | ImplicitConversionKind SecondICK = ICK_Identity; |
2060 | 1 | if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { |
2061 | | // The unqualified versions of the types are the same: there's no |
2062 | | // conversion to do. |
2063 | 0 | SCS.Second = ICK_Identity; |
2064 | 1 | } else if (S.IsIntegralPromotion(From, FromType, ToType)) { |
2065 | | // Integral promotion (C++ 4.5). |
2066 | 0 | SCS.Second = ICK_Integral_Promotion; |
2067 | 0 | FromType = ToType.getUnqualifiedType(); |
2068 | 1 | } else if (S.IsFloatingPointPromotion(FromType, ToType)) { |
2069 | | // Floating point promotion (C++ 4.6). |
2070 | 0 | SCS.Second = ICK_Floating_Promotion; |
2071 | 0 | FromType = ToType.getUnqualifiedType(); |
2072 | 1 | } else if (S.IsComplexPromotion(FromType, ToType)) { |
2073 | | // Complex promotion (Clang extension) |
2074 | 0 | SCS.Second = ICK_Complex_Promotion; |
2075 | 0 | FromType = ToType.getUnqualifiedType(); |
2076 | 1 | } else if (ToType->isBooleanType() && |
2077 | 1 | (FromType->isArithmeticType() || |
2078 | 0 | FromType->isAnyPointerType() || |
2079 | 0 | FromType->isBlockPointerType() || |
2080 | 0 | FromType->isMemberPointerType())) { |
2081 | | // Boolean conversions (C++ 4.12). |
2082 | 0 | SCS.Second = ICK_Boolean_Conversion; |
2083 | 0 | FromType = S.Context.BoolTy; |
2084 | 1 | } else if (FromType->isIntegralOrUnscopedEnumerationType() && |
2085 | 1 | ToType->isIntegralType(S.Context)) { |
2086 | | // Integral conversions (C++ 4.7). |
2087 | 0 | SCS.Second = ICK_Integral_Conversion; |
2088 | 0 | FromType = ToType.getUnqualifiedType(); |
2089 | 1 | } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { |
2090 | | // Complex conversions (C99 6.3.1.6) |
2091 | 0 | SCS.Second = ICK_Complex_Conversion; |
2092 | 0 | FromType = ToType.getUnqualifiedType(); |
2093 | 1 | } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || |
2094 | 1 | (ToType->isAnyComplexType() && FromType->isArithmeticType())) { |
2095 | | // Complex-real conversions (C99 6.3.1.7) |
2096 | 0 | SCS.Second = ICK_Complex_Real; |
2097 | 0 | FromType = ToType.getUnqualifiedType(); |
2098 | 1 | } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { |
2099 | | // FIXME: disable conversions between long double, __ibm128 and __float128 |
2100 | | // if their representation is different until there is back end support |
2101 | | // We of course allow this conversion if long double is really double. |
2102 | | |
2103 | | // Conversions between bfloat16 and float16 are currently not supported. |
2104 | 0 | if ((FromType->isBFloat16Type() && |
2105 | 0 | (ToType->isFloat16Type() || ToType->isHalfType())) || |
2106 | 0 | (ToType->isBFloat16Type() && |
2107 | 0 | (FromType->isFloat16Type() || FromType->isHalfType()))) |
2108 | 0 | return false; |
2109 | | |
2110 | | // Conversions between IEEE-quad and IBM-extended semantics are not |
2111 | | // permitted. |
2112 | 0 | const llvm::fltSemantics &FromSem = |
2113 | 0 | S.Context.getFloatTypeSemantics(FromType); |
2114 | 0 | const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType); |
2115 | 0 | if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() && |
2116 | 0 | &ToSem == &llvm::APFloat::IEEEquad()) || |
2117 | 0 | (&FromSem == &llvm::APFloat::IEEEquad() && |
2118 | 0 | &ToSem == &llvm::APFloat::PPCDoubleDouble())) |
2119 | 0 | return false; |
2120 | | |
2121 | | // Floating point conversions (C++ 4.8). |
2122 | 0 | SCS.Second = ICK_Floating_Conversion; |
2123 | 0 | FromType = ToType.getUnqualifiedType(); |
2124 | 1 | } else if ((FromType->isRealFloatingType() && |
2125 | 1 | ToType->isIntegralType(S.Context)) || |
2126 | 1 | (FromType->isIntegralOrUnscopedEnumerationType() && |
2127 | 1 | ToType->isRealFloatingType())) { |
2128 | | |
2129 | | // Floating-integral conversions (C++ 4.9). |
2130 | 0 | SCS.Second = ICK_Floating_Integral; |
2131 | 0 | FromType = ToType.getUnqualifiedType(); |
2132 | 1 | } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { |
2133 | 0 | SCS.Second = ICK_Block_Pointer_Conversion; |
2134 | 1 | } else if (AllowObjCWritebackConversion && |
2135 | 1 | S.isObjCWritebackConversion(FromType, ToType, FromType)) { |
2136 | 0 | SCS.Second = ICK_Writeback_Conversion; |
2137 | 1 | } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, |
2138 | 1 | FromType, IncompatibleObjC)) { |
2139 | | // Pointer conversions (C++ 4.10). |
2140 | 0 | SCS.Second = ICK_Pointer_Conversion; |
2141 | 0 | SCS.IncompatibleObjC = IncompatibleObjC; |
2142 | 0 | FromType = FromType.getUnqualifiedType(); |
2143 | 1 | } else if (S.IsMemberPointerConversion(From, FromType, ToType, |
2144 | 1 | InOverloadResolution, FromType)) { |
2145 | | // Pointer to member conversions (4.11). |
2146 | 0 | SCS.Second = ICK_Pointer_Member; |
2147 | 1 | } else if (IsVectorConversion(S, FromType, ToType, SecondICK, From, |
2148 | 1 | InOverloadResolution, CStyle)) { |
2149 | 0 | SCS.Second = SecondICK; |
2150 | 0 | FromType = ToType.getUnqualifiedType(); |
2151 | 1 | } else if (!S.getLangOpts().CPlusPlus && |
2152 | 1 | S.Context.typesAreCompatible(ToType, FromType)) { |
2153 | | // Compatible conversions (Clang extension for C function overloading) |
2154 | 0 | SCS.Second = ICK_Compatible_Conversion; |
2155 | 0 | FromType = ToType.getUnqualifiedType(); |
2156 | 1 | } else if (IsTransparentUnionStandardConversion(S, From, ToType, |
2157 | 1 | InOverloadResolution, |
2158 | 1 | SCS, CStyle)) { |
2159 | 0 | SCS.Second = ICK_TransparentUnionConversion; |
2160 | 0 | FromType = ToType; |
2161 | 1 | } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, |
2162 | 1 | CStyle)) { |
2163 | | // tryAtomicConversion has updated the standard conversion sequence |
2164 | | // appropriately. |
2165 | 0 | return true; |
2166 | 1 | } else if (ToType->isEventT() && |
2167 | 1 | From->isIntegerConstantExpr(S.getASTContext()) && |
2168 | 1 | From->EvaluateKnownConstInt(S.getASTContext()) == 0) { |
2169 | 0 | SCS.Second = ICK_Zero_Event_Conversion; |
2170 | 0 | FromType = ToType; |
2171 | 1 | } else if (ToType->isQueueT() && |
2172 | 1 | From->isIntegerConstantExpr(S.getASTContext()) && |
2173 | 1 | (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { |
2174 | 0 | SCS.Second = ICK_Zero_Queue_Conversion; |
2175 | 0 | FromType = ToType; |
2176 | 1 | } else if (ToType->isSamplerT() && |
2177 | 1 | From->isIntegerConstantExpr(S.getASTContext())) { |
2178 | 0 | SCS.Second = ICK_Compatible_Conversion; |
2179 | 0 | FromType = ToType; |
2180 | 1 | } else if (ToType->isFixedPointType() || FromType->isFixedPointType()) { |
2181 | 0 | SCS.Second = ICK_Fixed_Point_Conversion; |
2182 | 0 | FromType = ToType; |
2183 | 1 | } else { |
2184 | | // No second conversion required. |
2185 | 1 | SCS.Second = ICK_Identity; |
2186 | 1 | } |
2187 | 1 | SCS.setToType(1, FromType); |
2188 | | |
2189 | | // The third conversion can be a function pointer conversion or a |
2190 | | // qualification conversion (C++ [conv.fctptr], [conv.qual]). |
2191 | 1 | bool ObjCLifetimeConversion; |
2192 | 1 | if (S.IsFunctionConversion(FromType, ToType, FromType)) { |
2193 | | // Function pointer conversions (removing 'noexcept') including removal of |
2194 | | // 'noreturn' (Clang extension). |
2195 | 0 | SCS.Third = ICK_Function_Conversion; |
2196 | 1 | } else if (S.IsQualificationConversion(FromType, ToType, CStyle, |
2197 | 1 | ObjCLifetimeConversion)) { |
2198 | 0 | SCS.Third = ICK_Qualification; |
2199 | 0 | SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; |
2200 | 0 | FromType = ToType; |
2201 | 1 | } else { |
2202 | | // No conversion required |
2203 | 1 | SCS.Third = ICK_Identity; |
2204 | 1 | } |
2205 | | |
2206 | | // C++ [over.best.ics]p6: |
2207 | | // [...] Any difference in top-level cv-qualification is |
2208 | | // subsumed by the initialization itself and does not constitute |
2209 | | // a conversion. [...] |
2210 | 1 | QualType CanonFrom = S.Context.getCanonicalType(FromType); |
2211 | 1 | QualType CanonTo = S.Context.getCanonicalType(ToType); |
2212 | 1 | if (CanonFrom.getLocalUnqualifiedType() |
2213 | 1 | == CanonTo.getLocalUnqualifiedType() && |
2214 | 1 | CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { |
2215 | 0 | FromType = ToType; |
2216 | 0 | CanonFrom = CanonTo; |
2217 | 0 | } |
2218 | | |
2219 | 1 | SCS.setToType(2, FromType); |
2220 | | |
2221 | 1 | if (CanonFrom == CanonTo) |
2222 | 0 | return true; |
2223 | | |
2224 | | // If we have not converted the argument type to the parameter type, |
2225 | | // this is a bad conversion sequence, unless we're resolving an overload in C. |
2226 | 1 | if (S.getLangOpts().CPlusPlus || !InOverloadResolution) |
2227 | 1 | return false; |
2228 | | |
2229 | 0 | ExprResult ER = ExprResult{From}; |
2230 | 0 | Sema::AssignConvertType Conv = |
2231 | 0 | S.CheckSingleAssignmentConstraints(ToType, ER, |
2232 | 0 | /*Diagnose=*/false, |
2233 | 0 | /*DiagnoseCFAudited=*/false, |
2234 | 0 | /*ConvertRHS=*/false); |
2235 | 0 | ImplicitConversionKind SecondConv; |
2236 | 0 | switch (Conv) { |
2237 | 0 | case Sema::Compatible: |
2238 | 0 | SecondConv = ICK_C_Only_Conversion; |
2239 | 0 | break; |
2240 | | // For our purposes, discarding qualifiers is just as bad as using an |
2241 | | // incompatible pointer. Note that an IncompatiblePointer conversion can drop |
2242 | | // qualifiers, as well. |
2243 | 0 | case Sema::CompatiblePointerDiscardsQualifiers: |
2244 | 0 | case Sema::IncompatiblePointer: |
2245 | 0 | case Sema::IncompatiblePointerSign: |
2246 | 0 | SecondConv = ICK_Incompatible_Pointer_Conversion; |
2247 | 0 | break; |
2248 | 0 | default: |
2249 | 0 | return false; |
2250 | 0 | } |
2251 | | |
2252 | | // First can only be an lvalue conversion, so we pretend that this was the |
2253 | | // second conversion. First should already be valid from earlier in the |
2254 | | // function. |
2255 | 0 | SCS.Second = SecondConv; |
2256 | 0 | SCS.setToType(1, ToType); |
2257 | | |
2258 | | // Third is Identity, because Second should rank us worse than any other |
2259 | | // conversion. This could also be ICK_Qualification, but it's simpler to just |
2260 | | // lump everything in with the second conversion, and we don't gain anything |
2261 | | // from making this ICK_Qualification. |
2262 | 0 | SCS.Third = ICK_Identity; |
2263 | 0 | SCS.setToType(2, ToType); |
2264 | 0 | return true; |
2265 | 0 | } |
2266 | | |
2267 | | static bool |
2268 | | IsTransparentUnionStandardConversion(Sema &S, Expr* From, |
2269 | | QualType &ToType, |
2270 | | bool InOverloadResolution, |
2271 | | StandardConversionSequence &SCS, |
2272 | 1 | bool CStyle) { |
2273 | | |
2274 | 1 | const RecordType *UT = ToType->getAsUnionType(); |
2275 | 1 | if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) |
2276 | 1 | return false; |
2277 | | // The field to initialize within the transparent union. |
2278 | 0 | RecordDecl *UD = UT->getDecl(); |
2279 | | // It's compatible if the expression matches any of the fields. |
2280 | 0 | for (const auto *it : UD->fields()) { |
2281 | 0 | if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, |
2282 | 0 | CStyle, /*AllowObjCWritebackConversion=*/false)) { |
2283 | 0 | ToType = it->getType(); |
2284 | 0 | return true; |
2285 | 0 | } |
2286 | 0 | } |
2287 | 0 | return false; |
2288 | 0 | } |
2289 | | |
2290 | | /// IsIntegralPromotion - Determines whether the conversion from the |
2291 | | /// expression From (whose potentially-adjusted type is FromType) to |
2292 | | /// ToType is an integral promotion (C++ 4.5). If so, returns true and |
2293 | | /// sets PromotedType to the promoted type. |
2294 | 1 | bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { |
2295 | 1 | const BuiltinType *To = ToType->getAs<BuiltinType>(); |
2296 | | // All integers are built-in. |
2297 | 1 | if (!To) { |
2298 | 0 | return false; |
2299 | 0 | } |
2300 | | |
2301 | | // An rvalue of type char, signed char, unsigned char, short int, or |
2302 | | // unsigned short int can be converted to an rvalue of type int if |
2303 | | // int can represent all the values of the source type; otherwise, |
2304 | | // the source rvalue can be converted to an rvalue of type unsigned |
2305 | | // int (C++ 4.5p1). |
2306 | 1 | if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() && |
2307 | 1 | !FromType->isEnumeralType()) { |
2308 | 0 | if ( // We can promote any signed, promotable integer type to an int |
2309 | 0 | (FromType->isSignedIntegerType() || |
2310 | | // We can promote any unsigned integer type whose size is |
2311 | | // less than int to an int. |
2312 | 0 | Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { |
2313 | 0 | return To->getKind() == BuiltinType::Int; |
2314 | 0 | } |
2315 | | |
2316 | 0 | return To->getKind() == BuiltinType::UInt; |
2317 | 0 | } |
2318 | | |
2319 | | // C++11 [conv.prom]p3: |
2320 | | // A prvalue of an unscoped enumeration type whose underlying type is not |
2321 | | // fixed (7.2) can be converted to an rvalue a prvalue of the first of the |
2322 | | // following types that can represent all the values of the enumeration |
2323 | | // (i.e., the values in the range bmin to bmax as described in 7.2): int, |
2324 | | // unsigned int, long int, unsigned long int, long long int, or unsigned |
2325 | | // long long int. If none of the types in that list can represent all the |
2326 | | // values of the enumeration, an rvalue a prvalue of an unscoped enumeration |
2327 | | // type can be converted to an rvalue a prvalue of the extended integer type |
2328 | | // with lowest integer conversion rank (4.13) greater than the rank of long |
2329 | | // long in which all the values of the enumeration can be represented. If |
2330 | | // there are two such extended types, the signed one is chosen. |
2331 | | // C++11 [conv.prom]p4: |
2332 | | // A prvalue of an unscoped enumeration type whose underlying type is fixed |
2333 | | // can be converted to a prvalue of its underlying type. Moreover, if |
2334 | | // integral promotion can be applied to its underlying type, a prvalue of an |
2335 | | // unscoped enumeration type whose underlying type is fixed can also be |
2336 | | // converted to a prvalue of the promoted underlying type. |
2337 | 1 | if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { |
2338 | | // C++0x 7.2p9: Note that this implicit enum to int conversion is not |
2339 | | // provided for a scoped enumeration. |
2340 | 0 | if (FromEnumType->getDecl()->isScoped()) |
2341 | 0 | return false; |
2342 | | |
2343 | | // We can perform an integral promotion to the underlying type of the enum, |
2344 | | // even if that's not the promoted type. Note that the check for promoting |
2345 | | // the underlying type is based on the type alone, and does not consider |
2346 | | // the bitfield-ness of the actual source expression. |
2347 | 0 | if (FromEnumType->getDecl()->isFixed()) { |
2348 | 0 | QualType Underlying = FromEnumType->getDecl()->getIntegerType(); |
2349 | 0 | return Context.hasSameUnqualifiedType(Underlying, ToType) || |
2350 | 0 | IsIntegralPromotion(nullptr, Underlying, ToType); |
2351 | 0 | } |
2352 | | |
2353 | | // We have already pre-calculated the promotion type, so this is trivial. |
2354 | 0 | if (ToType->isIntegerType() && |
2355 | 0 | isCompleteType(From->getBeginLoc(), FromType)) |
2356 | 0 | return Context.hasSameUnqualifiedType( |
2357 | 0 | ToType, FromEnumType->getDecl()->getPromotionType()); |
2358 | | |
2359 | | // C++ [conv.prom]p5: |
2360 | | // If the bit-field has an enumerated type, it is treated as any other |
2361 | | // value of that type for promotion purposes. |
2362 | | // |
2363 | | // ... so do not fall through into the bit-field checks below in C++. |
2364 | 0 | if (getLangOpts().CPlusPlus) |
2365 | 0 | return false; |
2366 | 0 | } |
2367 | | |
2368 | | // C++0x [conv.prom]p2: |
2369 | | // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted |
2370 | | // to an rvalue a prvalue of the first of the following types that can |
2371 | | // represent all the values of its underlying type: int, unsigned int, |
2372 | | // long int, unsigned long int, long long int, or unsigned long long int. |
2373 | | // If none of the types in that list can represent all the values of its |
2374 | | // underlying type, an rvalue a prvalue of type char16_t, char32_t, |
2375 | | // or wchar_t can be converted to an rvalue a prvalue of its underlying |
2376 | | // type. |
2377 | 1 | if (FromType->isAnyCharacterType() && !FromType->isCharType() && |
2378 | 1 | ToType->isIntegerType()) { |
2379 | | // Determine whether the type we're converting from is signed or |
2380 | | // unsigned. |
2381 | 0 | bool FromIsSigned = FromType->isSignedIntegerType(); |
2382 | 0 | uint64_t FromSize = Context.getTypeSize(FromType); |
2383 | | |
2384 | | // The types we'll try to promote to, in the appropriate |
2385 | | // order. Try each of these types. |
2386 | 0 | QualType PromoteTypes[6] = { |
2387 | 0 | Context.IntTy, Context.UnsignedIntTy, |
2388 | 0 | Context.LongTy, Context.UnsignedLongTy , |
2389 | 0 | Context.LongLongTy, Context.UnsignedLongLongTy |
2390 | 0 | }; |
2391 | 0 | for (int Idx = 0; Idx < 6; ++Idx) { |
2392 | 0 | uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); |
2393 | 0 | if (FromSize < ToSize || |
2394 | 0 | (FromSize == ToSize && |
2395 | 0 | FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { |
2396 | | // We found the type that we can promote to. If this is the |
2397 | | // type we wanted, we have a promotion. Otherwise, no |
2398 | | // promotion. |
2399 | 0 | return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); |
2400 | 0 | } |
2401 | 0 | } |
2402 | 0 | } |
2403 | | |
2404 | | // An rvalue for an integral bit-field (9.6) can be converted to an |
2405 | | // rvalue of type int if int can represent all the values of the |
2406 | | // bit-field; otherwise, it can be converted to unsigned int if |
2407 | | // unsigned int can represent all the values of the bit-field. If |
2408 | | // the bit-field is larger yet, no integral promotion applies to |
2409 | | // it. If the bit-field has an enumerated type, it is treated as any |
2410 | | // other value of that type for promotion purposes (C++ 4.5p3). |
2411 | | // FIXME: We should delay checking of bit-fields until we actually perform the |
2412 | | // conversion. |
2413 | | // |
2414 | | // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be |
2415 | | // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum |
2416 | | // bit-fields and those whose underlying type is larger than int) for GCC |
2417 | | // compatibility. |
2418 | 1 | if (From) { |
2419 | 1 | if (FieldDecl *MemberDecl = From->getSourceBitField()) { |
2420 | 0 | std::optional<llvm::APSInt> BitWidth; |
2421 | 0 | if (FromType->isIntegralType(Context) && |
2422 | 0 | (BitWidth = |
2423 | 0 | MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) { |
2424 | 0 | llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned()); |
2425 | 0 | ToSize = Context.getTypeSize(ToType); |
2426 | | |
2427 | | // Are we promoting to an int from a bitfield that fits in an int? |
2428 | 0 | if (*BitWidth < ToSize || |
2429 | 0 | (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) { |
2430 | 0 | return To->getKind() == BuiltinType::Int; |
2431 | 0 | } |
2432 | | |
2433 | | // Are we promoting to an unsigned int from an unsigned bitfield |
2434 | | // that fits into an unsigned int? |
2435 | 0 | if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) { |
2436 | 0 | return To->getKind() == BuiltinType::UInt; |
2437 | 0 | } |
2438 | | |
2439 | 0 | return false; |
2440 | 0 | } |
2441 | 0 | } |
2442 | 1 | } |
2443 | | |
2444 | | // An rvalue of type bool can be converted to an rvalue of type int, |
2445 | | // with false becoming zero and true becoming one (C++ 4.5p4). |
2446 | 1 | if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { |
2447 | 0 | return true; |
2448 | 0 | } |
2449 | | |
2450 | 1 | return false; |
2451 | 1 | } |
2452 | | |
2453 | | /// IsFloatingPointPromotion - Determines whether the conversion from |
2454 | | /// FromType to ToType is a floating point promotion (C++ 4.6). If so, |
2455 | | /// returns true and sets PromotedType to the promoted type. |
2456 | 1 | bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { |
2457 | 1 | if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) |
2458 | 0 | if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { |
2459 | | /// An rvalue of type float can be converted to an rvalue of type |
2460 | | /// double. (C++ 4.6p1). |
2461 | 0 | if (FromBuiltin->getKind() == BuiltinType::Float && |
2462 | 0 | ToBuiltin->getKind() == BuiltinType::Double) |
2463 | 0 | return true; |
2464 | | |
2465 | | // C99 6.3.1.5p1: |
2466 | | // When a float is promoted to double or long double, or a |
2467 | | // double is promoted to long double [...]. |
2468 | 0 | if (!getLangOpts().CPlusPlus && |
2469 | 0 | (FromBuiltin->getKind() == BuiltinType::Float || |
2470 | 0 | FromBuiltin->getKind() == BuiltinType::Double) && |
2471 | 0 | (ToBuiltin->getKind() == BuiltinType::LongDouble || |
2472 | 0 | ToBuiltin->getKind() == BuiltinType::Float128 || |
2473 | 0 | ToBuiltin->getKind() == BuiltinType::Ibm128)) |
2474 | 0 | return true; |
2475 | | |
2476 | | // Half can be promoted to float. |
2477 | 0 | if (!getLangOpts().NativeHalfType && |
2478 | 0 | FromBuiltin->getKind() == BuiltinType::Half && |
2479 | 0 | ToBuiltin->getKind() == BuiltinType::Float) |
2480 | 0 | return true; |
2481 | 0 | } |
2482 | | |
2483 | 1 | return false; |
2484 | 1 | } |
2485 | | |
2486 | | /// Determine if a conversion is a complex promotion. |
2487 | | /// |
2488 | | /// A complex promotion is defined as a complex -> complex conversion |
2489 | | /// where the conversion between the underlying real types is a |
2490 | | /// floating-point or integral promotion. |
2491 | 1 | bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { |
2492 | 1 | const ComplexType *FromComplex = FromType->getAs<ComplexType>(); |
2493 | 1 | if (!FromComplex) |
2494 | 1 | return false; |
2495 | | |
2496 | 0 | const ComplexType *ToComplex = ToType->getAs<ComplexType>(); |
2497 | 0 | if (!ToComplex) |
2498 | 0 | return false; |
2499 | | |
2500 | 0 | return IsFloatingPointPromotion(FromComplex->getElementType(), |
2501 | 0 | ToComplex->getElementType()) || |
2502 | 0 | IsIntegralPromotion(nullptr, FromComplex->getElementType(), |
2503 | 0 | ToComplex->getElementType()); |
2504 | 0 | } |
2505 | | |
2506 | | /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from |
2507 | | /// the pointer type FromPtr to a pointer to type ToPointee, with the |
2508 | | /// same type qualifiers as FromPtr has on its pointee type. ToType, |
2509 | | /// if non-empty, will be a pointer to ToType that may or may not have |
2510 | | /// the right set of qualifiers on its pointee. |
2511 | | /// |
2512 | | static QualType |
2513 | | BuildSimilarlyQualifiedPointerType(const Type *FromPtr, |
2514 | | QualType ToPointee, QualType ToType, |
2515 | | ASTContext &Context, |
2516 | 0 | bool StripObjCLifetime = false) { |
2517 | 0 | assert((FromPtr->getTypeClass() == Type::Pointer || |
2518 | 0 | FromPtr->getTypeClass() == Type::ObjCObjectPointer) && |
2519 | 0 | "Invalid similarly-qualified pointer type"); |
2520 | | |
2521 | | /// Conversions to 'id' subsume cv-qualifier conversions. |
2522 | 0 | if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) |
2523 | 0 | return ToType.getUnqualifiedType(); |
2524 | | |
2525 | 0 | QualType CanonFromPointee |
2526 | 0 | = Context.getCanonicalType(FromPtr->getPointeeType()); |
2527 | 0 | QualType CanonToPointee = Context.getCanonicalType(ToPointee); |
2528 | 0 | Qualifiers Quals = CanonFromPointee.getQualifiers(); |
2529 | |
|
2530 | 0 | if (StripObjCLifetime) |
2531 | 0 | Quals.removeObjCLifetime(); |
2532 | | |
2533 | | // Exact qualifier match -> return the pointer type we're converting to. |
2534 | 0 | if (CanonToPointee.getLocalQualifiers() == Quals) { |
2535 | | // ToType is exactly what we need. Return it. |
2536 | 0 | if (!ToType.isNull()) |
2537 | 0 | return ToType.getUnqualifiedType(); |
2538 | | |
2539 | | // Build a pointer to ToPointee. It has the right qualifiers |
2540 | | // already. |
2541 | 0 | if (isa<ObjCObjectPointerType>(ToType)) |
2542 | 0 | return Context.getObjCObjectPointerType(ToPointee); |
2543 | 0 | return Context.getPointerType(ToPointee); |
2544 | 0 | } |
2545 | | |
2546 | | // Just build a canonical type that has the right qualifiers. |
2547 | 0 | QualType QualifiedCanonToPointee |
2548 | 0 | = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); |
2549 | |
|
2550 | 0 | if (isa<ObjCObjectPointerType>(ToType)) |
2551 | 0 | return Context.getObjCObjectPointerType(QualifiedCanonToPointee); |
2552 | 0 | return Context.getPointerType(QualifiedCanonToPointee); |
2553 | 0 | } |
2554 | | |
2555 | | static bool isNullPointerConstantForConversion(Expr *Expr, |
2556 | | bool InOverloadResolution, |
2557 | 0 | ASTContext &Context) { |
2558 | | // Handle value-dependent integral null pointer constants correctly. |
2559 | | // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 |
2560 | 0 | if (Expr->isValueDependent() && !Expr->isTypeDependent() && |
2561 | 0 | Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) |
2562 | 0 | return !InOverloadResolution; |
2563 | | |
2564 | 0 | return Expr->isNullPointerConstant(Context, |
2565 | 0 | InOverloadResolution? Expr::NPC_ValueDependentIsNotNull |
2566 | 0 | : Expr::NPC_ValueDependentIsNull); |
2567 | 0 | } |
2568 | | |
2569 | | /// IsPointerConversion - Determines whether the conversion of the |
2570 | | /// expression From, which has the (possibly adjusted) type FromType, |
2571 | | /// can be converted to the type ToType via a pointer conversion (C++ |
2572 | | /// 4.10). If so, returns true and places the converted type (that |
2573 | | /// might differ from ToType in its cv-qualifiers at some level) into |
2574 | | /// ConvertedType. |
2575 | | /// |
2576 | | /// This routine also supports conversions to and from block pointers |
2577 | | /// and conversions with Objective-C's 'id', 'id<protocols...>', and |
2578 | | /// pointers to interfaces. FIXME: Once we've determined the |
2579 | | /// appropriate overloading rules for Objective-C, we may want to |
2580 | | /// split the Objective-C checks into a different routine; however, |
2581 | | /// GCC seems to consider all of these conversions to be pointer |
2582 | | /// conversions, so for now they live here. IncompatibleObjC will be |
2583 | | /// set if the conversion is an allowed Objective-C conversion that |
2584 | | /// should result in a warning. |
2585 | | bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, |
2586 | | bool InOverloadResolution, |
2587 | | QualType& ConvertedType, |
2588 | 1 | bool &IncompatibleObjC) { |
2589 | 1 | IncompatibleObjC = false; |
2590 | 1 | if (isObjCPointerConversion(FromType, ToType, ConvertedType, |
2591 | 1 | IncompatibleObjC)) |
2592 | 0 | return true; |
2593 | | |
2594 | | // Conversion from a null pointer constant to any Objective-C pointer type. |
2595 | 1 | if (ToType->isObjCObjectPointerType() && |
2596 | 1 | isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { |
2597 | 0 | ConvertedType = ToType; |
2598 | 0 | return true; |
2599 | 0 | } |
2600 | | |
2601 | | // Blocks: Block pointers can be converted to void*. |
2602 | 1 | if (FromType->isBlockPointerType() && ToType->isPointerType() && |
2603 | 1 | ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { |
2604 | 0 | ConvertedType = ToType; |
2605 | 0 | return true; |
2606 | 0 | } |
2607 | | // Blocks: A null pointer constant can be converted to a block |
2608 | | // pointer type. |
2609 | 1 | if (ToType->isBlockPointerType() && |
2610 | 1 | isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { |
2611 | 0 | ConvertedType = ToType; |
2612 | 0 | return true; |
2613 | 0 | } |
2614 | | |
2615 | | // If the left-hand-side is nullptr_t, the right side can be a null |
2616 | | // pointer constant. |
2617 | 1 | if (ToType->isNullPtrType() && |
2618 | 1 | isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { |
2619 | 0 | ConvertedType = ToType; |
2620 | 0 | return true; |
2621 | 0 | } |
2622 | | |
2623 | 1 | const PointerType* ToTypePtr = ToType->getAs<PointerType>(); |
2624 | 1 | if (!ToTypePtr) |
2625 | 1 | return false; |
2626 | | |
2627 | | // A null pointer constant can be converted to a pointer type (C++ 4.10p1). |
2628 | 0 | if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { |
2629 | 0 | ConvertedType = ToType; |
2630 | 0 | return true; |
2631 | 0 | } |
2632 | | |
2633 | | // Beyond this point, both types need to be pointers |
2634 | | // , including objective-c pointers. |
2635 | 0 | QualType ToPointeeType = ToTypePtr->getPointeeType(); |
2636 | 0 | if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && |
2637 | 0 | !getLangOpts().ObjCAutoRefCount) { |
2638 | 0 | ConvertedType = BuildSimilarlyQualifiedPointerType( |
2639 | 0 | FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType, |
2640 | 0 | Context); |
2641 | 0 | return true; |
2642 | 0 | } |
2643 | 0 | const PointerType *FromTypePtr = FromType->getAs<PointerType>(); |
2644 | 0 | if (!FromTypePtr) |
2645 | 0 | return false; |
2646 | | |
2647 | 0 | QualType FromPointeeType = FromTypePtr->getPointeeType(); |
2648 | | |
2649 | | // If the unqualified pointee types are the same, this can't be a |
2650 | | // pointer conversion, so don't do all of the work below. |
2651 | 0 | if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) |
2652 | 0 | return false; |
2653 | | |
2654 | | // An rvalue of type "pointer to cv T," where T is an object type, |
2655 | | // can be converted to an rvalue of type "pointer to cv void" (C++ |
2656 | | // 4.10p2). |
2657 | 0 | if (FromPointeeType->isIncompleteOrObjectType() && |
2658 | 0 | ToPointeeType->isVoidType()) { |
2659 | 0 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, |
2660 | 0 | ToPointeeType, |
2661 | 0 | ToType, Context, |
2662 | 0 | /*StripObjCLifetime=*/true); |
2663 | 0 | return true; |
2664 | 0 | } |
2665 | | |
2666 | | // MSVC allows implicit function to void* type conversion. |
2667 | 0 | if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && |
2668 | 0 | ToPointeeType->isVoidType()) { |
2669 | 0 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, |
2670 | 0 | ToPointeeType, |
2671 | 0 | ToType, Context); |
2672 | 0 | return true; |
2673 | 0 | } |
2674 | | |
2675 | | // When we're overloading in C, we allow a special kind of pointer |
2676 | | // conversion for compatible-but-not-identical pointee types. |
2677 | 0 | if (!getLangOpts().CPlusPlus && |
2678 | 0 | Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { |
2679 | 0 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, |
2680 | 0 | ToPointeeType, |
2681 | 0 | ToType, Context); |
2682 | 0 | return true; |
2683 | 0 | } |
2684 | | |
2685 | | // C++ [conv.ptr]p3: |
2686 | | // |
2687 | | // An rvalue of type "pointer to cv D," where D is a class type, |
2688 | | // can be converted to an rvalue of type "pointer to cv B," where |
2689 | | // B is a base class (clause 10) of D. If B is an inaccessible |
2690 | | // (clause 11) or ambiguous (10.2) base class of D, a program that |
2691 | | // necessitates this conversion is ill-formed. The result of the |
2692 | | // conversion is a pointer to the base class sub-object of the |
2693 | | // derived class object. The null pointer value is converted to |
2694 | | // the null pointer value of the destination type. |
2695 | | // |
2696 | | // Note that we do not check for ambiguity or inaccessibility |
2697 | | // here. That is handled by CheckPointerConversion. |
2698 | 0 | if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && |
2699 | 0 | ToPointeeType->isRecordType() && |
2700 | 0 | !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && |
2701 | 0 | IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { |
2702 | 0 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, |
2703 | 0 | ToPointeeType, |
2704 | 0 | ToType, Context); |
2705 | 0 | return true; |
2706 | 0 | } |
2707 | | |
2708 | 0 | if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && |
2709 | 0 | Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { |
2710 | 0 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, |
2711 | 0 | ToPointeeType, |
2712 | 0 | ToType, Context); |
2713 | 0 | return true; |
2714 | 0 | } |
2715 | | |
2716 | 0 | return false; |
2717 | 0 | } |
2718 | | |
2719 | | /// Adopt the given qualifiers for the given type. |
2720 | 0 | static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ |
2721 | 0 | Qualifiers TQs = T.getQualifiers(); |
2722 | | |
2723 | | // Check whether qualifiers already match. |
2724 | 0 | if (TQs == Qs) |
2725 | 0 | return T; |
2726 | | |
2727 | 0 | if (Qs.compatiblyIncludes(TQs)) |
2728 | 0 | return Context.getQualifiedType(T, Qs); |
2729 | | |
2730 | 0 | return Context.getQualifiedType(T.getUnqualifiedType(), Qs); |
2731 | 0 | } |
2732 | | |
2733 | | /// isObjCPointerConversion - Determines whether this is an |
2734 | | /// Objective-C pointer conversion. Subroutine of IsPointerConversion, |
2735 | | /// with the same arguments and return values. |
2736 | | bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, |
2737 | | QualType& ConvertedType, |
2738 | 1 | bool &IncompatibleObjC) { |
2739 | 1 | if (!getLangOpts().ObjC) |
2740 | 1 | return false; |
2741 | | |
2742 | | // The set of qualifiers on the type we're converting from. |
2743 | 0 | Qualifiers FromQualifiers = FromType.getQualifiers(); |
2744 | | |
2745 | | // First, we handle all conversions on ObjC object pointer types. |
2746 | 0 | const ObjCObjectPointerType* ToObjCPtr = |
2747 | 0 | ToType->getAs<ObjCObjectPointerType>(); |
2748 | 0 | const ObjCObjectPointerType *FromObjCPtr = |
2749 | 0 | FromType->getAs<ObjCObjectPointerType>(); |
2750 | |
|
2751 | 0 | if (ToObjCPtr && FromObjCPtr) { |
2752 | | // If the pointee types are the same (ignoring qualifications), |
2753 | | // then this is not a pointer conversion. |
2754 | 0 | if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), |
2755 | 0 | FromObjCPtr->getPointeeType())) |
2756 | 0 | return false; |
2757 | | |
2758 | | // Conversion between Objective-C pointers. |
2759 | 0 | if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { |
2760 | 0 | const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); |
2761 | 0 | const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); |
2762 | 0 | if (getLangOpts().CPlusPlus && LHS && RHS && |
2763 | 0 | !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( |
2764 | 0 | FromObjCPtr->getPointeeType())) |
2765 | 0 | return false; |
2766 | 0 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, |
2767 | 0 | ToObjCPtr->getPointeeType(), |
2768 | 0 | ToType, Context); |
2769 | 0 | ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); |
2770 | 0 | return true; |
2771 | 0 | } |
2772 | | |
2773 | 0 | if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { |
2774 | | // Okay: this is some kind of implicit downcast of Objective-C |
2775 | | // interfaces, which is permitted. However, we're going to |
2776 | | // complain about it. |
2777 | 0 | IncompatibleObjC = true; |
2778 | 0 | ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, |
2779 | 0 | ToObjCPtr->getPointeeType(), |
2780 | 0 | ToType, Context); |
2781 | 0 | ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); |
2782 | 0 | return true; |
2783 | 0 | } |
2784 | 0 | } |
2785 | | // Beyond this point, both types need to be C pointers or block pointers. |
2786 | 0 | QualType ToPointeeType; |
2787 | 0 | if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) |
2788 | 0 | ToPointeeType = ToCPtr->getPointeeType(); |
2789 | 0 | else if (const BlockPointerType *ToBlockPtr = |
2790 | 0 | ToType->getAs<BlockPointerType>()) { |
2791 | | // Objective C++: We're able to convert from a pointer to any object |
2792 | | // to a block pointer type. |
2793 | 0 | if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { |
2794 | 0 | ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); |
2795 | 0 | return true; |
2796 | 0 | } |
2797 | 0 | ToPointeeType = ToBlockPtr->getPointeeType(); |
2798 | 0 | } |
2799 | 0 | else if (FromType->getAs<BlockPointerType>() && |
2800 | 0 | ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { |
2801 | | // Objective C++: We're able to convert from a block pointer type to a |
2802 | | // pointer to any object. |
2803 | 0 | ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); |
2804 | 0 | return true; |
2805 | 0 | } |
2806 | 0 | else |
2807 | 0 | return false; |
2808 | | |
2809 | 0 | QualType FromPointeeType; |
2810 | 0 | if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) |
2811 | 0 | FromPointeeType = FromCPtr->getPointeeType(); |
2812 | 0 | else if (const BlockPointerType *FromBlockPtr = |
2813 | 0 | FromType->getAs<BlockPointerType>()) |
2814 | 0 | FromPointeeType = FromBlockPtr->getPointeeType(); |
2815 | 0 | else |
2816 | 0 | return false; |
2817 | | |
2818 | | // If we have pointers to pointers, recursively check whether this |
2819 | | // is an Objective-C conversion. |
2820 | 0 | if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && |
2821 | 0 | isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, |
2822 | 0 | IncompatibleObjC)) { |
2823 | | // We always complain about this conversion. |
2824 | 0 | IncompatibleObjC = true; |
2825 | 0 | ConvertedType = Context.getPointerType(ConvertedType); |
2826 | 0 | ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); |
2827 | 0 | return true; |
2828 | 0 | } |
2829 | | // Allow conversion of pointee being objective-c pointer to another one; |
2830 | | // as in I* to id. |
2831 | 0 | if (FromPointeeType->getAs<ObjCObjectPointerType>() && |
2832 | 0 | ToPointeeType->getAs<ObjCObjectPointerType>() && |
2833 | 0 | isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, |
2834 | 0 | IncompatibleObjC)) { |
2835 | |
|
2836 | 0 | ConvertedType = Context.getPointerType(ConvertedType); |
2837 | 0 | ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); |
2838 | 0 | return true; |
2839 | 0 | } |
2840 | | |
2841 | | // If we have pointers to functions or blocks, check whether the only |
2842 | | // differences in the argument and result types are in Objective-C |
2843 | | // pointer conversions. If so, we permit the conversion (but |
2844 | | // complain about it). |
2845 | 0 | const FunctionProtoType *FromFunctionType |
2846 | 0 | = FromPointeeType->getAs<FunctionProtoType>(); |
2847 | 0 | const FunctionProtoType *ToFunctionType |
2848 | 0 | = ToPointeeType->getAs<FunctionProtoType>(); |
2849 | 0 | if (FromFunctionType && ToFunctionType) { |
2850 | | // If the function types are exactly the same, this isn't an |
2851 | | // Objective-C pointer conversion. |
2852 | 0 | if (Context.getCanonicalType(FromPointeeType) |
2853 | 0 | == Context.getCanonicalType(ToPointeeType)) |
2854 | 0 | return false; |
2855 | | |
2856 | | // Perform the quick checks that will tell us whether these |
2857 | | // function types are obviously different. |
2858 | 0 | if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || |
2859 | 0 | FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || |
2860 | 0 | FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) |
2861 | 0 | return false; |
2862 | | |
2863 | 0 | bool HasObjCConversion = false; |
2864 | 0 | if (Context.getCanonicalType(FromFunctionType->getReturnType()) == |
2865 | 0 | Context.getCanonicalType(ToFunctionType->getReturnType())) { |
2866 | | // Okay, the types match exactly. Nothing to do. |
2867 | 0 | } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), |
2868 | 0 | ToFunctionType->getReturnType(), |
2869 | 0 | ConvertedType, IncompatibleObjC)) { |
2870 | | // Okay, we have an Objective-C pointer conversion. |
2871 | 0 | HasObjCConversion = true; |
2872 | 0 | } else { |
2873 | | // Function types are too different. Abort. |
2874 | 0 | return false; |
2875 | 0 | } |
2876 | | |
2877 | | // Check argument types. |
2878 | 0 | for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); |
2879 | 0 | ArgIdx != NumArgs; ++ArgIdx) { |
2880 | 0 | QualType FromArgType = FromFunctionType->getParamType(ArgIdx); |
2881 | 0 | QualType ToArgType = ToFunctionType->getParamType(ArgIdx); |
2882 | 0 | if (Context.getCanonicalType(FromArgType) |
2883 | 0 | == Context.getCanonicalType(ToArgType)) { |
2884 | | // Okay, the types match exactly. Nothing to do. |
2885 | 0 | } else if (isObjCPointerConversion(FromArgType, ToArgType, |
2886 | 0 | ConvertedType, IncompatibleObjC)) { |
2887 | | // Okay, we have an Objective-C pointer conversion. |
2888 | 0 | HasObjCConversion = true; |
2889 | 0 | } else { |
2890 | | // Argument types are too different. Abort. |
2891 | 0 | return false; |
2892 | 0 | } |
2893 | 0 | } |
2894 | | |
2895 | 0 | if (HasObjCConversion) { |
2896 | | // We had an Objective-C conversion. Allow this pointer |
2897 | | // conversion, but complain about it. |
2898 | 0 | ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); |
2899 | 0 | IncompatibleObjC = true; |
2900 | 0 | return true; |
2901 | 0 | } |
2902 | 0 | } |
2903 | | |
2904 | 0 | return false; |
2905 | 0 | } |
2906 | | |
2907 | | /// Determine whether this is an Objective-C writeback conversion, |
2908 | | /// used for parameter passing when performing automatic reference counting. |
2909 | | /// |
2910 | | /// \param FromType The type we're converting form. |
2911 | | /// |
2912 | | /// \param ToType The type we're converting to. |
2913 | | /// |
2914 | | /// \param ConvertedType The type that will be produced after applying |
2915 | | /// this conversion. |
2916 | | bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, |
2917 | 0 | QualType &ConvertedType) { |
2918 | 0 | if (!getLangOpts().ObjCAutoRefCount || |
2919 | 0 | Context.hasSameUnqualifiedType(FromType, ToType)) |
2920 | 0 | return false; |
2921 | | |
2922 | | // Parameter must be a pointer to __autoreleasing (with no other qualifiers). |
2923 | 0 | QualType ToPointee; |
2924 | 0 | if (const PointerType *ToPointer = ToType->getAs<PointerType>()) |
2925 | 0 | ToPointee = ToPointer->getPointeeType(); |
2926 | 0 | else |
2927 | 0 | return false; |
2928 | | |
2929 | 0 | Qualifiers ToQuals = ToPointee.getQualifiers(); |
2930 | 0 | if (!ToPointee->isObjCLifetimeType() || |
2931 | 0 | ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || |
2932 | 0 | !ToQuals.withoutObjCLifetime().empty()) |
2933 | 0 | return false; |
2934 | | |
2935 | | // Argument must be a pointer to __strong to __weak. |
2936 | 0 | QualType FromPointee; |
2937 | 0 | if (const PointerType *FromPointer = FromType->getAs<PointerType>()) |
2938 | 0 | FromPointee = FromPointer->getPointeeType(); |
2939 | 0 | else |
2940 | 0 | return false; |
2941 | | |
2942 | 0 | Qualifiers FromQuals = FromPointee.getQualifiers(); |
2943 | 0 | if (!FromPointee->isObjCLifetimeType() || |
2944 | 0 | (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && |
2945 | 0 | FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) |
2946 | 0 | return false; |
2947 | | |
2948 | | // Make sure that we have compatible qualifiers. |
2949 | 0 | FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); |
2950 | 0 | if (!ToQuals.compatiblyIncludes(FromQuals)) |
2951 | 0 | return false; |
2952 | | |
2953 | | // Remove qualifiers from the pointee type we're converting from; they |
2954 | | // aren't used in the compatibility check belong, and we'll be adding back |
2955 | | // qualifiers (with __autoreleasing) if the compatibility check succeeds. |
2956 | 0 | FromPointee = FromPointee.getUnqualifiedType(); |
2957 | | |
2958 | | // The unqualified form of the pointee types must be compatible. |
2959 | 0 | ToPointee = ToPointee.getUnqualifiedType(); |
2960 | 0 | bool IncompatibleObjC; |
2961 | 0 | if (Context.typesAreCompatible(FromPointee, ToPointee)) |
2962 | 0 | FromPointee = ToPointee; |
2963 | 0 | else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, |
2964 | 0 | IncompatibleObjC)) |
2965 | 0 | return false; |
2966 | | |
2967 | | /// Construct the type we're converting to, which is a pointer to |
2968 | | /// __autoreleasing pointee. |
2969 | 0 | FromPointee = Context.getQualifiedType(FromPointee, FromQuals); |
2970 | 0 | ConvertedType = Context.getPointerType(FromPointee); |
2971 | 0 | return true; |
2972 | 0 | } |
2973 | | |
2974 | | bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, |
2975 | 1 | QualType& ConvertedType) { |
2976 | 1 | QualType ToPointeeType; |
2977 | 1 | if (const BlockPointerType *ToBlockPtr = |
2978 | 1 | ToType->getAs<BlockPointerType>()) |
2979 | 0 | ToPointeeType = ToBlockPtr->getPointeeType(); |
2980 | 1 | else |
2981 | 1 | return false; |
2982 | | |
2983 | 0 | QualType FromPointeeType; |
2984 | 0 | if (const BlockPointerType *FromBlockPtr = |
2985 | 0 | FromType->getAs<BlockPointerType>()) |
2986 | 0 | FromPointeeType = FromBlockPtr->getPointeeType(); |
2987 | 0 | else |
2988 | 0 | return false; |
2989 | | // We have pointer to blocks, check whether the only |
2990 | | // differences in the argument and result types are in Objective-C |
2991 | | // pointer conversions. If so, we permit the conversion. |
2992 | | |
2993 | 0 | const FunctionProtoType *FromFunctionType |
2994 | 0 | = FromPointeeType->getAs<FunctionProtoType>(); |
2995 | 0 | const FunctionProtoType *ToFunctionType |
2996 | 0 | = ToPointeeType->getAs<FunctionProtoType>(); |
2997 | |
|
2998 | 0 | if (!FromFunctionType || !ToFunctionType) |
2999 | 0 | return false; |
3000 | | |
3001 | 0 | if (Context.hasSameType(FromPointeeType, ToPointeeType)) |
3002 | 0 | return true; |
3003 | | |
3004 | | // Perform the quick checks that will tell us whether these |
3005 | | // function types are obviously different. |
3006 | 0 | if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || |
3007 | 0 | FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) |
3008 | 0 | return false; |
3009 | | |
3010 | 0 | FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); |
3011 | 0 | FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); |
3012 | 0 | if (FromEInfo != ToEInfo) |
3013 | 0 | return false; |
3014 | | |
3015 | 0 | bool IncompatibleObjC = false; |
3016 | 0 | if (Context.hasSameType(FromFunctionType->getReturnType(), |
3017 | 0 | ToFunctionType->getReturnType())) { |
3018 | | // Okay, the types match exactly. Nothing to do. |
3019 | 0 | } else { |
3020 | 0 | QualType RHS = FromFunctionType->getReturnType(); |
3021 | 0 | QualType LHS = ToFunctionType->getReturnType(); |
3022 | 0 | if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && |
3023 | 0 | !RHS.hasQualifiers() && LHS.hasQualifiers()) |
3024 | 0 | LHS = LHS.getUnqualifiedType(); |
3025 | |
|
3026 | 0 | if (Context.hasSameType(RHS,LHS)) { |
3027 | | // OK exact match. |
3028 | 0 | } else if (isObjCPointerConversion(RHS, LHS, |
3029 | 0 | ConvertedType, IncompatibleObjC)) { |
3030 | 0 | if (IncompatibleObjC) |
3031 | 0 | return false; |
3032 | | // Okay, we have an Objective-C pointer conversion. |
3033 | 0 | } |
3034 | 0 | else |
3035 | 0 | return false; |
3036 | 0 | } |
3037 | | |
3038 | | // Check argument types. |
3039 | 0 | for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); |
3040 | 0 | ArgIdx != NumArgs; ++ArgIdx) { |
3041 | 0 | IncompatibleObjC = false; |
3042 | 0 | QualType FromArgType = FromFunctionType->getParamType(ArgIdx); |
3043 | 0 | QualType ToArgType = ToFunctionType->getParamType(ArgIdx); |
3044 | 0 | if (Context.hasSameType(FromArgType, ToArgType)) { |
3045 | | // Okay, the types match exactly. Nothing to do. |
3046 | 0 | } else if (isObjCPointerConversion(ToArgType, FromArgType, |
3047 | 0 | ConvertedType, IncompatibleObjC)) { |
3048 | 0 | if (IncompatibleObjC) |
3049 | 0 | return false; |
3050 | | // Okay, we have an Objective-C pointer conversion. |
3051 | 0 | } else |
3052 | | // Argument types are too different. Abort. |
3053 | 0 | return false; |
3054 | 0 | } |
3055 | | |
3056 | 0 | SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; |
3057 | 0 | bool CanUseToFPT, CanUseFromFPT; |
3058 | 0 | if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, |
3059 | 0 | CanUseToFPT, CanUseFromFPT, |
3060 | 0 | NewParamInfos)) |
3061 | 0 | return false; |
3062 | | |
3063 | 0 | ConvertedType = ToType; |
3064 | 0 | return true; |
3065 | 0 | } |
3066 | | |
3067 | | enum { |
3068 | | ft_default, |
3069 | | ft_different_class, |
3070 | | ft_parameter_arity, |
3071 | | ft_parameter_mismatch, |
3072 | | ft_return_type, |
3073 | | ft_qualifer_mismatch, |
3074 | | ft_noexcept |
3075 | | }; |
3076 | | |
3077 | | /// Attempts to get the FunctionProtoType from a Type. Handles |
3078 | | /// MemberFunctionPointers properly. |
3079 | 0 | static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { |
3080 | 0 | if (auto *FPT = FromType->getAs<FunctionProtoType>()) |
3081 | 0 | return FPT; |
3082 | | |
3083 | 0 | if (auto *MPT = FromType->getAs<MemberPointerType>()) |
3084 | 0 | return MPT->getPointeeType()->getAs<FunctionProtoType>(); |
3085 | | |
3086 | 0 | return nullptr; |
3087 | 0 | } |
3088 | | |
3089 | | /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing |
3090 | | /// function types. Catches different number of parameter, mismatch in |
3091 | | /// parameter types, and different return types. |
3092 | | void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, |
3093 | 0 | QualType FromType, QualType ToType) { |
3094 | | // If either type is not valid, include no extra info. |
3095 | 0 | if (FromType.isNull() || ToType.isNull()) { |
3096 | 0 | PDiag << ft_default; |
3097 | 0 | return; |
3098 | 0 | } |
3099 | | |
3100 | | // Get the function type from the pointers. |
3101 | 0 | if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { |
3102 | 0 | const auto *FromMember = FromType->castAs<MemberPointerType>(), |
3103 | 0 | *ToMember = ToType->castAs<MemberPointerType>(); |
3104 | 0 | if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { |
3105 | 0 | PDiag << ft_different_class << QualType(ToMember->getClass(), 0) |
3106 | 0 | << QualType(FromMember->getClass(), 0); |
3107 | 0 | return; |
3108 | 0 | } |
3109 | 0 | FromType = FromMember->getPointeeType(); |
3110 | 0 | ToType = ToMember->getPointeeType(); |
3111 | 0 | } |
3112 | | |
3113 | 0 | if (FromType->isPointerType()) |
3114 | 0 | FromType = FromType->getPointeeType(); |
3115 | 0 | if (ToType->isPointerType()) |
3116 | 0 | ToType = ToType->getPointeeType(); |
3117 | | |
3118 | | // Remove references. |
3119 | 0 | FromType = FromType.getNonReferenceType(); |
3120 | 0 | ToType = ToType.getNonReferenceType(); |
3121 | | |
3122 | | // Don't print extra info for non-specialized template functions. |
3123 | 0 | if (FromType->isInstantiationDependentType() && |
3124 | 0 | !FromType->getAs<TemplateSpecializationType>()) { |
3125 | 0 | PDiag << ft_default; |
3126 | 0 | return; |
3127 | 0 | } |
3128 | | |
3129 | | // No extra info for same types. |
3130 | 0 | if (Context.hasSameType(FromType, ToType)) { |
3131 | 0 | PDiag << ft_default; |
3132 | 0 | return; |
3133 | 0 | } |
3134 | | |
3135 | 0 | const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), |
3136 | 0 | *ToFunction = tryGetFunctionProtoType(ToType); |
3137 | | |
3138 | | // Both types need to be function types. |
3139 | 0 | if (!FromFunction || !ToFunction) { |
3140 | 0 | PDiag << ft_default; |
3141 | 0 | return; |
3142 | 0 | } |
3143 | | |
3144 | 0 | if (FromFunction->getNumParams() != ToFunction->getNumParams()) { |
3145 | 0 | PDiag << ft_parameter_arity << ToFunction->getNumParams() |
3146 | 0 | << FromFunction->getNumParams(); |
3147 | 0 | return; |
3148 | 0 | } |
3149 | | |
3150 | | // Handle different parameter types. |
3151 | 0 | unsigned ArgPos; |
3152 | 0 | if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { |
3153 | 0 | PDiag << ft_parameter_mismatch << ArgPos + 1 |
3154 | 0 | << ToFunction->getParamType(ArgPos) |
3155 | 0 | << FromFunction->getParamType(ArgPos); |
3156 | 0 | return; |
3157 | 0 | } |
3158 | | |
3159 | | // Handle different return type. |
3160 | 0 | if (!Context.hasSameType(FromFunction->getReturnType(), |
3161 | 0 | ToFunction->getReturnType())) { |
3162 | 0 | PDiag << ft_return_type << ToFunction->getReturnType() |
3163 | 0 | << FromFunction->getReturnType(); |
3164 | 0 | return; |
3165 | 0 | } |
3166 | | |
3167 | 0 | if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { |
3168 | 0 | PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() |
3169 | 0 | << FromFunction->getMethodQuals(); |
3170 | 0 | return; |
3171 | 0 | } |
3172 | | |
3173 | | // Handle exception specification differences on canonical type (in C++17 |
3174 | | // onwards). |
3175 | 0 | if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) |
3176 | 0 | ->isNothrow() != |
3177 | 0 | cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) |
3178 | 0 | ->isNothrow()) { |
3179 | 0 | PDiag << ft_noexcept; |
3180 | 0 | return; |
3181 | 0 | } |
3182 | | |
3183 | | // Unable to find a difference, so add no extra info. |
3184 | 0 | PDiag << ft_default; |
3185 | 0 | } |
3186 | | |
3187 | | /// FunctionParamTypesAreEqual - This routine checks two function proto types |
3188 | | /// for equality of their parameter types. Caller has already checked that |
3189 | | /// they have same number of parameters. If the parameters are different, |
3190 | | /// ArgPos will have the parameter index of the first different parameter. |
3191 | | /// If `Reversed` is true, the parameters of `NewType` will be compared in |
3192 | | /// reverse order. That's useful if one of the functions is being used as a C++20 |
3193 | | /// synthesized operator overload with a reversed parameter order. |
3194 | | bool Sema::FunctionParamTypesAreEqual(ArrayRef<QualType> Old, |
3195 | | ArrayRef<QualType> New, unsigned *ArgPos, |
3196 | 0 | bool Reversed) { |
3197 | 0 | assert(llvm::size(Old) == llvm::size(New) && |
3198 | 0 | "Can't compare parameters of functions with different number of " |
3199 | 0 | "parameters!"); |
3200 | | |
3201 | 0 | for (auto &&[Idx, Type] : llvm::enumerate(Old)) { |
3202 | | // Reverse iterate over the parameters of `OldType` if `Reversed` is true. |
3203 | 0 | size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx; |
3204 | | |
3205 | | // Ignore address spaces in pointee type. This is to disallow overloading |
3206 | | // on __ptr32/__ptr64 address spaces. |
3207 | 0 | QualType OldType = |
3208 | 0 | Context.removePtrSizeAddrSpace(Type.getUnqualifiedType()); |
3209 | 0 | QualType NewType = |
3210 | 0 | Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType()); |
3211 | |
|
3212 | 0 | if (!Context.hasSameType(OldType, NewType)) { |
3213 | 0 | if (ArgPos) |
3214 | 0 | *ArgPos = Idx; |
3215 | 0 | return false; |
3216 | 0 | } |
3217 | 0 | } |
3218 | 0 | return true; |
3219 | 0 | } |
3220 | | |
3221 | | bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, |
3222 | | const FunctionProtoType *NewType, |
3223 | 0 | unsigned *ArgPos, bool Reversed) { |
3224 | 0 | return FunctionParamTypesAreEqual(OldType->param_types(), |
3225 | 0 | NewType->param_types(), ArgPos, Reversed); |
3226 | 0 | } |
3227 | | |
3228 | | bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction, |
3229 | | const FunctionDecl *NewFunction, |
3230 | | unsigned *ArgPos, |
3231 | 0 | bool Reversed) { |
3232 | |
|
3233 | 0 | if (OldFunction->getNumNonObjectParams() != |
3234 | 0 | NewFunction->getNumNonObjectParams()) |
3235 | 0 | return false; |
3236 | | |
3237 | 0 | unsigned OldIgnore = |
3238 | 0 | unsigned(OldFunction->hasCXXExplicitFunctionObjectParameter()); |
3239 | 0 | unsigned NewIgnore = |
3240 | 0 | unsigned(NewFunction->hasCXXExplicitFunctionObjectParameter()); |
3241 | |
|
3242 | 0 | auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType()); |
3243 | 0 | auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType()); |
3244 | |
|
3245 | 0 | return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore), |
3246 | 0 | NewPT->param_types().slice(NewIgnore), |
3247 | 0 | ArgPos, Reversed); |
3248 | 0 | } |
3249 | | |
3250 | | /// CheckPointerConversion - Check the pointer conversion from the |
3251 | | /// expression From to the type ToType. This routine checks for |
3252 | | /// ambiguous or inaccessible derived-to-base pointer |
3253 | | /// conversions for which IsPointerConversion has already returned |
3254 | | /// true. It returns true and produces a diagnostic if there was an |
3255 | | /// error, or returns false otherwise. |
3256 | | bool Sema::CheckPointerConversion(Expr *From, QualType ToType, |
3257 | | CastKind &Kind, |
3258 | | CXXCastPath& BasePath, |
3259 | | bool IgnoreBaseAccess, |
3260 | 0 | bool Diagnose) { |
3261 | 0 | QualType FromType = From->getType(); |
3262 | 0 | bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; |
3263 | |
|
3264 | 0 | Kind = CK_BitCast; |
3265 | |
|
3266 | 0 | if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && |
3267 | 0 | From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == |
3268 | 0 | Expr::NPCK_ZeroExpression) { |
3269 | 0 | if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) |
3270 | 0 | DiagRuntimeBehavior(From->getExprLoc(), From, |
3271 | 0 | PDiag(diag::warn_impcast_bool_to_null_pointer) |
3272 | 0 | << ToType << From->getSourceRange()); |
3273 | 0 | else if (!isUnevaluatedContext()) |
3274 | 0 | Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) |
3275 | 0 | << ToType << From->getSourceRange(); |
3276 | 0 | } |
3277 | 0 | if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { |
3278 | 0 | if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { |
3279 | 0 | QualType FromPointeeType = FromPtrType->getPointeeType(), |
3280 | 0 | ToPointeeType = ToPtrType->getPointeeType(); |
3281 | |
|
3282 | 0 | if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && |
3283 | 0 | !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { |
3284 | | // We must have a derived-to-base conversion. Check an |
3285 | | // ambiguous or inaccessible conversion. |
3286 | 0 | unsigned InaccessibleID = 0; |
3287 | 0 | unsigned AmbiguousID = 0; |
3288 | 0 | if (Diagnose) { |
3289 | 0 | InaccessibleID = diag::err_upcast_to_inaccessible_base; |
3290 | 0 | AmbiguousID = diag::err_ambiguous_derived_to_base_conv; |
3291 | 0 | } |
3292 | 0 | if (CheckDerivedToBaseConversion( |
3293 | 0 | FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID, |
3294 | 0 | From->getExprLoc(), From->getSourceRange(), DeclarationName(), |
3295 | 0 | &BasePath, IgnoreBaseAccess)) |
3296 | 0 | return true; |
3297 | | |
3298 | | // The conversion was successful. |
3299 | 0 | Kind = CK_DerivedToBase; |
3300 | 0 | } |
3301 | | |
3302 | 0 | if (Diagnose && !IsCStyleOrFunctionalCast && |
3303 | 0 | FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { |
3304 | 0 | assert(getLangOpts().MSVCCompat && |
3305 | 0 | "this should only be possible with MSVCCompat!"); |
3306 | 0 | Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) |
3307 | 0 | << From->getSourceRange(); |
3308 | 0 | } |
3309 | 0 | } |
3310 | 0 | } else if (const ObjCObjectPointerType *ToPtrType = |
3311 | 0 | ToType->getAs<ObjCObjectPointerType>()) { |
3312 | 0 | if (const ObjCObjectPointerType *FromPtrType = |
3313 | 0 | FromType->getAs<ObjCObjectPointerType>()) { |
3314 | | // Objective-C++ conversions are always okay. |
3315 | | // FIXME: We should have a different class of conversions for the |
3316 | | // Objective-C++ implicit conversions. |
3317 | 0 | if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) |
3318 | 0 | return false; |
3319 | 0 | } else if (FromType->isBlockPointerType()) { |
3320 | 0 | Kind = CK_BlockPointerToObjCPointerCast; |
3321 | 0 | } else { |
3322 | 0 | Kind = CK_CPointerToObjCPointerCast; |
3323 | 0 | } |
3324 | 0 | } else if (ToType->isBlockPointerType()) { |
3325 | 0 | if (!FromType->isBlockPointerType()) |
3326 | 0 | Kind = CK_AnyPointerToBlockPointerCast; |
3327 | 0 | } |
3328 | | |
3329 | | // We shouldn't fall into this case unless it's valid for other |
3330 | | // reasons. |
3331 | 0 | if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) |
3332 | 0 | Kind = CK_NullToPointer; |
3333 | |
|
3334 | 0 | return false; |
3335 | 0 | } |
3336 | | |
3337 | | /// IsMemberPointerConversion - Determines whether the conversion of the |
3338 | | /// expression From, which has the (possibly adjusted) type FromType, can be |
3339 | | /// converted to the type ToType via a member pointer conversion (C++ 4.11). |
3340 | | /// If so, returns true and places the converted type (that might differ from |
3341 | | /// ToType in its cv-qualifiers at some level) into ConvertedType. |
3342 | | bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, |
3343 | | QualType ToType, |
3344 | | bool InOverloadResolution, |
3345 | 1 | QualType &ConvertedType) { |
3346 | 1 | const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); |
3347 | 1 | if (!ToTypePtr) |
3348 | 1 | return false; |
3349 | | |
3350 | | // A null pointer constant can be converted to a member pointer (C++ 4.11p1) |
3351 | 0 | if (From->isNullPointerConstant(Context, |
3352 | 0 | InOverloadResolution? Expr::NPC_ValueDependentIsNotNull |
3353 | 0 | : Expr::NPC_ValueDependentIsNull)) { |
3354 | 0 | ConvertedType = ToType; |
3355 | 0 | return true; |
3356 | 0 | } |
3357 | | |
3358 | | // Otherwise, both types have to be member pointers. |
3359 | 0 | const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); |
3360 | 0 | if (!FromTypePtr) |
3361 | 0 | return false; |
3362 | | |
3363 | | // A pointer to member of B can be converted to a pointer to member of D, |
3364 | | // where D is derived from B (C++ 4.11p2). |
3365 | 0 | QualType FromClass(FromTypePtr->getClass(), 0); |
3366 | 0 | QualType ToClass(ToTypePtr->getClass(), 0); |
3367 | |
|
3368 | 0 | if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && |
3369 | 0 | IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { |
3370 | 0 | ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), |
3371 | 0 | ToClass.getTypePtr()); |
3372 | 0 | return true; |
3373 | 0 | } |
3374 | | |
3375 | 0 | return false; |
3376 | 0 | } |
3377 | | |
3378 | | /// CheckMemberPointerConversion - Check the member pointer conversion from the |
3379 | | /// expression From to the type ToType. This routine checks for ambiguous or |
3380 | | /// virtual or inaccessible base-to-derived member pointer conversions |
3381 | | /// for which IsMemberPointerConversion has already returned true. It returns |
3382 | | /// true and produces a diagnostic if there was an error, or returns false |
3383 | | /// otherwise. |
3384 | | bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, |
3385 | | CastKind &Kind, |
3386 | | CXXCastPath &BasePath, |
3387 | 0 | bool IgnoreBaseAccess) { |
3388 | 0 | QualType FromType = From->getType(); |
3389 | 0 | const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); |
3390 | 0 | if (!FromPtrType) { |
3391 | | // This must be a null pointer to member pointer conversion |
3392 | 0 | assert(From->isNullPointerConstant(Context, |
3393 | 0 | Expr::NPC_ValueDependentIsNull) && |
3394 | 0 | "Expr must be null pointer constant!"); |
3395 | 0 | Kind = CK_NullToMemberPointer; |
3396 | 0 | return false; |
3397 | 0 | } |
3398 | | |
3399 | 0 | const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); |
3400 | 0 | assert(ToPtrType && "No member pointer cast has a target type " |
3401 | 0 | "that is not a member pointer."); |
3402 | | |
3403 | 0 | QualType FromClass = QualType(FromPtrType->getClass(), 0); |
3404 | 0 | QualType ToClass = QualType(ToPtrType->getClass(), 0); |
3405 | | |
3406 | | // FIXME: What about dependent types? |
3407 | 0 | assert(FromClass->isRecordType() && "Pointer into non-class."); |
3408 | 0 | assert(ToClass->isRecordType() && "Pointer into non-class."); |
3409 | | |
3410 | 0 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, |
3411 | 0 | /*DetectVirtual=*/true); |
3412 | 0 | bool DerivationOkay = |
3413 | 0 | IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); |
3414 | 0 | assert(DerivationOkay && |
3415 | 0 | "Should not have been called if derivation isn't OK."); |
3416 | 0 | (void)DerivationOkay; |
3417 | |
|
3418 | 0 | if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). |
3419 | 0 | getUnqualifiedType())) { |
3420 | 0 | std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); |
3421 | 0 | Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) |
3422 | 0 | << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); |
3423 | 0 | return true; |
3424 | 0 | } |
3425 | | |
3426 | 0 | if (const RecordType *VBase = Paths.getDetectedVirtual()) { |
3427 | 0 | Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) |
3428 | 0 | << FromClass << ToClass << QualType(VBase, 0) |
3429 | 0 | << From->getSourceRange(); |
3430 | 0 | return true; |
3431 | 0 | } |
3432 | | |
3433 | 0 | if (!IgnoreBaseAccess) |
3434 | 0 | CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, |
3435 | 0 | Paths.front(), |
3436 | 0 | diag::err_downcast_from_inaccessible_base); |
3437 | | |
3438 | | // Must be a base to derived member conversion. |
3439 | 0 | BuildBasePathArray(Paths, BasePath); |
3440 | 0 | Kind = CK_BaseToDerivedMemberPointer; |
3441 | 0 | return false; |
3442 | 0 | } |
3443 | | |
3444 | | /// Determine whether the lifetime conversion between the two given |
3445 | | /// qualifiers sets is nontrivial. |
3446 | | static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, |
3447 | 0 | Qualifiers ToQuals) { |
3448 | | // Converting anything to const __unsafe_unretained is trivial. |
3449 | 0 | if (ToQuals.hasConst() && |
3450 | 0 | ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) |
3451 | 0 | return false; |
3452 | | |
3453 | 0 | return true; |
3454 | 0 | } |
3455 | | |
3456 | | /// Perform a single iteration of the loop for checking if a qualification |
3457 | | /// conversion is valid. |
3458 | | /// |
3459 | | /// Specifically, check whether any change between the qualifiers of \p |
3460 | | /// FromType and \p ToType is permissible, given knowledge about whether every |
3461 | | /// outer layer is const-qualified. |
3462 | | static bool isQualificationConversionStep(QualType FromType, QualType ToType, |
3463 | | bool CStyle, bool IsTopLevel, |
3464 | | bool &PreviousToQualsIncludeConst, |
3465 | 0 | bool &ObjCLifetimeConversion) { |
3466 | 0 | Qualifiers FromQuals = FromType.getQualifiers(); |
3467 | 0 | Qualifiers ToQuals = ToType.getQualifiers(); |
3468 | | |
3469 | | // Ignore __unaligned qualifier. |
3470 | 0 | FromQuals.removeUnaligned(); |
3471 | | |
3472 | | // Objective-C ARC: |
3473 | | // Check Objective-C lifetime conversions. |
3474 | 0 | if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) { |
3475 | 0 | if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { |
3476 | 0 | if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) |
3477 | 0 | ObjCLifetimeConversion = true; |
3478 | 0 | FromQuals.removeObjCLifetime(); |
3479 | 0 | ToQuals.removeObjCLifetime(); |
3480 | 0 | } else { |
3481 | | // Qualification conversions cannot cast between different |
3482 | | // Objective-C lifetime qualifiers. |
3483 | 0 | return false; |
3484 | 0 | } |
3485 | 0 | } |
3486 | | |
3487 | | // Allow addition/removal of GC attributes but not changing GC attributes. |
3488 | 0 | if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && |
3489 | 0 | (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { |
3490 | 0 | FromQuals.removeObjCGCAttr(); |
3491 | 0 | ToQuals.removeObjCGCAttr(); |
3492 | 0 | } |
3493 | | |
3494 | | // -- for every j > 0, if const is in cv 1,j then const is in cv |
3495 | | // 2,j, and similarly for volatile. |
3496 | 0 | if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) |
3497 | 0 | return false; |
3498 | | |
3499 | | // If address spaces mismatch: |
3500 | | // - in top level it is only valid to convert to addr space that is a |
3501 | | // superset in all cases apart from C-style casts where we allow |
3502 | | // conversions between overlapping address spaces. |
3503 | | // - in non-top levels it is not a valid conversion. |
3504 | 0 | if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() && |
3505 | 0 | (!IsTopLevel || |
3506 | 0 | !(ToQuals.isAddressSpaceSupersetOf(FromQuals) || |
3507 | 0 | (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals))))) |
3508 | 0 | return false; |
3509 | | |
3510 | | // -- if the cv 1,j and cv 2,j are different, then const is in |
3511 | | // every cv for 0 < k < j. |
3512 | 0 | if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() && |
3513 | 0 | !PreviousToQualsIncludeConst) |
3514 | 0 | return false; |
3515 | | |
3516 | | // The following wording is from C++20, where the result of the conversion |
3517 | | // is T3, not T2. |
3518 | | // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is |
3519 | | // "array of unknown bound of" |
3520 | 0 | if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType()) |
3521 | 0 | return false; |
3522 | | |
3523 | | // -- if the resulting P3,i is different from P1,i [...], then const is |
3524 | | // added to every cv 3_k for 0 < k < i. |
3525 | 0 | if (!CStyle && FromType->isConstantArrayType() && |
3526 | 0 | ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst) |
3527 | 0 | return false; |
3528 | | |
3529 | | // Keep track of whether all prior cv-qualifiers in the "to" type |
3530 | | // include const. |
3531 | 0 | PreviousToQualsIncludeConst = |
3532 | 0 | PreviousToQualsIncludeConst && ToQuals.hasConst(); |
3533 | 0 | return true; |
3534 | 0 | } |
3535 | | |
3536 | | /// IsQualificationConversion - Determines whether the conversion from |
3537 | | /// an rvalue of type FromType to ToType is a qualification conversion |
3538 | | /// (C++ 4.4). |
3539 | | /// |
3540 | | /// \param ObjCLifetimeConversion Output parameter that will be set to indicate |
3541 | | /// when the qualification conversion involves a change in the Objective-C |
3542 | | /// object lifetime. |
3543 | | bool |
3544 | | Sema::IsQualificationConversion(QualType FromType, QualType ToType, |
3545 | 1 | bool CStyle, bool &ObjCLifetimeConversion) { |
3546 | 1 | FromType = Context.getCanonicalType(FromType); |
3547 | 1 | ToType = Context.getCanonicalType(ToType); |
3548 | 1 | ObjCLifetimeConversion = false; |
3549 | | |
3550 | | // If FromType and ToType are the same type, this is not a |
3551 | | // qualification conversion. |
3552 | 1 | if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) |
3553 | 0 | return false; |
3554 | | |
3555 | | // (C++ 4.4p4): |
3556 | | // A conversion can add cv-qualifiers at levels other than the first |
3557 | | // in multi-level pointers, subject to the following rules: [...] |
3558 | 1 | bool PreviousToQualsIncludeConst = true; |
3559 | 1 | bool UnwrappedAnyPointer = false; |
3560 | 1 | while (Context.UnwrapSimilarTypes(FromType, ToType)) { |
3561 | 0 | if (!isQualificationConversionStep( |
3562 | 0 | FromType, ToType, CStyle, !UnwrappedAnyPointer, |
3563 | 0 | PreviousToQualsIncludeConst, ObjCLifetimeConversion)) |
3564 | 0 | return false; |
3565 | 0 | UnwrappedAnyPointer = true; |
3566 | 0 | } |
3567 | | |
3568 | | // We are left with FromType and ToType being the pointee types |
3569 | | // after unwrapping the original FromType and ToType the same number |
3570 | | // of times. If we unwrapped any pointers, and if FromType and |
3571 | | // ToType have the same unqualified type (since we checked |
3572 | | // qualifiers above), then this is a qualification conversion. |
3573 | 1 | return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); |
3574 | 1 | } |
3575 | | |
3576 | | /// - Determine whether this is a conversion from a scalar type to an |
3577 | | /// atomic type. |
3578 | | /// |
3579 | | /// If successful, updates \c SCS's second and third steps in the conversion |
3580 | | /// sequence to finish the conversion. |
3581 | | static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, |
3582 | | bool InOverloadResolution, |
3583 | | StandardConversionSequence &SCS, |
3584 | 1 | bool CStyle) { |
3585 | 1 | const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); |
3586 | 1 | if (!ToAtomic) |
3587 | 1 | return false; |
3588 | | |
3589 | 0 | StandardConversionSequence InnerSCS; |
3590 | 0 | if (!IsStandardConversion(S, From, ToAtomic->getValueType(), |
3591 | 0 | InOverloadResolution, InnerSCS, |
3592 | 0 | CStyle, /*AllowObjCWritebackConversion=*/false)) |
3593 | 0 | return false; |
3594 | | |
3595 | 0 | SCS.Second = InnerSCS.Second; |
3596 | 0 | SCS.setToType(1, InnerSCS.getToType(1)); |
3597 | 0 | SCS.Third = InnerSCS.Third; |
3598 | 0 | SCS.QualificationIncludesObjCLifetime |
3599 | 0 | = InnerSCS.QualificationIncludesObjCLifetime; |
3600 | 0 | SCS.setToType(2, InnerSCS.getToType(2)); |
3601 | 0 | return true; |
3602 | 0 | } |
3603 | | |
3604 | | static bool isFirstArgumentCompatibleWithType(ASTContext &Context, |
3605 | | CXXConstructorDecl *Constructor, |
3606 | 0 | QualType Type) { |
3607 | 0 | const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>(); |
3608 | 0 | if (CtorType->getNumParams() > 0) { |
3609 | 0 | QualType FirstArg = CtorType->getParamType(0); |
3610 | 0 | if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) |
3611 | 0 | return true; |
3612 | 0 | } |
3613 | 0 | return false; |
3614 | 0 | } |
3615 | | |
3616 | | static OverloadingResult |
3617 | | IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, |
3618 | | CXXRecordDecl *To, |
3619 | | UserDefinedConversionSequence &User, |
3620 | | OverloadCandidateSet &CandidateSet, |
3621 | 0 | bool AllowExplicit) { |
3622 | 0 | CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); |
3623 | 0 | for (auto *D : S.LookupConstructors(To)) { |
3624 | 0 | auto Info = getConstructorInfo(D); |
3625 | 0 | if (!Info) |
3626 | 0 | continue; |
3627 | | |
3628 | 0 | bool Usable = !Info.Constructor->isInvalidDecl() && |
3629 | 0 | S.isInitListConstructor(Info.Constructor); |
3630 | 0 | if (Usable) { |
3631 | 0 | bool SuppressUserConversions = false; |
3632 | 0 | if (Info.ConstructorTmpl) |
3633 | 0 | S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, |
3634 | 0 | /*ExplicitArgs*/ nullptr, From, |
3635 | 0 | CandidateSet, SuppressUserConversions, |
3636 | 0 | /*PartialOverloading*/ false, |
3637 | 0 | AllowExplicit); |
3638 | 0 | else |
3639 | 0 | S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, |
3640 | 0 | CandidateSet, SuppressUserConversions, |
3641 | 0 | /*PartialOverloading*/ false, AllowExplicit); |
3642 | 0 | } |
3643 | 0 | } |
3644 | |
|
3645 | 0 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
3646 | |
|
3647 | 0 | OverloadCandidateSet::iterator Best; |
3648 | 0 | switch (auto Result = |
3649 | 0 | CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { |
3650 | 0 | case OR_Deleted: |
3651 | 0 | case OR_Success: { |
3652 | | // Record the standard conversion we used and the conversion function. |
3653 | 0 | CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); |
3654 | 0 | QualType ThisType = Constructor->getFunctionObjectParameterType(); |
3655 | | // Initializer lists don't have conversions as such. |
3656 | 0 | User.Before.setAsIdentityConversion(); |
3657 | 0 | User.HadMultipleCandidates = HadMultipleCandidates; |
3658 | 0 | User.ConversionFunction = Constructor; |
3659 | 0 | User.FoundConversionFunction = Best->FoundDecl; |
3660 | 0 | User.After.setAsIdentityConversion(); |
3661 | 0 | User.After.setFromType(ThisType); |
3662 | 0 | User.After.setAllToTypes(ToType); |
3663 | 0 | return Result; |
3664 | 0 | } |
3665 | | |
3666 | 0 | case OR_No_Viable_Function: |
3667 | 0 | return OR_No_Viable_Function; |
3668 | 0 | case OR_Ambiguous: |
3669 | 0 | return OR_Ambiguous; |
3670 | 0 | } |
3671 | | |
3672 | 0 | llvm_unreachable("Invalid OverloadResult!"); |
3673 | 0 | } |
3674 | | |
3675 | | /// Determines whether there is a user-defined conversion sequence |
3676 | | /// (C++ [over.ics.user]) that converts expression From to the type |
3677 | | /// ToType. If such a conversion exists, User will contain the |
3678 | | /// user-defined conversion sequence that performs such a conversion |
3679 | | /// and this routine will return true. Otherwise, this routine returns |
3680 | | /// false and User is unspecified. |
3681 | | /// |
3682 | | /// \param AllowExplicit true if the conversion should consider C++0x |
3683 | | /// "explicit" conversion functions as well as non-explicit conversion |
3684 | | /// functions (C++0x [class.conv.fct]p2). |
3685 | | /// |
3686 | | /// \param AllowObjCConversionOnExplicit true if the conversion should |
3687 | | /// allow an extra Objective-C pointer conversion on uses of explicit |
3688 | | /// constructors. Requires \c AllowExplicit to also be set. |
3689 | | static OverloadingResult |
3690 | | IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, |
3691 | | UserDefinedConversionSequence &User, |
3692 | | OverloadCandidateSet &CandidateSet, |
3693 | | AllowedExplicit AllowExplicit, |
3694 | 2 | bool AllowObjCConversionOnExplicit) { |
3695 | 2 | assert(AllowExplicit != AllowedExplicit::None || |
3696 | 2 | !AllowObjCConversionOnExplicit); |
3697 | 0 | CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); |
3698 | | |
3699 | | // Whether we will only visit constructors. |
3700 | 2 | bool ConstructorsOnly = false; |
3701 | | |
3702 | | // If the type we are conversion to is a class type, enumerate its |
3703 | | // constructors. |
3704 | 2 | if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { |
3705 | | // C++ [over.match.ctor]p1: |
3706 | | // When objects of class type are direct-initialized (8.5), or |
3707 | | // copy-initialized from an expression of the same or a |
3708 | | // derived class type (8.5), overload resolution selects the |
3709 | | // constructor. [...] For copy-initialization, the candidate |
3710 | | // functions are all the converting constructors (12.3.1) of |
3711 | | // that class. The argument list is the expression-list within |
3712 | | // the parentheses of the initializer. |
3713 | 0 | if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || |
3714 | 0 | (From->getType()->getAs<RecordType>() && |
3715 | 0 | S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) |
3716 | 0 | ConstructorsOnly = true; |
3717 | |
|
3718 | 0 | if (!S.isCompleteType(From->getExprLoc(), ToType)) { |
3719 | | // We're not going to find any constructors. |
3720 | 0 | } else if (CXXRecordDecl *ToRecordDecl |
3721 | 0 | = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { |
3722 | |
|
3723 | 0 | Expr **Args = &From; |
3724 | 0 | unsigned NumArgs = 1; |
3725 | 0 | bool ListInitializing = false; |
3726 | 0 | if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { |
3727 | | // But first, see if there is an init-list-constructor that will work. |
3728 | 0 | OverloadingResult Result = IsInitializerListConstructorConversion( |
3729 | 0 | S, From, ToType, ToRecordDecl, User, CandidateSet, |
3730 | 0 | AllowExplicit == AllowedExplicit::All); |
3731 | 0 | if (Result != OR_No_Viable_Function) |
3732 | 0 | return Result; |
3733 | | // Never mind. |
3734 | 0 | CandidateSet.clear( |
3735 | 0 | OverloadCandidateSet::CSK_InitByUserDefinedConversion); |
3736 | | |
3737 | | // If we're list-initializing, we pass the individual elements as |
3738 | | // arguments, not the entire list. |
3739 | 0 | Args = InitList->getInits(); |
3740 | 0 | NumArgs = InitList->getNumInits(); |
3741 | 0 | ListInitializing = true; |
3742 | 0 | } |
3743 | | |
3744 | 0 | for (auto *D : S.LookupConstructors(ToRecordDecl)) { |
3745 | 0 | auto Info = getConstructorInfo(D); |
3746 | 0 | if (!Info) |
3747 | 0 | continue; |
3748 | | |
3749 | 0 | bool Usable = !Info.Constructor->isInvalidDecl(); |
3750 | 0 | if (!ListInitializing) |
3751 | 0 | Usable = Usable && Info.Constructor->isConvertingConstructor( |
3752 | 0 | /*AllowExplicit*/ true); |
3753 | 0 | if (Usable) { |
3754 | 0 | bool SuppressUserConversions = !ConstructorsOnly; |
3755 | | // C++20 [over.best.ics.general]/4.5: |
3756 | | // if the target is the first parameter of a constructor [of class |
3757 | | // X] and the constructor [...] is a candidate by [...] the second |
3758 | | // phase of [over.match.list] when the initializer list has exactly |
3759 | | // one element that is itself an initializer list, [...] and the |
3760 | | // conversion is to X or reference to cv X, user-defined conversion |
3761 | | // sequences are not cnosidered. |
3762 | 0 | if (SuppressUserConversions && ListInitializing) { |
3763 | 0 | SuppressUserConversions = |
3764 | 0 | NumArgs == 1 && isa<InitListExpr>(Args[0]) && |
3765 | 0 | isFirstArgumentCompatibleWithType(S.Context, Info.Constructor, |
3766 | 0 | ToType); |
3767 | 0 | } |
3768 | 0 | if (Info.ConstructorTmpl) |
3769 | 0 | S.AddTemplateOverloadCandidate( |
3770 | 0 | Info.ConstructorTmpl, Info.FoundDecl, |
3771 | 0 | /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs), |
3772 | 0 | CandidateSet, SuppressUserConversions, |
3773 | 0 | /*PartialOverloading*/ false, |
3774 | 0 | AllowExplicit == AllowedExplicit::All); |
3775 | 0 | else |
3776 | | // Allow one user-defined conversion when user specifies a |
3777 | | // From->ToType conversion via an static cast (c-style, etc). |
3778 | 0 | S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, |
3779 | 0 | llvm::ArrayRef(Args, NumArgs), CandidateSet, |
3780 | 0 | SuppressUserConversions, |
3781 | 0 | /*PartialOverloading*/ false, |
3782 | 0 | AllowExplicit == AllowedExplicit::All); |
3783 | 0 | } |
3784 | 0 | } |
3785 | 0 | } |
3786 | 0 | } |
3787 | | |
3788 | | // Enumerate conversion functions, if we're allowed to. |
3789 | 2 | if (ConstructorsOnly || isa<InitListExpr>(From)) { |
3790 | 2 | } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { |
3791 | | // No conversion functions from incomplete types. |
3792 | 2 | } else if (const RecordType *FromRecordType = |
3793 | 2 | From->getType()->getAs<RecordType>()) { |
3794 | 0 | if (CXXRecordDecl *FromRecordDecl |
3795 | 0 | = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { |
3796 | | // Add all of the conversion functions as candidates. |
3797 | 0 | const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); |
3798 | 0 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { |
3799 | 0 | DeclAccessPair FoundDecl = I.getPair(); |
3800 | 0 | NamedDecl *D = FoundDecl.getDecl(); |
3801 | 0 | CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); |
3802 | 0 | if (isa<UsingShadowDecl>(D)) |
3803 | 0 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); |
3804 | |
|
3805 | 0 | CXXConversionDecl *Conv; |
3806 | 0 | FunctionTemplateDecl *ConvTemplate; |
3807 | 0 | if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) |
3808 | 0 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); |
3809 | 0 | else |
3810 | 0 | Conv = cast<CXXConversionDecl>(D); |
3811 | |
|
3812 | 0 | if (ConvTemplate) |
3813 | 0 | S.AddTemplateConversionCandidate( |
3814 | 0 | ConvTemplate, FoundDecl, ActingContext, From, ToType, |
3815 | 0 | CandidateSet, AllowObjCConversionOnExplicit, |
3816 | 0 | AllowExplicit != AllowedExplicit::None); |
3817 | 0 | else |
3818 | 0 | S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType, |
3819 | 0 | CandidateSet, AllowObjCConversionOnExplicit, |
3820 | 0 | AllowExplicit != AllowedExplicit::None); |
3821 | 0 | } |
3822 | 0 | } |
3823 | 0 | } |
3824 | | |
3825 | 2 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
3826 | | |
3827 | 2 | OverloadCandidateSet::iterator Best; |
3828 | 2 | switch (auto Result = |
3829 | 2 | CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { |
3830 | 0 | case OR_Success: |
3831 | 0 | case OR_Deleted: |
3832 | | // Record the standard conversion we used and the conversion function. |
3833 | 0 | if (CXXConstructorDecl *Constructor |
3834 | 0 | = dyn_cast<CXXConstructorDecl>(Best->Function)) { |
3835 | | // C++ [over.ics.user]p1: |
3836 | | // If the user-defined conversion is specified by a |
3837 | | // constructor (12.3.1), the initial standard conversion |
3838 | | // sequence converts the source type to the type required by |
3839 | | // the argument of the constructor. |
3840 | | // |
3841 | 0 | if (isa<InitListExpr>(From)) { |
3842 | | // Initializer lists don't have conversions as such. |
3843 | 0 | User.Before.setAsIdentityConversion(); |
3844 | 0 | } else { |
3845 | 0 | if (Best->Conversions[0].isEllipsis()) |
3846 | 0 | User.EllipsisConversion = true; |
3847 | 0 | else { |
3848 | 0 | User.Before = Best->Conversions[0].Standard; |
3849 | 0 | User.EllipsisConversion = false; |
3850 | 0 | } |
3851 | 0 | } |
3852 | 0 | User.HadMultipleCandidates = HadMultipleCandidates; |
3853 | 0 | User.ConversionFunction = Constructor; |
3854 | 0 | User.FoundConversionFunction = Best->FoundDecl; |
3855 | 0 | User.After.setAsIdentityConversion(); |
3856 | 0 | User.After.setFromType(Constructor->getFunctionObjectParameterType()); |
3857 | 0 | User.After.setAllToTypes(ToType); |
3858 | 0 | return Result; |
3859 | 0 | } |
3860 | 0 | if (CXXConversionDecl *Conversion |
3861 | 0 | = dyn_cast<CXXConversionDecl>(Best->Function)) { |
3862 | | // C++ [over.ics.user]p1: |
3863 | | // |
3864 | | // [...] If the user-defined conversion is specified by a |
3865 | | // conversion function (12.3.2), the initial standard |
3866 | | // conversion sequence converts the source type to the |
3867 | | // implicit object parameter of the conversion function. |
3868 | 0 | User.Before = Best->Conversions[0].Standard; |
3869 | 0 | User.HadMultipleCandidates = HadMultipleCandidates; |
3870 | 0 | User.ConversionFunction = Conversion; |
3871 | 0 | User.FoundConversionFunction = Best->FoundDecl; |
3872 | 0 | User.EllipsisConversion = false; |
3873 | | |
3874 | | // C++ [over.ics.user]p2: |
3875 | | // The second standard conversion sequence converts the |
3876 | | // result of the user-defined conversion to the target type |
3877 | | // for the sequence. Since an implicit conversion sequence |
3878 | | // is an initialization, the special rules for |
3879 | | // initialization by user-defined conversion apply when |
3880 | | // selecting the best user-defined conversion for a |
3881 | | // user-defined conversion sequence (see 13.3.3 and |
3882 | | // 13.3.3.1). |
3883 | 0 | User.After = Best->FinalConversion; |
3884 | 0 | return Result; |
3885 | 0 | } |
3886 | 0 | llvm_unreachable("Not a constructor or conversion function?"); |
3887 | |
|
3888 | 2 | case OR_No_Viable_Function: |
3889 | 2 | return OR_No_Viable_Function; |
3890 | | |
3891 | 0 | case OR_Ambiguous: |
3892 | 0 | return OR_Ambiguous; |
3893 | 2 | } |
3894 | | |
3895 | 0 | llvm_unreachable("Invalid OverloadResult!"); |
3896 | 0 | } |
3897 | | |
3898 | | bool |
3899 | 1 | Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { |
3900 | 1 | ImplicitConversionSequence ICS; |
3901 | 1 | OverloadCandidateSet CandidateSet(From->getExprLoc(), |
3902 | 1 | OverloadCandidateSet::CSK_Normal); |
3903 | 1 | OverloadingResult OvResult = |
3904 | 1 | IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, |
3905 | 1 | CandidateSet, AllowedExplicit::None, false); |
3906 | | |
3907 | 1 | if (!(OvResult == OR_Ambiguous || |
3908 | 1 | (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) |
3909 | 1 | return false; |
3910 | | |
3911 | 0 | auto Cands = CandidateSet.CompleteCandidates( |
3912 | 0 | *this, |
3913 | 0 | OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, |
3914 | 0 | From); |
3915 | 0 | if (OvResult == OR_Ambiguous) |
3916 | 0 | Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) |
3917 | 0 | << From->getType() << ToType << From->getSourceRange(); |
3918 | 0 | else { // OR_No_Viable_Function && !CandidateSet.empty() |
3919 | 0 | if (!RequireCompleteType(From->getBeginLoc(), ToType, |
3920 | 0 | diag::err_typecheck_nonviable_condition_incomplete, |
3921 | 0 | From->getType(), From->getSourceRange())) |
3922 | 0 | Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) |
3923 | 0 | << false << From->getType() << From->getSourceRange() << ToType; |
3924 | 0 | } |
3925 | |
|
3926 | 0 | CandidateSet.NoteCandidates( |
3927 | 0 | *this, From, Cands); |
3928 | 0 | return true; |
3929 | 1 | } |
3930 | | |
3931 | | // Helper for compareConversionFunctions that gets the FunctionType that the |
3932 | | // conversion-operator return value 'points' to, or nullptr. |
3933 | | static const FunctionType * |
3934 | 0 | getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) { |
3935 | 0 | const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>(); |
3936 | 0 | const PointerType *RetPtrTy = |
3937 | 0 | ConvFuncTy->getReturnType()->getAs<PointerType>(); |
3938 | |
|
3939 | 0 | if (!RetPtrTy) |
3940 | 0 | return nullptr; |
3941 | | |
3942 | 0 | return RetPtrTy->getPointeeType()->getAs<FunctionType>(); |
3943 | 0 | } |
3944 | | |
3945 | | /// Compare the user-defined conversion functions or constructors |
3946 | | /// of two user-defined conversion sequences to determine whether any ordering |
3947 | | /// is possible. |
3948 | | static ImplicitConversionSequence::CompareKind |
3949 | | compareConversionFunctions(Sema &S, FunctionDecl *Function1, |
3950 | 0 | FunctionDecl *Function2) { |
3951 | 0 | CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); |
3952 | 0 | CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2); |
3953 | 0 | if (!Conv1 || !Conv2) |
3954 | 0 | return ImplicitConversionSequence::Indistinguishable; |
3955 | | |
3956 | 0 | if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda()) |
3957 | 0 | return ImplicitConversionSequence::Indistinguishable; |
3958 | | |
3959 | | // Objective-C++: |
3960 | | // If both conversion functions are implicitly-declared conversions from |
3961 | | // a lambda closure type to a function pointer and a block pointer, |
3962 | | // respectively, always prefer the conversion to a function pointer, |
3963 | | // because the function pointer is more lightweight and is more likely |
3964 | | // to keep code working. |
3965 | 0 | if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) { |
3966 | 0 | bool Block1 = Conv1->getConversionType()->isBlockPointerType(); |
3967 | 0 | bool Block2 = Conv2->getConversionType()->isBlockPointerType(); |
3968 | 0 | if (Block1 != Block2) |
3969 | 0 | return Block1 ? ImplicitConversionSequence::Worse |
3970 | 0 | : ImplicitConversionSequence::Better; |
3971 | 0 | } |
3972 | | |
3973 | | // In order to support multiple calling conventions for the lambda conversion |
3974 | | // operator (such as when the free and member function calling convention is |
3975 | | // different), prefer the 'free' mechanism, followed by the calling-convention |
3976 | | // of operator(). The latter is in place to support the MSVC-like solution of |
3977 | | // defining ALL of the possible conversions in regards to calling-convention. |
3978 | 0 | const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1); |
3979 | 0 | const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2); |
3980 | |
|
3981 | 0 | if (Conv1FuncRet && Conv2FuncRet && |
3982 | 0 | Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) { |
3983 | 0 | CallingConv Conv1CC = Conv1FuncRet->getCallConv(); |
3984 | 0 | CallingConv Conv2CC = Conv2FuncRet->getCallConv(); |
3985 | |
|
3986 | 0 | CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator(); |
3987 | 0 | const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>(); |
3988 | |
|
3989 | 0 | CallingConv CallOpCC = |
3990 | 0 | CallOp->getType()->castAs<FunctionType>()->getCallConv(); |
3991 | 0 | CallingConv DefaultFree = S.Context.getDefaultCallingConvention( |
3992 | 0 | CallOpProto->isVariadic(), /*IsCXXMethod=*/false); |
3993 | 0 | CallingConv DefaultMember = S.Context.getDefaultCallingConvention( |
3994 | 0 | CallOpProto->isVariadic(), /*IsCXXMethod=*/true); |
3995 | |
|
3996 | 0 | CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC}; |
3997 | 0 | for (CallingConv CC : PrefOrder) { |
3998 | 0 | if (Conv1CC == CC) |
3999 | 0 | return ImplicitConversionSequence::Better; |
4000 | 0 | if (Conv2CC == CC) |
4001 | 0 | return ImplicitConversionSequence::Worse; |
4002 | 0 | } |
4003 | 0 | } |
4004 | | |
4005 | 0 | return ImplicitConversionSequence::Indistinguishable; |
4006 | 0 | } |
4007 | | |
4008 | | static bool hasDeprecatedStringLiteralToCharPtrConversion( |
4009 | 0 | const ImplicitConversionSequence &ICS) { |
4010 | 0 | return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || |
4011 | 0 | (ICS.isUserDefined() && |
4012 | 0 | ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); |
4013 | 0 | } |
4014 | | |
4015 | | /// CompareImplicitConversionSequences - Compare two implicit |
4016 | | /// conversion sequences to determine whether one is better than the |
4017 | | /// other or if they are indistinguishable (C++ 13.3.3.2). |
4018 | | static ImplicitConversionSequence::CompareKind |
4019 | | CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, |
4020 | | const ImplicitConversionSequence& ICS1, |
4021 | | const ImplicitConversionSequence& ICS2) |
4022 | 0 | { |
4023 | | // (C++ 13.3.3.2p2): When comparing the basic forms of implicit |
4024 | | // conversion sequences (as defined in 13.3.3.1) |
4025 | | // -- a standard conversion sequence (13.3.3.1.1) is a better |
4026 | | // conversion sequence than a user-defined conversion sequence or |
4027 | | // an ellipsis conversion sequence, and |
4028 | | // -- a user-defined conversion sequence (13.3.3.1.2) is a better |
4029 | | // conversion sequence than an ellipsis conversion sequence |
4030 | | // (13.3.3.1.3). |
4031 | | // |
4032 | | // C++0x [over.best.ics]p10: |
4033 | | // For the purpose of ranking implicit conversion sequences as |
4034 | | // described in 13.3.3.2, the ambiguous conversion sequence is |
4035 | | // treated as a user-defined sequence that is indistinguishable |
4036 | | // from any other user-defined conversion sequence. |
4037 | | |
4038 | | // String literal to 'char *' conversion has been deprecated in C++03. It has |
4039 | | // been removed from C++11. We still accept this conversion, if it happens at |
4040 | | // the best viable function. Otherwise, this conversion is considered worse |
4041 | | // than ellipsis conversion. Consider this as an extension; this is not in the |
4042 | | // standard. For example: |
4043 | | // |
4044 | | // int &f(...); // #1 |
4045 | | // void f(char*); // #2 |
4046 | | // void g() { int &r = f("foo"); } |
4047 | | // |
4048 | | // In C++03, we pick #2 as the best viable function. |
4049 | | // In C++11, we pick #1 as the best viable function, because ellipsis |
4050 | | // conversion is better than string-literal to char* conversion (since there |
4051 | | // is no such conversion in C++11). If there was no #1 at all or #1 couldn't |
4052 | | // convert arguments, #2 would be the best viable function in C++11. |
4053 | | // If the best viable function has this conversion, a warning will be issued |
4054 | | // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. |
4055 | |
|
4056 | 0 | if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && |
4057 | 0 | hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != |
4058 | 0 | hasDeprecatedStringLiteralToCharPtrConversion(ICS2) && |
4059 | | // Ill-formedness must not differ |
4060 | 0 | ICS1.isBad() == ICS2.isBad()) |
4061 | 0 | return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) |
4062 | 0 | ? ImplicitConversionSequence::Worse |
4063 | 0 | : ImplicitConversionSequence::Better; |
4064 | | |
4065 | 0 | if (ICS1.getKindRank() < ICS2.getKindRank()) |
4066 | 0 | return ImplicitConversionSequence::Better; |
4067 | 0 | if (ICS2.getKindRank() < ICS1.getKindRank()) |
4068 | 0 | return ImplicitConversionSequence::Worse; |
4069 | | |
4070 | | // The following checks require both conversion sequences to be of |
4071 | | // the same kind. |
4072 | 0 | if (ICS1.getKind() != ICS2.getKind()) |
4073 | 0 | return ImplicitConversionSequence::Indistinguishable; |
4074 | | |
4075 | 0 | ImplicitConversionSequence::CompareKind Result = |
4076 | 0 | ImplicitConversionSequence::Indistinguishable; |
4077 | | |
4078 | | // Two implicit conversion sequences of the same form are |
4079 | | // indistinguishable conversion sequences unless one of the |
4080 | | // following rules apply: (C++ 13.3.3.2p3): |
4081 | | |
4082 | | // List-initialization sequence L1 is a better conversion sequence than |
4083 | | // list-initialization sequence L2 if: |
4084 | | // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, |
4085 | | // if not that, |
4086 | | // — L1 and L2 convert to arrays of the same element type, and either the |
4087 | | // number of elements n_1 initialized by L1 is less than the number of |
4088 | | // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to |
4089 | | // an array of unknown bound and L1 does not, |
4090 | | // even if one of the other rules in this paragraph would otherwise apply. |
4091 | 0 | if (!ICS1.isBad()) { |
4092 | 0 | bool StdInit1 = false, StdInit2 = false; |
4093 | 0 | if (ICS1.hasInitializerListContainerType()) |
4094 | 0 | StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(), |
4095 | 0 | nullptr); |
4096 | 0 | if (ICS2.hasInitializerListContainerType()) |
4097 | 0 | StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(), |
4098 | 0 | nullptr); |
4099 | 0 | if (StdInit1 != StdInit2) |
4100 | 0 | return StdInit1 ? ImplicitConversionSequence::Better |
4101 | 0 | : ImplicitConversionSequence::Worse; |
4102 | | |
4103 | 0 | if (ICS1.hasInitializerListContainerType() && |
4104 | 0 | ICS2.hasInitializerListContainerType()) |
4105 | 0 | if (auto *CAT1 = S.Context.getAsConstantArrayType( |
4106 | 0 | ICS1.getInitializerListContainerType())) |
4107 | 0 | if (auto *CAT2 = S.Context.getAsConstantArrayType( |
4108 | 0 | ICS2.getInitializerListContainerType())) { |
4109 | 0 | if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(), |
4110 | 0 | CAT2->getElementType())) { |
4111 | | // Both to arrays of the same element type |
4112 | 0 | if (CAT1->getSize() != CAT2->getSize()) |
4113 | | // Different sized, the smaller wins |
4114 | 0 | return CAT1->getSize().ult(CAT2->getSize()) |
4115 | 0 | ? ImplicitConversionSequence::Better |
4116 | 0 | : ImplicitConversionSequence::Worse; |
4117 | 0 | if (ICS1.isInitializerListOfIncompleteArray() != |
4118 | 0 | ICS2.isInitializerListOfIncompleteArray()) |
4119 | | // One is incomplete, it loses |
4120 | 0 | return ICS2.isInitializerListOfIncompleteArray() |
4121 | 0 | ? ImplicitConversionSequence::Better |
4122 | 0 | : ImplicitConversionSequence::Worse; |
4123 | 0 | } |
4124 | 0 | } |
4125 | 0 | } |
4126 | | |
4127 | 0 | if (ICS1.isStandard()) |
4128 | | // Standard conversion sequence S1 is a better conversion sequence than |
4129 | | // standard conversion sequence S2 if [...] |
4130 | 0 | Result = CompareStandardConversionSequences(S, Loc, |
4131 | 0 | ICS1.Standard, ICS2.Standard); |
4132 | 0 | else if (ICS1.isUserDefined()) { |
4133 | | // User-defined conversion sequence U1 is a better conversion |
4134 | | // sequence than another user-defined conversion sequence U2 if |
4135 | | // they contain the same user-defined conversion function or |
4136 | | // constructor and if the second standard conversion sequence of |
4137 | | // U1 is better than the second standard conversion sequence of |
4138 | | // U2 (C++ 13.3.3.2p3). |
4139 | 0 | if (ICS1.UserDefined.ConversionFunction == |
4140 | 0 | ICS2.UserDefined.ConversionFunction) |
4141 | 0 | Result = CompareStandardConversionSequences(S, Loc, |
4142 | 0 | ICS1.UserDefined.After, |
4143 | 0 | ICS2.UserDefined.After); |
4144 | 0 | else |
4145 | 0 | Result = compareConversionFunctions(S, |
4146 | 0 | ICS1.UserDefined.ConversionFunction, |
4147 | 0 | ICS2.UserDefined.ConversionFunction); |
4148 | 0 | } |
4149 | |
|
4150 | 0 | return Result; |
4151 | 0 | } |
4152 | | |
4153 | | // Per 13.3.3.2p3, compare the given standard conversion sequences to |
4154 | | // determine if one is a proper subset of the other. |
4155 | | static ImplicitConversionSequence::CompareKind |
4156 | | compareStandardConversionSubsets(ASTContext &Context, |
4157 | | const StandardConversionSequence& SCS1, |
4158 | 0 | const StandardConversionSequence& SCS2) { |
4159 | 0 | ImplicitConversionSequence::CompareKind Result |
4160 | 0 | = ImplicitConversionSequence::Indistinguishable; |
4161 | | |
4162 | | // the identity conversion sequence is considered to be a subsequence of |
4163 | | // any non-identity conversion sequence |
4164 | 0 | if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) |
4165 | 0 | return ImplicitConversionSequence::Better; |
4166 | 0 | else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) |
4167 | 0 | return ImplicitConversionSequence::Worse; |
4168 | | |
4169 | 0 | if (SCS1.Second != SCS2.Second) { |
4170 | 0 | if (SCS1.Second == ICK_Identity) |
4171 | 0 | Result = ImplicitConversionSequence::Better; |
4172 | 0 | else if (SCS2.Second == ICK_Identity) |
4173 | 0 | Result = ImplicitConversionSequence::Worse; |
4174 | 0 | else |
4175 | 0 | return ImplicitConversionSequence::Indistinguishable; |
4176 | 0 | } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) |
4177 | 0 | return ImplicitConversionSequence::Indistinguishable; |
4178 | | |
4179 | 0 | if (SCS1.Third == SCS2.Third) { |
4180 | 0 | return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result |
4181 | 0 | : ImplicitConversionSequence::Indistinguishable; |
4182 | 0 | } |
4183 | | |
4184 | 0 | if (SCS1.Third == ICK_Identity) |
4185 | 0 | return Result == ImplicitConversionSequence::Worse |
4186 | 0 | ? ImplicitConversionSequence::Indistinguishable |
4187 | 0 | : ImplicitConversionSequence::Better; |
4188 | | |
4189 | 0 | if (SCS2.Third == ICK_Identity) |
4190 | 0 | return Result == ImplicitConversionSequence::Better |
4191 | 0 | ? ImplicitConversionSequence::Indistinguishable |
4192 | 0 | : ImplicitConversionSequence::Worse; |
4193 | | |
4194 | 0 | return ImplicitConversionSequence::Indistinguishable; |
4195 | 0 | } |
4196 | | |
4197 | | /// Determine whether one of the given reference bindings is better |
4198 | | /// than the other based on what kind of bindings they are. |
4199 | | static bool |
4200 | | isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, |
4201 | 0 | const StandardConversionSequence &SCS2) { |
4202 | | // C++0x [over.ics.rank]p3b4: |
4203 | | // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an |
4204 | | // implicit object parameter of a non-static member function declared |
4205 | | // without a ref-qualifier, and *either* S1 binds an rvalue reference |
4206 | | // to an rvalue and S2 binds an lvalue reference *or S1 binds an |
4207 | | // lvalue reference to a function lvalue and S2 binds an rvalue |
4208 | | // reference*. |
4209 | | // |
4210 | | // FIXME: Rvalue references. We're going rogue with the above edits, |
4211 | | // because the semantics in the current C++0x working paper (N3225 at the |
4212 | | // time of this writing) break the standard definition of std::forward |
4213 | | // and std::reference_wrapper when dealing with references to functions. |
4214 | | // Proposed wording changes submitted to CWG for consideration. |
4215 | 0 | if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || |
4216 | 0 | SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) |
4217 | 0 | return false; |
4218 | | |
4219 | 0 | return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && |
4220 | 0 | SCS2.IsLvalueReference) || |
4221 | 0 | (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && |
4222 | 0 | !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); |
4223 | 0 | } |
4224 | | |
4225 | | enum class FixedEnumPromotion { |
4226 | | None, |
4227 | | ToUnderlyingType, |
4228 | | ToPromotedUnderlyingType |
4229 | | }; |
4230 | | |
4231 | | /// Returns kind of fixed enum promotion the \a SCS uses. |
4232 | | static FixedEnumPromotion |
4233 | 0 | getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { |
4234 | |
|
4235 | 0 | if (SCS.Second != ICK_Integral_Promotion) |
4236 | 0 | return FixedEnumPromotion::None; |
4237 | | |
4238 | 0 | QualType FromType = SCS.getFromType(); |
4239 | 0 | if (!FromType->isEnumeralType()) |
4240 | 0 | return FixedEnumPromotion::None; |
4241 | | |
4242 | 0 | EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl(); |
4243 | 0 | if (!Enum->isFixed()) |
4244 | 0 | return FixedEnumPromotion::None; |
4245 | | |
4246 | 0 | QualType UnderlyingType = Enum->getIntegerType(); |
4247 | 0 | if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) |
4248 | 0 | return FixedEnumPromotion::ToUnderlyingType; |
4249 | | |
4250 | 0 | return FixedEnumPromotion::ToPromotedUnderlyingType; |
4251 | 0 | } |
4252 | | |
4253 | | /// CompareStandardConversionSequences - Compare two standard |
4254 | | /// conversion sequences to determine whether one is better than the |
4255 | | /// other or if they are indistinguishable (C++ 13.3.3.2p3). |
4256 | | static ImplicitConversionSequence::CompareKind |
4257 | | CompareStandardConversionSequences(Sema &S, SourceLocation Loc, |
4258 | | const StandardConversionSequence& SCS1, |
4259 | | const StandardConversionSequence& SCS2) |
4260 | 0 | { |
4261 | | // Standard conversion sequence S1 is a better conversion sequence |
4262 | | // than standard conversion sequence S2 if (C++ 13.3.3.2p3): |
4263 | | |
4264 | | // -- S1 is a proper subsequence of S2 (comparing the conversion |
4265 | | // sequences in the canonical form defined by 13.3.3.1.1, |
4266 | | // excluding any Lvalue Transformation; the identity conversion |
4267 | | // sequence is considered to be a subsequence of any |
4268 | | // non-identity conversion sequence) or, if not that, |
4269 | 0 | if (ImplicitConversionSequence::CompareKind CK |
4270 | 0 | = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) |
4271 | 0 | return CK; |
4272 | | |
4273 | | // -- the rank of S1 is better than the rank of S2 (by the rules |
4274 | | // defined below), or, if not that, |
4275 | 0 | ImplicitConversionRank Rank1 = SCS1.getRank(); |
4276 | 0 | ImplicitConversionRank Rank2 = SCS2.getRank(); |
4277 | 0 | if (Rank1 < Rank2) |
4278 | 0 | return ImplicitConversionSequence::Better; |
4279 | 0 | else if (Rank2 < Rank1) |
4280 | 0 | return ImplicitConversionSequence::Worse; |
4281 | | |
4282 | | // (C++ 13.3.3.2p4): Two conversion sequences with the same rank |
4283 | | // are indistinguishable unless one of the following rules |
4284 | | // applies: |
4285 | | |
4286 | | // A conversion that is not a conversion of a pointer, or |
4287 | | // pointer to member, to bool is better than another conversion |
4288 | | // that is such a conversion. |
4289 | 0 | if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) |
4290 | 0 | return SCS2.isPointerConversionToBool() |
4291 | 0 | ? ImplicitConversionSequence::Better |
4292 | 0 | : ImplicitConversionSequence::Worse; |
4293 | | |
4294 | | // C++14 [over.ics.rank]p4b2: |
4295 | | // This is retroactively applied to C++11 by CWG 1601. |
4296 | | // |
4297 | | // A conversion that promotes an enumeration whose underlying type is fixed |
4298 | | // to its underlying type is better than one that promotes to the promoted |
4299 | | // underlying type, if the two are different. |
4300 | 0 | FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); |
4301 | 0 | FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); |
4302 | 0 | if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && |
4303 | 0 | FEP1 != FEP2) |
4304 | 0 | return FEP1 == FixedEnumPromotion::ToUnderlyingType |
4305 | 0 | ? ImplicitConversionSequence::Better |
4306 | 0 | : ImplicitConversionSequence::Worse; |
4307 | | |
4308 | | // C++ [over.ics.rank]p4b2: |
4309 | | // |
4310 | | // If class B is derived directly or indirectly from class A, |
4311 | | // conversion of B* to A* is better than conversion of B* to |
4312 | | // void*, and conversion of A* to void* is better than conversion |
4313 | | // of B* to void*. |
4314 | 0 | bool SCS1ConvertsToVoid |
4315 | 0 | = SCS1.isPointerConversionToVoidPointer(S.Context); |
4316 | 0 | bool SCS2ConvertsToVoid |
4317 | 0 | = SCS2.isPointerConversionToVoidPointer(S.Context); |
4318 | 0 | if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { |
4319 | | // Exactly one of the conversion sequences is a conversion to |
4320 | | // a void pointer; it's the worse conversion. |
4321 | 0 | return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better |
4322 | 0 | : ImplicitConversionSequence::Worse; |
4323 | 0 | } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { |
4324 | | // Neither conversion sequence converts to a void pointer; compare |
4325 | | // their derived-to-base conversions. |
4326 | 0 | if (ImplicitConversionSequence::CompareKind DerivedCK |
4327 | 0 | = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) |
4328 | 0 | return DerivedCK; |
4329 | 0 | } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && |
4330 | 0 | !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { |
4331 | | // Both conversion sequences are conversions to void |
4332 | | // pointers. Compare the source types to determine if there's an |
4333 | | // inheritance relationship in their sources. |
4334 | 0 | QualType FromType1 = SCS1.getFromType(); |
4335 | 0 | QualType FromType2 = SCS2.getFromType(); |
4336 | | |
4337 | | // Adjust the types we're converting from via the array-to-pointer |
4338 | | // conversion, if we need to. |
4339 | 0 | if (SCS1.First == ICK_Array_To_Pointer) |
4340 | 0 | FromType1 = S.Context.getArrayDecayedType(FromType1); |
4341 | 0 | if (SCS2.First == ICK_Array_To_Pointer) |
4342 | 0 | FromType2 = S.Context.getArrayDecayedType(FromType2); |
4343 | |
|
4344 | 0 | QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); |
4345 | 0 | QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); |
4346 | |
|
4347 | 0 | if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) |
4348 | 0 | return ImplicitConversionSequence::Better; |
4349 | 0 | else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) |
4350 | 0 | return ImplicitConversionSequence::Worse; |
4351 | | |
4352 | | // Objective-C++: If one interface is more specific than the |
4353 | | // other, it is the better one. |
4354 | 0 | const ObjCObjectPointerType* FromObjCPtr1 |
4355 | 0 | = FromType1->getAs<ObjCObjectPointerType>(); |
4356 | 0 | const ObjCObjectPointerType* FromObjCPtr2 |
4357 | 0 | = FromType2->getAs<ObjCObjectPointerType>(); |
4358 | 0 | if (FromObjCPtr1 && FromObjCPtr2) { |
4359 | 0 | bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, |
4360 | 0 | FromObjCPtr2); |
4361 | 0 | bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, |
4362 | 0 | FromObjCPtr1); |
4363 | 0 | if (AssignLeft != AssignRight) { |
4364 | 0 | return AssignLeft? ImplicitConversionSequence::Better |
4365 | 0 | : ImplicitConversionSequence::Worse; |
4366 | 0 | } |
4367 | 0 | } |
4368 | 0 | } |
4369 | | |
4370 | 0 | if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { |
4371 | | // Check for a better reference binding based on the kind of bindings. |
4372 | 0 | if (isBetterReferenceBindingKind(SCS1, SCS2)) |
4373 | 0 | return ImplicitConversionSequence::Better; |
4374 | 0 | else if (isBetterReferenceBindingKind(SCS2, SCS1)) |
4375 | 0 | return ImplicitConversionSequence::Worse; |
4376 | 0 | } |
4377 | | |
4378 | | // Compare based on qualification conversions (C++ 13.3.3.2p3, |
4379 | | // bullet 3). |
4380 | 0 | if (ImplicitConversionSequence::CompareKind QualCK |
4381 | 0 | = CompareQualificationConversions(S, SCS1, SCS2)) |
4382 | 0 | return QualCK; |
4383 | | |
4384 | 0 | if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { |
4385 | | // C++ [over.ics.rank]p3b4: |
4386 | | // -- S1 and S2 are reference bindings (8.5.3), and the types to |
4387 | | // which the references refer are the same type except for |
4388 | | // top-level cv-qualifiers, and the type to which the reference |
4389 | | // initialized by S2 refers is more cv-qualified than the type |
4390 | | // to which the reference initialized by S1 refers. |
4391 | 0 | QualType T1 = SCS1.getToType(2); |
4392 | 0 | QualType T2 = SCS2.getToType(2); |
4393 | 0 | T1 = S.Context.getCanonicalType(T1); |
4394 | 0 | T2 = S.Context.getCanonicalType(T2); |
4395 | 0 | Qualifiers T1Quals, T2Quals; |
4396 | 0 | QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); |
4397 | 0 | QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); |
4398 | 0 | if (UnqualT1 == UnqualT2) { |
4399 | | // Objective-C++ ARC: If the references refer to objects with different |
4400 | | // lifetimes, prefer bindings that don't change lifetime. |
4401 | 0 | if (SCS1.ObjCLifetimeConversionBinding != |
4402 | 0 | SCS2.ObjCLifetimeConversionBinding) { |
4403 | 0 | return SCS1.ObjCLifetimeConversionBinding |
4404 | 0 | ? ImplicitConversionSequence::Worse |
4405 | 0 | : ImplicitConversionSequence::Better; |
4406 | 0 | } |
4407 | | |
4408 | | // If the type is an array type, promote the element qualifiers to the |
4409 | | // type for comparison. |
4410 | 0 | if (isa<ArrayType>(T1) && T1Quals) |
4411 | 0 | T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); |
4412 | 0 | if (isa<ArrayType>(T2) && T2Quals) |
4413 | 0 | T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); |
4414 | 0 | if (T2.isMoreQualifiedThan(T1)) |
4415 | 0 | return ImplicitConversionSequence::Better; |
4416 | 0 | if (T1.isMoreQualifiedThan(T2)) |
4417 | 0 | return ImplicitConversionSequence::Worse; |
4418 | 0 | } |
4419 | 0 | } |
4420 | | |
4421 | | // In Microsoft mode (below 19.28), prefer an integral conversion to a |
4422 | | // floating-to-integral conversion if the integral conversion |
4423 | | // is between types of the same size. |
4424 | | // For example: |
4425 | | // void f(float); |
4426 | | // void f(int); |
4427 | | // int main { |
4428 | | // long a; |
4429 | | // f(a); |
4430 | | // } |
4431 | | // Here, MSVC will call f(int) instead of generating a compile error |
4432 | | // as clang will do in standard mode. |
4433 | 0 | if (S.getLangOpts().MSVCCompat && |
4434 | 0 | !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) && |
4435 | 0 | SCS1.Second == ICK_Integral_Conversion && |
4436 | 0 | SCS2.Second == ICK_Floating_Integral && |
4437 | 0 | S.Context.getTypeSize(SCS1.getFromType()) == |
4438 | 0 | S.Context.getTypeSize(SCS1.getToType(2))) |
4439 | 0 | return ImplicitConversionSequence::Better; |
4440 | | |
4441 | | // Prefer a compatible vector conversion over a lax vector conversion |
4442 | | // For example: |
4443 | | // |
4444 | | // typedef float __v4sf __attribute__((__vector_size__(16))); |
4445 | | // void f(vector float); |
4446 | | // void f(vector signed int); |
4447 | | // int main() { |
4448 | | // __v4sf a; |
4449 | | // f(a); |
4450 | | // } |
4451 | | // Here, we'd like to choose f(vector float) and not |
4452 | | // report an ambiguous call error |
4453 | 0 | if (SCS1.Second == ICK_Vector_Conversion && |
4454 | 0 | SCS2.Second == ICK_Vector_Conversion) { |
4455 | 0 | bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( |
4456 | 0 | SCS1.getFromType(), SCS1.getToType(2)); |
4457 | 0 | bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( |
4458 | 0 | SCS2.getFromType(), SCS2.getToType(2)); |
4459 | |
|
4460 | 0 | if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) |
4461 | 0 | return SCS1IsCompatibleVectorConversion |
4462 | 0 | ? ImplicitConversionSequence::Better |
4463 | 0 | : ImplicitConversionSequence::Worse; |
4464 | 0 | } |
4465 | | |
4466 | 0 | if (SCS1.Second == ICK_SVE_Vector_Conversion && |
4467 | 0 | SCS2.Second == ICK_SVE_Vector_Conversion) { |
4468 | 0 | bool SCS1IsCompatibleSVEVectorConversion = |
4469 | 0 | S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2)); |
4470 | 0 | bool SCS2IsCompatibleSVEVectorConversion = |
4471 | 0 | S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2)); |
4472 | |
|
4473 | 0 | if (SCS1IsCompatibleSVEVectorConversion != |
4474 | 0 | SCS2IsCompatibleSVEVectorConversion) |
4475 | 0 | return SCS1IsCompatibleSVEVectorConversion |
4476 | 0 | ? ImplicitConversionSequence::Better |
4477 | 0 | : ImplicitConversionSequence::Worse; |
4478 | 0 | } |
4479 | | |
4480 | 0 | if (SCS1.Second == ICK_RVV_Vector_Conversion && |
4481 | 0 | SCS2.Second == ICK_RVV_Vector_Conversion) { |
4482 | 0 | bool SCS1IsCompatibleRVVVectorConversion = |
4483 | 0 | S.Context.areCompatibleRVVTypes(SCS1.getFromType(), SCS1.getToType(2)); |
4484 | 0 | bool SCS2IsCompatibleRVVVectorConversion = |
4485 | 0 | S.Context.areCompatibleRVVTypes(SCS2.getFromType(), SCS2.getToType(2)); |
4486 | |
|
4487 | 0 | if (SCS1IsCompatibleRVVVectorConversion != |
4488 | 0 | SCS2IsCompatibleRVVVectorConversion) |
4489 | 0 | return SCS1IsCompatibleRVVVectorConversion |
4490 | 0 | ? ImplicitConversionSequence::Better |
4491 | 0 | : ImplicitConversionSequence::Worse; |
4492 | 0 | } |
4493 | | |
4494 | 0 | return ImplicitConversionSequence::Indistinguishable; |
4495 | 0 | } |
4496 | | |
4497 | | /// CompareQualificationConversions - Compares two standard conversion |
4498 | | /// sequences to determine whether they can be ranked based on their |
4499 | | /// qualification conversions (C++ 13.3.3.2p3 bullet 3). |
4500 | | static ImplicitConversionSequence::CompareKind |
4501 | | CompareQualificationConversions(Sema &S, |
4502 | | const StandardConversionSequence& SCS1, |
4503 | 0 | const StandardConversionSequence& SCS2) { |
4504 | | // C++ [over.ics.rank]p3: |
4505 | | // -- S1 and S2 differ only in their qualification conversion and |
4506 | | // yield similar types T1 and T2 (C++ 4.4), respectively, [...] |
4507 | | // [C++98] |
4508 | | // [...] and the cv-qualification signature of type T1 is a proper subset |
4509 | | // of the cv-qualification signature of type T2, and S1 is not the |
4510 | | // deprecated string literal array-to-pointer conversion (4.2). |
4511 | | // [C++2a] |
4512 | | // [...] where T1 can be converted to T2 by a qualification conversion. |
4513 | 0 | if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || |
4514 | 0 | SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) |
4515 | 0 | return ImplicitConversionSequence::Indistinguishable; |
4516 | | |
4517 | | // FIXME: the example in the standard doesn't use a qualification |
4518 | | // conversion (!) |
4519 | 0 | QualType T1 = SCS1.getToType(2); |
4520 | 0 | QualType T2 = SCS2.getToType(2); |
4521 | 0 | T1 = S.Context.getCanonicalType(T1); |
4522 | 0 | T2 = S.Context.getCanonicalType(T2); |
4523 | 0 | assert(!T1->isReferenceType() && !T2->isReferenceType()); |
4524 | 0 | Qualifiers T1Quals, T2Quals; |
4525 | 0 | QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); |
4526 | 0 | QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); |
4527 | | |
4528 | | // If the types are the same, we won't learn anything by unwrapping |
4529 | | // them. |
4530 | 0 | if (UnqualT1 == UnqualT2) |
4531 | 0 | return ImplicitConversionSequence::Indistinguishable; |
4532 | | |
4533 | | // Don't ever prefer a standard conversion sequence that uses the deprecated |
4534 | | // string literal array to pointer conversion. |
4535 | 0 | bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr; |
4536 | 0 | bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr; |
4537 | | |
4538 | | // Objective-C++ ARC: |
4539 | | // Prefer qualification conversions not involving a change in lifetime |
4540 | | // to qualification conversions that do change lifetime. |
4541 | 0 | if (SCS1.QualificationIncludesObjCLifetime && |
4542 | 0 | !SCS2.QualificationIncludesObjCLifetime) |
4543 | 0 | CanPick1 = false; |
4544 | 0 | if (SCS2.QualificationIncludesObjCLifetime && |
4545 | 0 | !SCS1.QualificationIncludesObjCLifetime) |
4546 | 0 | CanPick2 = false; |
4547 | |
|
4548 | 0 | bool ObjCLifetimeConversion; |
4549 | 0 | if (CanPick1 && |
4550 | 0 | !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion)) |
4551 | 0 | CanPick1 = false; |
4552 | | // FIXME: In Objective-C ARC, we can have qualification conversions in both |
4553 | | // directions, so we can't short-cut this second check in general. |
4554 | 0 | if (CanPick2 && |
4555 | 0 | !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion)) |
4556 | 0 | CanPick2 = false; |
4557 | |
|
4558 | 0 | if (CanPick1 != CanPick2) |
4559 | 0 | return CanPick1 ? ImplicitConversionSequence::Better |
4560 | 0 | : ImplicitConversionSequence::Worse; |
4561 | 0 | return ImplicitConversionSequence::Indistinguishable; |
4562 | 0 | } |
4563 | | |
4564 | | /// CompareDerivedToBaseConversions - Compares two standard conversion |
4565 | | /// sequences to determine whether they can be ranked based on their |
4566 | | /// various kinds of derived-to-base conversions (C++ |
4567 | | /// [over.ics.rank]p4b3). As part of these checks, we also look at |
4568 | | /// conversions between Objective-C interface types. |
4569 | | static ImplicitConversionSequence::CompareKind |
4570 | | CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, |
4571 | | const StandardConversionSequence& SCS1, |
4572 | 0 | const StandardConversionSequence& SCS2) { |
4573 | 0 | QualType FromType1 = SCS1.getFromType(); |
4574 | 0 | QualType ToType1 = SCS1.getToType(1); |
4575 | 0 | QualType FromType2 = SCS2.getFromType(); |
4576 | 0 | QualType ToType2 = SCS2.getToType(1); |
4577 | | |
4578 | | // Adjust the types we're converting from via the array-to-pointer |
4579 | | // conversion, if we need to. |
4580 | 0 | if (SCS1.First == ICK_Array_To_Pointer) |
4581 | 0 | FromType1 = S.Context.getArrayDecayedType(FromType1); |
4582 | 0 | if (SCS2.First == ICK_Array_To_Pointer) |
4583 | 0 | FromType2 = S.Context.getArrayDecayedType(FromType2); |
4584 | | |
4585 | | // Canonicalize all of the types. |
4586 | 0 | FromType1 = S.Context.getCanonicalType(FromType1); |
4587 | 0 | ToType1 = S.Context.getCanonicalType(ToType1); |
4588 | 0 | FromType2 = S.Context.getCanonicalType(FromType2); |
4589 | 0 | ToType2 = S.Context.getCanonicalType(ToType2); |
4590 | | |
4591 | | // C++ [over.ics.rank]p4b3: |
4592 | | // |
4593 | | // If class B is derived directly or indirectly from class A and |
4594 | | // class C is derived directly or indirectly from B, |
4595 | | // |
4596 | | // Compare based on pointer conversions. |
4597 | 0 | if (SCS1.Second == ICK_Pointer_Conversion && |
4598 | 0 | SCS2.Second == ICK_Pointer_Conversion && |
4599 | | /*FIXME: Remove if Objective-C id conversions get their own rank*/ |
4600 | 0 | FromType1->isPointerType() && FromType2->isPointerType() && |
4601 | 0 | ToType1->isPointerType() && ToType2->isPointerType()) { |
4602 | 0 | QualType FromPointee1 = |
4603 | 0 | FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); |
4604 | 0 | QualType ToPointee1 = |
4605 | 0 | ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); |
4606 | 0 | QualType FromPointee2 = |
4607 | 0 | FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); |
4608 | 0 | QualType ToPointee2 = |
4609 | 0 | ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); |
4610 | | |
4611 | | // -- conversion of C* to B* is better than conversion of C* to A*, |
4612 | 0 | if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { |
4613 | 0 | if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) |
4614 | 0 | return ImplicitConversionSequence::Better; |
4615 | 0 | else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) |
4616 | 0 | return ImplicitConversionSequence::Worse; |
4617 | 0 | } |
4618 | | |
4619 | | // -- conversion of B* to A* is better than conversion of C* to A*, |
4620 | 0 | if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { |
4621 | 0 | if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) |
4622 | 0 | return ImplicitConversionSequence::Better; |
4623 | 0 | else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) |
4624 | 0 | return ImplicitConversionSequence::Worse; |
4625 | 0 | } |
4626 | 0 | } else if (SCS1.Second == ICK_Pointer_Conversion && |
4627 | 0 | SCS2.Second == ICK_Pointer_Conversion) { |
4628 | 0 | const ObjCObjectPointerType *FromPtr1 |
4629 | 0 | = FromType1->getAs<ObjCObjectPointerType>(); |
4630 | 0 | const ObjCObjectPointerType *FromPtr2 |
4631 | 0 | = FromType2->getAs<ObjCObjectPointerType>(); |
4632 | 0 | const ObjCObjectPointerType *ToPtr1 |
4633 | 0 | = ToType1->getAs<ObjCObjectPointerType>(); |
4634 | 0 | const ObjCObjectPointerType *ToPtr2 |
4635 | 0 | = ToType2->getAs<ObjCObjectPointerType>(); |
4636 | |
|
4637 | 0 | if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { |
4638 | | // Apply the same conversion ranking rules for Objective-C pointer types |
4639 | | // that we do for C++ pointers to class types. However, we employ the |
4640 | | // Objective-C pseudo-subtyping relationship used for assignment of |
4641 | | // Objective-C pointer types. |
4642 | 0 | bool FromAssignLeft |
4643 | 0 | = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); |
4644 | 0 | bool FromAssignRight |
4645 | 0 | = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); |
4646 | 0 | bool ToAssignLeft |
4647 | 0 | = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); |
4648 | 0 | bool ToAssignRight |
4649 | 0 | = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); |
4650 | | |
4651 | | // A conversion to an a non-id object pointer type or qualified 'id' |
4652 | | // type is better than a conversion to 'id'. |
4653 | 0 | if (ToPtr1->isObjCIdType() && |
4654 | 0 | (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) |
4655 | 0 | return ImplicitConversionSequence::Worse; |
4656 | 0 | if (ToPtr2->isObjCIdType() && |
4657 | 0 | (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) |
4658 | 0 | return ImplicitConversionSequence::Better; |
4659 | | |
4660 | | // A conversion to a non-id object pointer type is better than a |
4661 | | // conversion to a qualified 'id' type |
4662 | 0 | if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) |
4663 | 0 | return ImplicitConversionSequence::Worse; |
4664 | 0 | if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) |
4665 | 0 | return ImplicitConversionSequence::Better; |
4666 | | |
4667 | | // A conversion to an a non-Class object pointer type or qualified 'Class' |
4668 | | // type is better than a conversion to 'Class'. |
4669 | 0 | if (ToPtr1->isObjCClassType() && |
4670 | 0 | (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) |
4671 | 0 | return ImplicitConversionSequence::Worse; |
4672 | 0 | if (ToPtr2->isObjCClassType() && |
4673 | 0 | (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) |
4674 | 0 | return ImplicitConversionSequence::Better; |
4675 | | |
4676 | | // A conversion to a non-Class object pointer type is better than a |
4677 | | // conversion to a qualified 'Class' type. |
4678 | 0 | if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) |
4679 | 0 | return ImplicitConversionSequence::Worse; |
4680 | 0 | if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) |
4681 | 0 | return ImplicitConversionSequence::Better; |
4682 | | |
4683 | | // -- "conversion of C* to B* is better than conversion of C* to A*," |
4684 | 0 | if (S.Context.hasSameType(FromType1, FromType2) && |
4685 | 0 | !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && |
4686 | 0 | (ToAssignLeft != ToAssignRight)) { |
4687 | 0 | if (FromPtr1->isSpecialized()) { |
4688 | | // "conversion of B<A> * to B * is better than conversion of B * to |
4689 | | // C *. |
4690 | 0 | bool IsFirstSame = |
4691 | 0 | FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); |
4692 | 0 | bool IsSecondSame = |
4693 | 0 | FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); |
4694 | 0 | if (IsFirstSame) { |
4695 | 0 | if (!IsSecondSame) |
4696 | 0 | return ImplicitConversionSequence::Better; |
4697 | 0 | } else if (IsSecondSame) |
4698 | 0 | return ImplicitConversionSequence::Worse; |
4699 | 0 | } |
4700 | 0 | return ToAssignLeft? ImplicitConversionSequence::Worse |
4701 | 0 | : ImplicitConversionSequence::Better; |
4702 | 0 | } |
4703 | | |
4704 | | // -- "conversion of B* to A* is better than conversion of C* to A*," |
4705 | 0 | if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && |
4706 | 0 | (FromAssignLeft != FromAssignRight)) |
4707 | 0 | return FromAssignLeft? ImplicitConversionSequence::Better |
4708 | 0 | : ImplicitConversionSequence::Worse; |
4709 | 0 | } |
4710 | 0 | } |
4711 | | |
4712 | | // Ranking of member-pointer types. |
4713 | 0 | if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && |
4714 | 0 | FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && |
4715 | 0 | ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { |
4716 | 0 | const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>(); |
4717 | 0 | const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>(); |
4718 | 0 | const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>(); |
4719 | 0 | const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>(); |
4720 | 0 | const Type *FromPointeeType1 = FromMemPointer1->getClass(); |
4721 | 0 | const Type *ToPointeeType1 = ToMemPointer1->getClass(); |
4722 | 0 | const Type *FromPointeeType2 = FromMemPointer2->getClass(); |
4723 | 0 | const Type *ToPointeeType2 = ToMemPointer2->getClass(); |
4724 | 0 | QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); |
4725 | 0 | QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); |
4726 | 0 | QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); |
4727 | 0 | QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); |
4728 | | // conversion of A::* to B::* is better than conversion of A::* to C::*, |
4729 | 0 | if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { |
4730 | 0 | if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) |
4731 | 0 | return ImplicitConversionSequence::Worse; |
4732 | 0 | else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) |
4733 | 0 | return ImplicitConversionSequence::Better; |
4734 | 0 | } |
4735 | | // conversion of B::* to C::* is better than conversion of A::* to C::* |
4736 | 0 | if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { |
4737 | 0 | if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) |
4738 | 0 | return ImplicitConversionSequence::Better; |
4739 | 0 | else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) |
4740 | 0 | return ImplicitConversionSequence::Worse; |
4741 | 0 | } |
4742 | 0 | } |
4743 | | |
4744 | 0 | if (SCS1.Second == ICK_Derived_To_Base) { |
4745 | | // -- conversion of C to B is better than conversion of C to A, |
4746 | | // -- binding of an expression of type C to a reference of type |
4747 | | // B& is better than binding an expression of type C to a |
4748 | | // reference of type A&, |
4749 | 0 | if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && |
4750 | 0 | !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { |
4751 | 0 | if (S.IsDerivedFrom(Loc, ToType1, ToType2)) |
4752 | 0 | return ImplicitConversionSequence::Better; |
4753 | 0 | else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) |
4754 | 0 | return ImplicitConversionSequence::Worse; |
4755 | 0 | } |
4756 | | |
4757 | | // -- conversion of B to A is better than conversion of C to A. |
4758 | | // -- binding of an expression of type B to a reference of type |
4759 | | // A& is better than binding an expression of type C to a |
4760 | | // reference of type A&, |
4761 | 0 | if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && |
4762 | 0 | S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { |
4763 | 0 | if (S.IsDerivedFrom(Loc, FromType2, FromType1)) |
4764 | 0 | return ImplicitConversionSequence::Better; |
4765 | 0 | else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) |
4766 | 0 | return ImplicitConversionSequence::Worse; |
4767 | 0 | } |
4768 | 0 | } |
4769 | | |
4770 | 0 | return ImplicitConversionSequence::Indistinguishable; |
4771 | 0 | } |
4772 | | |
4773 | 0 | static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { |
4774 | 0 | if (!T.getQualifiers().hasUnaligned()) |
4775 | 0 | return T; |
4776 | | |
4777 | 0 | Qualifiers Q; |
4778 | 0 | T = Ctx.getUnqualifiedArrayType(T, Q); |
4779 | 0 | Q.removeUnaligned(); |
4780 | 0 | return Ctx.getQualifiedType(T, Q); |
4781 | 0 | } |
4782 | | |
4783 | | /// CompareReferenceRelationship - Compare the two types T1 and T2 to |
4784 | | /// determine whether they are reference-compatible, |
4785 | | /// reference-related, or incompatible, for use in C++ initialization by |
4786 | | /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference |
4787 | | /// type, and the first type (T1) is the pointee type of the reference |
4788 | | /// type being initialized. |
4789 | | Sema::ReferenceCompareResult |
4790 | | Sema::CompareReferenceRelationship(SourceLocation Loc, |
4791 | | QualType OrigT1, QualType OrigT2, |
4792 | 0 | ReferenceConversions *ConvOut) { |
4793 | 0 | assert(!OrigT1->isReferenceType() && |
4794 | 0 | "T1 must be the pointee type of the reference type"); |
4795 | 0 | assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); |
4796 | | |
4797 | 0 | QualType T1 = Context.getCanonicalType(OrigT1); |
4798 | 0 | QualType T2 = Context.getCanonicalType(OrigT2); |
4799 | 0 | Qualifiers T1Quals, T2Quals; |
4800 | 0 | QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); |
4801 | 0 | QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); |
4802 | |
|
4803 | 0 | ReferenceConversions ConvTmp; |
4804 | 0 | ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; |
4805 | 0 | Conv = ReferenceConversions(); |
4806 | | |
4807 | | // C++2a [dcl.init.ref]p4: |
4808 | | // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is |
4809 | | // reference-related to "cv2 T2" if T1 is similar to T2, or |
4810 | | // T1 is a base class of T2. |
4811 | | // "cv1 T1" is reference-compatible with "cv2 T2" if |
4812 | | // a prvalue of type "pointer to cv2 T2" can be converted to the type |
4813 | | // "pointer to cv1 T1" via a standard conversion sequence. |
4814 | | |
4815 | | // Check for standard conversions we can apply to pointers: derived-to-base |
4816 | | // conversions, ObjC pointer conversions, and function pointer conversions. |
4817 | | // (Qualification conversions are checked last.) |
4818 | 0 | QualType ConvertedT2; |
4819 | 0 | if (UnqualT1 == UnqualT2) { |
4820 | | // Nothing to do. |
4821 | 0 | } else if (isCompleteType(Loc, OrigT2) && |
4822 | 0 | IsDerivedFrom(Loc, UnqualT2, UnqualT1)) |
4823 | 0 | Conv |= ReferenceConversions::DerivedToBase; |
4824 | 0 | else if (UnqualT1->isObjCObjectOrInterfaceType() && |
4825 | 0 | UnqualT2->isObjCObjectOrInterfaceType() && |
4826 | 0 | Context.canBindObjCObjectType(UnqualT1, UnqualT2)) |
4827 | 0 | Conv |= ReferenceConversions::ObjC; |
4828 | 0 | else if (UnqualT2->isFunctionType() && |
4829 | 0 | IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { |
4830 | 0 | Conv |= ReferenceConversions::Function; |
4831 | | // No need to check qualifiers; function types don't have them. |
4832 | 0 | return Ref_Compatible; |
4833 | 0 | } |
4834 | 0 | bool ConvertedReferent = Conv != 0; |
4835 | | |
4836 | | // We can have a qualification conversion. Compute whether the types are |
4837 | | // similar at the same time. |
4838 | 0 | bool PreviousToQualsIncludeConst = true; |
4839 | 0 | bool TopLevel = true; |
4840 | 0 | do { |
4841 | 0 | if (T1 == T2) |
4842 | 0 | break; |
4843 | | |
4844 | | // We will need a qualification conversion. |
4845 | 0 | Conv |= ReferenceConversions::Qualification; |
4846 | | |
4847 | | // Track whether we performed a qualification conversion anywhere other |
4848 | | // than the top level. This matters for ranking reference bindings in |
4849 | | // overload resolution. |
4850 | 0 | if (!TopLevel) |
4851 | 0 | Conv |= ReferenceConversions::NestedQualification; |
4852 | | |
4853 | | // MS compiler ignores __unaligned qualifier for references; do the same. |
4854 | 0 | T1 = withoutUnaligned(Context, T1); |
4855 | 0 | T2 = withoutUnaligned(Context, T2); |
4856 | | |
4857 | | // If we find a qualifier mismatch, the types are not reference-compatible, |
4858 | | // but are still be reference-related if they're similar. |
4859 | 0 | bool ObjCLifetimeConversion = false; |
4860 | 0 | if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel, |
4861 | 0 | PreviousToQualsIncludeConst, |
4862 | 0 | ObjCLifetimeConversion)) |
4863 | 0 | return (ConvertedReferent || Context.hasSimilarType(T1, T2)) |
4864 | 0 | ? Ref_Related |
4865 | 0 | : Ref_Incompatible; |
4866 | | |
4867 | | // FIXME: Should we track this for any level other than the first? |
4868 | 0 | if (ObjCLifetimeConversion) |
4869 | 0 | Conv |= ReferenceConversions::ObjCLifetime; |
4870 | |
|
4871 | 0 | TopLevel = false; |
4872 | 0 | } while (Context.UnwrapSimilarTypes(T1, T2)); |
4873 | | |
4874 | | // At this point, if the types are reference-related, we must either have the |
4875 | | // same inner type (ignoring qualifiers), or must have already worked out how |
4876 | | // to convert the referent. |
4877 | 0 | return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) |
4878 | 0 | ? Ref_Compatible |
4879 | 0 | : Ref_Incompatible; |
4880 | 0 | } |
4881 | | |
4882 | | /// Look for a user-defined conversion to a value reference-compatible |
4883 | | /// with DeclType. Return true if something definite is found. |
4884 | | static bool |
4885 | | FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, |
4886 | | QualType DeclType, SourceLocation DeclLoc, |
4887 | | Expr *Init, QualType T2, bool AllowRvalues, |
4888 | 0 | bool AllowExplicit) { |
4889 | 0 | assert(T2->isRecordType() && "Can only find conversions of record types."); |
4890 | 0 | auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); |
4891 | |
|
4892 | 0 | OverloadCandidateSet CandidateSet( |
4893 | 0 | DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); |
4894 | 0 | const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); |
4895 | 0 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { |
4896 | 0 | NamedDecl *D = *I; |
4897 | 0 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); |
4898 | 0 | if (isa<UsingShadowDecl>(D)) |
4899 | 0 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); |
4900 | |
|
4901 | 0 | FunctionTemplateDecl *ConvTemplate |
4902 | 0 | = dyn_cast<FunctionTemplateDecl>(D); |
4903 | 0 | CXXConversionDecl *Conv; |
4904 | 0 | if (ConvTemplate) |
4905 | 0 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); |
4906 | 0 | else |
4907 | 0 | Conv = cast<CXXConversionDecl>(D); |
4908 | |
|
4909 | 0 | if (AllowRvalues) { |
4910 | | // If we are initializing an rvalue reference, don't permit conversion |
4911 | | // functions that return lvalues. |
4912 | 0 | if (!ConvTemplate && DeclType->isRValueReferenceType()) { |
4913 | 0 | const ReferenceType *RefType |
4914 | 0 | = Conv->getConversionType()->getAs<LValueReferenceType>(); |
4915 | 0 | if (RefType && !RefType->getPointeeType()->isFunctionType()) |
4916 | 0 | continue; |
4917 | 0 | } |
4918 | | |
4919 | 0 | if (!ConvTemplate && |
4920 | 0 | S.CompareReferenceRelationship( |
4921 | 0 | DeclLoc, |
4922 | 0 | Conv->getConversionType() |
4923 | 0 | .getNonReferenceType() |
4924 | 0 | .getUnqualifiedType(), |
4925 | 0 | DeclType.getNonReferenceType().getUnqualifiedType()) == |
4926 | 0 | Sema::Ref_Incompatible) |
4927 | 0 | continue; |
4928 | 0 | } else { |
4929 | | // If the conversion function doesn't return a reference type, |
4930 | | // it can't be considered for this conversion. An rvalue reference |
4931 | | // is only acceptable if its referencee is a function type. |
4932 | |
|
4933 | 0 | const ReferenceType *RefType = |
4934 | 0 | Conv->getConversionType()->getAs<ReferenceType>(); |
4935 | 0 | if (!RefType || |
4936 | 0 | (!RefType->isLValueReferenceType() && |
4937 | 0 | !RefType->getPointeeType()->isFunctionType())) |
4938 | 0 | continue; |
4939 | 0 | } |
4940 | | |
4941 | 0 | if (ConvTemplate) |
4942 | 0 | S.AddTemplateConversionCandidate( |
4943 | 0 | ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, |
4944 | 0 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); |
4945 | 0 | else |
4946 | 0 | S.AddConversionCandidate( |
4947 | 0 | Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, |
4948 | 0 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); |
4949 | 0 | } |
4950 | |
|
4951 | 0 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
4952 | |
|
4953 | 0 | OverloadCandidateSet::iterator Best; |
4954 | 0 | switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { |
4955 | 0 | case OR_Success: |
4956 | | // C++ [over.ics.ref]p1: |
4957 | | // |
4958 | | // [...] If the parameter binds directly to the result of |
4959 | | // applying a conversion function to the argument |
4960 | | // expression, the implicit conversion sequence is a |
4961 | | // user-defined conversion sequence (13.3.3.1.2), with the |
4962 | | // second standard conversion sequence either an identity |
4963 | | // conversion or, if the conversion function returns an |
4964 | | // entity of a type that is a derived class of the parameter |
4965 | | // type, a derived-to-base Conversion. |
4966 | 0 | if (!Best->FinalConversion.DirectBinding) |
4967 | 0 | return false; |
4968 | | |
4969 | 0 | ICS.setUserDefined(); |
4970 | 0 | ICS.UserDefined.Before = Best->Conversions[0].Standard; |
4971 | 0 | ICS.UserDefined.After = Best->FinalConversion; |
4972 | 0 | ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; |
4973 | 0 | ICS.UserDefined.ConversionFunction = Best->Function; |
4974 | 0 | ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; |
4975 | 0 | ICS.UserDefined.EllipsisConversion = false; |
4976 | 0 | assert(ICS.UserDefined.After.ReferenceBinding && |
4977 | 0 | ICS.UserDefined.After.DirectBinding && |
4978 | 0 | "Expected a direct reference binding!"); |
4979 | 0 | return true; |
4980 | | |
4981 | 0 | case OR_Ambiguous: |
4982 | 0 | ICS.setAmbiguous(); |
4983 | 0 | for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); |
4984 | 0 | Cand != CandidateSet.end(); ++Cand) |
4985 | 0 | if (Cand->Best) |
4986 | 0 | ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); |
4987 | 0 | return true; |
4988 | | |
4989 | 0 | case OR_No_Viable_Function: |
4990 | 0 | case OR_Deleted: |
4991 | | // There was no suitable conversion, or we found a deleted |
4992 | | // conversion; continue with other checks. |
4993 | 0 | return false; |
4994 | 0 | } |
4995 | | |
4996 | 0 | llvm_unreachable("Invalid OverloadResult!"); |
4997 | 0 | } |
4998 | | |
4999 | | /// Compute an implicit conversion sequence for reference |
5000 | | /// initialization. |
5001 | | static ImplicitConversionSequence |
5002 | | TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, |
5003 | | SourceLocation DeclLoc, |
5004 | | bool SuppressUserConversions, |
5005 | 0 | bool AllowExplicit) { |
5006 | 0 | assert(DeclType->isReferenceType() && "Reference init needs a reference"); |
5007 | | |
5008 | | // Most paths end in a failed conversion. |
5009 | 0 | ImplicitConversionSequence ICS; |
5010 | 0 | ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); |
5011 | |
|
5012 | 0 | QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); |
5013 | 0 | QualType T2 = Init->getType(); |
5014 | | |
5015 | | // If the initializer is the address of an overloaded function, try |
5016 | | // to resolve the overloaded function. If all goes well, T2 is the |
5017 | | // type of the resulting function. |
5018 | 0 | if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { |
5019 | 0 | DeclAccessPair Found; |
5020 | 0 | if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, |
5021 | 0 | false, Found)) |
5022 | 0 | T2 = Fn->getType(); |
5023 | 0 | } |
5024 | | |
5025 | | // Compute some basic properties of the types and the initializer. |
5026 | 0 | bool isRValRef = DeclType->isRValueReferenceType(); |
5027 | 0 | Expr::Classification InitCategory = Init->Classify(S.Context); |
5028 | |
|
5029 | 0 | Sema::ReferenceConversions RefConv; |
5030 | 0 | Sema::ReferenceCompareResult RefRelationship = |
5031 | 0 | S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); |
5032 | |
|
5033 | 0 | auto SetAsReferenceBinding = [&](bool BindsDirectly) { |
5034 | 0 | ICS.setStandard(); |
5035 | 0 | ICS.Standard.First = ICK_Identity; |
5036 | | // FIXME: A reference binding can be a function conversion too. We should |
5037 | | // consider that when ordering reference-to-function bindings. |
5038 | 0 | ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) |
5039 | 0 | ? ICK_Derived_To_Base |
5040 | 0 | : (RefConv & Sema::ReferenceConversions::ObjC) |
5041 | 0 | ? ICK_Compatible_Conversion |
5042 | 0 | : ICK_Identity; |
5043 | | // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank |
5044 | | // a reference binding that performs a non-top-level qualification |
5045 | | // conversion as a qualification conversion, not as an identity conversion. |
5046 | 0 | ICS.Standard.Third = (RefConv & |
5047 | 0 | Sema::ReferenceConversions::NestedQualification) |
5048 | 0 | ? ICK_Qualification |
5049 | 0 | : ICK_Identity; |
5050 | 0 | ICS.Standard.setFromType(T2); |
5051 | 0 | ICS.Standard.setToType(0, T2); |
5052 | 0 | ICS.Standard.setToType(1, T1); |
5053 | 0 | ICS.Standard.setToType(2, T1); |
5054 | 0 | ICS.Standard.ReferenceBinding = true; |
5055 | 0 | ICS.Standard.DirectBinding = BindsDirectly; |
5056 | 0 | ICS.Standard.IsLvalueReference = !isRValRef; |
5057 | 0 | ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); |
5058 | 0 | ICS.Standard.BindsToRvalue = InitCategory.isRValue(); |
5059 | 0 | ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; |
5060 | 0 | ICS.Standard.ObjCLifetimeConversionBinding = |
5061 | 0 | (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; |
5062 | 0 | ICS.Standard.CopyConstructor = nullptr; |
5063 | 0 | ICS.Standard.DeprecatedStringLiteralToCharPtr = false; |
5064 | 0 | }; |
5065 | | |
5066 | | // C++0x [dcl.init.ref]p5: |
5067 | | // A reference to type "cv1 T1" is initialized by an expression |
5068 | | // of type "cv2 T2" as follows: |
5069 | | |
5070 | | // -- If reference is an lvalue reference and the initializer expression |
5071 | 0 | if (!isRValRef) { |
5072 | | // -- is an lvalue (but is not a bit-field), and "cv1 T1" is |
5073 | | // reference-compatible with "cv2 T2," or |
5074 | | // |
5075 | | // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. |
5076 | 0 | if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { |
5077 | | // C++ [over.ics.ref]p1: |
5078 | | // When a parameter of reference type binds directly (8.5.3) |
5079 | | // to an argument expression, the implicit conversion sequence |
5080 | | // is the identity conversion, unless the argument expression |
5081 | | // has a type that is a derived class of the parameter type, |
5082 | | // in which case the implicit conversion sequence is a |
5083 | | // derived-to-base Conversion (13.3.3.1). |
5084 | 0 | SetAsReferenceBinding(/*BindsDirectly=*/true); |
5085 | | |
5086 | | // Nothing more to do: the inaccessibility/ambiguity check for |
5087 | | // derived-to-base conversions is suppressed when we're |
5088 | | // computing the implicit conversion sequence (C++ |
5089 | | // [over.best.ics]p2). |
5090 | 0 | return ICS; |
5091 | 0 | } |
5092 | | |
5093 | | // -- has a class type (i.e., T2 is a class type), where T1 is |
5094 | | // not reference-related to T2, and can be implicitly |
5095 | | // converted to an lvalue of type "cv3 T3," where "cv1 T1" |
5096 | | // is reference-compatible with "cv3 T3" 92) (this |
5097 | | // conversion is selected by enumerating the applicable |
5098 | | // conversion functions (13.3.1.6) and choosing the best |
5099 | | // one through overload resolution (13.3)), |
5100 | 0 | if (!SuppressUserConversions && T2->isRecordType() && |
5101 | 0 | S.isCompleteType(DeclLoc, T2) && |
5102 | 0 | RefRelationship == Sema::Ref_Incompatible) { |
5103 | 0 | if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, |
5104 | 0 | Init, T2, /*AllowRvalues=*/false, |
5105 | 0 | AllowExplicit)) |
5106 | 0 | return ICS; |
5107 | 0 | } |
5108 | 0 | } |
5109 | | |
5110 | | // -- Otherwise, the reference shall be an lvalue reference to a |
5111 | | // non-volatile const type (i.e., cv1 shall be const), or the reference |
5112 | | // shall be an rvalue reference. |
5113 | 0 | if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) { |
5114 | 0 | if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible) |
5115 | 0 | ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); |
5116 | 0 | return ICS; |
5117 | 0 | } |
5118 | | |
5119 | | // -- If the initializer expression |
5120 | | // |
5121 | | // -- is an xvalue, class prvalue, array prvalue or function |
5122 | | // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or |
5123 | 0 | if (RefRelationship == Sema::Ref_Compatible && |
5124 | 0 | (InitCategory.isXValue() || |
5125 | 0 | (InitCategory.isPRValue() && |
5126 | 0 | (T2->isRecordType() || T2->isArrayType())) || |
5127 | 0 | (InitCategory.isLValue() && T2->isFunctionType()))) { |
5128 | | // In C++11, this is always a direct binding. In C++98/03, it's a direct |
5129 | | // binding unless we're binding to a class prvalue. |
5130 | | // Note: Although xvalues wouldn't normally show up in C++98/03 code, we |
5131 | | // allow the use of rvalue references in C++98/03 for the benefit of |
5132 | | // standard library implementors; therefore, we need the xvalue check here. |
5133 | 0 | SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || |
5134 | 0 | !(InitCategory.isPRValue() || T2->isRecordType())); |
5135 | 0 | return ICS; |
5136 | 0 | } |
5137 | | |
5138 | | // -- has a class type (i.e., T2 is a class type), where T1 is not |
5139 | | // reference-related to T2, and can be implicitly converted to |
5140 | | // an xvalue, class prvalue, or function lvalue of type |
5141 | | // "cv3 T3", where "cv1 T1" is reference-compatible with |
5142 | | // "cv3 T3", |
5143 | | // |
5144 | | // then the reference is bound to the value of the initializer |
5145 | | // expression in the first case and to the result of the conversion |
5146 | | // in the second case (or, in either case, to an appropriate base |
5147 | | // class subobject). |
5148 | 0 | if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && |
5149 | 0 | T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && |
5150 | 0 | FindConversionForRefInit(S, ICS, DeclType, DeclLoc, |
5151 | 0 | Init, T2, /*AllowRvalues=*/true, |
5152 | 0 | AllowExplicit)) { |
5153 | | // In the second case, if the reference is an rvalue reference |
5154 | | // and the second standard conversion sequence of the |
5155 | | // user-defined conversion sequence includes an lvalue-to-rvalue |
5156 | | // conversion, the program is ill-formed. |
5157 | 0 | if (ICS.isUserDefined() && isRValRef && |
5158 | 0 | ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) |
5159 | 0 | ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); |
5160 | |
|
5161 | 0 | return ICS; |
5162 | 0 | } |
5163 | | |
5164 | | // A temporary of function type cannot be created; don't even try. |
5165 | 0 | if (T1->isFunctionType()) |
5166 | 0 | return ICS; |
5167 | | |
5168 | | // -- Otherwise, a temporary of type "cv1 T1" is created and |
5169 | | // initialized from the initializer expression using the |
5170 | | // rules for a non-reference copy initialization (8.5). The |
5171 | | // reference is then bound to the temporary. If T1 is |
5172 | | // reference-related to T2, cv1 must be the same |
5173 | | // cv-qualification as, or greater cv-qualification than, |
5174 | | // cv2; otherwise, the program is ill-formed. |
5175 | 0 | if (RefRelationship == Sema::Ref_Related) { |
5176 | | // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then |
5177 | | // we would be reference-compatible or reference-compatible with |
5178 | | // added qualification. But that wasn't the case, so the reference |
5179 | | // initialization fails. |
5180 | | // |
5181 | | // Note that we only want to check address spaces and cvr-qualifiers here. |
5182 | | // ObjC GC, lifetime and unaligned qualifiers aren't important. |
5183 | 0 | Qualifiers T1Quals = T1.getQualifiers(); |
5184 | 0 | Qualifiers T2Quals = T2.getQualifiers(); |
5185 | 0 | T1Quals.removeObjCGCAttr(); |
5186 | 0 | T1Quals.removeObjCLifetime(); |
5187 | 0 | T2Quals.removeObjCGCAttr(); |
5188 | 0 | T2Quals.removeObjCLifetime(); |
5189 | | // MS compiler ignores __unaligned qualifier for references; do the same. |
5190 | 0 | T1Quals.removeUnaligned(); |
5191 | 0 | T2Quals.removeUnaligned(); |
5192 | 0 | if (!T1Quals.compatiblyIncludes(T2Quals)) |
5193 | 0 | return ICS; |
5194 | 0 | } |
5195 | | |
5196 | | // If at least one of the types is a class type, the types are not |
5197 | | // related, and we aren't allowed any user conversions, the |
5198 | | // reference binding fails. This case is important for breaking |
5199 | | // recursion, since TryImplicitConversion below will attempt to |
5200 | | // create a temporary through the use of a copy constructor. |
5201 | 0 | if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && |
5202 | 0 | (T1->isRecordType() || T2->isRecordType())) |
5203 | 0 | return ICS; |
5204 | | |
5205 | | // If T1 is reference-related to T2 and the reference is an rvalue |
5206 | | // reference, the initializer expression shall not be an lvalue. |
5207 | 0 | if (RefRelationship >= Sema::Ref_Related && isRValRef && |
5208 | 0 | Init->Classify(S.Context).isLValue()) { |
5209 | 0 | ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType); |
5210 | 0 | return ICS; |
5211 | 0 | } |
5212 | | |
5213 | | // C++ [over.ics.ref]p2: |
5214 | | // When a parameter of reference type is not bound directly to |
5215 | | // an argument expression, the conversion sequence is the one |
5216 | | // required to convert the argument expression to the |
5217 | | // underlying type of the reference according to |
5218 | | // 13.3.3.1. Conceptually, this conversion sequence corresponds |
5219 | | // to copy-initializing a temporary of the underlying type with |
5220 | | // the argument expression. Any difference in top-level |
5221 | | // cv-qualification is subsumed by the initialization itself |
5222 | | // and does not constitute a conversion. |
5223 | 0 | ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, |
5224 | 0 | AllowedExplicit::None, |
5225 | 0 | /*InOverloadResolution=*/false, |
5226 | 0 | /*CStyle=*/false, |
5227 | 0 | /*AllowObjCWritebackConversion=*/false, |
5228 | 0 | /*AllowObjCConversionOnExplicit=*/false); |
5229 | | |
5230 | | // Of course, that's still a reference binding. |
5231 | 0 | if (ICS.isStandard()) { |
5232 | 0 | ICS.Standard.ReferenceBinding = true; |
5233 | 0 | ICS.Standard.IsLvalueReference = !isRValRef; |
5234 | 0 | ICS.Standard.BindsToFunctionLvalue = false; |
5235 | 0 | ICS.Standard.BindsToRvalue = true; |
5236 | 0 | ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; |
5237 | 0 | ICS.Standard.ObjCLifetimeConversionBinding = false; |
5238 | 0 | } else if (ICS.isUserDefined()) { |
5239 | 0 | const ReferenceType *LValRefType = |
5240 | 0 | ICS.UserDefined.ConversionFunction->getReturnType() |
5241 | 0 | ->getAs<LValueReferenceType>(); |
5242 | | |
5243 | | // C++ [over.ics.ref]p3: |
5244 | | // Except for an implicit object parameter, for which see 13.3.1, a |
5245 | | // standard conversion sequence cannot be formed if it requires [...] |
5246 | | // binding an rvalue reference to an lvalue other than a function |
5247 | | // lvalue. |
5248 | | // Note that the function case is not possible here. |
5249 | 0 | if (isRValRef && LValRefType) { |
5250 | 0 | ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); |
5251 | 0 | return ICS; |
5252 | 0 | } |
5253 | | |
5254 | 0 | ICS.UserDefined.After.ReferenceBinding = true; |
5255 | 0 | ICS.UserDefined.After.IsLvalueReference = !isRValRef; |
5256 | 0 | ICS.UserDefined.After.BindsToFunctionLvalue = false; |
5257 | 0 | ICS.UserDefined.After.BindsToRvalue = !LValRefType; |
5258 | 0 | ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; |
5259 | 0 | ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; |
5260 | 0 | } |
5261 | | |
5262 | 0 | return ICS; |
5263 | 0 | } |
5264 | | |
5265 | | static ImplicitConversionSequence |
5266 | | TryCopyInitialization(Sema &S, Expr *From, QualType ToType, |
5267 | | bool SuppressUserConversions, |
5268 | | bool InOverloadResolution, |
5269 | | bool AllowObjCWritebackConversion, |
5270 | | bool AllowExplicit = false); |
5271 | | |
5272 | | /// TryListConversion - Try to copy-initialize a value of type ToType from the |
5273 | | /// initializer list From. |
5274 | | static ImplicitConversionSequence |
5275 | | TryListConversion(Sema &S, InitListExpr *From, QualType ToType, |
5276 | | bool SuppressUserConversions, |
5277 | | bool InOverloadResolution, |
5278 | 0 | bool AllowObjCWritebackConversion) { |
5279 | | // C++11 [over.ics.list]p1: |
5280 | | // When an argument is an initializer list, it is not an expression and |
5281 | | // special rules apply for converting it to a parameter type. |
5282 | |
|
5283 | 0 | ImplicitConversionSequence Result; |
5284 | 0 | Result.setBad(BadConversionSequence::no_conversion, From, ToType); |
5285 | | |
5286 | | // We need a complete type for what follows. With one C++20 exception, |
5287 | | // incomplete types can never be initialized from init lists. |
5288 | 0 | QualType InitTy = ToType; |
5289 | 0 | const ArrayType *AT = S.Context.getAsArrayType(ToType); |
5290 | 0 | if (AT && S.getLangOpts().CPlusPlus20) |
5291 | 0 | if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) |
5292 | | // C++20 allows list initialization of an incomplete array type. |
5293 | 0 | InitTy = IAT->getElementType(); |
5294 | 0 | if (!S.isCompleteType(From->getBeginLoc(), InitTy)) |
5295 | 0 | return Result; |
5296 | | |
5297 | | // C++20 [over.ics.list]/2: |
5298 | | // If the initializer list is a designated-initializer-list, a conversion |
5299 | | // is only possible if the parameter has an aggregate type |
5300 | | // |
5301 | | // FIXME: The exception for reference initialization here is not part of the |
5302 | | // language rules, but follow other compilers in adding it as a tentative DR |
5303 | | // resolution. |
5304 | 0 | bool IsDesignatedInit = From->hasDesignatedInit(); |
5305 | 0 | if (!ToType->isAggregateType() && !ToType->isReferenceType() && |
5306 | 0 | IsDesignatedInit) |
5307 | 0 | return Result; |
5308 | | |
5309 | | // Per DR1467: |
5310 | | // If the parameter type is a class X and the initializer list has a single |
5311 | | // element of type cv U, where U is X or a class derived from X, the |
5312 | | // implicit conversion sequence is the one required to convert the element |
5313 | | // to the parameter type. |
5314 | | // |
5315 | | // Otherwise, if the parameter type is a character array [... ] |
5316 | | // and the initializer list has a single element that is an |
5317 | | // appropriately-typed string literal (8.5.2 [dcl.init.string]), the |
5318 | | // implicit conversion sequence is the identity conversion. |
5319 | 0 | if (From->getNumInits() == 1 && !IsDesignatedInit) { |
5320 | 0 | if (ToType->isRecordType()) { |
5321 | 0 | QualType InitType = From->getInit(0)->getType(); |
5322 | 0 | if (S.Context.hasSameUnqualifiedType(InitType, ToType) || |
5323 | 0 | S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) |
5324 | 0 | return TryCopyInitialization(S, From->getInit(0), ToType, |
5325 | 0 | SuppressUserConversions, |
5326 | 0 | InOverloadResolution, |
5327 | 0 | AllowObjCWritebackConversion); |
5328 | 0 | } |
5329 | | |
5330 | 0 | if (AT && S.IsStringInit(From->getInit(0), AT)) { |
5331 | 0 | InitializedEntity Entity = |
5332 | 0 | InitializedEntity::InitializeParameter(S.Context, ToType, |
5333 | 0 | /*Consumed=*/false); |
5334 | 0 | if (S.CanPerformCopyInitialization(Entity, From)) { |
5335 | 0 | Result.setStandard(); |
5336 | 0 | Result.Standard.setAsIdentityConversion(); |
5337 | 0 | Result.Standard.setFromType(ToType); |
5338 | 0 | Result.Standard.setAllToTypes(ToType); |
5339 | 0 | return Result; |
5340 | 0 | } |
5341 | 0 | } |
5342 | 0 | } |
5343 | | |
5344 | | // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). |
5345 | | // C++11 [over.ics.list]p2: |
5346 | | // If the parameter type is std::initializer_list<X> or "array of X" and |
5347 | | // all the elements can be implicitly converted to X, the implicit |
5348 | | // conversion sequence is the worst conversion necessary to convert an |
5349 | | // element of the list to X. |
5350 | | // |
5351 | | // C++14 [over.ics.list]p3: |
5352 | | // Otherwise, if the parameter type is "array of N X", if the initializer |
5353 | | // list has exactly N elements or if it has fewer than N elements and X is |
5354 | | // default-constructible, and if all the elements of the initializer list |
5355 | | // can be implicitly converted to X, the implicit conversion sequence is |
5356 | | // the worst conversion necessary to convert an element of the list to X. |
5357 | 0 | if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) { |
5358 | 0 | unsigned e = From->getNumInits(); |
5359 | 0 | ImplicitConversionSequence DfltElt; |
5360 | 0 | DfltElt.setBad(BadConversionSequence::no_conversion, QualType(), |
5361 | 0 | QualType()); |
5362 | 0 | QualType ContTy = ToType; |
5363 | 0 | bool IsUnbounded = false; |
5364 | 0 | if (AT) { |
5365 | 0 | InitTy = AT->getElementType(); |
5366 | 0 | if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) { |
5367 | 0 | if (CT->getSize().ult(e)) { |
5368 | | // Too many inits, fatally bad |
5369 | 0 | Result.setBad(BadConversionSequence::too_many_initializers, From, |
5370 | 0 | ToType); |
5371 | 0 | Result.setInitializerListContainerType(ContTy, IsUnbounded); |
5372 | 0 | return Result; |
5373 | 0 | } |
5374 | 0 | if (CT->getSize().ugt(e)) { |
5375 | | // Need an init from empty {}, is there one? |
5376 | 0 | InitListExpr EmptyList(S.Context, From->getEndLoc(), std::nullopt, |
5377 | 0 | From->getEndLoc()); |
5378 | 0 | EmptyList.setType(S.Context.VoidTy); |
5379 | 0 | DfltElt = TryListConversion( |
5380 | 0 | S, &EmptyList, InitTy, SuppressUserConversions, |
5381 | 0 | InOverloadResolution, AllowObjCWritebackConversion); |
5382 | 0 | if (DfltElt.isBad()) { |
5383 | | // No {} init, fatally bad |
5384 | 0 | Result.setBad(BadConversionSequence::too_few_initializers, From, |
5385 | 0 | ToType); |
5386 | 0 | Result.setInitializerListContainerType(ContTy, IsUnbounded); |
5387 | 0 | return Result; |
5388 | 0 | } |
5389 | 0 | } |
5390 | 0 | } else { |
5391 | 0 | assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array"); |
5392 | 0 | IsUnbounded = true; |
5393 | 0 | if (!e) { |
5394 | | // Cannot convert to zero-sized. |
5395 | 0 | Result.setBad(BadConversionSequence::too_few_initializers, From, |
5396 | 0 | ToType); |
5397 | 0 | Result.setInitializerListContainerType(ContTy, IsUnbounded); |
5398 | 0 | return Result; |
5399 | 0 | } |
5400 | 0 | llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e); |
5401 | 0 | ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr, |
5402 | 0 | ArraySizeModifier::Normal, 0); |
5403 | 0 | } |
5404 | 0 | } |
5405 | | |
5406 | 0 | Result.setStandard(); |
5407 | 0 | Result.Standard.setAsIdentityConversion(); |
5408 | 0 | Result.Standard.setFromType(InitTy); |
5409 | 0 | Result.Standard.setAllToTypes(InitTy); |
5410 | 0 | for (unsigned i = 0; i < e; ++i) { |
5411 | 0 | Expr *Init = From->getInit(i); |
5412 | 0 | ImplicitConversionSequence ICS = TryCopyInitialization( |
5413 | 0 | S, Init, InitTy, SuppressUserConversions, InOverloadResolution, |
5414 | 0 | AllowObjCWritebackConversion); |
5415 | | |
5416 | | // Keep the worse conversion seen so far. |
5417 | | // FIXME: Sequences are not totally ordered, so 'worse' can be |
5418 | | // ambiguous. CWG has been informed. |
5419 | 0 | if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS, |
5420 | 0 | Result) == |
5421 | 0 | ImplicitConversionSequence::Worse) { |
5422 | 0 | Result = ICS; |
5423 | | // Bail as soon as we find something unconvertible. |
5424 | 0 | if (Result.isBad()) { |
5425 | 0 | Result.setInitializerListContainerType(ContTy, IsUnbounded); |
5426 | 0 | return Result; |
5427 | 0 | } |
5428 | 0 | } |
5429 | 0 | } |
5430 | | |
5431 | | // If we needed any implicit {} initialization, compare that now. |
5432 | | // over.ics.list/6 indicates we should compare that conversion. Again CWG |
5433 | | // has been informed that this might not be the best thing. |
5434 | 0 | if (!DfltElt.isBad() && CompareImplicitConversionSequences( |
5435 | 0 | S, From->getEndLoc(), DfltElt, Result) == |
5436 | 0 | ImplicitConversionSequence::Worse) |
5437 | 0 | Result = DfltElt; |
5438 | | // Record the type being initialized so that we may compare sequences |
5439 | 0 | Result.setInitializerListContainerType(ContTy, IsUnbounded); |
5440 | 0 | return Result; |
5441 | 0 | } |
5442 | | |
5443 | | // C++14 [over.ics.list]p4: |
5444 | | // C++11 [over.ics.list]p3: |
5445 | | // Otherwise, if the parameter is a non-aggregate class X and overload |
5446 | | // resolution chooses a single best constructor [...] the implicit |
5447 | | // conversion sequence is a user-defined conversion sequence. If multiple |
5448 | | // constructors are viable but none is better than the others, the |
5449 | | // implicit conversion sequence is a user-defined conversion sequence. |
5450 | 0 | if (ToType->isRecordType() && !ToType->isAggregateType()) { |
5451 | | // This function can deal with initializer lists. |
5452 | 0 | return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, |
5453 | 0 | AllowedExplicit::None, |
5454 | 0 | InOverloadResolution, /*CStyle=*/false, |
5455 | 0 | AllowObjCWritebackConversion, |
5456 | 0 | /*AllowObjCConversionOnExplicit=*/false); |
5457 | 0 | } |
5458 | | |
5459 | | // C++14 [over.ics.list]p5: |
5460 | | // C++11 [over.ics.list]p4: |
5461 | | // Otherwise, if the parameter has an aggregate type which can be |
5462 | | // initialized from the initializer list [...] the implicit conversion |
5463 | | // sequence is a user-defined conversion sequence. |
5464 | 0 | if (ToType->isAggregateType()) { |
5465 | | // Type is an aggregate, argument is an init list. At this point it comes |
5466 | | // down to checking whether the initialization works. |
5467 | | // FIXME: Find out whether this parameter is consumed or not. |
5468 | 0 | InitializedEntity Entity = |
5469 | 0 | InitializedEntity::InitializeParameter(S.Context, ToType, |
5470 | 0 | /*Consumed=*/false); |
5471 | 0 | if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, |
5472 | 0 | From)) { |
5473 | 0 | Result.setUserDefined(); |
5474 | 0 | Result.UserDefined.Before.setAsIdentityConversion(); |
5475 | | // Initializer lists don't have a type. |
5476 | 0 | Result.UserDefined.Before.setFromType(QualType()); |
5477 | 0 | Result.UserDefined.Before.setAllToTypes(QualType()); |
5478 | |
|
5479 | 0 | Result.UserDefined.After.setAsIdentityConversion(); |
5480 | 0 | Result.UserDefined.After.setFromType(ToType); |
5481 | 0 | Result.UserDefined.After.setAllToTypes(ToType); |
5482 | 0 | Result.UserDefined.ConversionFunction = nullptr; |
5483 | 0 | } |
5484 | 0 | return Result; |
5485 | 0 | } |
5486 | | |
5487 | | // C++14 [over.ics.list]p6: |
5488 | | // C++11 [over.ics.list]p5: |
5489 | | // Otherwise, if the parameter is a reference, see 13.3.3.1.4. |
5490 | 0 | if (ToType->isReferenceType()) { |
5491 | | // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't |
5492 | | // mention initializer lists in any way. So we go by what list- |
5493 | | // initialization would do and try to extrapolate from that. |
5494 | |
|
5495 | 0 | QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); |
5496 | | |
5497 | | // If the initializer list has a single element that is reference-related |
5498 | | // to the parameter type, we initialize the reference from that. |
5499 | 0 | if (From->getNumInits() == 1 && !IsDesignatedInit) { |
5500 | 0 | Expr *Init = From->getInit(0); |
5501 | |
|
5502 | 0 | QualType T2 = Init->getType(); |
5503 | | |
5504 | | // If the initializer is the address of an overloaded function, try |
5505 | | // to resolve the overloaded function. If all goes well, T2 is the |
5506 | | // type of the resulting function. |
5507 | 0 | if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { |
5508 | 0 | DeclAccessPair Found; |
5509 | 0 | if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( |
5510 | 0 | Init, ToType, false, Found)) |
5511 | 0 | T2 = Fn->getType(); |
5512 | 0 | } |
5513 | | |
5514 | | // Compute some basic properties of the types and the initializer. |
5515 | 0 | Sema::ReferenceCompareResult RefRelationship = |
5516 | 0 | S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); |
5517 | |
|
5518 | 0 | if (RefRelationship >= Sema::Ref_Related) { |
5519 | 0 | return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), |
5520 | 0 | SuppressUserConversions, |
5521 | 0 | /*AllowExplicit=*/false); |
5522 | 0 | } |
5523 | 0 | } |
5524 | | |
5525 | | // Otherwise, we bind the reference to a temporary created from the |
5526 | | // initializer list. |
5527 | 0 | Result = TryListConversion(S, From, T1, SuppressUserConversions, |
5528 | 0 | InOverloadResolution, |
5529 | 0 | AllowObjCWritebackConversion); |
5530 | 0 | if (Result.isFailure()) |
5531 | 0 | return Result; |
5532 | 0 | assert(!Result.isEllipsis() && |
5533 | 0 | "Sub-initialization cannot result in ellipsis conversion."); |
5534 | | |
5535 | | // Can we even bind to a temporary? |
5536 | 0 | if (ToType->isRValueReferenceType() || |
5537 | 0 | (T1.isConstQualified() && !T1.isVolatileQualified())) { |
5538 | 0 | StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : |
5539 | 0 | Result.UserDefined.After; |
5540 | 0 | SCS.ReferenceBinding = true; |
5541 | 0 | SCS.IsLvalueReference = ToType->isLValueReferenceType(); |
5542 | 0 | SCS.BindsToRvalue = true; |
5543 | 0 | SCS.BindsToFunctionLvalue = false; |
5544 | 0 | SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; |
5545 | 0 | SCS.ObjCLifetimeConversionBinding = false; |
5546 | 0 | } else |
5547 | 0 | Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, |
5548 | 0 | From, ToType); |
5549 | 0 | return Result; |
5550 | 0 | } |
5551 | | |
5552 | | // C++14 [over.ics.list]p7: |
5553 | | // C++11 [over.ics.list]p6: |
5554 | | // Otherwise, if the parameter type is not a class: |
5555 | 0 | if (!ToType->isRecordType()) { |
5556 | | // - if the initializer list has one element that is not itself an |
5557 | | // initializer list, the implicit conversion sequence is the one |
5558 | | // required to convert the element to the parameter type. |
5559 | 0 | unsigned NumInits = From->getNumInits(); |
5560 | 0 | if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) |
5561 | 0 | Result = TryCopyInitialization(S, From->getInit(0), ToType, |
5562 | 0 | SuppressUserConversions, |
5563 | 0 | InOverloadResolution, |
5564 | 0 | AllowObjCWritebackConversion); |
5565 | | // - if the initializer list has no elements, the implicit conversion |
5566 | | // sequence is the identity conversion. |
5567 | 0 | else if (NumInits == 0) { |
5568 | 0 | Result.setStandard(); |
5569 | 0 | Result.Standard.setAsIdentityConversion(); |
5570 | 0 | Result.Standard.setFromType(ToType); |
5571 | 0 | Result.Standard.setAllToTypes(ToType); |
5572 | 0 | } |
5573 | 0 | return Result; |
5574 | 0 | } |
5575 | | |
5576 | | // C++14 [over.ics.list]p8: |
5577 | | // C++11 [over.ics.list]p7: |
5578 | | // In all cases other than those enumerated above, no conversion is possible |
5579 | 0 | return Result; |
5580 | 0 | } |
5581 | | |
5582 | | /// TryCopyInitialization - Try to copy-initialize a value of type |
5583 | | /// ToType from the expression From. Return the implicit conversion |
5584 | | /// sequence required to pass this argument, which may be a bad |
5585 | | /// conversion sequence (meaning that the argument cannot be passed to |
5586 | | /// a parameter of this type). If @p SuppressUserConversions, then we |
5587 | | /// do not permit any user-defined conversion sequences. |
5588 | | static ImplicitConversionSequence |
5589 | | TryCopyInitialization(Sema &S, Expr *From, QualType ToType, |
5590 | | bool SuppressUserConversions, |
5591 | | bool InOverloadResolution, |
5592 | | bool AllowObjCWritebackConversion, |
5593 | 1 | bool AllowExplicit) { |
5594 | 1 | if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) |
5595 | 0 | return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, |
5596 | 0 | InOverloadResolution,AllowObjCWritebackConversion); |
5597 | | |
5598 | 1 | if (ToType->isReferenceType()) |
5599 | 0 | return TryReferenceInit(S, From, ToType, |
5600 | 0 | /*FIXME:*/ From->getBeginLoc(), |
5601 | 0 | SuppressUserConversions, AllowExplicit); |
5602 | | |
5603 | 1 | return TryImplicitConversion(S, From, ToType, |
5604 | 1 | SuppressUserConversions, |
5605 | 1 | AllowedExplicit::None, |
5606 | 1 | InOverloadResolution, |
5607 | 1 | /*CStyle=*/false, |
5608 | 1 | AllowObjCWritebackConversion, |
5609 | 1 | /*AllowObjCConversionOnExplicit=*/false); |
5610 | 1 | } |
5611 | | |
5612 | | static bool TryCopyInitialization(const CanQualType FromQTy, |
5613 | | const CanQualType ToQTy, |
5614 | | Sema &S, |
5615 | | SourceLocation Loc, |
5616 | 0 | ExprValueKind FromVK) { |
5617 | 0 | OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); |
5618 | 0 | ImplicitConversionSequence ICS = |
5619 | 0 | TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); |
5620 | |
|
5621 | 0 | return !ICS.isBad(); |
5622 | 0 | } |
5623 | | |
5624 | | /// TryObjectArgumentInitialization - Try to initialize the object |
5625 | | /// parameter of the given member function (@c Method) from the |
5626 | | /// expression @p From. |
5627 | | static ImplicitConversionSequence TryObjectArgumentInitialization( |
5628 | | Sema &S, SourceLocation Loc, QualType FromType, |
5629 | | Expr::Classification FromClassification, CXXMethodDecl *Method, |
5630 | | const CXXRecordDecl *ActingContext, bool InOverloadResolution = false, |
5631 | | QualType ExplicitParameterType = QualType(), |
5632 | 0 | bool SuppressUserConversion = false) { |
5633 | | |
5634 | | // We need to have an object of class type. |
5635 | 0 | if (const auto *PT = FromType->getAs<PointerType>()) { |
5636 | 0 | FromType = PT->getPointeeType(); |
5637 | | |
5638 | | // When we had a pointer, it's implicitly dereferenced, so we |
5639 | | // better have an lvalue. |
5640 | 0 | assert(FromClassification.isLValue()); |
5641 | 0 | } |
5642 | | |
5643 | 0 | auto ValueKindFromClassification = [](Expr::Classification C) { |
5644 | 0 | if (C.isPRValue()) |
5645 | 0 | return clang::VK_PRValue; |
5646 | 0 | if (C.isXValue()) |
5647 | 0 | return VK_XValue; |
5648 | 0 | return clang::VK_LValue; |
5649 | 0 | }; |
5650 | |
|
5651 | 0 | if (Method->isExplicitObjectMemberFunction()) { |
5652 | 0 | if (ExplicitParameterType.isNull()) |
5653 | 0 | ExplicitParameterType = Method->getFunctionObjectParameterReferenceType(); |
5654 | 0 | OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(), |
5655 | 0 | ValueKindFromClassification(FromClassification)); |
5656 | 0 | ImplicitConversionSequence ICS = TryCopyInitialization( |
5657 | 0 | S, &TmpExpr, ExplicitParameterType, SuppressUserConversion, |
5658 | 0 | /*InOverloadResolution=*/true, false); |
5659 | 0 | if (ICS.isBad()) |
5660 | 0 | ICS.Bad.FromExpr = nullptr; |
5661 | 0 | return ICS; |
5662 | 0 | } |
5663 | | |
5664 | 0 | assert(FromType->isRecordType()); |
5665 | | |
5666 | 0 | QualType ClassType = S.Context.getTypeDeclType(ActingContext); |
5667 | | // [class.dtor]p2: A destructor can be invoked for a const, volatile or |
5668 | | // const volatile object. |
5669 | 0 | Qualifiers Quals = Method->getMethodQualifiers(); |
5670 | 0 | if (isa<CXXDestructorDecl>(Method)) { |
5671 | 0 | Quals.addConst(); |
5672 | 0 | Quals.addVolatile(); |
5673 | 0 | } |
5674 | |
|
5675 | 0 | QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); |
5676 | | |
5677 | | // Set up the conversion sequence as a "bad" conversion, to allow us |
5678 | | // to exit early. |
5679 | 0 | ImplicitConversionSequence ICS; |
5680 | | |
5681 | | // C++0x [over.match.funcs]p4: |
5682 | | // For non-static member functions, the type of the implicit object |
5683 | | // parameter is |
5684 | | // |
5685 | | // - "lvalue reference to cv X" for functions declared without a |
5686 | | // ref-qualifier or with the & ref-qualifier |
5687 | | // - "rvalue reference to cv X" for functions declared with the && |
5688 | | // ref-qualifier |
5689 | | // |
5690 | | // where X is the class of which the function is a member and cv is the |
5691 | | // cv-qualification on the member function declaration. |
5692 | | // |
5693 | | // However, when finding an implicit conversion sequence for the argument, we |
5694 | | // are not allowed to perform user-defined conversions |
5695 | | // (C++ [over.match.funcs]p5). We perform a simplified version of |
5696 | | // reference binding here, that allows class rvalues to bind to |
5697 | | // non-constant references. |
5698 | | |
5699 | | // First check the qualifiers. |
5700 | 0 | QualType FromTypeCanon = S.Context.getCanonicalType(FromType); |
5701 | | // MSVC ignores __unaligned qualifier for overload candidates; do the same. |
5702 | 0 | if (ImplicitParamType.getCVRQualifiers() != |
5703 | 0 | FromTypeCanon.getLocalCVRQualifiers() && |
5704 | 0 | !ImplicitParamType.isAtLeastAsQualifiedAs( |
5705 | 0 | withoutUnaligned(S.Context, FromTypeCanon))) { |
5706 | 0 | ICS.setBad(BadConversionSequence::bad_qualifiers, |
5707 | 0 | FromType, ImplicitParamType); |
5708 | 0 | return ICS; |
5709 | 0 | } |
5710 | | |
5711 | 0 | if (FromTypeCanon.hasAddressSpace()) { |
5712 | 0 | Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); |
5713 | 0 | Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); |
5714 | 0 | if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { |
5715 | 0 | ICS.setBad(BadConversionSequence::bad_qualifiers, |
5716 | 0 | FromType, ImplicitParamType); |
5717 | 0 | return ICS; |
5718 | 0 | } |
5719 | 0 | } |
5720 | | |
5721 | | // Check that we have either the same type or a derived type. It |
5722 | | // affects the conversion rank. |
5723 | 0 | QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); |
5724 | 0 | ImplicitConversionKind SecondKind; |
5725 | 0 | if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { |
5726 | 0 | SecondKind = ICK_Identity; |
5727 | 0 | } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) { |
5728 | 0 | SecondKind = ICK_Derived_To_Base; |
5729 | 0 | } else if (!Method->isExplicitObjectMemberFunction()) { |
5730 | 0 | ICS.setBad(BadConversionSequence::unrelated_class, |
5731 | 0 | FromType, ImplicitParamType); |
5732 | 0 | return ICS; |
5733 | 0 | } |
5734 | | |
5735 | | // Check the ref-qualifier. |
5736 | 0 | switch (Method->getRefQualifier()) { |
5737 | 0 | case RQ_None: |
5738 | | // Do nothing; we don't care about lvalueness or rvalueness. |
5739 | 0 | break; |
5740 | | |
5741 | 0 | case RQ_LValue: |
5742 | 0 | if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { |
5743 | | // non-const lvalue reference cannot bind to an rvalue |
5744 | 0 | ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, |
5745 | 0 | ImplicitParamType); |
5746 | 0 | return ICS; |
5747 | 0 | } |
5748 | 0 | break; |
5749 | | |
5750 | 0 | case RQ_RValue: |
5751 | 0 | if (!FromClassification.isRValue()) { |
5752 | | // rvalue reference cannot bind to an lvalue |
5753 | 0 | ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, |
5754 | 0 | ImplicitParamType); |
5755 | 0 | return ICS; |
5756 | 0 | } |
5757 | 0 | break; |
5758 | 0 | } |
5759 | | |
5760 | | // Success. Mark this as a reference binding. |
5761 | 0 | ICS.setStandard(); |
5762 | 0 | ICS.Standard.setAsIdentityConversion(); |
5763 | 0 | ICS.Standard.Second = SecondKind; |
5764 | 0 | ICS.Standard.setFromType(FromType); |
5765 | 0 | ICS.Standard.setAllToTypes(ImplicitParamType); |
5766 | 0 | ICS.Standard.ReferenceBinding = true; |
5767 | 0 | ICS.Standard.DirectBinding = true; |
5768 | 0 | ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; |
5769 | 0 | ICS.Standard.BindsToFunctionLvalue = false; |
5770 | 0 | ICS.Standard.BindsToRvalue = FromClassification.isRValue(); |
5771 | 0 | ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier |
5772 | 0 | = (Method->getRefQualifier() == RQ_None); |
5773 | 0 | return ICS; |
5774 | 0 | } |
5775 | | |
5776 | | /// PerformObjectArgumentInitialization - Perform initialization of |
5777 | | /// the implicit object parameter for the given Method with the given |
5778 | | /// expression. |
5779 | | ExprResult Sema::PerformImplicitObjectArgumentInitialization( |
5780 | | Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, |
5781 | 0 | CXXMethodDecl *Method) { |
5782 | 0 | QualType FromRecordType, DestType; |
5783 | 0 | QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType(); |
5784 | |
|
5785 | 0 | Expr::Classification FromClassification; |
5786 | 0 | if (const PointerType *PT = From->getType()->getAs<PointerType>()) { |
5787 | 0 | FromRecordType = PT->getPointeeType(); |
5788 | 0 | DestType = Method->getThisType(); |
5789 | 0 | FromClassification = Expr::Classification::makeSimpleLValue(); |
5790 | 0 | } else { |
5791 | 0 | FromRecordType = From->getType(); |
5792 | 0 | DestType = ImplicitParamRecordType; |
5793 | 0 | FromClassification = From->Classify(Context); |
5794 | | |
5795 | | // When performing member access on a prvalue, materialize a temporary. |
5796 | 0 | if (From->isPRValue()) { |
5797 | 0 | From = CreateMaterializeTemporaryExpr(FromRecordType, From, |
5798 | 0 | Method->getRefQualifier() != |
5799 | 0 | RefQualifierKind::RQ_RValue); |
5800 | 0 | } |
5801 | 0 | } |
5802 | | |
5803 | | // Note that we always use the true parent context when performing |
5804 | | // the actual argument initialization. |
5805 | 0 | ImplicitConversionSequence ICS = TryObjectArgumentInitialization( |
5806 | 0 | *this, From->getBeginLoc(), From->getType(), FromClassification, Method, |
5807 | 0 | Method->getParent()); |
5808 | 0 | if (ICS.isBad()) { |
5809 | 0 | switch (ICS.Bad.Kind) { |
5810 | 0 | case BadConversionSequence::bad_qualifiers: { |
5811 | 0 | Qualifiers FromQs = FromRecordType.getQualifiers(); |
5812 | 0 | Qualifiers ToQs = DestType.getQualifiers(); |
5813 | 0 | unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); |
5814 | 0 | if (CVR) { |
5815 | 0 | Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) |
5816 | 0 | << Method->getDeclName() << FromRecordType << (CVR - 1) |
5817 | 0 | << From->getSourceRange(); |
5818 | 0 | Diag(Method->getLocation(), diag::note_previous_decl) |
5819 | 0 | << Method->getDeclName(); |
5820 | 0 | return ExprError(); |
5821 | 0 | } |
5822 | 0 | break; |
5823 | 0 | } |
5824 | | |
5825 | 0 | case BadConversionSequence::lvalue_ref_to_rvalue: |
5826 | 0 | case BadConversionSequence::rvalue_ref_to_lvalue: { |
5827 | 0 | bool IsRValueQualified = |
5828 | 0 | Method->getRefQualifier() == RefQualifierKind::RQ_RValue; |
5829 | 0 | Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) |
5830 | 0 | << Method->getDeclName() << FromClassification.isRValue() |
5831 | 0 | << IsRValueQualified; |
5832 | 0 | Diag(Method->getLocation(), diag::note_previous_decl) |
5833 | 0 | << Method->getDeclName(); |
5834 | 0 | return ExprError(); |
5835 | 0 | } |
5836 | | |
5837 | 0 | case BadConversionSequence::no_conversion: |
5838 | 0 | case BadConversionSequence::unrelated_class: |
5839 | 0 | break; |
5840 | | |
5841 | 0 | case BadConversionSequence::too_few_initializers: |
5842 | 0 | case BadConversionSequence::too_many_initializers: |
5843 | 0 | llvm_unreachable("Lists are not objects"); |
5844 | 0 | } |
5845 | | |
5846 | 0 | return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) |
5847 | 0 | << ImplicitParamRecordType << FromRecordType |
5848 | 0 | << From->getSourceRange(); |
5849 | 0 | } |
5850 | | |
5851 | 0 | if (ICS.Standard.Second == ICK_Derived_To_Base) { |
5852 | 0 | ExprResult FromRes = |
5853 | 0 | PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); |
5854 | 0 | if (FromRes.isInvalid()) |
5855 | 0 | return ExprError(); |
5856 | 0 | From = FromRes.get(); |
5857 | 0 | } |
5858 | | |
5859 | 0 | if (!Context.hasSameType(From->getType(), DestType)) { |
5860 | 0 | CastKind CK; |
5861 | 0 | QualType PteeTy = DestType->getPointeeType(); |
5862 | 0 | LangAS DestAS = |
5863 | 0 | PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); |
5864 | 0 | if (FromRecordType.getAddressSpace() != DestAS) |
5865 | 0 | CK = CK_AddressSpaceConversion; |
5866 | 0 | else |
5867 | 0 | CK = CK_NoOp; |
5868 | 0 | From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); |
5869 | 0 | } |
5870 | 0 | return From; |
5871 | 0 | } |
5872 | | |
5873 | | /// TryContextuallyConvertToBool - Attempt to contextually convert the |
5874 | | /// expression From to bool (C++0x [conv]p3). |
5875 | | static ImplicitConversionSequence |
5876 | 0 | TryContextuallyConvertToBool(Sema &S, Expr *From) { |
5877 | | // C++ [dcl.init]/17.8: |
5878 | | // - Otherwise, if the initialization is direct-initialization, the source |
5879 | | // type is std::nullptr_t, and the destination type is bool, the initial |
5880 | | // value of the object being initialized is false. |
5881 | 0 | if (From->getType()->isNullPtrType()) |
5882 | 0 | return ImplicitConversionSequence::getNullptrToBool(From->getType(), |
5883 | 0 | S.Context.BoolTy, |
5884 | 0 | From->isGLValue()); |
5885 | | |
5886 | | // All other direct-initialization of bool is equivalent to an implicit |
5887 | | // conversion to bool in which explicit conversions are permitted. |
5888 | 0 | return TryImplicitConversion(S, From, S.Context.BoolTy, |
5889 | 0 | /*SuppressUserConversions=*/false, |
5890 | 0 | AllowedExplicit::Conversions, |
5891 | 0 | /*InOverloadResolution=*/false, |
5892 | 0 | /*CStyle=*/false, |
5893 | 0 | /*AllowObjCWritebackConversion=*/false, |
5894 | 0 | /*AllowObjCConversionOnExplicit=*/false); |
5895 | 0 | } |
5896 | | |
5897 | | /// PerformContextuallyConvertToBool - Perform a contextual conversion |
5898 | | /// of the expression From to bool (C++0x [conv]p3). |
5899 | 0 | ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { |
5900 | 0 | if (checkPlaceholderForOverload(*this, From)) |
5901 | 0 | return ExprError(); |
5902 | | |
5903 | 0 | ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); |
5904 | 0 | if (!ICS.isBad()) |
5905 | 0 | return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); |
5906 | | |
5907 | 0 | if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) |
5908 | 0 | return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) |
5909 | 0 | << From->getType() << From->getSourceRange(); |
5910 | 0 | return ExprError(); |
5911 | 0 | } |
5912 | | |
5913 | | /// Check that the specified conversion is permitted in a converted constant |
5914 | | /// expression, according to C++11 [expr.const]p3. Return true if the conversion |
5915 | | /// is acceptable. |
5916 | | static bool CheckConvertedConstantConversions(Sema &S, |
5917 | 0 | StandardConversionSequence &SCS) { |
5918 | | // Since we know that the target type is an integral or unscoped enumeration |
5919 | | // type, most conversion kinds are impossible. All possible First and Third |
5920 | | // conversions are fine. |
5921 | 0 | switch (SCS.Second) { |
5922 | 0 | case ICK_Identity: |
5923 | 0 | case ICK_Integral_Promotion: |
5924 | 0 | case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. |
5925 | 0 | case ICK_Zero_Queue_Conversion: |
5926 | 0 | return true; |
5927 | | |
5928 | 0 | case ICK_Boolean_Conversion: |
5929 | | // Conversion from an integral or unscoped enumeration type to bool is |
5930 | | // classified as ICK_Boolean_Conversion, but it's also arguably an integral |
5931 | | // conversion, so we allow it in a converted constant expression. |
5932 | | // |
5933 | | // FIXME: Per core issue 1407, we should not allow this, but that breaks |
5934 | | // a lot of popular code. We should at least add a warning for this |
5935 | | // (non-conforming) extension. |
5936 | 0 | return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && |
5937 | 0 | SCS.getToType(2)->isBooleanType(); |
5938 | | |
5939 | 0 | case ICK_Pointer_Conversion: |
5940 | 0 | case ICK_Pointer_Member: |
5941 | | // C++1z: null pointer conversions and null member pointer conversions are |
5942 | | // only permitted if the source type is std::nullptr_t. |
5943 | 0 | return SCS.getFromType()->isNullPtrType(); |
5944 | | |
5945 | 0 | case ICK_Floating_Promotion: |
5946 | 0 | case ICK_Complex_Promotion: |
5947 | 0 | case ICK_Floating_Conversion: |
5948 | 0 | case ICK_Complex_Conversion: |
5949 | 0 | case ICK_Floating_Integral: |
5950 | 0 | case ICK_Compatible_Conversion: |
5951 | 0 | case ICK_Derived_To_Base: |
5952 | 0 | case ICK_Vector_Conversion: |
5953 | 0 | case ICK_SVE_Vector_Conversion: |
5954 | 0 | case ICK_RVV_Vector_Conversion: |
5955 | 0 | case ICK_Vector_Splat: |
5956 | 0 | case ICK_Complex_Real: |
5957 | 0 | case ICK_Block_Pointer_Conversion: |
5958 | 0 | case ICK_TransparentUnionConversion: |
5959 | 0 | case ICK_Writeback_Conversion: |
5960 | 0 | case ICK_Zero_Event_Conversion: |
5961 | 0 | case ICK_C_Only_Conversion: |
5962 | 0 | case ICK_Incompatible_Pointer_Conversion: |
5963 | 0 | case ICK_Fixed_Point_Conversion: |
5964 | 0 | return false; |
5965 | | |
5966 | 0 | case ICK_Lvalue_To_Rvalue: |
5967 | 0 | case ICK_Array_To_Pointer: |
5968 | 0 | case ICK_Function_To_Pointer: |
5969 | 0 | llvm_unreachable("found a first conversion kind in Second"); |
5970 | |
|
5971 | 0 | case ICK_Function_Conversion: |
5972 | 0 | case ICK_Qualification: |
5973 | 0 | llvm_unreachable("found a third conversion kind in Second"); |
5974 | |
|
5975 | 0 | case ICK_Num_Conversion_Kinds: |
5976 | 0 | break; |
5977 | 0 | } |
5978 | | |
5979 | 0 | llvm_unreachable("unknown conversion kind"); |
5980 | 0 | } |
5981 | | |
5982 | | /// BuildConvertedConstantExpression - Check that the expression From is a |
5983 | | /// converted constant expression of type T, perform the conversion but |
5984 | | /// does not evaluate the expression |
5985 | | static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From, |
5986 | | QualType T, |
5987 | | Sema::CCEKind CCE, |
5988 | | NamedDecl *Dest, |
5989 | 1 | APValue &PreNarrowingValue) { |
5990 | 1 | assert(S.getLangOpts().CPlusPlus11 && |
5991 | 1 | "converted constant expression outside C++11"); |
5992 | | |
5993 | 1 | if (checkPlaceholderForOverload(S, From)) |
5994 | 0 | return ExprError(); |
5995 | | |
5996 | | // C++1z [expr.const]p3: |
5997 | | // A converted constant expression of type T is an expression, |
5998 | | // implicitly converted to type T, where the converted |
5999 | | // expression is a constant expression and the implicit conversion |
6000 | | // sequence contains only [... list of conversions ...]. |
6001 | 1 | ImplicitConversionSequence ICS = |
6002 | 1 | (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept) |
6003 | 1 | ? TryContextuallyConvertToBool(S, From) |
6004 | 1 | : TryCopyInitialization(S, From, T, |
6005 | 1 | /*SuppressUserConversions=*/false, |
6006 | 1 | /*InOverloadResolution=*/false, |
6007 | 1 | /*AllowObjCWritebackConversion=*/false, |
6008 | 1 | /*AllowExplicit=*/false); |
6009 | 1 | StandardConversionSequence *SCS = nullptr; |
6010 | 1 | switch (ICS.getKind()) { |
6011 | 0 | case ImplicitConversionSequence::StandardConversion: |
6012 | 0 | SCS = &ICS.Standard; |
6013 | 0 | break; |
6014 | 0 | case ImplicitConversionSequence::UserDefinedConversion: |
6015 | 0 | if (T->isRecordType()) |
6016 | 0 | SCS = &ICS.UserDefined.Before; |
6017 | 0 | else |
6018 | 0 | SCS = &ICS.UserDefined.After; |
6019 | 0 | break; |
6020 | 0 | case ImplicitConversionSequence::AmbiguousConversion: |
6021 | 1 | case ImplicitConversionSequence::BadConversion: |
6022 | 1 | if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) |
6023 | 1 | return S.Diag(From->getBeginLoc(), |
6024 | 1 | diag::err_typecheck_converted_constant_expression) |
6025 | 1 | << From->getType() << From->getSourceRange() << T; |
6026 | 0 | return ExprError(); |
6027 | | |
6028 | 0 | case ImplicitConversionSequence::EllipsisConversion: |
6029 | 0 | case ImplicitConversionSequence::StaticObjectArgumentConversion: |
6030 | 0 | llvm_unreachable("bad conversion in converted constant expression"); |
6031 | 1 | } |
6032 | | |
6033 | | // Check that we would only use permitted conversions. |
6034 | 0 | if (!CheckConvertedConstantConversions(S, *SCS)) { |
6035 | 0 | return S.Diag(From->getBeginLoc(), |
6036 | 0 | diag::err_typecheck_converted_constant_expression_disallowed) |
6037 | 0 | << From->getType() << From->getSourceRange() << T; |
6038 | 0 | } |
6039 | | // [...] and where the reference binding (if any) binds directly. |
6040 | 0 | if (SCS->ReferenceBinding && !SCS->DirectBinding) { |
6041 | 0 | return S.Diag(From->getBeginLoc(), |
6042 | 0 | diag::err_typecheck_converted_constant_expression_indirect) |
6043 | 0 | << From->getType() << From->getSourceRange() << T; |
6044 | 0 | } |
6045 | | // 'TryCopyInitialization' returns incorrect info for attempts to bind |
6046 | | // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely, |
6047 | | // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not |
6048 | | // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this |
6049 | | // case explicitly. |
6050 | 0 | if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) { |
6051 | 0 | return S.Diag(From->getBeginLoc(), |
6052 | 0 | diag::err_reference_bind_to_bitfield_in_cce) |
6053 | 0 | << From->getSourceRange(); |
6054 | 0 | } |
6055 | | |
6056 | | // Usually we can simply apply the ImplicitConversionSequence we formed |
6057 | | // earlier, but that's not guaranteed to work when initializing an object of |
6058 | | // class type. |
6059 | 0 | ExprResult Result; |
6060 | 0 | if (T->isRecordType()) { |
6061 | 0 | assert(CCE == Sema::CCEK_TemplateArg && |
6062 | 0 | "unexpected class type converted constant expr"); |
6063 | 0 | Result = S.PerformCopyInitialization( |
6064 | 0 | InitializedEntity::InitializeTemplateParameter( |
6065 | 0 | T, cast<NonTypeTemplateParmDecl>(Dest)), |
6066 | 0 | SourceLocation(), From); |
6067 | 0 | } else { |
6068 | 0 | Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); |
6069 | 0 | } |
6070 | 0 | if (Result.isInvalid()) |
6071 | 0 | return Result; |
6072 | | |
6073 | | // C++2a [intro.execution]p5: |
6074 | | // A full-expression is [...] a constant-expression [...] |
6075 | 0 | Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), |
6076 | 0 | /*DiscardedValue=*/false, /*IsConstexpr=*/true, |
6077 | 0 | CCE == Sema::CCEKind::CCEK_TemplateArg); |
6078 | 0 | if (Result.isInvalid()) |
6079 | 0 | return Result; |
6080 | | |
6081 | | // Check for a narrowing implicit conversion. |
6082 | 0 | bool ReturnPreNarrowingValue = false; |
6083 | 0 | QualType PreNarrowingType; |
6084 | 0 | switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, |
6085 | 0 | PreNarrowingType)) { |
6086 | 0 | case NK_Dependent_Narrowing: |
6087 | | // Implicit conversion to a narrower type, but the expression is |
6088 | | // value-dependent so we can't tell whether it's actually narrowing. |
6089 | 0 | case NK_Variable_Narrowing: |
6090 | | // Implicit conversion to a narrower type, and the value is not a constant |
6091 | | // expression. We'll diagnose this in a moment. |
6092 | 0 | case NK_Not_Narrowing: |
6093 | 0 | break; |
6094 | | |
6095 | 0 | case NK_Constant_Narrowing: |
6096 | 0 | if (CCE == Sema::CCEK_ArrayBound && |
6097 | 0 | PreNarrowingType->isIntegralOrEnumerationType() && |
6098 | 0 | PreNarrowingValue.isInt()) { |
6099 | | // Don't diagnose array bound narrowing here; we produce more precise |
6100 | | // errors by allowing the un-narrowed value through. |
6101 | 0 | ReturnPreNarrowingValue = true; |
6102 | 0 | break; |
6103 | 0 | } |
6104 | 0 | S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) |
6105 | 0 | << CCE << /*Constant*/ 1 |
6106 | 0 | << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; |
6107 | 0 | break; |
6108 | | |
6109 | 0 | case NK_Type_Narrowing: |
6110 | | // FIXME: It would be better to diagnose that the expression is not a |
6111 | | // constant expression. |
6112 | 0 | S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) |
6113 | 0 | << CCE << /*Constant*/ 0 << From->getType() << T; |
6114 | 0 | break; |
6115 | 0 | } |
6116 | 0 | if (!ReturnPreNarrowingValue) |
6117 | 0 | PreNarrowingValue = {}; |
6118 | |
|
6119 | 0 | return Result; |
6120 | 0 | } |
6121 | | |
6122 | | /// CheckConvertedConstantExpression - Check that the expression From is a |
6123 | | /// converted constant expression of type T, perform the conversion and produce |
6124 | | /// the converted expression, per C++11 [expr.const]p3. |
6125 | | static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, |
6126 | | QualType T, APValue &Value, |
6127 | | Sema::CCEKind CCE, |
6128 | | bool RequireInt, |
6129 | 1 | NamedDecl *Dest) { |
6130 | | |
6131 | 1 | APValue PreNarrowingValue; |
6132 | 1 | ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest, |
6133 | 1 | PreNarrowingValue); |
6134 | 1 | if (Result.isInvalid() || Result.get()->isValueDependent()) { |
6135 | 1 | Value = APValue(); |
6136 | 1 | return Result; |
6137 | 1 | } |
6138 | 0 | return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE, |
6139 | 0 | RequireInt, PreNarrowingValue); |
6140 | 1 | } |
6141 | | |
6142 | | ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T, |
6143 | | CCEKind CCE, |
6144 | 0 | NamedDecl *Dest) { |
6145 | 0 | APValue PreNarrowingValue; |
6146 | 0 | return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest, |
6147 | 0 | PreNarrowingValue); |
6148 | 0 | } |
6149 | | |
6150 | | ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, |
6151 | | APValue &Value, CCEKind CCE, |
6152 | 0 | NamedDecl *Dest) { |
6153 | 0 | return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false, |
6154 | 0 | Dest); |
6155 | 0 | } |
6156 | | |
6157 | | ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, |
6158 | | llvm::APSInt &Value, |
6159 | 1 | CCEKind CCE) { |
6160 | 1 | assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); |
6161 | | |
6162 | 0 | APValue V; |
6163 | 1 | auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true, |
6164 | 1 | /*Dest=*/nullptr); |
6165 | 1 | if (!R.isInvalid() && !R.get()->isValueDependent()) |
6166 | 0 | Value = V.getInt(); |
6167 | 1 | return R; |
6168 | 1 | } |
6169 | | |
6170 | | /// EvaluateConvertedConstantExpression - Evaluate an Expression |
6171 | | /// That is a converted constant expression |
6172 | | /// (which was built with BuildConvertedConstantExpression) |
6173 | | ExprResult |
6174 | | Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value, |
6175 | | Sema::CCEKind CCE, bool RequireInt, |
6176 | 0 | const APValue &PreNarrowingValue) { |
6177 | |
|
6178 | 0 | ExprResult Result = E; |
6179 | | // Check the expression is a constant expression. |
6180 | 0 | SmallVector<PartialDiagnosticAt, 8> Notes; |
6181 | 0 | Expr::EvalResult Eval; |
6182 | 0 | Eval.Diag = &Notes; |
6183 | |
|
6184 | 0 | ConstantExprKind Kind; |
6185 | 0 | if (CCE == Sema::CCEK_TemplateArg && T->isRecordType()) |
6186 | 0 | Kind = ConstantExprKind::ClassTemplateArgument; |
6187 | 0 | else if (CCE == Sema::CCEK_TemplateArg) |
6188 | 0 | Kind = ConstantExprKind::NonClassTemplateArgument; |
6189 | 0 | else |
6190 | 0 | Kind = ConstantExprKind::Normal; |
6191 | |
|
6192 | 0 | if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) || |
6193 | 0 | (RequireInt && !Eval.Val.isInt())) { |
6194 | | // The expression can't be folded, so we can't keep it at this position in |
6195 | | // the AST. |
6196 | 0 | Result = ExprError(); |
6197 | 0 | } else { |
6198 | 0 | Value = Eval.Val; |
6199 | |
|
6200 | 0 | if (Notes.empty()) { |
6201 | | // It's a constant expression. |
6202 | 0 | Expr *E = ConstantExpr::Create(Context, Result.get(), Value); |
6203 | 0 | if (!PreNarrowingValue.isAbsent()) |
6204 | 0 | Value = std::move(PreNarrowingValue); |
6205 | 0 | return E; |
6206 | 0 | } |
6207 | 0 | } |
6208 | | |
6209 | | // It's not a constant expression. Produce an appropriate diagnostic. |
6210 | 0 | if (Notes.size() == 1 && |
6211 | 0 | Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) { |
6212 | 0 | Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; |
6213 | 0 | } else if (!Notes.empty() && Notes[0].second.getDiagID() == |
6214 | 0 | diag::note_constexpr_invalid_template_arg) { |
6215 | 0 | Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg); |
6216 | 0 | for (unsigned I = 0; I < Notes.size(); ++I) |
6217 | 0 | Diag(Notes[I].first, Notes[I].second); |
6218 | 0 | } else { |
6219 | 0 | Diag(E->getBeginLoc(), diag::err_expr_not_cce) |
6220 | 0 | << CCE << E->getSourceRange(); |
6221 | 0 | for (unsigned I = 0; I < Notes.size(); ++I) |
6222 | 0 | Diag(Notes[I].first, Notes[I].second); |
6223 | 0 | } |
6224 | 0 | return ExprError(); |
6225 | 0 | } |
6226 | | |
6227 | | /// dropPointerConversions - If the given standard conversion sequence |
6228 | | /// involves any pointer conversions, remove them. This may change |
6229 | | /// the result type of the conversion sequence. |
6230 | 0 | static void dropPointerConversion(StandardConversionSequence &SCS) { |
6231 | 0 | if (SCS.Second == ICK_Pointer_Conversion) { |
6232 | 0 | SCS.Second = ICK_Identity; |
6233 | 0 | SCS.Third = ICK_Identity; |
6234 | 0 | SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; |
6235 | 0 | } |
6236 | 0 | } |
6237 | | |
6238 | | /// TryContextuallyConvertToObjCPointer - Attempt to contextually |
6239 | | /// convert the expression From to an Objective-C pointer type. |
6240 | | static ImplicitConversionSequence |
6241 | 0 | TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { |
6242 | | // Do an implicit conversion to 'id'. |
6243 | 0 | QualType Ty = S.Context.getObjCIdType(); |
6244 | 0 | ImplicitConversionSequence ICS |
6245 | 0 | = TryImplicitConversion(S, From, Ty, |
6246 | | // FIXME: Are these flags correct? |
6247 | 0 | /*SuppressUserConversions=*/false, |
6248 | 0 | AllowedExplicit::Conversions, |
6249 | 0 | /*InOverloadResolution=*/false, |
6250 | 0 | /*CStyle=*/false, |
6251 | 0 | /*AllowObjCWritebackConversion=*/false, |
6252 | 0 | /*AllowObjCConversionOnExplicit=*/true); |
6253 | | |
6254 | | // Strip off any final conversions to 'id'. |
6255 | 0 | switch (ICS.getKind()) { |
6256 | 0 | case ImplicitConversionSequence::BadConversion: |
6257 | 0 | case ImplicitConversionSequence::AmbiguousConversion: |
6258 | 0 | case ImplicitConversionSequence::EllipsisConversion: |
6259 | 0 | case ImplicitConversionSequence::StaticObjectArgumentConversion: |
6260 | 0 | break; |
6261 | | |
6262 | 0 | case ImplicitConversionSequence::UserDefinedConversion: |
6263 | 0 | dropPointerConversion(ICS.UserDefined.After); |
6264 | 0 | break; |
6265 | | |
6266 | 0 | case ImplicitConversionSequence::StandardConversion: |
6267 | 0 | dropPointerConversion(ICS.Standard); |
6268 | 0 | break; |
6269 | 0 | } |
6270 | | |
6271 | 0 | return ICS; |
6272 | 0 | } |
6273 | | |
6274 | | /// PerformContextuallyConvertToObjCPointer - Perform a contextual |
6275 | | /// conversion of the expression From to an Objective-C pointer type. |
6276 | | /// Returns a valid but null ExprResult if no conversion sequence exists. |
6277 | 0 | ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { |
6278 | 0 | if (checkPlaceholderForOverload(*this, From)) |
6279 | 0 | return ExprError(); |
6280 | | |
6281 | 0 | QualType Ty = Context.getObjCIdType(); |
6282 | 0 | ImplicitConversionSequence ICS = |
6283 | 0 | TryContextuallyConvertToObjCPointer(*this, From); |
6284 | 0 | if (!ICS.isBad()) |
6285 | 0 | return PerformImplicitConversion(From, Ty, ICS, AA_Converting); |
6286 | 0 | return ExprResult(); |
6287 | 0 | } |
6288 | | |
6289 | 0 | static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) { |
6290 | 0 | const Expr *Base = nullptr; |
6291 | 0 | assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) && |
6292 | 0 | "expected a member expression"); |
6293 | | |
6294 | 0 | if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE); |
6295 | 0 | M && !M->isImplicitAccess()) |
6296 | 0 | Base = M->getBase(); |
6297 | 0 | else if (const auto M = dyn_cast<MemberExpr>(MemExprE); |
6298 | 0 | M && !M->isImplicitAccess()) |
6299 | 0 | Base = M->getBase(); |
6300 | |
|
6301 | 0 | QualType T = Base ? Base->getType() : S.getCurrentThisType(); |
6302 | |
|
6303 | 0 | if (T->isPointerType()) |
6304 | 0 | T = T->getPointeeType(); |
6305 | |
|
6306 | 0 | return T; |
6307 | 0 | } |
6308 | | |
6309 | | static Expr *GetExplicitObjectExpr(Sema &S, Expr *Obj, |
6310 | 0 | const FunctionDecl *Fun) { |
6311 | 0 | QualType ObjType = Obj->getType(); |
6312 | 0 | if (ObjType->isPointerType()) { |
6313 | 0 | ObjType = ObjType->getPointeeType(); |
6314 | 0 | Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType, |
6315 | 0 | VK_LValue, OK_Ordinary, SourceLocation(), |
6316 | 0 | /*CanOverflow=*/false, FPOptionsOverride()); |
6317 | 0 | } |
6318 | 0 | if (Obj->Classify(S.getASTContext()).isPRValue()) { |
6319 | 0 | Obj = S.CreateMaterializeTemporaryExpr( |
6320 | 0 | ObjType, Obj, |
6321 | 0 | !Fun->getParamDecl(0)->getType()->isRValueReferenceType()); |
6322 | 0 | } |
6323 | 0 | return Obj; |
6324 | 0 | } |
6325 | | |
6326 | | ExprResult Sema::InitializeExplicitObjectArgument(Sema &S, Expr *Obj, |
6327 | 0 | FunctionDecl *Fun) { |
6328 | 0 | Obj = GetExplicitObjectExpr(S, Obj, Fun); |
6329 | 0 | return S.PerformCopyInitialization( |
6330 | 0 | InitializedEntity::InitializeParameter(S.Context, Fun->getParamDecl(0)), |
6331 | 0 | Obj->getExprLoc(), Obj); |
6332 | 0 | } |
6333 | | |
6334 | | static void PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method, |
6335 | | Expr *Object, MultiExprArg &Args, |
6336 | 0 | SmallVectorImpl<Expr *> &NewArgs) { |
6337 | 0 | assert(Method->isExplicitObjectMemberFunction() && |
6338 | 0 | "Method is not an explicit member function"); |
6339 | 0 | assert(NewArgs.empty() && "NewArgs should be empty"); |
6340 | 0 | NewArgs.reserve(Args.size() + 1); |
6341 | 0 | Expr *This = GetExplicitObjectExpr(S, Object, Method); |
6342 | 0 | NewArgs.push_back(This); |
6343 | 0 | NewArgs.append(Args.begin(), Args.end()); |
6344 | 0 | Args = NewArgs; |
6345 | 0 | } |
6346 | | |
6347 | | /// Determine whether the provided type is an integral type, or an enumeration |
6348 | | /// type of a permitted flavor. |
6349 | 2 | bool Sema::ICEConvertDiagnoser::match(QualType T) { |
6350 | 2 | return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() |
6351 | 2 | : T->isIntegralOrUnscopedEnumerationType(); |
6352 | 2 | } |
6353 | | |
6354 | | static ExprResult |
6355 | | diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, |
6356 | | Sema::ContextualImplicitConverter &Converter, |
6357 | 0 | QualType T, UnresolvedSetImpl &ViableConversions) { |
6358 | |
|
6359 | 0 | if (Converter.Suppress) |
6360 | 0 | return ExprError(); |
6361 | | |
6362 | 0 | Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); |
6363 | 0 | for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { |
6364 | 0 | CXXConversionDecl *Conv = |
6365 | 0 | cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); |
6366 | 0 | QualType ConvTy = Conv->getConversionType().getNonReferenceType(); |
6367 | 0 | Converter.noteAmbiguous(SemaRef, Conv, ConvTy); |
6368 | 0 | } |
6369 | 0 | return From; |
6370 | 0 | } |
6371 | | |
6372 | | static bool |
6373 | | diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, |
6374 | | Sema::ContextualImplicitConverter &Converter, |
6375 | | QualType T, bool HadMultipleCandidates, |
6376 | 0 | UnresolvedSetImpl &ExplicitConversions) { |
6377 | 0 | if (ExplicitConversions.size() == 1 && !Converter.Suppress) { |
6378 | 0 | DeclAccessPair Found = ExplicitConversions[0]; |
6379 | 0 | CXXConversionDecl *Conversion = |
6380 | 0 | cast<CXXConversionDecl>(Found->getUnderlyingDecl()); |
6381 | | |
6382 | | // The user probably meant to invoke the given explicit |
6383 | | // conversion; use it. |
6384 | 0 | QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); |
6385 | 0 | std::string TypeStr; |
6386 | 0 | ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); |
6387 | |
|
6388 | 0 | Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) |
6389 | 0 | << FixItHint::CreateInsertion(From->getBeginLoc(), |
6390 | 0 | "static_cast<" + TypeStr + ">(") |
6391 | 0 | << FixItHint::CreateInsertion( |
6392 | 0 | SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); |
6393 | 0 | Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); |
6394 | | |
6395 | | // If we aren't in a SFINAE context, build a call to the |
6396 | | // explicit conversion function. |
6397 | 0 | if (SemaRef.isSFINAEContext()) |
6398 | 0 | return true; |
6399 | | |
6400 | 0 | SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); |
6401 | 0 | ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, |
6402 | 0 | HadMultipleCandidates); |
6403 | 0 | if (Result.isInvalid()) |
6404 | 0 | return true; |
6405 | | // Record usage of conversion in an implicit cast. |
6406 | 0 | From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), |
6407 | 0 | CK_UserDefinedConversion, Result.get(), |
6408 | 0 | nullptr, Result.get()->getValueKind(), |
6409 | 0 | SemaRef.CurFPFeatureOverrides()); |
6410 | 0 | } |
6411 | 0 | return false; |
6412 | 0 | } |
6413 | | |
6414 | | static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, |
6415 | | Sema::ContextualImplicitConverter &Converter, |
6416 | | QualType T, bool HadMultipleCandidates, |
6417 | 0 | DeclAccessPair &Found) { |
6418 | 0 | CXXConversionDecl *Conversion = |
6419 | 0 | cast<CXXConversionDecl>(Found->getUnderlyingDecl()); |
6420 | 0 | SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); |
6421 | |
|
6422 | 0 | QualType ToType = Conversion->getConversionType().getNonReferenceType(); |
6423 | 0 | if (!Converter.SuppressConversion) { |
6424 | 0 | if (SemaRef.isSFINAEContext()) |
6425 | 0 | return true; |
6426 | | |
6427 | 0 | Converter.diagnoseConversion(SemaRef, Loc, T, ToType) |
6428 | 0 | << From->getSourceRange(); |
6429 | 0 | } |
6430 | | |
6431 | 0 | ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, |
6432 | 0 | HadMultipleCandidates); |
6433 | 0 | if (Result.isInvalid()) |
6434 | 0 | return true; |
6435 | | // Record usage of conversion in an implicit cast. |
6436 | 0 | From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), |
6437 | 0 | CK_UserDefinedConversion, Result.get(), |
6438 | 0 | nullptr, Result.get()->getValueKind(), |
6439 | 0 | SemaRef.CurFPFeatureOverrides()); |
6440 | 0 | return false; |
6441 | 0 | } |
6442 | | |
6443 | | static ExprResult finishContextualImplicitConversion( |
6444 | | Sema &SemaRef, SourceLocation Loc, Expr *From, |
6445 | 0 | Sema::ContextualImplicitConverter &Converter) { |
6446 | 0 | if (!Converter.match(From->getType()) && !Converter.Suppress) |
6447 | 0 | Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) |
6448 | 0 | << From->getSourceRange(); |
6449 | |
|
6450 | 0 | return SemaRef.DefaultLvalueConversion(From); |
6451 | 0 | } |
6452 | | |
6453 | | static void |
6454 | | collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, |
6455 | | UnresolvedSetImpl &ViableConversions, |
6456 | 0 | OverloadCandidateSet &CandidateSet) { |
6457 | 0 | for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { |
6458 | 0 | DeclAccessPair FoundDecl = ViableConversions[I]; |
6459 | 0 | NamedDecl *D = FoundDecl.getDecl(); |
6460 | 0 | CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); |
6461 | 0 | if (isa<UsingShadowDecl>(D)) |
6462 | 0 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); |
6463 | |
|
6464 | 0 | CXXConversionDecl *Conv; |
6465 | 0 | FunctionTemplateDecl *ConvTemplate; |
6466 | 0 | if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) |
6467 | 0 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); |
6468 | 0 | else |
6469 | 0 | Conv = cast<CXXConversionDecl>(D); |
6470 | |
|
6471 | 0 | if (ConvTemplate) |
6472 | 0 | SemaRef.AddTemplateConversionCandidate( |
6473 | 0 | ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, |
6474 | 0 | /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); |
6475 | 0 | else |
6476 | 0 | SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, |
6477 | 0 | ToType, CandidateSet, |
6478 | 0 | /*AllowObjCConversionOnExplicit=*/false, |
6479 | 0 | /*AllowExplicit*/ true); |
6480 | 0 | } |
6481 | 0 | } |
6482 | | |
6483 | | /// Attempt to convert the given expression to a type which is accepted |
6484 | | /// by the given converter. |
6485 | | /// |
6486 | | /// This routine will attempt to convert an expression of class type to a |
6487 | | /// type accepted by the specified converter. In C++11 and before, the class |
6488 | | /// must have a single non-explicit conversion function converting to a matching |
6489 | | /// type. In C++1y, there can be multiple such conversion functions, but only |
6490 | | /// one target type. |
6491 | | /// |
6492 | | /// \param Loc The source location of the construct that requires the |
6493 | | /// conversion. |
6494 | | /// |
6495 | | /// \param From The expression we're converting from. |
6496 | | /// |
6497 | | /// \param Converter Used to control and diagnose the conversion process. |
6498 | | /// |
6499 | | /// \returns The expression, converted to an integral or enumeration type if |
6500 | | /// successful. |
6501 | | ExprResult Sema::PerformContextualImplicitConversion( |
6502 | 2 | SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { |
6503 | | // We can't perform any more checking for type-dependent expressions. |
6504 | 2 | if (From->isTypeDependent()) |
6505 | 0 | return From; |
6506 | | |
6507 | | // Process placeholders immediately. |
6508 | 2 | if (From->hasPlaceholderType()) { |
6509 | 0 | ExprResult result = CheckPlaceholderExpr(From); |
6510 | 0 | if (result.isInvalid()) |
6511 | 0 | return result; |
6512 | 0 | From = result.get(); |
6513 | 0 | } |
6514 | | |
6515 | | // Try converting the expression to an Lvalue first, to get rid of qualifiers. |
6516 | 2 | ExprResult Converted = DefaultLvalueConversion(From); |
6517 | 2 | QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType(); |
6518 | | // If the expression already has a matching type, we're golden. |
6519 | 2 | if (Converter.match(T)) |
6520 | 2 | return Converted; |
6521 | | |
6522 | | // FIXME: Check for missing '()' if T is a function type? |
6523 | | |
6524 | | // We can only perform contextual implicit conversions on objects of class |
6525 | | // type. |
6526 | 0 | const RecordType *RecordTy = T->getAs<RecordType>(); |
6527 | 0 | if (!RecordTy || !getLangOpts().CPlusPlus) { |
6528 | 0 | if (!Converter.Suppress) |
6529 | 0 | Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); |
6530 | 0 | return From; |
6531 | 0 | } |
6532 | | |
6533 | | // We must have a complete class type. |
6534 | 0 | struct TypeDiagnoserPartialDiag : TypeDiagnoser { |
6535 | 0 | ContextualImplicitConverter &Converter; |
6536 | 0 | Expr *From; |
6537 | |
|
6538 | 0 | TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) |
6539 | 0 | : Converter(Converter), From(From) {} |
6540 | |
|
6541 | 0 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { |
6542 | 0 | Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); |
6543 | 0 | } |
6544 | 0 | } IncompleteDiagnoser(Converter, From); |
6545 | |
|
6546 | 0 | if (Converter.Suppress ? !isCompleteType(Loc, T) |
6547 | 0 | : RequireCompleteType(Loc, T, IncompleteDiagnoser)) |
6548 | 0 | return From; |
6549 | | |
6550 | | // Look for a conversion to an integral or enumeration type. |
6551 | 0 | UnresolvedSet<4> |
6552 | 0 | ViableConversions; // These are *potentially* viable in C++1y. |
6553 | 0 | UnresolvedSet<4> ExplicitConversions; |
6554 | 0 | const auto &Conversions = |
6555 | 0 | cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); |
6556 | |
|
6557 | 0 | bool HadMultipleCandidates = |
6558 | 0 | (std::distance(Conversions.begin(), Conversions.end()) > 1); |
6559 | | |
6560 | | // To check that there is only one target type, in C++1y: |
6561 | 0 | QualType ToType; |
6562 | 0 | bool HasUniqueTargetType = true; |
6563 | | |
6564 | | // Collect explicit or viable (potentially in C++1y) conversions. |
6565 | 0 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { |
6566 | 0 | NamedDecl *D = (*I)->getUnderlyingDecl(); |
6567 | 0 | CXXConversionDecl *Conversion; |
6568 | 0 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); |
6569 | 0 | if (ConvTemplate) { |
6570 | 0 | if (getLangOpts().CPlusPlus14) |
6571 | 0 | Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); |
6572 | 0 | else |
6573 | 0 | continue; // C++11 does not consider conversion operator templates(?). |
6574 | 0 | } else |
6575 | 0 | Conversion = cast<CXXConversionDecl>(D); |
6576 | | |
6577 | 0 | assert((!ConvTemplate || getLangOpts().CPlusPlus14) && |
6578 | 0 | "Conversion operator templates are considered potentially " |
6579 | 0 | "viable in C++1y"); |
6580 | | |
6581 | 0 | QualType CurToType = Conversion->getConversionType().getNonReferenceType(); |
6582 | 0 | if (Converter.match(CurToType) || ConvTemplate) { |
6583 | |
|
6584 | 0 | if (Conversion->isExplicit()) { |
6585 | | // FIXME: For C++1y, do we need this restriction? |
6586 | | // cf. diagnoseNoViableConversion() |
6587 | 0 | if (!ConvTemplate) |
6588 | 0 | ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); |
6589 | 0 | } else { |
6590 | 0 | if (!ConvTemplate && getLangOpts().CPlusPlus14) { |
6591 | 0 | if (ToType.isNull()) |
6592 | 0 | ToType = CurToType.getUnqualifiedType(); |
6593 | 0 | else if (HasUniqueTargetType && |
6594 | 0 | (CurToType.getUnqualifiedType() != ToType)) |
6595 | 0 | HasUniqueTargetType = false; |
6596 | 0 | } |
6597 | 0 | ViableConversions.addDecl(I.getDecl(), I.getAccess()); |
6598 | 0 | } |
6599 | 0 | } |
6600 | 0 | } |
6601 | |
|
6602 | 0 | if (getLangOpts().CPlusPlus14) { |
6603 | | // C++1y [conv]p6: |
6604 | | // ... An expression e of class type E appearing in such a context |
6605 | | // is said to be contextually implicitly converted to a specified |
6606 | | // type T and is well-formed if and only if e can be implicitly |
6607 | | // converted to a type T that is determined as follows: E is searched |
6608 | | // for conversion functions whose return type is cv T or reference to |
6609 | | // cv T such that T is allowed by the context. There shall be |
6610 | | // exactly one such T. |
6611 | | |
6612 | | // If no unique T is found: |
6613 | 0 | if (ToType.isNull()) { |
6614 | 0 | if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, |
6615 | 0 | HadMultipleCandidates, |
6616 | 0 | ExplicitConversions)) |
6617 | 0 | return ExprError(); |
6618 | 0 | return finishContextualImplicitConversion(*this, Loc, From, Converter); |
6619 | 0 | } |
6620 | | |
6621 | | // If more than one unique Ts are found: |
6622 | 0 | if (!HasUniqueTargetType) |
6623 | 0 | return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, |
6624 | 0 | ViableConversions); |
6625 | | |
6626 | | // If one unique T is found: |
6627 | | // First, build a candidate set from the previously recorded |
6628 | | // potentially viable conversions. |
6629 | 0 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); |
6630 | 0 | collectViableConversionCandidates(*this, From, ToType, ViableConversions, |
6631 | 0 | CandidateSet); |
6632 | | |
6633 | | // Then, perform overload resolution over the candidate set. |
6634 | 0 | OverloadCandidateSet::iterator Best; |
6635 | 0 | switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { |
6636 | 0 | case OR_Success: { |
6637 | | // Apply this conversion. |
6638 | 0 | DeclAccessPair Found = |
6639 | 0 | DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); |
6640 | 0 | if (recordConversion(*this, Loc, From, Converter, T, |
6641 | 0 | HadMultipleCandidates, Found)) |
6642 | 0 | return ExprError(); |
6643 | 0 | break; |
6644 | 0 | } |
6645 | 0 | case OR_Ambiguous: |
6646 | 0 | return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, |
6647 | 0 | ViableConversions); |
6648 | 0 | case OR_No_Viable_Function: |
6649 | 0 | if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, |
6650 | 0 | HadMultipleCandidates, |
6651 | 0 | ExplicitConversions)) |
6652 | 0 | return ExprError(); |
6653 | 0 | [[fallthrough]]; |
6654 | 0 | case OR_Deleted: |
6655 | | // We'll complain below about a non-integral condition type. |
6656 | 0 | break; |
6657 | 0 | } |
6658 | 0 | } else { |
6659 | 0 | switch (ViableConversions.size()) { |
6660 | 0 | case 0: { |
6661 | 0 | if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, |
6662 | 0 | HadMultipleCandidates, |
6663 | 0 | ExplicitConversions)) |
6664 | 0 | return ExprError(); |
6665 | | |
6666 | | // We'll complain below about a non-integral condition type. |
6667 | 0 | break; |
6668 | 0 | } |
6669 | 0 | case 1: { |
6670 | | // Apply this conversion. |
6671 | 0 | DeclAccessPair Found = ViableConversions[0]; |
6672 | 0 | if (recordConversion(*this, Loc, From, Converter, T, |
6673 | 0 | HadMultipleCandidates, Found)) |
6674 | 0 | return ExprError(); |
6675 | 0 | break; |
6676 | 0 | } |
6677 | 0 | default: |
6678 | 0 | return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, |
6679 | 0 | ViableConversions); |
6680 | 0 | } |
6681 | 0 | } |
6682 | | |
6683 | 0 | return finishContextualImplicitConversion(*this, Loc, From, Converter); |
6684 | 0 | } |
6685 | | |
6686 | | /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is |
6687 | | /// an acceptable non-member overloaded operator for a call whose |
6688 | | /// arguments have types T1 (and, if non-empty, T2). This routine |
6689 | | /// implements the check in C++ [over.match.oper]p3b2 concerning |
6690 | | /// enumeration types. |
6691 | | static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, |
6692 | | FunctionDecl *Fn, |
6693 | 0 | ArrayRef<Expr *> Args) { |
6694 | 0 | QualType T1 = Args[0]->getType(); |
6695 | 0 | QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); |
6696 | |
|
6697 | 0 | if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) |
6698 | 0 | return true; |
6699 | | |
6700 | 0 | if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) |
6701 | 0 | return true; |
6702 | | |
6703 | 0 | const auto *Proto = Fn->getType()->castAs<FunctionProtoType>(); |
6704 | 0 | if (Proto->getNumParams() < 1) |
6705 | 0 | return false; |
6706 | | |
6707 | 0 | if (T1->isEnumeralType()) { |
6708 | 0 | QualType ArgType = Proto->getParamType(0).getNonReferenceType(); |
6709 | 0 | if (Context.hasSameUnqualifiedType(T1, ArgType)) |
6710 | 0 | return true; |
6711 | 0 | } |
6712 | | |
6713 | 0 | if (Proto->getNumParams() < 2) |
6714 | 0 | return false; |
6715 | | |
6716 | 0 | if (!T2.isNull() && T2->isEnumeralType()) { |
6717 | 0 | QualType ArgType = Proto->getParamType(1).getNonReferenceType(); |
6718 | 0 | if (Context.hasSameUnqualifiedType(T2, ArgType)) |
6719 | 0 | return true; |
6720 | 0 | } |
6721 | | |
6722 | 0 | return false; |
6723 | 0 | } |
6724 | | |
6725 | | /// AddOverloadCandidate - Adds the given function to the set of |
6726 | | /// candidate functions, using the given function call arguments. If |
6727 | | /// @p SuppressUserConversions, then don't allow user-defined |
6728 | | /// conversions via constructors or conversion operators. |
6729 | | /// |
6730 | | /// \param PartialOverloading true if we are performing "partial" overloading |
6731 | | /// based on an incomplete set of function arguments. This feature is used by |
6732 | | /// code completion. |
6733 | | void Sema::AddOverloadCandidate( |
6734 | | FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, |
6735 | | OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, |
6736 | | bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, |
6737 | | ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, |
6738 | 0 | OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) { |
6739 | 0 | const FunctionProtoType *Proto |
6740 | 0 | = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); |
6741 | 0 | assert(Proto && "Functions without a prototype cannot be overloaded"); |
6742 | 0 | assert(!Function->getDescribedFunctionTemplate() && |
6743 | 0 | "Use AddTemplateOverloadCandidate for function templates"); |
6744 | | |
6745 | 0 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { |
6746 | 0 | if (!isa<CXXConstructorDecl>(Method)) { |
6747 | | // If we get here, it's because we're calling a member function |
6748 | | // that is named without a member access expression (e.g., |
6749 | | // "this->f") that was either written explicitly or created |
6750 | | // implicitly. This can happen with a qualified call to a member |
6751 | | // function, e.g., X::f(). We use an empty type for the implied |
6752 | | // object argument (C++ [over.call.func]p3), and the acting context |
6753 | | // is irrelevant. |
6754 | 0 | AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), |
6755 | 0 | Expr::Classification::makeSimpleLValue(), Args, |
6756 | 0 | CandidateSet, SuppressUserConversions, |
6757 | 0 | PartialOverloading, EarlyConversions, PO); |
6758 | 0 | return; |
6759 | 0 | } |
6760 | | // We treat a constructor like a non-member function, since its object |
6761 | | // argument doesn't participate in overload resolution. |
6762 | 0 | } |
6763 | | |
6764 | 0 | if (!CandidateSet.isNewCandidate(Function, PO)) |
6765 | 0 | return; |
6766 | | |
6767 | | // C++11 [class.copy]p11: [DR1402] |
6768 | | // A defaulted move constructor that is defined as deleted is ignored by |
6769 | | // overload resolution. |
6770 | 0 | CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); |
6771 | 0 | if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && |
6772 | 0 | Constructor->isMoveConstructor()) |
6773 | 0 | return; |
6774 | | |
6775 | | // Overload resolution is always an unevaluated context. |
6776 | 0 | EnterExpressionEvaluationContext Unevaluated( |
6777 | 0 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
6778 | | |
6779 | | // C++ [over.match.oper]p3: |
6780 | | // if no operand has a class type, only those non-member functions in the |
6781 | | // lookup set that have a first parameter of type T1 or "reference to |
6782 | | // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there |
6783 | | // is a right operand) a second parameter of type T2 or "reference to |
6784 | | // (possibly cv-qualified) T2", when T2 is an enumeration type, are |
6785 | | // candidate functions. |
6786 | 0 | if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && |
6787 | 0 | !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) |
6788 | 0 | return; |
6789 | | |
6790 | | // Add this candidate |
6791 | 0 | OverloadCandidate &Candidate = |
6792 | 0 | CandidateSet.addCandidate(Args.size(), EarlyConversions); |
6793 | 0 | Candidate.FoundDecl = FoundDecl; |
6794 | 0 | Candidate.Function = Function; |
6795 | 0 | Candidate.Viable = true; |
6796 | 0 | Candidate.RewriteKind = |
6797 | 0 | CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); |
6798 | 0 | Candidate.IsSurrogate = false; |
6799 | 0 | Candidate.IsADLCandidate = IsADLCandidate; |
6800 | 0 | Candidate.IgnoreObjectArgument = false; |
6801 | 0 | Candidate.ExplicitCallArguments = Args.size(); |
6802 | | |
6803 | | // Explicit functions are not actually candidates at all if we're not |
6804 | | // allowing them in this context, but keep them around so we can point |
6805 | | // to them in diagnostics. |
6806 | 0 | if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) { |
6807 | 0 | Candidate.Viable = false; |
6808 | 0 | Candidate.FailureKind = ovl_fail_explicit; |
6809 | 0 | return; |
6810 | 0 | } |
6811 | | |
6812 | | // Functions with internal linkage are only viable in the same module unit. |
6813 | 0 | if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) { |
6814 | | /// FIXME: Currently, the semantics of linkage in clang is slightly |
6815 | | /// different from the semantics in C++ spec. In C++ spec, only names |
6816 | | /// have linkage. So that all entities of the same should share one |
6817 | | /// linkage. But in clang, different entities of the same could have |
6818 | | /// different linkage. |
6819 | 0 | NamedDecl *ND = Function; |
6820 | 0 | if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) |
6821 | 0 | ND = SpecInfo->getTemplate(); |
6822 | |
|
6823 | 0 | if (ND->getFormalLinkage() == Linkage::Internal) { |
6824 | 0 | Candidate.Viable = false; |
6825 | 0 | Candidate.FailureKind = ovl_fail_module_mismatched; |
6826 | 0 | return; |
6827 | 0 | } |
6828 | 0 | } |
6829 | | |
6830 | 0 | if (Function->isMultiVersion() && |
6831 | 0 | ((Function->hasAttr<TargetAttr>() && |
6832 | 0 | !Function->getAttr<TargetAttr>()->isDefaultVersion()) || |
6833 | 0 | (Function->hasAttr<TargetVersionAttr>() && |
6834 | 0 | !Function->getAttr<TargetVersionAttr>()->isDefaultVersion()))) { |
6835 | 0 | Candidate.Viable = false; |
6836 | 0 | Candidate.FailureKind = ovl_non_default_multiversion_function; |
6837 | 0 | return; |
6838 | 0 | } |
6839 | | |
6840 | 0 | if (Constructor) { |
6841 | | // C++ [class.copy]p3: |
6842 | | // A member function template is never instantiated to perform the copy |
6843 | | // of a class object to an object of its class type. |
6844 | 0 | QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); |
6845 | 0 | if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && |
6846 | 0 | (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || |
6847 | 0 | IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), |
6848 | 0 | ClassType))) { |
6849 | 0 | Candidate.Viable = false; |
6850 | 0 | Candidate.FailureKind = ovl_fail_illegal_constructor; |
6851 | 0 | return; |
6852 | 0 | } |
6853 | | |
6854 | | // C++ [over.match.funcs]p8: (proposed DR resolution) |
6855 | | // A constructor inherited from class type C that has a first parameter |
6856 | | // of type "reference to P" (including such a constructor instantiated |
6857 | | // from a template) is excluded from the set of candidate functions when |
6858 | | // constructing an object of type cv D if the argument list has exactly |
6859 | | // one argument and D is reference-related to P and P is reference-related |
6860 | | // to C. |
6861 | 0 | auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); |
6862 | 0 | if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && |
6863 | 0 | Constructor->getParamDecl(0)->getType()->isReferenceType()) { |
6864 | 0 | QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); |
6865 | 0 | QualType C = Context.getRecordType(Constructor->getParent()); |
6866 | 0 | QualType D = Context.getRecordType(Shadow->getParent()); |
6867 | 0 | SourceLocation Loc = Args.front()->getExprLoc(); |
6868 | 0 | if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && |
6869 | 0 | (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { |
6870 | 0 | Candidate.Viable = false; |
6871 | 0 | Candidate.FailureKind = ovl_fail_inhctor_slice; |
6872 | 0 | return; |
6873 | 0 | } |
6874 | 0 | } |
6875 | | |
6876 | | // Check that the constructor is capable of constructing an object in the |
6877 | | // destination address space. |
6878 | 0 | if (!Qualifiers::isAddressSpaceSupersetOf( |
6879 | 0 | Constructor->getMethodQualifiers().getAddressSpace(), |
6880 | 0 | CandidateSet.getDestAS())) { |
6881 | 0 | Candidate.Viable = false; |
6882 | 0 | Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; |
6883 | 0 | } |
6884 | 0 | } |
6885 | | |
6886 | 0 | unsigned NumParams = Proto->getNumParams(); |
6887 | | |
6888 | | // (C++ 13.3.2p2): A candidate function having fewer than m |
6889 | | // parameters is viable only if it has an ellipsis in its parameter |
6890 | | // list (8.3.5). |
6891 | 0 | if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && |
6892 | 0 | !Proto->isVariadic() && |
6893 | 0 | shouldEnforceArgLimit(PartialOverloading, Function)) { |
6894 | 0 | Candidate.Viable = false; |
6895 | 0 | Candidate.FailureKind = ovl_fail_too_many_arguments; |
6896 | 0 | return; |
6897 | 0 | } |
6898 | | |
6899 | | // (C++ 13.3.2p2): A candidate function having more than m parameters |
6900 | | // is viable only if the (m+1)st parameter has a default argument |
6901 | | // (8.3.6). For the purposes of overload resolution, the |
6902 | | // parameter list is truncated on the right, so that there are |
6903 | | // exactly m parameters. |
6904 | 0 | unsigned MinRequiredArgs = Function->getMinRequiredArguments(); |
6905 | 0 | if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs && |
6906 | 0 | !PartialOverloading) { |
6907 | | // Not enough arguments. |
6908 | 0 | Candidate.Viable = false; |
6909 | 0 | Candidate.FailureKind = ovl_fail_too_few_arguments; |
6910 | 0 | return; |
6911 | 0 | } |
6912 | | |
6913 | | // (CUDA B.1): Check for invalid calls between targets. |
6914 | 0 | if (getLangOpts().CUDA) { |
6915 | 0 | const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true); |
6916 | | // Skip the check for callers that are implicit members, because in this |
6917 | | // case we may not yet know what the member's target is; the target is |
6918 | | // inferred for the member automatically, based on the bases and fields of |
6919 | | // the class. |
6920 | 0 | if (!(Caller && Caller->isImplicit()) && |
6921 | 0 | !IsAllowedCUDACall(Caller, Function)) { |
6922 | 0 | Candidate.Viable = false; |
6923 | 0 | Candidate.FailureKind = ovl_fail_bad_target; |
6924 | 0 | return; |
6925 | 0 | } |
6926 | 0 | } |
6927 | | |
6928 | 0 | if (Function->getTrailingRequiresClause()) { |
6929 | 0 | ConstraintSatisfaction Satisfaction; |
6930 | 0 | if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {}, |
6931 | 0 | /*ForOverloadResolution*/ true) || |
6932 | 0 | !Satisfaction.IsSatisfied) { |
6933 | 0 | Candidate.Viable = false; |
6934 | 0 | Candidate.FailureKind = ovl_fail_constraints_not_satisfied; |
6935 | 0 | return; |
6936 | 0 | } |
6937 | 0 | } |
6938 | | |
6939 | | // Determine the implicit conversion sequences for each of the |
6940 | | // arguments. |
6941 | 0 | for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { |
6942 | 0 | unsigned ConvIdx = |
6943 | 0 | PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; |
6944 | 0 | if (Candidate.Conversions[ConvIdx].isInitialized()) { |
6945 | | // We already formed a conversion sequence for this parameter during |
6946 | | // template argument deduction. |
6947 | 0 | } else if (ArgIdx < NumParams) { |
6948 | | // (C++ 13.3.2p3): for F to be a viable function, there shall |
6949 | | // exist for each argument an implicit conversion sequence |
6950 | | // (13.3.3.1) that converts that argument to the corresponding |
6951 | | // parameter of F. |
6952 | 0 | QualType ParamType = Proto->getParamType(ArgIdx); |
6953 | 0 | Candidate.Conversions[ConvIdx] = TryCopyInitialization( |
6954 | 0 | *this, Args[ArgIdx], ParamType, SuppressUserConversions, |
6955 | 0 | /*InOverloadResolution=*/true, |
6956 | | /*AllowObjCWritebackConversion=*/ |
6957 | 0 | getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); |
6958 | 0 | if (Candidate.Conversions[ConvIdx].isBad()) { |
6959 | 0 | Candidate.Viable = false; |
6960 | 0 | Candidate.FailureKind = ovl_fail_bad_conversion; |
6961 | 0 | return; |
6962 | 0 | } |
6963 | 0 | } else { |
6964 | | // (C++ 13.3.2p2): For the purposes of overload resolution, any |
6965 | | // argument for which there is no corresponding parameter is |
6966 | | // considered to ""match the ellipsis" (C+ 13.3.3.1.3). |
6967 | 0 | Candidate.Conversions[ConvIdx].setEllipsis(); |
6968 | 0 | } |
6969 | 0 | } |
6970 | | |
6971 | 0 | if (EnableIfAttr *FailedAttr = |
6972 | 0 | CheckEnableIf(Function, CandidateSet.getLocation(), Args)) { |
6973 | 0 | Candidate.Viable = false; |
6974 | 0 | Candidate.FailureKind = ovl_fail_enable_if; |
6975 | 0 | Candidate.DeductionFailure.Data = FailedAttr; |
6976 | 0 | return; |
6977 | 0 | } |
6978 | 0 | } |
6979 | | |
6980 | | ObjCMethodDecl * |
6981 | | Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, |
6982 | 0 | SmallVectorImpl<ObjCMethodDecl *> &Methods) { |
6983 | 0 | if (Methods.size() <= 1) |
6984 | 0 | return nullptr; |
6985 | | |
6986 | 0 | for (unsigned b = 0, e = Methods.size(); b < e; b++) { |
6987 | 0 | bool Match = true; |
6988 | 0 | ObjCMethodDecl *Method = Methods[b]; |
6989 | 0 | unsigned NumNamedArgs = Sel.getNumArgs(); |
6990 | | // Method might have more arguments than selector indicates. This is due |
6991 | | // to addition of c-style arguments in method. |
6992 | 0 | if (Method->param_size() > NumNamedArgs) |
6993 | 0 | NumNamedArgs = Method->param_size(); |
6994 | 0 | if (Args.size() < NumNamedArgs) |
6995 | 0 | continue; |
6996 | | |
6997 | 0 | for (unsigned i = 0; i < NumNamedArgs; i++) { |
6998 | | // We can't do any type-checking on a type-dependent argument. |
6999 | 0 | if (Args[i]->isTypeDependent()) { |
7000 | 0 | Match = false; |
7001 | 0 | break; |
7002 | 0 | } |
7003 | | |
7004 | 0 | ParmVarDecl *param = Method->parameters()[i]; |
7005 | 0 | Expr *argExpr = Args[i]; |
7006 | 0 | assert(argExpr && "SelectBestMethod(): missing expression"); |
7007 | | |
7008 | | // Strip the unbridged-cast placeholder expression off unless it's |
7009 | | // a consumed argument. |
7010 | 0 | if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && |
7011 | 0 | !param->hasAttr<CFConsumedAttr>()) |
7012 | 0 | argExpr = stripARCUnbridgedCast(argExpr); |
7013 | | |
7014 | | // If the parameter is __unknown_anytype, move on to the next method. |
7015 | 0 | if (param->getType() == Context.UnknownAnyTy) { |
7016 | 0 | Match = false; |
7017 | 0 | break; |
7018 | 0 | } |
7019 | | |
7020 | 0 | ImplicitConversionSequence ConversionState |
7021 | 0 | = TryCopyInitialization(*this, argExpr, param->getType(), |
7022 | 0 | /*SuppressUserConversions*/false, |
7023 | 0 | /*InOverloadResolution=*/true, |
7024 | | /*AllowObjCWritebackConversion=*/ |
7025 | 0 | getLangOpts().ObjCAutoRefCount, |
7026 | 0 | /*AllowExplicit*/false); |
7027 | | // This function looks for a reasonably-exact match, so we consider |
7028 | | // incompatible pointer conversions to be a failure here. |
7029 | 0 | if (ConversionState.isBad() || |
7030 | 0 | (ConversionState.isStandard() && |
7031 | 0 | ConversionState.Standard.Second == |
7032 | 0 | ICK_Incompatible_Pointer_Conversion)) { |
7033 | 0 | Match = false; |
7034 | 0 | break; |
7035 | 0 | } |
7036 | 0 | } |
7037 | | // Promote additional arguments to variadic methods. |
7038 | 0 | if (Match && Method->isVariadic()) { |
7039 | 0 | for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { |
7040 | 0 | if (Args[i]->isTypeDependent()) { |
7041 | 0 | Match = false; |
7042 | 0 | break; |
7043 | 0 | } |
7044 | 0 | ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, |
7045 | 0 | nullptr); |
7046 | 0 | if (Arg.isInvalid()) { |
7047 | 0 | Match = false; |
7048 | 0 | break; |
7049 | 0 | } |
7050 | 0 | } |
7051 | 0 | } else { |
7052 | | // Check for extra arguments to non-variadic methods. |
7053 | 0 | if (Args.size() != NumNamedArgs) |
7054 | 0 | Match = false; |
7055 | 0 | else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { |
7056 | | // Special case when selectors have no argument. In this case, select |
7057 | | // one with the most general result type of 'id'. |
7058 | 0 | for (unsigned b = 0, e = Methods.size(); b < e; b++) { |
7059 | 0 | QualType ReturnT = Methods[b]->getReturnType(); |
7060 | 0 | if (ReturnT->isObjCIdType()) |
7061 | 0 | return Methods[b]; |
7062 | 0 | } |
7063 | 0 | } |
7064 | 0 | } |
7065 | | |
7066 | 0 | if (Match) |
7067 | 0 | return Method; |
7068 | 0 | } |
7069 | 0 | return nullptr; |
7070 | 0 | } |
7071 | | |
7072 | | static bool convertArgsForAvailabilityChecks( |
7073 | | Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, |
7074 | | ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, |
7075 | 0 | Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) { |
7076 | 0 | if (ThisArg) { |
7077 | 0 | CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); |
7078 | 0 | assert(!isa<CXXConstructorDecl>(Method) && |
7079 | 0 | "Shouldn't have `this` for ctors!"); |
7080 | 0 | assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); |
7081 | 0 | ExprResult R = S.PerformImplicitObjectArgumentInitialization( |
7082 | 0 | ThisArg, /*Qualifier=*/nullptr, Method, Method); |
7083 | 0 | if (R.isInvalid()) |
7084 | 0 | return false; |
7085 | 0 | ConvertedThis = R.get(); |
7086 | 0 | } else { |
7087 | 0 | if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { |
7088 | 0 | (void)MD; |
7089 | 0 | assert((MissingImplicitThis || MD->isStatic() || |
7090 | 0 | isa<CXXConstructorDecl>(MD)) && |
7091 | 0 | "Expected `this` for non-ctor instance methods"); |
7092 | 0 | } |
7093 | 0 | ConvertedThis = nullptr; |
7094 | 0 | } |
7095 | | |
7096 | | // Ignore any variadic arguments. Converting them is pointless, since the |
7097 | | // user can't refer to them in the function condition. |
7098 | 0 | unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); |
7099 | | |
7100 | | // Convert the arguments. |
7101 | 0 | for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { |
7102 | 0 | ExprResult R; |
7103 | 0 | R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( |
7104 | 0 | S.Context, Function->getParamDecl(I)), |
7105 | 0 | SourceLocation(), Args[I]); |
7106 | |
|
7107 | 0 | if (R.isInvalid()) |
7108 | 0 | return false; |
7109 | | |
7110 | 0 | ConvertedArgs.push_back(R.get()); |
7111 | 0 | } |
7112 | | |
7113 | 0 | if (Trap.hasErrorOccurred()) |
7114 | 0 | return false; |
7115 | | |
7116 | | // Push default arguments if needed. |
7117 | 0 | if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { |
7118 | 0 | for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { |
7119 | 0 | ParmVarDecl *P = Function->getParamDecl(i); |
7120 | 0 | if (!P->hasDefaultArg()) |
7121 | 0 | return false; |
7122 | 0 | ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P); |
7123 | 0 | if (R.isInvalid()) |
7124 | 0 | return false; |
7125 | 0 | ConvertedArgs.push_back(R.get()); |
7126 | 0 | } |
7127 | | |
7128 | 0 | if (Trap.hasErrorOccurred()) |
7129 | 0 | return false; |
7130 | 0 | } |
7131 | 0 | return true; |
7132 | 0 | } |
7133 | | |
7134 | | EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, |
7135 | | SourceLocation CallLoc, |
7136 | | ArrayRef<Expr *> Args, |
7137 | 0 | bool MissingImplicitThis) { |
7138 | 0 | auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); |
7139 | 0 | if (EnableIfAttrs.begin() == EnableIfAttrs.end()) |
7140 | 0 | return nullptr; |
7141 | | |
7142 | 0 | SFINAETrap Trap(*this); |
7143 | 0 | SmallVector<Expr *, 16> ConvertedArgs; |
7144 | | // FIXME: We should look into making enable_if late-parsed. |
7145 | 0 | Expr *DiscardedThis; |
7146 | 0 | if (!convertArgsForAvailabilityChecks( |
7147 | 0 | *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap, |
7148 | 0 | /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) |
7149 | 0 | return *EnableIfAttrs.begin(); |
7150 | | |
7151 | 0 | for (auto *EIA : EnableIfAttrs) { |
7152 | 0 | APValue Result; |
7153 | | // FIXME: This doesn't consider value-dependent cases, because doing so is |
7154 | | // very difficult. Ideally, we should handle them more gracefully. |
7155 | 0 | if (EIA->getCond()->isValueDependent() || |
7156 | 0 | !EIA->getCond()->EvaluateWithSubstitution( |
7157 | 0 | Result, Context, Function, llvm::ArrayRef(ConvertedArgs))) |
7158 | 0 | return EIA; |
7159 | | |
7160 | 0 | if (!Result.isInt() || !Result.getInt().getBoolValue()) |
7161 | 0 | return EIA; |
7162 | 0 | } |
7163 | 0 | return nullptr; |
7164 | 0 | } |
7165 | | |
7166 | | template <typename CheckFn> |
7167 | | static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, |
7168 | | bool ArgDependent, SourceLocation Loc, |
7169 | 59 | CheckFn &&IsSuccessful) { |
7170 | 59 | SmallVector<const DiagnoseIfAttr *, 8> Attrs; |
7171 | 59 | for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { |
7172 | 0 | if (ArgDependent == DIA->getArgDependent()) |
7173 | 0 | Attrs.push_back(DIA); |
7174 | 0 | } |
7175 | | |
7176 | | // Common case: No diagnose_if attributes, so we can quit early. |
7177 | 59 | if (Attrs.empty()) |
7178 | 59 | return false; |
7179 | | |
7180 | 0 | auto WarningBegin = std::stable_partition( |
7181 | 0 | Attrs.begin(), Attrs.end(), |
7182 | 0 | [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); Unexecuted instantiation: SemaOverload.cpp:diagnoseDiagnoseIfAttrsWith<clang::Sema::diagnoseArgDependentDiagnoseIfAttrs(clang::FunctionDecl const*, clang::Expr const*, llvm::ArrayRef<clang::Expr const*>, clang::SourceLocation)::$_1>(clang::Sema&, clang::NamedDecl const*, bool, clang::SourceLocation, clang::Sema::diagnoseArgDependentDiagnoseIfAttrs(clang::FunctionDecl const*, clang::Expr const*, llvm::ArrayRef<clang::Expr const*>, clang::SourceLocation)::$_1&&)::{lambda(clang::DiagnoseIfAttr const*)#1}::operator()(clang::DiagnoseIfAttr const*) const Unexecuted instantiation: SemaOverload.cpp:diagnoseDiagnoseIfAttrsWith<clang::Sema::diagnoseArgIndependentDiagnoseIfAttrs(clang::NamedDecl const*, clang::SourceLocation)::$_2>(clang::Sema&, clang::NamedDecl const*, bool, clang::SourceLocation, clang::Sema::diagnoseArgIndependentDiagnoseIfAttrs(clang::NamedDecl const*, clang::SourceLocation)::$_2&&)::{lambda(clang::DiagnoseIfAttr const*)#1}::operator()(clang::DiagnoseIfAttr const*) const |
7183 | | |
7184 | | // Note that diagnose_if attributes are late-parsed, so they appear in the |
7185 | | // correct order (unlike enable_if attributes). |
7186 | 0 | auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), |
7187 | 0 | IsSuccessful); |
7188 | 0 | if (ErrAttr != WarningBegin) { |
7189 | 0 | const DiagnoseIfAttr *DIA = *ErrAttr; |
7190 | 0 | S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); |
7191 | 0 | S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) |
7192 | 0 | << DIA->getParent() << DIA->getCond()->getSourceRange(); |
7193 | 0 | return true; |
7194 | 0 | } |
7195 | | |
7196 | 0 | for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) |
7197 | 0 | if (IsSuccessful(DIA)) { |
7198 | 0 | S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); |
7199 | 0 | S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) |
7200 | 0 | << DIA->getParent() << DIA->getCond()->getSourceRange(); |
7201 | 0 | } |
7202 | |
|
7203 | 0 | return false; |
7204 | 0 | } Unexecuted instantiation: SemaOverload.cpp:bool diagnoseDiagnoseIfAttrsWith<clang::Sema::diagnoseArgDependentDiagnoseIfAttrs(clang::FunctionDecl const*, clang::Expr const*, llvm::ArrayRef<clang::Expr const*>, clang::SourceLocation)::$_1>(clang::Sema&, clang::NamedDecl const*, bool, clang::SourceLocation, clang::Sema::diagnoseArgDependentDiagnoseIfAttrs(clang::FunctionDecl const*, clang::Expr const*, llvm::ArrayRef<clang::Expr const*>, clang::SourceLocation)::$_1&&) SemaOverload.cpp:bool diagnoseDiagnoseIfAttrsWith<clang::Sema::diagnoseArgIndependentDiagnoseIfAttrs(clang::NamedDecl const*, clang::SourceLocation)::$_2>(clang::Sema&, clang::NamedDecl const*, bool, clang::SourceLocation, clang::Sema::diagnoseArgIndependentDiagnoseIfAttrs(clang::NamedDecl const*, clang::SourceLocation)::$_2&&) Line | Count | Source | 7169 | 59 | CheckFn &&IsSuccessful) { | 7170 | 59 | SmallVector<const DiagnoseIfAttr *, 8> Attrs; | 7171 | 59 | for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { | 7172 | 0 | if (ArgDependent == DIA->getArgDependent()) | 7173 | 0 | Attrs.push_back(DIA); | 7174 | 0 | } | 7175 | | | 7176 | | // Common case: No diagnose_if attributes, so we can quit early. | 7177 | 59 | if (Attrs.empty()) | 7178 | 59 | return false; | 7179 | | | 7180 | 0 | auto WarningBegin = std::stable_partition( | 7181 | 0 | Attrs.begin(), Attrs.end(), | 7182 | 0 | [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); | 7183 | | | 7184 | | // Note that diagnose_if attributes are late-parsed, so they appear in the | 7185 | | // correct order (unlike enable_if attributes). | 7186 | 0 | auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), | 7187 | 0 | IsSuccessful); | 7188 | 0 | if (ErrAttr != WarningBegin) { | 7189 | 0 | const DiagnoseIfAttr *DIA = *ErrAttr; | 7190 | 0 | S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); | 7191 | 0 | S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) | 7192 | 0 | << DIA->getParent() << DIA->getCond()->getSourceRange(); | 7193 | 0 | return true; | 7194 | 0 | } | 7195 | | | 7196 | 0 | for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) | 7197 | 0 | if (IsSuccessful(DIA)) { | 7198 | 0 | S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); | 7199 | 0 | S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) | 7200 | 0 | << DIA->getParent() << DIA->getCond()->getSourceRange(); | 7201 | 0 | } | 7202 | |
| 7203 | 0 | return false; | 7204 | 0 | } |
|
7205 | | |
7206 | | bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, |
7207 | | const Expr *ThisArg, |
7208 | | ArrayRef<const Expr *> Args, |
7209 | 0 | SourceLocation Loc) { |
7210 | 0 | return diagnoseDiagnoseIfAttrsWith( |
7211 | 0 | *this, Function, /*ArgDependent=*/true, Loc, |
7212 | 0 | [&](const DiagnoseIfAttr *DIA) { |
7213 | 0 | APValue Result; |
7214 | | // It's sane to use the same Args for any redecl of this function, since |
7215 | | // EvaluateWithSubstitution only cares about the position of each |
7216 | | // argument in the arg list, not the ParmVarDecl* it maps to. |
7217 | 0 | if (!DIA->getCond()->EvaluateWithSubstitution( |
7218 | 0 | Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) |
7219 | 0 | return false; |
7220 | 0 | return Result.isInt() && Result.getInt().getBoolValue(); |
7221 | 0 | }); |
7222 | 0 | } |
7223 | | |
7224 | | bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, |
7225 | 59 | SourceLocation Loc) { |
7226 | 59 | return diagnoseDiagnoseIfAttrsWith( |
7227 | 59 | *this, ND, /*ArgDependent=*/false, Loc, |
7228 | 59 | [&](const DiagnoseIfAttr *DIA) { |
7229 | 0 | bool Result; |
7230 | 0 | return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && |
7231 | 0 | Result; |
7232 | 0 | }); |
7233 | 59 | } |
7234 | | |
7235 | | /// Add all of the function declarations in the given function set to |
7236 | | /// the overload candidate set. |
7237 | | void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, |
7238 | | ArrayRef<Expr *> Args, |
7239 | | OverloadCandidateSet &CandidateSet, |
7240 | | TemplateArgumentListInfo *ExplicitTemplateArgs, |
7241 | | bool SuppressUserConversions, |
7242 | | bool PartialOverloading, |
7243 | 0 | bool FirstArgumentIsBase) { |
7244 | 0 | for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { |
7245 | 0 | NamedDecl *D = F.getDecl()->getUnderlyingDecl(); |
7246 | 0 | ArrayRef<Expr *> FunctionArgs = Args; |
7247 | |
|
7248 | 0 | FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); |
7249 | 0 | FunctionDecl *FD = |
7250 | 0 | FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); |
7251 | |
|
7252 | 0 | if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { |
7253 | 0 | QualType ObjectType; |
7254 | 0 | Expr::Classification ObjectClassification; |
7255 | 0 | if (Args.size() > 0) { |
7256 | 0 | if (Expr *E = Args[0]) { |
7257 | | // Use the explicit base to restrict the lookup: |
7258 | 0 | ObjectType = E->getType(); |
7259 | | // Pointers in the object arguments are implicitly dereferenced, so we |
7260 | | // always classify them as l-values. |
7261 | 0 | if (!ObjectType.isNull() && ObjectType->isPointerType()) |
7262 | 0 | ObjectClassification = Expr::Classification::makeSimpleLValue(); |
7263 | 0 | else |
7264 | 0 | ObjectClassification = E->Classify(Context); |
7265 | 0 | } // .. else there is an implicit base. |
7266 | 0 | FunctionArgs = Args.slice(1); |
7267 | 0 | } |
7268 | 0 | if (FunTmpl) { |
7269 | 0 | AddMethodTemplateCandidate( |
7270 | 0 | FunTmpl, F.getPair(), |
7271 | 0 | cast<CXXRecordDecl>(FunTmpl->getDeclContext()), |
7272 | 0 | ExplicitTemplateArgs, ObjectType, ObjectClassification, |
7273 | 0 | FunctionArgs, CandidateSet, SuppressUserConversions, |
7274 | 0 | PartialOverloading); |
7275 | 0 | } else { |
7276 | 0 | AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), |
7277 | 0 | cast<CXXMethodDecl>(FD)->getParent(), ObjectType, |
7278 | 0 | ObjectClassification, FunctionArgs, CandidateSet, |
7279 | 0 | SuppressUserConversions, PartialOverloading); |
7280 | 0 | } |
7281 | 0 | } else { |
7282 | | // This branch handles both standalone functions and static methods. |
7283 | | |
7284 | | // Slice the first argument (which is the base) when we access |
7285 | | // static method as non-static. |
7286 | 0 | if (Args.size() > 0 && |
7287 | 0 | (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && |
7288 | 0 | !isa<CXXConstructorDecl>(FD)))) { |
7289 | 0 | assert(cast<CXXMethodDecl>(FD)->isStatic()); |
7290 | 0 | FunctionArgs = Args.slice(1); |
7291 | 0 | } |
7292 | 0 | if (FunTmpl) { |
7293 | 0 | AddTemplateOverloadCandidate(FunTmpl, F.getPair(), |
7294 | 0 | ExplicitTemplateArgs, FunctionArgs, |
7295 | 0 | CandidateSet, SuppressUserConversions, |
7296 | 0 | PartialOverloading); |
7297 | 0 | } else { |
7298 | 0 | AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, |
7299 | 0 | SuppressUserConversions, PartialOverloading); |
7300 | 0 | } |
7301 | 0 | } |
7302 | 0 | } |
7303 | 0 | } |
7304 | | |
7305 | | /// AddMethodCandidate - Adds a named decl (which is some kind of |
7306 | | /// method) as a method candidate to the given overload set. |
7307 | | void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, |
7308 | | Expr::Classification ObjectClassification, |
7309 | | ArrayRef<Expr *> Args, |
7310 | | OverloadCandidateSet &CandidateSet, |
7311 | | bool SuppressUserConversions, |
7312 | 0 | OverloadCandidateParamOrder PO) { |
7313 | 0 | NamedDecl *Decl = FoundDecl.getDecl(); |
7314 | 0 | CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); |
7315 | |
|
7316 | 0 | if (isa<UsingShadowDecl>(Decl)) |
7317 | 0 | Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); |
7318 | |
|
7319 | 0 | if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { |
7320 | 0 | assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && |
7321 | 0 | "Expected a member function template"); |
7322 | 0 | AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, |
7323 | 0 | /*ExplicitArgs*/ nullptr, ObjectType, |
7324 | 0 | ObjectClassification, Args, CandidateSet, |
7325 | 0 | SuppressUserConversions, false, PO); |
7326 | 0 | } else { |
7327 | 0 | AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, |
7328 | 0 | ObjectType, ObjectClassification, Args, CandidateSet, |
7329 | 0 | SuppressUserConversions, false, std::nullopt, PO); |
7330 | 0 | } |
7331 | 0 | } |
7332 | | |
7333 | | /// AddMethodCandidate - Adds the given C++ member function to the set |
7334 | | /// of candidate functions, using the given function call arguments |
7335 | | /// and the object argument (@c Object). For example, in a call |
7336 | | /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain |
7337 | | /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't |
7338 | | /// allow user-defined conversions via constructors or conversion |
7339 | | /// operators. |
7340 | | void |
7341 | | Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, |
7342 | | CXXRecordDecl *ActingContext, QualType ObjectType, |
7343 | | Expr::Classification ObjectClassification, |
7344 | | ArrayRef<Expr *> Args, |
7345 | | OverloadCandidateSet &CandidateSet, |
7346 | | bool SuppressUserConversions, |
7347 | | bool PartialOverloading, |
7348 | | ConversionSequenceList EarlyConversions, |
7349 | 0 | OverloadCandidateParamOrder PO) { |
7350 | 0 | const FunctionProtoType *Proto |
7351 | 0 | = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); |
7352 | 0 | assert(Proto && "Methods without a prototype cannot be overloaded"); |
7353 | 0 | assert(!isa<CXXConstructorDecl>(Method) && |
7354 | 0 | "Use AddOverloadCandidate for constructors"); |
7355 | | |
7356 | 0 | if (!CandidateSet.isNewCandidate(Method, PO)) |
7357 | 0 | return; |
7358 | | |
7359 | | // C++11 [class.copy]p23: [DR1402] |
7360 | | // A defaulted move assignment operator that is defined as deleted is |
7361 | | // ignored by overload resolution. |
7362 | 0 | if (Method->isDefaulted() && Method->isDeleted() && |
7363 | 0 | Method->isMoveAssignmentOperator()) |
7364 | 0 | return; |
7365 | | |
7366 | | // Overload resolution is always an unevaluated context. |
7367 | 0 | EnterExpressionEvaluationContext Unevaluated( |
7368 | 0 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
7369 | | |
7370 | | // Add this candidate |
7371 | 0 | OverloadCandidate &Candidate = |
7372 | 0 | CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); |
7373 | 0 | Candidate.FoundDecl = FoundDecl; |
7374 | 0 | Candidate.Function = Method; |
7375 | 0 | Candidate.RewriteKind = |
7376 | 0 | CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); |
7377 | 0 | Candidate.IsSurrogate = false; |
7378 | 0 | Candidate.IgnoreObjectArgument = false; |
7379 | 0 | Candidate.ExplicitCallArguments = Args.size(); |
7380 | |
|
7381 | 0 | unsigned NumParams = Method->getNumExplicitParams(); |
7382 | 0 | unsigned ExplicitOffset = Method->isExplicitObjectMemberFunction() ? 1 : 0; |
7383 | | |
7384 | | // (C++ 13.3.2p2): A candidate function having fewer than m |
7385 | | // parameters is viable only if it has an ellipsis in its parameter |
7386 | | // list (8.3.5). |
7387 | 0 | if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && |
7388 | 0 | !Proto->isVariadic() && |
7389 | 0 | shouldEnforceArgLimit(PartialOverloading, Method)) { |
7390 | 0 | Candidate.Viable = false; |
7391 | 0 | Candidate.FailureKind = ovl_fail_too_many_arguments; |
7392 | 0 | return; |
7393 | 0 | } |
7394 | | |
7395 | | // (C++ 13.3.2p2): A candidate function having more than m parameters |
7396 | | // is viable only if the (m+1)st parameter has a default argument |
7397 | | // (8.3.6). For the purposes of overload resolution, the |
7398 | | // parameter list is truncated on the right, so that there are |
7399 | | // exactly m parameters. |
7400 | 0 | unsigned MinRequiredArgs = Method->getMinRequiredExplicitArguments(); |
7401 | 0 | if (Args.size() < MinRequiredArgs && !PartialOverloading) { |
7402 | | // Not enough arguments. |
7403 | 0 | Candidate.Viable = false; |
7404 | 0 | Candidate.FailureKind = ovl_fail_too_few_arguments; |
7405 | 0 | return; |
7406 | 0 | } |
7407 | | |
7408 | 0 | Candidate.Viable = true; |
7409 | |
|
7410 | 0 | unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; |
7411 | 0 | if (ObjectType.isNull()) |
7412 | 0 | Candidate.IgnoreObjectArgument = true; |
7413 | 0 | else if (Method->isStatic()) { |
7414 | | // [over.best.ics.general]p8 |
7415 | | // When the parameter is the implicit object parameter of a static member |
7416 | | // function, the implicit conversion sequence is a standard conversion |
7417 | | // sequence that is neither better nor worse than any other standard |
7418 | | // conversion sequence. |
7419 | | // |
7420 | | // This is a rule that was introduced in C++23 to support static lambdas. We |
7421 | | // apply it retroactively because we want to support static lambdas as an |
7422 | | // extension and it doesn't hurt previous code. |
7423 | 0 | Candidate.Conversions[FirstConvIdx].setStaticObjectArgument(); |
7424 | 0 | } else { |
7425 | | // Determine the implicit conversion sequence for the object |
7426 | | // parameter. |
7427 | 0 | Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization( |
7428 | 0 | *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, |
7429 | 0 | Method, ActingContext, /*InOverloadResolution=*/true); |
7430 | 0 | if (Candidate.Conversions[FirstConvIdx].isBad()) { |
7431 | 0 | Candidate.Viable = false; |
7432 | 0 | Candidate.FailureKind = ovl_fail_bad_conversion; |
7433 | 0 | return; |
7434 | 0 | } |
7435 | 0 | } |
7436 | | |
7437 | | // (CUDA B.1): Check for invalid calls between targets. |
7438 | 0 | if (getLangOpts().CUDA) |
7439 | 0 | if (!IsAllowedCUDACall(getCurFunctionDecl(/*AllowLambda=*/true), Method)) { |
7440 | 0 | Candidate.Viable = false; |
7441 | 0 | Candidate.FailureKind = ovl_fail_bad_target; |
7442 | 0 | return; |
7443 | 0 | } |
7444 | | |
7445 | 0 | if (Method->getTrailingRequiresClause()) { |
7446 | 0 | ConstraintSatisfaction Satisfaction; |
7447 | 0 | if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {}, |
7448 | 0 | /*ForOverloadResolution*/ true) || |
7449 | 0 | !Satisfaction.IsSatisfied) { |
7450 | 0 | Candidate.Viable = false; |
7451 | 0 | Candidate.FailureKind = ovl_fail_constraints_not_satisfied; |
7452 | 0 | return; |
7453 | 0 | } |
7454 | 0 | } |
7455 | | |
7456 | | // Determine the implicit conversion sequences for each of the |
7457 | | // arguments. |
7458 | 0 | for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { |
7459 | 0 | unsigned ConvIdx = |
7460 | 0 | PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); |
7461 | 0 | if (Candidate.Conversions[ConvIdx].isInitialized()) { |
7462 | | // We already formed a conversion sequence for this parameter during |
7463 | | // template argument deduction. |
7464 | 0 | } else if (ArgIdx < NumParams) { |
7465 | | // (C++ 13.3.2p3): for F to be a viable function, there shall |
7466 | | // exist for each argument an implicit conversion sequence |
7467 | | // (13.3.3.1) that converts that argument to the corresponding |
7468 | | // parameter of F. |
7469 | 0 | QualType ParamType = Proto->getParamType(ArgIdx + ExplicitOffset); |
7470 | 0 | Candidate.Conversions[ConvIdx] |
7471 | 0 | = TryCopyInitialization(*this, Args[ArgIdx], ParamType, |
7472 | 0 | SuppressUserConversions, |
7473 | 0 | /*InOverloadResolution=*/true, |
7474 | | /*AllowObjCWritebackConversion=*/ |
7475 | 0 | getLangOpts().ObjCAutoRefCount); |
7476 | 0 | if (Candidate.Conversions[ConvIdx].isBad()) { |
7477 | 0 | Candidate.Viable = false; |
7478 | 0 | Candidate.FailureKind = ovl_fail_bad_conversion; |
7479 | 0 | return; |
7480 | 0 | } |
7481 | 0 | } else { |
7482 | | // (C++ 13.3.2p2): For the purposes of overload resolution, any |
7483 | | // argument for which there is no corresponding parameter is |
7484 | | // considered to "match the ellipsis" (C+ 13.3.3.1.3). |
7485 | 0 | Candidate.Conversions[ConvIdx].setEllipsis(); |
7486 | 0 | } |
7487 | 0 | } |
7488 | | |
7489 | 0 | if (EnableIfAttr *FailedAttr = |
7490 | 0 | CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) { |
7491 | 0 | Candidate.Viable = false; |
7492 | 0 | Candidate.FailureKind = ovl_fail_enable_if; |
7493 | 0 | Candidate.DeductionFailure.Data = FailedAttr; |
7494 | 0 | return; |
7495 | 0 | } |
7496 | | |
7497 | 0 | if (Method->isMultiVersion() && |
7498 | 0 | ((Method->hasAttr<TargetAttr>() && |
7499 | 0 | !Method->getAttr<TargetAttr>()->isDefaultVersion()) || |
7500 | 0 | (Method->hasAttr<TargetVersionAttr>() && |
7501 | 0 | !Method->getAttr<TargetVersionAttr>()->isDefaultVersion()))) { |
7502 | 0 | Candidate.Viable = false; |
7503 | 0 | Candidate.FailureKind = ovl_non_default_multiversion_function; |
7504 | 0 | } |
7505 | 0 | } |
7506 | | |
7507 | | /// Add a C++ member function template as a candidate to the candidate |
7508 | | /// set, using template argument deduction to produce an appropriate member |
7509 | | /// function template specialization. |
7510 | | void Sema::AddMethodTemplateCandidate( |
7511 | | FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, |
7512 | | CXXRecordDecl *ActingContext, |
7513 | | TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, |
7514 | | Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, |
7515 | | OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, |
7516 | 0 | bool PartialOverloading, OverloadCandidateParamOrder PO) { |
7517 | 0 | if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) |
7518 | 0 | return; |
7519 | | |
7520 | | // C++ [over.match.funcs]p7: |
7521 | | // In each case where a candidate is a function template, candidate |
7522 | | // function template specializations are generated using template argument |
7523 | | // deduction (14.8.3, 14.8.2). Those candidates are then handled as |
7524 | | // candidate functions in the usual way.113) A given name can refer to one |
7525 | | // or more function templates and also to a set of overloaded non-template |
7526 | | // functions. In such a case, the candidate functions generated from each |
7527 | | // function template are combined with the set of non-template candidate |
7528 | | // functions. |
7529 | 0 | TemplateDeductionInfo Info(CandidateSet.getLocation()); |
7530 | 0 | FunctionDecl *Specialization = nullptr; |
7531 | 0 | ConversionSequenceList Conversions; |
7532 | 0 | if (TemplateDeductionResult Result = DeduceTemplateArguments( |
7533 | 0 | MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, |
7534 | 0 | PartialOverloading, /*AggregateDeductionCandidate=*/false, ObjectType, |
7535 | 0 | ObjectClassification, [&](ArrayRef<QualType> ParamTypes) { |
7536 | 0 | return CheckNonDependentConversions( |
7537 | 0 | MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, |
7538 | 0 | SuppressUserConversions, ActingContext, ObjectType, |
7539 | 0 | ObjectClassification, PO); |
7540 | 0 | })) { |
7541 | 0 | OverloadCandidate &Candidate = |
7542 | 0 | CandidateSet.addCandidate(Conversions.size(), Conversions); |
7543 | 0 | Candidate.FoundDecl = FoundDecl; |
7544 | 0 | Candidate.Function = MethodTmpl->getTemplatedDecl(); |
7545 | 0 | Candidate.Viable = false; |
7546 | 0 | Candidate.RewriteKind = |
7547 | 0 | CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); |
7548 | 0 | Candidate.IsSurrogate = false; |
7549 | 0 | Candidate.IgnoreObjectArgument = |
7550 | 0 | cast<CXXMethodDecl>(Candidate.Function)->isStatic() || |
7551 | 0 | ObjectType.isNull(); |
7552 | 0 | Candidate.ExplicitCallArguments = Args.size(); |
7553 | 0 | if (Result == TDK_NonDependentConversionFailure) |
7554 | 0 | Candidate.FailureKind = ovl_fail_bad_conversion; |
7555 | 0 | else { |
7556 | 0 | Candidate.FailureKind = ovl_fail_bad_deduction; |
7557 | 0 | Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, |
7558 | 0 | Info); |
7559 | 0 | } |
7560 | 0 | return; |
7561 | 0 | } |
7562 | | |
7563 | | // Add the function template specialization produced by template argument |
7564 | | // deduction as a candidate. |
7565 | 0 | assert(Specialization && "Missing member function template specialization?"); |
7566 | 0 | assert(isa<CXXMethodDecl>(Specialization) && |
7567 | 0 | "Specialization is not a member function?"); |
7568 | 0 | AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, |
7569 | 0 | ActingContext, ObjectType, ObjectClassification, Args, |
7570 | 0 | CandidateSet, SuppressUserConversions, PartialOverloading, |
7571 | 0 | Conversions, PO); |
7572 | 0 | } |
7573 | | |
7574 | | /// Determine whether a given function template has a simple explicit specifier |
7575 | | /// or a non-value-dependent explicit-specification that evaluates to true. |
7576 | 0 | static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) { |
7577 | 0 | return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit(); |
7578 | 0 | } |
7579 | | |
7580 | | /// Add a C++ function template specialization as a candidate |
7581 | | /// in the candidate set, using template argument deduction to produce |
7582 | | /// an appropriate function template specialization. |
7583 | | void Sema::AddTemplateOverloadCandidate( |
7584 | | FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, |
7585 | | TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, |
7586 | | OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, |
7587 | | bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, |
7588 | 0 | OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) { |
7589 | 0 | if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) |
7590 | 0 | return; |
7591 | | |
7592 | | // If the function template has a non-dependent explicit specification, |
7593 | | // exclude it now if appropriate; we are not permitted to perform deduction |
7594 | | // and substitution in this case. |
7595 | 0 | if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { |
7596 | 0 | OverloadCandidate &Candidate = CandidateSet.addCandidate(); |
7597 | 0 | Candidate.FoundDecl = FoundDecl; |
7598 | 0 | Candidate.Function = FunctionTemplate->getTemplatedDecl(); |
7599 | 0 | Candidate.Viable = false; |
7600 | 0 | Candidate.FailureKind = ovl_fail_explicit; |
7601 | 0 | return; |
7602 | 0 | } |
7603 | | |
7604 | | // C++ [over.match.funcs]p7: |
7605 | | // In each case where a candidate is a function template, candidate |
7606 | | // function template specializations are generated using template argument |
7607 | | // deduction (14.8.3, 14.8.2). Those candidates are then handled as |
7608 | | // candidate functions in the usual way.113) A given name can refer to one |
7609 | | // or more function templates and also to a set of overloaded non-template |
7610 | | // functions. In such a case, the candidate functions generated from each |
7611 | | // function template are combined with the set of non-template candidate |
7612 | | // functions. |
7613 | 0 | TemplateDeductionInfo Info(CandidateSet.getLocation()); |
7614 | 0 | FunctionDecl *Specialization = nullptr; |
7615 | 0 | ConversionSequenceList Conversions; |
7616 | 0 | if (TemplateDeductionResult Result = DeduceTemplateArguments( |
7617 | 0 | FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, |
7618 | 0 | PartialOverloading, AggregateCandidateDeduction, |
7619 | 0 | /*ObjectType=*/QualType(), |
7620 | 0 | /*ObjectClassification=*/Expr::Classification(), |
7621 | 0 | [&](ArrayRef<QualType> ParamTypes) { |
7622 | 0 | return CheckNonDependentConversions( |
7623 | 0 | FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, |
7624 | 0 | SuppressUserConversions, nullptr, QualType(), {}, PO); |
7625 | 0 | })) { |
7626 | 0 | OverloadCandidate &Candidate = |
7627 | 0 | CandidateSet.addCandidate(Conversions.size(), Conversions); |
7628 | 0 | Candidate.FoundDecl = FoundDecl; |
7629 | 0 | Candidate.Function = FunctionTemplate->getTemplatedDecl(); |
7630 | 0 | Candidate.Viable = false; |
7631 | 0 | Candidate.RewriteKind = |
7632 | 0 | CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); |
7633 | 0 | Candidate.IsSurrogate = false; |
7634 | 0 | Candidate.IsADLCandidate = IsADLCandidate; |
7635 | | // Ignore the object argument if there is one, since we don't have an object |
7636 | | // type. |
7637 | 0 | Candidate.IgnoreObjectArgument = |
7638 | 0 | isa<CXXMethodDecl>(Candidate.Function) && |
7639 | 0 | !isa<CXXConstructorDecl>(Candidate.Function); |
7640 | 0 | Candidate.ExplicitCallArguments = Args.size(); |
7641 | 0 | if (Result == TDK_NonDependentConversionFailure) |
7642 | 0 | Candidate.FailureKind = ovl_fail_bad_conversion; |
7643 | 0 | else { |
7644 | 0 | Candidate.FailureKind = ovl_fail_bad_deduction; |
7645 | 0 | Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, |
7646 | 0 | Info); |
7647 | 0 | } |
7648 | 0 | return; |
7649 | 0 | } |
7650 | | |
7651 | | // Add the function template specialization produced by template argument |
7652 | | // deduction as a candidate. |
7653 | 0 | assert(Specialization && "Missing function template specialization?"); |
7654 | 0 | AddOverloadCandidate( |
7655 | 0 | Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, |
7656 | 0 | PartialOverloading, AllowExplicit, |
7657 | 0 | /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO, |
7658 | 0 | Info.AggregateDeductionCandidateHasMismatchedArity); |
7659 | 0 | } |
7660 | | |
7661 | | /// Check that implicit conversion sequences can be formed for each argument |
7662 | | /// whose corresponding parameter has a non-dependent type, per DR1391's |
7663 | | /// [temp.deduct.call]p10. |
7664 | | bool Sema::CheckNonDependentConversions( |
7665 | | FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, |
7666 | | ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, |
7667 | | ConversionSequenceList &Conversions, bool SuppressUserConversions, |
7668 | | CXXRecordDecl *ActingContext, QualType ObjectType, |
7669 | 0 | Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { |
7670 | | // FIXME: The cases in which we allow explicit conversions for constructor |
7671 | | // arguments never consider calling a constructor template. It's not clear |
7672 | | // that is correct. |
7673 | 0 | const bool AllowExplicit = false; |
7674 | |
|
7675 | 0 | auto *FD = FunctionTemplate->getTemplatedDecl(); |
7676 | 0 | auto *Method = dyn_cast<CXXMethodDecl>(FD); |
7677 | 0 | bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); |
7678 | 0 | unsigned ThisConversions = HasThisConversion ? 1 : 0; |
7679 | |
|
7680 | 0 | Conversions = |
7681 | 0 | CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); |
7682 | | |
7683 | | // Overload resolution is always an unevaluated context. |
7684 | 0 | EnterExpressionEvaluationContext Unevaluated( |
7685 | 0 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
7686 | | |
7687 | | // For a method call, check the 'this' conversion here too. DR1391 doesn't |
7688 | | // require that, but this check should never result in a hard error, and |
7689 | | // overload resolution is permitted to sidestep instantiations. |
7690 | 0 | if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && |
7691 | 0 | !ObjectType.isNull()) { |
7692 | 0 | unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; |
7693 | 0 | if (!FD->hasCXXExplicitFunctionObjectParameter() || |
7694 | 0 | !ParamTypes[0]->isDependentType()) { |
7695 | 0 | Conversions[ConvIdx] = TryObjectArgumentInitialization( |
7696 | 0 | *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, |
7697 | 0 | Method, ActingContext, /*InOverloadResolution=*/true, |
7698 | 0 | FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0] |
7699 | 0 | : QualType()); |
7700 | 0 | if (Conversions[ConvIdx].isBad()) |
7701 | 0 | return true; |
7702 | 0 | } |
7703 | 0 | } |
7704 | | |
7705 | 0 | unsigned Offset = |
7706 | 0 | Method && Method->hasCXXExplicitFunctionObjectParameter() ? 1 : 0; |
7707 | |
|
7708 | 0 | for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; |
7709 | 0 | ++I) { |
7710 | 0 | QualType ParamType = ParamTypes[I + Offset]; |
7711 | 0 | if (!ParamType->isDependentType()) { |
7712 | 0 | unsigned ConvIdx; |
7713 | 0 | if (PO == OverloadCandidateParamOrder::Reversed) { |
7714 | 0 | ConvIdx = Args.size() - 1 - I; |
7715 | 0 | assert(Args.size() + ThisConversions == 2 && |
7716 | 0 | "number of args (including 'this') must be exactly 2 for " |
7717 | 0 | "reversed order"); |
7718 | | // For members, there would be only one arg 'Args[0]' whose ConvIdx |
7719 | | // would also be 0. 'this' got ConvIdx = 1 previously. |
7720 | 0 | assert(!HasThisConversion || (ConvIdx == 0 && I == 0)); |
7721 | 0 | } else { |
7722 | | // For members, 'this' got ConvIdx = 0 previously. |
7723 | 0 | ConvIdx = ThisConversions + I; |
7724 | 0 | } |
7725 | 0 | Conversions[ConvIdx] |
7726 | 0 | = TryCopyInitialization(*this, Args[I], ParamType, |
7727 | 0 | SuppressUserConversions, |
7728 | 0 | /*InOverloadResolution=*/true, |
7729 | | /*AllowObjCWritebackConversion=*/ |
7730 | 0 | getLangOpts().ObjCAutoRefCount, |
7731 | 0 | AllowExplicit); |
7732 | 0 | if (Conversions[ConvIdx].isBad()) |
7733 | 0 | return true; |
7734 | 0 | } |
7735 | 0 | } |
7736 | | |
7737 | 0 | return false; |
7738 | 0 | } |
7739 | | |
7740 | | /// Determine whether this is an allowable conversion from the result |
7741 | | /// of an explicit conversion operator to the expected type, per C++ |
7742 | | /// [over.match.conv]p1 and [over.match.ref]p1. |
7743 | | /// |
7744 | | /// \param ConvType The return type of the conversion function. |
7745 | | /// |
7746 | | /// \param ToType The type we are converting to. |
7747 | | /// |
7748 | | /// \param AllowObjCPointerConversion Allow a conversion from one |
7749 | | /// Objective-C pointer to another. |
7750 | | /// |
7751 | | /// \returns true if the conversion is allowable, false otherwise. |
7752 | | static bool isAllowableExplicitConversion(Sema &S, |
7753 | | QualType ConvType, QualType ToType, |
7754 | 0 | bool AllowObjCPointerConversion) { |
7755 | 0 | QualType ToNonRefType = ToType.getNonReferenceType(); |
7756 | | |
7757 | | // Easy case: the types are the same. |
7758 | 0 | if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) |
7759 | 0 | return true; |
7760 | | |
7761 | | // Allow qualification conversions. |
7762 | 0 | bool ObjCLifetimeConversion; |
7763 | 0 | if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, |
7764 | 0 | ObjCLifetimeConversion)) |
7765 | 0 | return true; |
7766 | | |
7767 | | // If we're not allowed to consider Objective-C pointer conversions, |
7768 | | // we're done. |
7769 | 0 | if (!AllowObjCPointerConversion) |
7770 | 0 | return false; |
7771 | | |
7772 | | // Is this an Objective-C pointer conversion? |
7773 | 0 | bool IncompatibleObjC = false; |
7774 | 0 | QualType ConvertedType; |
7775 | 0 | return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, |
7776 | 0 | IncompatibleObjC); |
7777 | 0 | } |
7778 | | |
7779 | | /// AddConversionCandidate - Add a C++ conversion function as a |
7780 | | /// candidate in the candidate set (C++ [over.match.conv], |
7781 | | /// C++ [over.match.copy]). From is the expression we're converting from, |
7782 | | /// and ToType is the type that we're eventually trying to convert to |
7783 | | /// (which may or may not be the same type as the type that the |
7784 | | /// conversion function produces). |
7785 | | void Sema::AddConversionCandidate( |
7786 | | CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, |
7787 | | CXXRecordDecl *ActingContext, Expr *From, QualType ToType, |
7788 | | OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, |
7789 | 0 | bool AllowExplicit, bool AllowResultConversion) { |
7790 | 0 | assert(!Conversion->getDescribedFunctionTemplate() && |
7791 | 0 | "Conversion function templates use AddTemplateConversionCandidate"); |
7792 | 0 | QualType ConvType = Conversion->getConversionType().getNonReferenceType(); |
7793 | 0 | if (!CandidateSet.isNewCandidate(Conversion)) |
7794 | 0 | return; |
7795 | | |
7796 | | // If the conversion function has an undeduced return type, trigger its |
7797 | | // deduction now. |
7798 | 0 | if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { |
7799 | 0 | if (DeduceReturnType(Conversion, From->getExprLoc())) |
7800 | 0 | return; |
7801 | 0 | ConvType = Conversion->getConversionType().getNonReferenceType(); |
7802 | 0 | } |
7803 | | |
7804 | | // If we don't allow any conversion of the result type, ignore conversion |
7805 | | // functions that don't convert to exactly (possibly cv-qualified) T. |
7806 | 0 | if (!AllowResultConversion && |
7807 | 0 | !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) |
7808 | 0 | return; |
7809 | | |
7810 | | // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion |
7811 | | // operator is only a candidate if its return type is the target type or |
7812 | | // can be converted to the target type with a qualification conversion. |
7813 | | // |
7814 | | // FIXME: Include such functions in the candidate list and explain why we |
7815 | | // can't select them. |
7816 | 0 | if (Conversion->isExplicit() && |
7817 | 0 | !isAllowableExplicitConversion(*this, ConvType, ToType, |
7818 | 0 | AllowObjCConversionOnExplicit)) |
7819 | 0 | return; |
7820 | | |
7821 | | // Overload resolution is always an unevaluated context. |
7822 | 0 | EnterExpressionEvaluationContext Unevaluated( |
7823 | 0 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
7824 | | |
7825 | | // Add this candidate |
7826 | 0 | OverloadCandidate &Candidate = CandidateSet.addCandidate(1); |
7827 | 0 | Candidate.FoundDecl = FoundDecl; |
7828 | 0 | Candidate.Function = Conversion; |
7829 | 0 | Candidate.IsSurrogate = false; |
7830 | 0 | Candidate.IgnoreObjectArgument = false; |
7831 | 0 | Candidate.FinalConversion.setAsIdentityConversion(); |
7832 | 0 | Candidate.FinalConversion.setFromType(ConvType); |
7833 | 0 | Candidate.FinalConversion.setAllToTypes(ToType); |
7834 | 0 | Candidate.Viable = true; |
7835 | 0 | Candidate.ExplicitCallArguments = 1; |
7836 | | |
7837 | | // Explicit functions are not actually candidates at all if we're not |
7838 | | // allowing them in this context, but keep them around so we can point |
7839 | | // to them in diagnostics. |
7840 | 0 | if (!AllowExplicit && Conversion->isExplicit()) { |
7841 | 0 | Candidate.Viable = false; |
7842 | 0 | Candidate.FailureKind = ovl_fail_explicit; |
7843 | 0 | return; |
7844 | 0 | } |
7845 | | |
7846 | | // C++ [over.match.funcs]p4: |
7847 | | // For conversion functions, the function is considered to be a member of |
7848 | | // the class of the implicit implied object argument for the purpose of |
7849 | | // defining the type of the implicit object parameter. |
7850 | | // |
7851 | | // Determine the implicit conversion sequence for the implicit |
7852 | | // object parameter. |
7853 | 0 | QualType ObjectType = From->getType(); |
7854 | 0 | if (const auto *FromPtrType = ObjectType->getAs<PointerType>()) |
7855 | 0 | ObjectType = FromPtrType->getPointeeType(); |
7856 | 0 | const auto *ConversionContext = |
7857 | 0 | cast<CXXRecordDecl>(ObjectType->castAs<RecordType>()->getDecl()); |
7858 | | |
7859 | | // C++23 [over.best.ics.general] |
7860 | | // However, if the target is [...] |
7861 | | // - the object parameter of a user-defined conversion function |
7862 | | // [...] user-defined conversion sequences are not considered. |
7863 | 0 | Candidate.Conversions[0] = TryObjectArgumentInitialization( |
7864 | 0 | *this, CandidateSet.getLocation(), From->getType(), |
7865 | 0 | From->Classify(Context), Conversion, ConversionContext, |
7866 | 0 | /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(), |
7867 | 0 | /*SuppressUserConversion*/ true); |
7868 | |
|
7869 | 0 | if (Candidate.Conversions[0].isBad()) { |
7870 | 0 | Candidate.Viable = false; |
7871 | 0 | Candidate.FailureKind = ovl_fail_bad_conversion; |
7872 | 0 | return; |
7873 | 0 | } |
7874 | | |
7875 | 0 | if (Conversion->getTrailingRequiresClause()) { |
7876 | 0 | ConstraintSatisfaction Satisfaction; |
7877 | 0 | if (CheckFunctionConstraints(Conversion, Satisfaction) || |
7878 | 0 | !Satisfaction.IsSatisfied) { |
7879 | 0 | Candidate.Viable = false; |
7880 | 0 | Candidate.FailureKind = ovl_fail_constraints_not_satisfied; |
7881 | 0 | return; |
7882 | 0 | } |
7883 | 0 | } |
7884 | | |
7885 | | // We won't go through a user-defined type conversion function to convert a |
7886 | | // derived to base as such conversions are given Conversion Rank. They only |
7887 | | // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] |
7888 | 0 | QualType FromCanon |
7889 | 0 | = Context.getCanonicalType(From->getType().getUnqualifiedType()); |
7890 | 0 | QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); |
7891 | 0 | if (FromCanon == ToCanon || |
7892 | 0 | IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { |
7893 | 0 | Candidate.Viable = false; |
7894 | 0 | Candidate.FailureKind = ovl_fail_trivial_conversion; |
7895 | 0 | return; |
7896 | 0 | } |
7897 | | |
7898 | | // To determine what the conversion from the result of calling the |
7899 | | // conversion function to the type we're eventually trying to |
7900 | | // convert to (ToType), we need to synthesize a call to the |
7901 | | // conversion function and attempt copy initialization from it. This |
7902 | | // makes sure that we get the right semantics with respect to |
7903 | | // lvalues/rvalues and the type. Fortunately, we can allocate this |
7904 | | // call on the stack and we don't need its arguments to be |
7905 | | // well-formed. |
7906 | 0 | DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), |
7907 | 0 | VK_LValue, From->getBeginLoc()); |
7908 | 0 | ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, |
7909 | 0 | Context.getPointerType(Conversion->getType()), |
7910 | 0 | CK_FunctionToPointerDecay, &ConversionRef, |
7911 | 0 | VK_PRValue, FPOptionsOverride()); |
7912 | |
|
7913 | 0 | QualType ConversionType = Conversion->getConversionType(); |
7914 | 0 | if (!isCompleteType(From->getBeginLoc(), ConversionType)) { |
7915 | 0 | Candidate.Viable = false; |
7916 | 0 | Candidate.FailureKind = ovl_fail_bad_final_conversion; |
7917 | 0 | return; |
7918 | 0 | } |
7919 | | |
7920 | 0 | ExprValueKind VK = Expr::getValueKindForType(ConversionType); |
7921 | | |
7922 | | // Note that it is safe to allocate CallExpr on the stack here because |
7923 | | // there are 0 arguments (i.e., nothing is allocated using ASTContext's |
7924 | | // allocator). |
7925 | 0 | QualType CallResultType = ConversionType.getNonLValueExprType(Context); |
7926 | |
|
7927 | 0 | alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; |
7928 | 0 | CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( |
7929 | 0 | Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); |
7930 | |
|
7931 | 0 | ImplicitConversionSequence ICS = |
7932 | 0 | TryCopyInitialization(*this, TheTemporaryCall, ToType, |
7933 | 0 | /*SuppressUserConversions=*/true, |
7934 | 0 | /*InOverloadResolution=*/false, |
7935 | 0 | /*AllowObjCWritebackConversion=*/false); |
7936 | |
|
7937 | 0 | switch (ICS.getKind()) { |
7938 | 0 | case ImplicitConversionSequence::StandardConversion: |
7939 | 0 | Candidate.FinalConversion = ICS.Standard; |
7940 | | |
7941 | | // C++ [over.ics.user]p3: |
7942 | | // If the user-defined conversion is specified by a specialization of a |
7943 | | // conversion function template, the second standard conversion sequence |
7944 | | // shall have exact match rank. |
7945 | 0 | if (Conversion->getPrimaryTemplate() && |
7946 | 0 | GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { |
7947 | 0 | Candidate.Viable = false; |
7948 | 0 | Candidate.FailureKind = ovl_fail_final_conversion_not_exact; |
7949 | 0 | return; |
7950 | 0 | } |
7951 | | |
7952 | | // C++0x [dcl.init.ref]p5: |
7953 | | // In the second case, if the reference is an rvalue reference and |
7954 | | // the second standard conversion sequence of the user-defined |
7955 | | // conversion sequence includes an lvalue-to-rvalue conversion, the |
7956 | | // program is ill-formed. |
7957 | 0 | if (ToType->isRValueReferenceType() && |
7958 | 0 | ICS.Standard.First == ICK_Lvalue_To_Rvalue) { |
7959 | 0 | Candidate.Viable = false; |
7960 | 0 | Candidate.FailureKind = ovl_fail_bad_final_conversion; |
7961 | 0 | return; |
7962 | 0 | } |
7963 | 0 | break; |
7964 | | |
7965 | 0 | case ImplicitConversionSequence::BadConversion: |
7966 | 0 | Candidate.Viable = false; |
7967 | 0 | Candidate.FailureKind = ovl_fail_bad_final_conversion; |
7968 | 0 | return; |
7969 | | |
7970 | 0 | default: |
7971 | 0 | llvm_unreachable( |
7972 | 0 | "Can only end up with a standard conversion sequence or failure"); |
7973 | 0 | } |
7974 | | |
7975 | 0 | if (EnableIfAttr *FailedAttr = |
7976 | 0 | CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) { |
7977 | 0 | Candidate.Viable = false; |
7978 | 0 | Candidate.FailureKind = ovl_fail_enable_if; |
7979 | 0 | Candidate.DeductionFailure.Data = FailedAttr; |
7980 | 0 | return; |
7981 | 0 | } |
7982 | | |
7983 | 0 | if (Conversion->isMultiVersion() && |
7984 | 0 | ((Conversion->hasAttr<TargetAttr>() && |
7985 | 0 | !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) || |
7986 | 0 | (Conversion->hasAttr<TargetVersionAttr>() && |
7987 | 0 | !Conversion->getAttr<TargetVersionAttr>()->isDefaultVersion()))) { |
7988 | 0 | Candidate.Viable = false; |
7989 | 0 | Candidate.FailureKind = ovl_non_default_multiversion_function; |
7990 | 0 | } |
7991 | 0 | } |
7992 | | |
7993 | | /// Adds a conversion function template specialization |
7994 | | /// candidate to the overload set, using template argument deduction |
7995 | | /// to deduce the template arguments of the conversion function |
7996 | | /// template from the type that we are converting to (C++ |
7997 | | /// [temp.deduct.conv]). |
7998 | | void Sema::AddTemplateConversionCandidate( |
7999 | | FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, |
8000 | | CXXRecordDecl *ActingDC, Expr *From, QualType ToType, |
8001 | | OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, |
8002 | 0 | bool AllowExplicit, bool AllowResultConversion) { |
8003 | 0 | assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && |
8004 | 0 | "Only conversion function templates permitted here"); |
8005 | | |
8006 | 0 | if (!CandidateSet.isNewCandidate(FunctionTemplate)) |
8007 | 0 | return; |
8008 | | |
8009 | | // If the function template has a non-dependent explicit specification, |
8010 | | // exclude it now if appropriate; we are not permitted to perform deduction |
8011 | | // and substitution in this case. |
8012 | 0 | if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { |
8013 | 0 | OverloadCandidate &Candidate = CandidateSet.addCandidate(); |
8014 | 0 | Candidate.FoundDecl = FoundDecl; |
8015 | 0 | Candidate.Function = FunctionTemplate->getTemplatedDecl(); |
8016 | 0 | Candidate.Viable = false; |
8017 | 0 | Candidate.FailureKind = ovl_fail_explicit; |
8018 | 0 | return; |
8019 | 0 | } |
8020 | | |
8021 | 0 | QualType ObjectType = From->getType(); |
8022 | 0 | Expr::Classification ObjectClassification = From->Classify(getASTContext()); |
8023 | |
|
8024 | 0 | TemplateDeductionInfo Info(CandidateSet.getLocation()); |
8025 | 0 | CXXConversionDecl *Specialization = nullptr; |
8026 | 0 | if (TemplateDeductionResult Result = DeduceTemplateArguments( |
8027 | 0 | FunctionTemplate, ObjectType, ObjectClassification, ToType, |
8028 | 0 | Specialization, Info)) { |
8029 | 0 | OverloadCandidate &Candidate = CandidateSet.addCandidate(); |
8030 | 0 | Candidate.FoundDecl = FoundDecl; |
8031 | 0 | Candidate.Function = FunctionTemplate->getTemplatedDecl(); |
8032 | 0 | Candidate.Viable = false; |
8033 | 0 | Candidate.FailureKind = ovl_fail_bad_deduction; |
8034 | 0 | Candidate.IsSurrogate = false; |
8035 | 0 | Candidate.IgnoreObjectArgument = false; |
8036 | 0 | Candidate.ExplicitCallArguments = 1; |
8037 | 0 | Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, |
8038 | 0 | Info); |
8039 | 0 | return; |
8040 | 0 | } |
8041 | | |
8042 | | // Add the conversion function template specialization produced by |
8043 | | // template argument deduction as a candidate. |
8044 | 0 | assert(Specialization && "Missing function template specialization?"); |
8045 | 0 | AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, |
8046 | 0 | CandidateSet, AllowObjCConversionOnExplicit, |
8047 | 0 | AllowExplicit, AllowResultConversion); |
8048 | 0 | } |
8049 | | |
8050 | | /// AddSurrogateCandidate - Adds a "surrogate" candidate function that |
8051 | | /// converts the given @c Object to a function pointer via the |
8052 | | /// conversion function @c Conversion, and then attempts to call it |
8053 | | /// with the given arguments (C++ [over.call.object]p2-4). Proto is |
8054 | | /// the type of function that we'll eventually be calling. |
8055 | | void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, |
8056 | | DeclAccessPair FoundDecl, |
8057 | | CXXRecordDecl *ActingContext, |
8058 | | const FunctionProtoType *Proto, |
8059 | | Expr *Object, |
8060 | | ArrayRef<Expr *> Args, |
8061 | 0 | OverloadCandidateSet& CandidateSet) { |
8062 | 0 | if (!CandidateSet.isNewCandidate(Conversion)) |
8063 | 0 | return; |
8064 | | |
8065 | | // Overload resolution is always an unevaluated context. |
8066 | 0 | EnterExpressionEvaluationContext Unevaluated( |
8067 | 0 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
8068 | |
|
8069 | 0 | OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); |
8070 | 0 | Candidate.FoundDecl = FoundDecl; |
8071 | 0 | Candidate.Function = nullptr; |
8072 | 0 | Candidate.Surrogate = Conversion; |
8073 | 0 | Candidate.Viable = true; |
8074 | 0 | Candidate.IsSurrogate = true; |
8075 | 0 | Candidate.IgnoreObjectArgument = false; |
8076 | 0 | Candidate.ExplicitCallArguments = Args.size(); |
8077 | | |
8078 | | // Determine the implicit conversion sequence for the implicit |
8079 | | // object parameter. |
8080 | 0 | ImplicitConversionSequence ObjectInit; |
8081 | 0 | if (Conversion->hasCXXExplicitFunctionObjectParameter()) { |
8082 | 0 | ObjectInit = TryCopyInitialization(*this, Object, |
8083 | 0 | Conversion->getParamDecl(0)->getType(), |
8084 | 0 | /*SuppressUserConversions=*/false, |
8085 | 0 | /*InOverloadResolution=*/true, false); |
8086 | 0 | } else { |
8087 | 0 | ObjectInit = TryObjectArgumentInitialization( |
8088 | 0 | *this, CandidateSet.getLocation(), Object->getType(), |
8089 | 0 | Object->Classify(Context), Conversion, ActingContext); |
8090 | 0 | } |
8091 | |
|
8092 | 0 | if (ObjectInit.isBad()) { |
8093 | 0 | Candidate.Viable = false; |
8094 | 0 | Candidate.FailureKind = ovl_fail_bad_conversion; |
8095 | 0 | Candidate.Conversions[0] = ObjectInit; |
8096 | 0 | return; |
8097 | 0 | } |
8098 | | |
8099 | | // The first conversion is actually a user-defined conversion whose |
8100 | | // first conversion is ObjectInit's standard conversion (which is |
8101 | | // effectively a reference binding). Record it as such. |
8102 | 0 | Candidate.Conversions[0].setUserDefined(); |
8103 | 0 | Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; |
8104 | 0 | Candidate.Conversions[0].UserDefined.EllipsisConversion = false; |
8105 | 0 | Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; |
8106 | 0 | Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; |
8107 | 0 | Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; |
8108 | 0 | Candidate.Conversions[0].UserDefined.After |
8109 | 0 | = Candidate.Conversions[0].UserDefined.Before; |
8110 | 0 | Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); |
8111 | | |
8112 | | // Find the |
8113 | 0 | unsigned NumParams = Proto->getNumParams(); |
8114 | | |
8115 | | // (C++ 13.3.2p2): A candidate function having fewer than m |
8116 | | // parameters is viable only if it has an ellipsis in its parameter |
8117 | | // list (8.3.5). |
8118 | 0 | if (Args.size() > NumParams && !Proto->isVariadic()) { |
8119 | 0 | Candidate.Viable = false; |
8120 | 0 | Candidate.FailureKind = ovl_fail_too_many_arguments; |
8121 | 0 | return; |
8122 | 0 | } |
8123 | | |
8124 | | // Function types don't have any default arguments, so just check if |
8125 | | // we have enough arguments. |
8126 | 0 | if (Args.size() < NumParams) { |
8127 | | // Not enough arguments. |
8128 | 0 | Candidate.Viable = false; |
8129 | 0 | Candidate.FailureKind = ovl_fail_too_few_arguments; |
8130 | 0 | return; |
8131 | 0 | } |
8132 | | |
8133 | | // Determine the implicit conversion sequences for each of the |
8134 | | // arguments. |
8135 | 0 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
8136 | 0 | if (ArgIdx < NumParams) { |
8137 | | // (C++ 13.3.2p3): for F to be a viable function, there shall |
8138 | | // exist for each argument an implicit conversion sequence |
8139 | | // (13.3.3.1) that converts that argument to the corresponding |
8140 | | // parameter of F. |
8141 | 0 | QualType ParamType = Proto->getParamType(ArgIdx); |
8142 | 0 | Candidate.Conversions[ArgIdx + 1] |
8143 | 0 | = TryCopyInitialization(*this, Args[ArgIdx], ParamType, |
8144 | 0 | /*SuppressUserConversions=*/false, |
8145 | 0 | /*InOverloadResolution=*/false, |
8146 | | /*AllowObjCWritebackConversion=*/ |
8147 | 0 | getLangOpts().ObjCAutoRefCount); |
8148 | 0 | if (Candidate.Conversions[ArgIdx + 1].isBad()) { |
8149 | 0 | Candidate.Viable = false; |
8150 | 0 | Candidate.FailureKind = ovl_fail_bad_conversion; |
8151 | 0 | return; |
8152 | 0 | } |
8153 | 0 | } else { |
8154 | | // (C++ 13.3.2p2): For the purposes of overload resolution, any |
8155 | | // argument for which there is no corresponding parameter is |
8156 | | // considered to ""match the ellipsis" (C+ 13.3.3.1.3). |
8157 | 0 | Candidate.Conversions[ArgIdx + 1].setEllipsis(); |
8158 | 0 | } |
8159 | 0 | } |
8160 | | |
8161 | 0 | if (Conversion->getTrailingRequiresClause()) { |
8162 | 0 | ConstraintSatisfaction Satisfaction; |
8163 | 0 | if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {}, |
8164 | 0 | /*ForOverloadResolution*/ true) || |
8165 | 0 | !Satisfaction.IsSatisfied) { |
8166 | 0 | Candidate.Viable = false; |
8167 | 0 | Candidate.FailureKind = ovl_fail_constraints_not_satisfied; |
8168 | 0 | return; |
8169 | 0 | } |
8170 | 0 | } |
8171 | | |
8172 | 0 | if (EnableIfAttr *FailedAttr = |
8173 | 0 | CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) { |
8174 | 0 | Candidate.Viable = false; |
8175 | 0 | Candidate.FailureKind = ovl_fail_enable_if; |
8176 | 0 | Candidate.DeductionFailure.Data = FailedAttr; |
8177 | 0 | return; |
8178 | 0 | } |
8179 | 0 | } |
8180 | | |
8181 | | /// Add all of the non-member operator function declarations in the given |
8182 | | /// function set to the overload candidate set. |
8183 | | void Sema::AddNonMemberOperatorCandidates( |
8184 | | const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, |
8185 | | OverloadCandidateSet &CandidateSet, |
8186 | 0 | TemplateArgumentListInfo *ExplicitTemplateArgs) { |
8187 | 0 | for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { |
8188 | 0 | NamedDecl *D = F.getDecl()->getUnderlyingDecl(); |
8189 | 0 | ArrayRef<Expr *> FunctionArgs = Args; |
8190 | |
|
8191 | 0 | FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); |
8192 | 0 | FunctionDecl *FD = |
8193 | 0 | FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); |
8194 | | |
8195 | | // Don't consider rewritten functions if we're not rewriting. |
8196 | 0 | if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) |
8197 | 0 | continue; |
8198 | | |
8199 | 0 | assert(!isa<CXXMethodDecl>(FD) && |
8200 | 0 | "unqualified operator lookup found a member function"); |
8201 | | |
8202 | 0 | if (FunTmpl) { |
8203 | 0 | AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, |
8204 | 0 | FunctionArgs, CandidateSet); |
8205 | 0 | if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) |
8206 | 0 | AddTemplateOverloadCandidate( |
8207 | 0 | FunTmpl, F.getPair(), ExplicitTemplateArgs, |
8208 | 0 | {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, |
8209 | 0 | true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); |
8210 | 0 | } else { |
8211 | 0 | if (ExplicitTemplateArgs) |
8212 | 0 | continue; |
8213 | 0 | AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); |
8214 | 0 | if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) |
8215 | 0 | AddOverloadCandidate( |
8216 | 0 | FD, F.getPair(), {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, |
8217 | 0 | false, false, true, false, ADLCallKind::NotADL, std::nullopt, |
8218 | 0 | OverloadCandidateParamOrder::Reversed); |
8219 | 0 | } |
8220 | 0 | } |
8221 | 0 | } |
8222 | | |
8223 | | /// Add overload candidates for overloaded operators that are |
8224 | | /// member functions. |
8225 | | /// |
8226 | | /// Add the overloaded operator candidates that are member functions |
8227 | | /// for the operator Op that was used in an operator expression such |
8228 | | /// as "x Op y". , Args/NumArgs provides the operator arguments, and |
8229 | | /// CandidateSet will store the added overload candidates. (C++ |
8230 | | /// [over.match.oper]). |
8231 | | void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, |
8232 | | SourceLocation OpLoc, |
8233 | | ArrayRef<Expr *> Args, |
8234 | | OverloadCandidateSet &CandidateSet, |
8235 | 0 | OverloadCandidateParamOrder PO) { |
8236 | 0 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); |
8237 | | |
8238 | | // C++ [over.match.oper]p3: |
8239 | | // For a unary operator @ with an operand of a type whose |
8240 | | // cv-unqualified version is T1, and for a binary operator @ with |
8241 | | // a left operand of a type whose cv-unqualified version is T1 and |
8242 | | // a right operand of a type whose cv-unqualified version is T2, |
8243 | | // three sets of candidate functions, designated member |
8244 | | // candidates, non-member candidates and built-in candidates, are |
8245 | | // constructed as follows: |
8246 | 0 | QualType T1 = Args[0]->getType(); |
8247 | | |
8248 | | // -- If T1 is a complete class type or a class currently being |
8249 | | // defined, the set of member candidates is the result of the |
8250 | | // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, |
8251 | | // the set of member candidates is empty. |
8252 | 0 | if (const RecordType *T1Rec = T1->getAs<RecordType>()) { |
8253 | | // Complete the type if it can be completed. |
8254 | 0 | if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) |
8255 | 0 | return; |
8256 | | // If the type is neither complete nor being defined, bail out now. |
8257 | 0 | if (!T1Rec->getDecl()->getDefinition()) |
8258 | 0 | return; |
8259 | | |
8260 | 0 | LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); |
8261 | 0 | LookupQualifiedName(Operators, T1Rec->getDecl()); |
8262 | 0 | Operators.suppressAccessDiagnostics(); |
8263 | |
|
8264 | 0 | for (LookupResult::iterator Oper = Operators.begin(), |
8265 | 0 | OperEnd = Operators.end(); |
8266 | 0 | Oper != OperEnd; ++Oper) { |
8267 | 0 | if (Oper->getAsFunction() && |
8268 | 0 | PO == OverloadCandidateParamOrder::Reversed && |
8269 | 0 | !CandidateSet.getRewriteInfo().shouldAddReversed( |
8270 | 0 | *this, {Args[1], Args[0]}, Oper->getAsFunction())) |
8271 | 0 | continue; |
8272 | 0 | AddMethodCandidate(Oper.getPair(), Args[0]->getType(), |
8273 | 0 | Args[0]->Classify(Context), Args.slice(1), |
8274 | 0 | CandidateSet, /*SuppressUserConversion=*/false, PO); |
8275 | 0 | } |
8276 | 0 | } |
8277 | 0 | } |
8278 | | |
8279 | | /// AddBuiltinCandidate - Add a candidate for a built-in |
8280 | | /// operator. ResultTy and ParamTys are the result and parameter types |
8281 | | /// of the built-in candidate, respectively. Args and NumArgs are the |
8282 | | /// arguments being passed to the candidate. IsAssignmentOperator |
8283 | | /// should be true when this built-in candidate is an assignment |
8284 | | /// operator. NumContextualBoolArguments is the number of arguments |
8285 | | /// (at the beginning of the argument list) that will be contextually |
8286 | | /// converted to bool. |
8287 | | void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, |
8288 | | OverloadCandidateSet& CandidateSet, |
8289 | | bool IsAssignmentOperator, |
8290 | 0 | unsigned NumContextualBoolArguments) { |
8291 | | // Overload resolution is always an unevaluated context. |
8292 | 0 | EnterExpressionEvaluationContext Unevaluated( |
8293 | 0 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
8294 | | |
8295 | | // Add this candidate |
8296 | 0 | OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); |
8297 | 0 | Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); |
8298 | 0 | Candidate.Function = nullptr; |
8299 | 0 | Candidate.IsSurrogate = false; |
8300 | 0 | Candidate.IgnoreObjectArgument = false; |
8301 | 0 | std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); |
8302 | | |
8303 | | // Determine the implicit conversion sequences for each of the |
8304 | | // arguments. |
8305 | 0 | Candidate.Viable = true; |
8306 | 0 | Candidate.ExplicitCallArguments = Args.size(); |
8307 | 0 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
8308 | | // C++ [over.match.oper]p4: |
8309 | | // For the built-in assignment operators, conversions of the |
8310 | | // left operand are restricted as follows: |
8311 | | // -- no temporaries are introduced to hold the left operand, and |
8312 | | // -- no user-defined conversions are applied to the left |
8313 | | // operand to achieve a type match with the left-most |
8314 | | // parameter of a built-in candidate. |
8315 | | // |
8316 | | // We block these conversions by turning off user-defined |
8317 | | // conversions, since that is the only way that initialization of |
8318 | | // a reference to a non-class type can occur from something that |
8319 | | // is not of the same type. |
8320 | 0 | if (ArgIdx < NumContextualBoolArguments) { |
8321 | 0 | assert(ParamTys[ArgIdx] == Context.BoolTy && |
8322 | 0 | "Contextual conversion to bool requires bool type"); |
8323 | 0 | Candidate.Conversions[ArgIdx] |
8324 | 0 | = TryContextuallyConvertToBool(*this, Args[ArgIdx]); |
8325 | 0 | } else { |
8326 | 0 | Candidate.Conversions[ArgIdx] |
8327 | 0 | = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], |
8328 | 0 | ArgIdx == 0 && IsAssignmentOperator, |
8329 | 0 | /*InOverloadResolution=*/false, |
8330 | | /*AllowObjCWritebackConversion=*/ |
8331 | 0 | getLangOpts().ObjCAutoRefCount); |
8332 | 0 | } |
8333 | 0 | if (Candidate.Conversions[ArgIdx].isBad()) { |
8334 | 0 | Candidate.Viable = false; |
8335 | 0 | Candidate.FailureKind = ovl_fail_bad_conversion; |
8336 | 0 | break; |
8337 | 0 | } |
8338 | 0 | } |
8339 | 0 | } |
8340 | | |
8341 | | namespace { |
8342 | | |
8343 | | /// BuiltinCandidateTypeSet - A set of types that will be used for the |
8344 | | /// candidate operator functions for built-in operators (C++ |
8345 | | /// [over.built]). The types are separated into pointer types and |
8346 | | /// enumeration types. |
8347 | | class BuiltinCandidateTypeSet { |
8348 | | /// TypeSet - A set of types. |
8349 | | typedef llvm::SmallSetVector<QualType, 8> TypeSet; |
8350 | | |
8351 | | /// PointerTypes - The set of pointer types that will be used in the |
8352 | | /// built-in candidates. |
8353 | | TypeSet PointerTypes; |
8354 | | |
8355 | | /// MemberPointerTypes - The set of member pointer types that will be |
8356 | | /// used in the built-in candidates. |
8357 | | TypeSet MemberPointerTypes; |
8358 | | |
8359 | | /// EnumerationTypes - The set of enumeration types that will be |
8360 | | /// used in the built-in candidates. |
8361 | | TypeSet EnumerationTypes; |
8362 | | |
8363 | | /// The set of vector types that will be used in the built-in |
8364 | | /// candidates. |
8365 | | TypeSet VectorTypes; |
8366 | | |
8367 | | /// The set of matrix types that will be used in the built-in |
8368 | | /// candidates. |
8369 | | TypeSet MatrixTypes; |
8370 | | |
8371 | | /// A flag indicating non-record types are viable candidates |
8372 | | bool HasNonRecordTypes; |
8373 | | |
8374 | | /// A flag indicating whether either arithmetic or enumeration types |
8375 | | /// were present in the candidate set. |
8376 | | bool HasArithmeticOrEnumeralTypes; |
8377 | | |
8378 | | /// A flag indicating whether the nullptr type was present in the |
8379 | | /// candidate set. |
8380 | | bool HasNullPtrType; |
8381 | | |
8382 | | /// Sema - The semantic analysis instance where we are building the |
8383 | | /// candidate type set. |
8384 | | Sema &SemaRef; |
8385 | | |
8386 | | /// Context - The AST context in which we will build the type sets. |
8387 | | ASTContext &Context; |
8388 | | |
8389 | | bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, |
8390 | | const Qualifiers &VisibleQuals); |
8391 | | bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); |
8392 | | |
8393 | | public: |
8394 | | /// iterator - Iterates through the types that are part of the set. |
8395 | | typedef TypeSet::iterator iterator; |
8396 | | |
8397 | | BuiltinCandidateTypeSet(Sema &SemaRef) |
8398 | | : HasNonRecordTypes(false), |
8399 | | HasArithmeticOrEnumeralTypes(false), |
8400 | | HasNullPtrType(false), |
8401 | | SemaRef(SemaRef), |
8402 | 0 | Context(SemaRef.Context) { } |
8403 | | |
8404 | | void AddTypesConvertedFrom(QualType Ty, |
8405 | | SourceLocation Loc, |
8406 | | bool AllowUserConversions, |
8407 | | bool AllowExplicitConversions, |
8408 | | const Qualifiers &VisibleTypeConversionsQuals); |
8409 | | |
8410 | 0 | llvm::iterator_range<iterator> pointer_types() { return PointerTypes; } |
8411 | 0 | llvm::iterator_range<iterator> member_pointer_types() { |
8412 | 0 | return MemberPointerTypes; |
8413 | 0 | } |
8414 | 0 | llvm::iterator_range<iterator> enumeration_types() { |
8415 | 0 | return EnumerationTypes; |
8416 | 0 | } |
8417 | 0 | llvm::iterator_range<iterator> vector_types() { return VectorTypes; } |
8418 | 0 | llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; } |
8419 | | |
8420 | 0 | bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); } |
8421 | 0 | bool hasNonRecordTypes() { return HasNonRecordTypes; } |
8422 | 0 | bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } |
8423 | 0 | bool hasNullPtrType() const { return HasNullPtrType; } |
8424 | | }; |
8425 | | |
8426 | | } // end anonymous namespace |
8427 | | |
8428 | | /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to |
8429 | | /// the set of pointer types along with any more-qualified variants of |
8430 | | /// that type. For example, if @p Ty is "int const *", this routine |
8431 | | /// will add "int const *", "int const volatile *", "int const |
8432 | | /// restrict *", and "int const volatile restrict *" to the set of |
8433 | | /// pointer types. Returns true if the add of @p Ty itself succeeded, |
8434 | | /// false otherwise. |
8435 | | /// |
8436 | | /// FIXME: what to do about extended qualifiers? |
8437 | | bool |
8438 | | BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, |
8439 | 0 | const Qualifiers &VisibleQuals) { |
8440 | | |
8441 | | // Insert this type. |
8442 | 0 | if (!PointerTypes.insert(Ty)) |
8443 | 0 | return false; |
8444 | | |
8445 | 0 | QualType PointeeTy; |
8446 | 0 | const PointerType *PointerTy = Ty->getAs<PointerType>(); |
8447 | 0 | bool buildObjCPtr = false; |
8448 | 0 | if (!PointerTy) { |
8449 | 0 | const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); |
8450 | 0 | PointeeTy = PTy->getPointeeType(); |
8451 | 0 | buildObjCPtr = true; |
8452 | 0 | } else { |
8453 | 0 | PointeeTy = PointerTy->getPointeeType(); |
8454 | 0 | } |
8455 | | |
8456 | | // Don't add qualified variants of arrays. For one, they're not allowed |
8457 | | // (the qualifier would sink to the element type), and for another, the |
8458 | | // only overload situation where it matters is subscript or pointer +- int, |
8459 | | // and those shouldn't have qualifier variants anyway. |
8460 | 0 | if (PointeeTy->isArrayType()) |
8461 | 0 | return true; |
8462 | | |
8463 | 0 | unsigned BaseCVR = PointeeTy.getCVRQualifiers(); |
8464 | 0 | bool hasVolatile = VisibleQuals.hasVolatile(); |
8465 | 0 | bool hasRestrict = VisibleQuals.hasRestrict(); |
8466 | | |
8467 | | // Iterate through all strict supersets of BaseCVR. |
8468 | 0 | for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { |
8469 | 0 | if ((CVR | BaseCVR) != CVR) continue; |
8470 | | // Skip over volatile if no volatile found anywhere in the types. |
8471 | 0 | if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; |
8472 | | |
8473 | | // Skip over restrict if no restrict found anywhere in the types, or if |
8474 | | // the type cannot be restrict-qualified. |
8475 | 0 | if ((CVR & Qualifiers::Restrict) && |
8476 | 0 | (!hasRestrict || |
8477 | 0 | (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) |
8478 | 0 | continue; |
8479 | | |
8480 | | // Build qualified pointee type. |
8481 | 0 | QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); |
8482 | | |
8483 | | // Build qualified pointer type. |
8484 | 0 | QualType QPointerTy; |
8485 | 0 | if (!buildObjCPtr) |
8486 | 0 | QPointerTy = Context.getPointerType(QPointeeTy); |
8487 | 0 | else |
8488 | 0 | QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); |
8489 | | |
8490 | | // Insert qualified pointer type. |
8491 | 0 | PointerTypes.insert(QPointerTy); |
8492 | 0 | } |
8493 | |
|
8494 | 0 | return true; |
8495 | 0 | } |
8496 | | |
8497 | | /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty |
8498 | | /// to the set of pointer types along with any more-qualified variants of |
8499 | | /// that type. For example, if @p Ty is "int const *", this routine |
8500 | | /// will add "int const *", "int const volatile *", "int const |
8501 | | /// restrict *", and "int const volatile restrict *" to the set of |
8502 | | /// pointer types. Returns true if the add of @p Ty itself succeeded, |
8503 | | /// false otherwise. |
8504 | | /// |
8505 | | /// FIXME: what to do about extended qualifiers? |
8506 | | bool |
8507 | | BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( |
8508 | 0 | QualType Ty) { |
8509 | | // Insert this type. |
8510 | 0 | if (!MemberPointerTypes.insert(Ty)) |
8511 | 0 | return false; |
8512 | | |
8513 | 0 | const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); |
8514 | 0 | assert(PointerTy && "type was not a member pointer type!"); |
8515 | | |
8516 | 0 | QualType PointeeTy = PointerTy->getPointeeType(); |
8517 | | // Don't add qualified variants of arrays. For one, they're not allowed |
8518 | | // (the qualifier would sink to the element type), and for another, the |
8519 | | // only overload situation where it matters is subscript or pointer +- int, |
8520 | | // and those shouldn't have qualifier variants anyway. |
8521 | 0 | if (PointeeTy->isArrayType()) |
8522 | 0 | return true; |
8523 | 0 | const Type *ClassTy = PointerTy->getClass(); |
8524 | | |
8525 | | // Iterate through all strict supersets of the pointee type's CVR |
8526 | | // qualifiers. |
8527 | 0 | unsigned BaseCVR = PointeeTy.getCVRQualifiers(); |
8528 | 0 | for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { |
8529 | 0 | if ((CVR | BaseCVR) != CVR) continue; |
8530 | | |
8531 | 0 | QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); |
8532 | 0 | MemberPointerTypes.insert( |
8533 | 0 | Context.getMemberPointerType(QPointeeTy, ClassTy)); |
8534 | 0 | } |
8535 | |
|
8536 | 0 | return true; |
8537 | 0 | } |
8538 | | |
8539 | | /// AddTypesConvertedFrom - Add each of the types to which the type @p |
8540 | | /// Ty can be implicit converted to the given set of @p Types. We're |
8541 | | /// primarily interested in pointer types and enumeration types. We also |
8542 | | /// take member pointer types, for the conditional operator. |
8543 | | /// AllowUserConversions is true if we should look at the conversion |
8544 | | /// functions of a class type, and AllowExplicitConversions if we |
8545 | | /// should also include the explicit conversion functions of a class |
8546 | | /// type. |
8547 | | void |
8548 | | BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, |
8549 | | SourceLocation Loc, |
8550 | | bool AllowUserConversions, |
8551 | | bool AllowExplicitConversions, |
8552 | 0 | const Qualifiers &VisibleQuals) { |
8553 | | // Only deal with canonical types. |
8554 | 0 | Ty = Context.getCanonicalType(Ty); |
8555 | | |
8556 | | // Look through reference types; they aren't part of the type of an |
8557 | | // expression for the purposes of conversions. |
8558 | 0 | if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) |
8559 | 0 | Ty = RefTy->getPointeeType(); |
8560 | | |
8561 | | // If we're dealing with an array type, decay to the pointer. |
8562 | 0 | if (Ty->isArrayType()) |
8563 | 0 | Ty = SemaRef.Context.getArrayDecayedType(Ty); |
8564 | | |
8565 | | // Otherwise, we don't care about qualifiers on the type. |
8566 | 0 | Ty = Ty.getLocalUnqualifiedType(); |
8567 | | |
8568 | | // Flag if we ever add a non-record type. |
8569 | 0 | const RecordType *TyRec = Ty->getAs<RecordType>(); |
8570 | 0 | HasNonRecordTypes = HasNonRecordTypes || !TyRec; |
8571 | | |
8572 | | // Flag if we encounter an arithmetic type. |
8573 | 0 | HasArithmeticOrEnumeralTypes = |
8574 | 0 | HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); |
8575 | |
|
8576 | 0 | if (Ty->isObjCIdType() || Ty->isObjCClassType()) |
8577 | 0 | PointerTypes.insert(Ty); |
8578 | 0 | else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { |
8579 | | // Insert our type, and its more-qualified variants, into the set |
8580 | | // of types. |
8581 | 0 | if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) |
8582 | 0 | return; |
8583 | 0 | } else if (Ty->isMemberPointerType()) { |
8584 | | // Member pointers are far easier, since the pointee can't be converted. |
8585 | 0 | if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) |
8586 | 0 | return; |
8587 | 0 | } else if (Ty->isEnumeralType()) { |
8588 | 0 | HasArithmeticOrEnumeralTypes = true; |
8589 | 0 | EnumerationTypes.insert(Ty); |
8590 | 0 | } else if (Ty->isVectorType()) { |
8591 | | // We treat vector types as arithmetic types in many contexts as an |
8592 | | // extension. |
8593 | 0 | HasArithmeticOrEnumeralTypes = true; |
8594 | 0 | VectorTypes.insert(Ty); |
8595 | 0 | } else if (Ty->isMatrixType()) { |
8596 | | // Similar to vector types, we treat vector types as arithmetic types in |
8597 | | // many contexts as an extension. |
8598 | 0 | HasArithmeticOrEnumeralTypes = true; |
8599 | 0 | MatrixTypes.insert(Ty); |
8600 | 0 | } else if (Ty->isNullPtrType()) { |
8601 | 0 | HasNullPtrType = true; |
8602 | 0 | } else if (AllowUserConversions && TyRec) { |
8603 | | // No conversion functions in incomplete types. |
8604 | 0 | if (!SemaRef.isCompleteType(Loc, Ty)) |
8605 | 0 | return; |
8606 | | |
8607 | 0 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); |
8608 | 0 | for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { |
8609 | 0 | if (isa<UsingShadowDecl>(D)) |
8610 | 0 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); |
8611 | | |
8612 | | // Skip conversion function templates; they don't tell us anything |
8613 | | // about which builtin types we can convert to. |
8614 | 0 | if (isa<FunctionTemplateDecl>(D)) |
8615 | 0 | continue; |
8616 | | |
8617 | 0 | CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); |
8618 | 0 | if (AllowExplicitConversions || !Conv->isExplicit()) { |
8619 | 0 | AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, |
8620 | 0 | VisibleQuals); |
8621 | 0 | } |
8622 | 0 | } |
8623 | 0 | } |
8624 | 0 | } |
8625 | | /// Helper function for adjusting address spaces for the pointer or reference |
8626 | | /// operands of builtin operators depending on the argument. |
8627 | | static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, |
8628 | 0 | Expr *Arg) { |
8629 | 0 | return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); |
8630 | 0 | } |
8631 | | |
8632 | | /// Helper function for AddBuiltinOperatorCandidates() that adds |
8633 | | /// the volatile- and non-volatile-qualified assignment operators for the |
8634 | | /// given type to the candidate set. |
8635 | | static void AddBuiltinAssignmentOperatorCandidates(Sema &S, |
8636 | | QualType T, |
8637 | | ArrayRef<Expr *> Args, |
8638 | 0 | OverloadCandidateSet &CandidateSet) { |
8639 | 0 | QualType ParamTypes[2]; |
8640 | | |
8641 | | // T& operator=(T&, T) |
8642 | 0 | ParamTypes[0] = S.Context.getLValueReferenceType( |
8643 | 0 | AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); |
8644 | 0 | ParamTypes[1] = T; |
8645 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
8646 | 0 | /*IsAssignmentOperator=*/true); |
8647 | |
|
8648 | 0 | if (!S.Context.getCanonicalType(T).isVolatileQualified()) { |
8649 | | // volatile T& operator=(volatile T&, T) |
8650 | 0 | ParamTypes[0] = S.Context.getLValueReferenceType( |
8651 | 0 | AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), |
8652 | 0 | Args[0])); |
8653 | 0 | ParamTypes[1] = T; |
8654 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
8655 | 0 | /*IsAssignmentOperator=*/true); |
8656 | 0 | } |
8657 | 0 | } |
8658 | | |
8659 | | /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, |
8660 | | /// if any, found in visible type conversion functions found in ArgExpr's type. |
8661 | 0 | static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { |
8662 | 0 | Qualifiers VRQuals; |
8663 | 0 | const RecordType *TyRec; |
8664 | 0 | if (const MemberPointerType *RHSMPType = |
8665 | 0 | ArgExpr->getType()->getAs<MemberPointerType>()) |
8666 | 0 | TyRec = RHSMPType->getClass()->getAs<RecordType>(); |
8667 | 0 | else |
8668 | 0 | TyRec = ArgExpr->getType()->getAs<RecordType>(); |
8669 | 0 | if (!TyRec) { |
8670 | | // Just to be safe, assume the worst case. |
8671 | 0 | VRQuals.addVolatile(); |
8672 | 0 | VRQuals.addRestrict(); |
8673 | 0 | return VRQuals; |
8674 | 0 | } |
8675 | | |
8676 | 0 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); |
8677 | 0 | if (!ClassDecl->hasDefinition()) |
8678 | 0 | return VRQuals; |
8679 | | |
8680 | 0 | for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { |
8681 | 0 | if (isa<UsingShadowDecl>(D)) |
8682 | 0 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); |
8683 | 0 | if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { |
8684 | 0 | QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); |
8685 | 0 | if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) |
8686 | 0 | CanTy = ResTypeRef->getPointeeType(); |
8687 | | // Need to go down the pointer/mempointer chain and add qualifiers |
8688 | | // as see them. |
8689 | 0 | bool done = false; |
8690 | 0 | while (!done) { |
8691 | 0 | if (CanTy.isRestrictQualified()) |
8692 | 0 | VRQuals.addRestrict(); |
8693 | 0 | if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) |
8694 | 0 | CanTy = ResTypePtr->getPointeeType(); |
8695 | 0 | else if (const MemberPointerType *ResTypeMPtr = |
8696 | 0 | CanTy->getAs<MemberPointerType>()) |
8697 | 0 | CanTy = ResTypeMPtr->getPointeeType(); |
8698 | 0 | else |
8699 | 0 | done = true; |
8700 | 0 | if (CanTy.isVolatileQualified()) |
8701 | 0 | VRQuals.addVolatile(); |
8702 | 0 | if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) |
8703 | 0 | return VRQuals; |
8704 | 0 | } |
8705 | 0 | } |
8706 | 0 | } |
8707 | 0 | return VRQuals; |
8708 | 0 | } |
8709 | | |
8710 | | // Note: We're currently only handling qualifiers that are meaningful for the |
8711 | | // LHS of compound assignment overloading. |
8712 | | static void forAllQualifierCombinationsImpl( |
8713 | | QualifiersAndAtomic Available, QualifiersAndAtomic Applied, |
8714 | 0 | llvm::function_ref<void(QualifiersAndAtomic)> Callback) { |
8715 | | // _Atomic |
8716 | 0 | if (Available.hasAtomic()) { |
8717 | 0 | Available.removeAtomic(); |
8718 | 0 | forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback); |
8719 | 0 | forAllQualifierCombinationsImpl(Available, Applied, Callback); |
8720 | 0 | return; |
8721 | 0 | } |
8722 | | |
8723 | | // volatile |
8724 | 0 | if (Available.hasVolatile()) { |
8725 | 0 | Available.removeVolatile(); |
8726 | 0 | assert(!Applied.hasVolatile()); |
8727 | 0 | forAllQualifierCombinationsImpl(Available, Applied.withVolatile(), |
8728 | 0 | Callback); |
8729 | 0 | forAllQualifierCombinationsImpl(Available, Applied, Callback); |
8730 | 0 | return; |
8731 | 0 | } |
8732 | | |
8733 | 0 | Callback(Applied); |
8734 | 0 | } |
8735 | | |
8736 | | static void forAllQualifierCombinations( |
8737 | | QualifiersAndAtomic Quals, |
8738 | 0 | llvm::function_ref<void(QualifiersAndAtomic)> Callback) { |
8739 | 0 | return forAllQualifierCombinationsImpl(Quals, QualifiersAndAtomic(), |
8740 | 0 | Callback); |
8741 | 0 | } |
8742 | | |
8743 | | static QualType makeQualifiedLValueReferenceType(QualType Base, |
8744 | | QualifiersAndAtomic Quals, |
8745 | 0 | Sema &S) { |
8746 | 0 | if (Quals.hasAtomic()) |
8747 | 0 | Base = S.Context.getAtomicType(Base); |
8748 | 0 | if (Quals.hasVolatile()) |
8749 | 0 | Base = S.Context.getVolatileType(Base); |
8750 | 0 | return S.Context.getLValueReferenceType(Base); |
8751 | 0 | } |
8752 | | |
8753 | | namespace { |
8754 | | |
8755 | | /// Helper class to manage the addition of builtin operator overload |
8756 | | /// candidates. It provides shared state and utility methods used throughout |
8757 | | /// the process, as well as a helper method to add each group of builtin |
8758 | | /// operator overloads from the standard to a candidate set. |
8759 | | class BuiltinOperatorOverloadBuilder { |
8760 | | // Common instance state available to all overload candidate addition methods. |
8761 | | Sema &S; |
8762 | | ArrayRef<Expr *> Args; |
8763 | | QualifiersAndAtomic VisibleTypeConversionsQuals; |
8764 | | bool HasArithmeticOrEnumeralCandidateType; |
8765 | | SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; |
8766 | | OverloadCandidateSet &CandidateSet; |
8767 | | |
8768 | | static constexpr int ArithmeticTypesCap = 24; |
8769 | | SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; |
8770 | | |
8771 | | // Define some indices used to iterate over the arithmetic types in |
8772 | | // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic |
8773 | | // types are that preserved by promotion (C++ [over.built]p2). |
8774 | | unsigned FirstIntegralType, |
8775 | | LastIntegralType; |
8776 | | unsigned FirstPromotedIntegralType, |
8777 | | LastPromotedIntegralType; |
8778 | | unsigned FirstPromotedArithmeticType, |
8779 | | LastPromotedArithmeticType; |
8780 | | unsigned NumArithmeticTypes; |
8781 | | |
8782 | 0 | void InitArithmeticTypes() { |
8783 | | // Start of promoted types. |
8784 | 0 | FirstPromotedArithmeticType = 0; |
8785 | 0 | ArithmeticTypes.push_back(S.Context.FloatTy); |
8786 | 0 | ArithmeticTypes.push_back(S.Context.DoubleTy); |
8787 | 0 | ArithmeticTypes.push_back(S.Context.LongDoubleTy); |
8788 | 0 | if (S.Context.getTargetInfo().hasFloat128Type()) |
8789 | 0 | ArithmeticTypes.push_back(S.Context.Float128Ty); |
8790 | 0 | if (S.Context.getTargetInfo().hasIbm128Type()) |
8791 | 0 | ArithmeticTypes.push_back(S.Context.Ibm128Ty); |
8792 | | |
8793 | | // Start of integral types. |
8794 | 0 | FirstIntegralType = ArithmeticTypes.size(); |
8795 | 0 | FirstPromotedIntegralType = ArithmeticTypes.size(); |
8796 | 0 | ArithmeticTypes.push_back(S.Context.IntTy); |
8797 | 0 | ArithmeticTypes.push_back(S.Context.LongTy); |
8798 | 0 | ArithmeticTypes.push_back(S.Context.LongLongTy); |
8799 | 0 | if (S.Context.getTargetInfo().hasInt128Type() || |
8800 | 0 | (S.Context.getAuxTargetInfo() && |
8801 | 0 | S.Context.getAuxTargetInfo()->hasInt128Type())) |
8802 | 0 | ArithmeticTypes.push_back(S.Context.Int128Ty); |
8803 | 0 | ArithmeticTypes.push_back(S.Context.UnsignedIntTy); |
8804 | 0 | ArithmeticTypes.push_back(S.Context.UnsignedLongTy); |
8805 | 0 | ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); |
8806 | 0 | if (S.Context.getTargetInfo().hasInt128Type() || |
8807 | 0 | (S.Context.getAuxTargetInfo() && |
8808 | 0 | S.Context.getAuxTargetInfo()->hasInt128Type())) |
8809 | 0 | ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); |
8810 | 0 | LastPromotedIntegralType = ArithmeticTypes.size(); |
8811 | 0 | LastPromotedArithmeticType = ArithmeticTypes.size(); |
8812 | | // End of promoted types. |
8813 | |
|
8814 | 0 | ArithmeticTypes.push_back(S.Context.BoolTy); |
8815 | 0 | ArithmeticTypes.push_back(S.Context.CharTy); |
8816 | 0 | ArithmeticTypes.push_back(S.Context.WCharTy); |
8817 | 0 | if (S.Context.getLangOpts().Char8) |
8818 | 0 | ArithmeticTypes.push_back(S.Context.Char8Ty); |
8819 | 0 | ArithmeticTypes.push_back(S.Context.Char16Ty); |
8820 | 0 | ArithmeticTypes.push_back(S.Context.Char32Ty); |
8821 | 0 | ArithmeticTypes.push_back(S.Context.SignedCharTy); |
8822 | 0 | ArithmeticTypes.push_back(S.Context.ShortTy); |
8823 | 0 | ArithmeticTypes.push_back(S.Context.UnsignedCharTy); |
8824 | 0 | ArithmeticTypes.push_back(S.Context.UnsignedShortTy); |
8825 | 0 | LastIntegralType = ArithmeticTypes.size(); |
8826 | 0 | NumArithmeticTypes = ArithmeticTypes.size(); |
8827 | | // End of integral types. |
8828 | | // FIXME: What about complex? What about half? |
8829 | |
|
8830 | 0 | assert(ArithmeticTypes.size() <= ArithmeticTypesCap && |
8831 | 0 | "Enough inline storage for all arithmetic types."); |
8832 | 0 | } |
8833 | | |
8834 | | /// Helper method to factor out the common pattern of adding overloads |
8835 | | /// for '++' and '--' builtin operators. |
8836 | | void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, |
8837 | | bool HasVolatile, |
8838 | 0 | bool HasRestrict) { |
8839 | 0 | QualType ParamTypes[2] = { |
8840 | 0 | S.Context.getLValueReferenceType(CandidateTy), |
8841 | 0 | S.Context.IntTy |
8842 | 0 | }; |
8843 | | |
8844 | | // Non-volatile version. |
8845 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8846 | | |
8847 | | // Use a heuristic to reduce number of builtin candidates in the set: |
8848 | | // add volatile version only if there are conversions to a volatile type. |
8849 | 0 | if (HasVolatile) { |
8850 | 0 | ParamTypes[0] = |
8851 | 0 | S.Context.getLValueReferenceType( |
8852 | 0 | S.Context.getVolatileType(CandidateTy)); |
8853 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8854 | 0 | } |
8855 | | |
8856 | | // Add restrict version only if there are conversions to a restrict type |
8857 | | // and our candidate type is a non-restrict-qualified pointer. |
8858 | 0 | if (HasRestrict && CandidateTy->isAnyPointerType() && |
8859 | 0 | !CandidateTy.isRestrictQualified()) { |
8860 | 0 | ParamTypes[0] |
8861 | 0 | = S.Context.getLValueReferenceType( |
8862 | 0 | S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); |
8863 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8864 | |
|
8865 | 0 | if (HasVolatile) { |
8866 | 0 | ParamTypes[0] |
8867 | 0 | = S.Context.getLValueReferenceType( |
8868 | 0 | S.Context.getCVRQualifiedType(CandidateTy, |
8869 | 0 | (Qualifiers::Volatile | |
8870 | 0 | Qualifiers::Restrict))); |
8871 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
8872 | 0 | } |
8873 | 0 | } |
8874 | |
|
8875 | 0 | } |
8876 | | |
8877 | | /// Helper to add an overload candidate for a binary builtin with types \p L |
8878 | | /// and \p R. |
8879 | 0 | void AddCandidate(QualType L, QualType R) { |
8880 | 0 | QualType LandR[2] = {L, R}; |
8881 | 0 | S.AddBuiltinCandidate(LandR, Args, CandidateSet); |
8882 | 0 | } |
8883 | | |
8884 | | public: |
8885 | | BuiltinOperatorOverloadBuilder( |
8886 | | Sema &S, ArrayRef<Expr *> Args, |
8887 | | QualifiersAndAtomic VisibleTypeConversionsQuals, |
8888 | | bool HasArithmeticOrEnumeralCandidateType, |
8889 | | SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, |
8890 | | OverloadCandidateSet &CandidateSet) |
8891 | | : S(S), Args(Args), |
8892 | | VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), |
8893 | | HasArithmeticOrEnumeralCandidateType( |
8894 | | HasArithmeticOrEnumeralCandidateType), |
8895 | | CandidateTypes(CandidateTypes), |
8896 | 0 | CandidateSet(CandidateSet) { |
8897 | |
|
8898 | 0 | InitArithmeticTypes(); |
8899 | 0 | } |
8900 | | |
8901 | | // Increment is deprecated for bool since C++17. |
8902 | | // |
8903 | | // C++ [over.built]p3: |
8904 | | // |
8905 | | // For every pair (T, VQ), where T is an arithmetic type other |
8906 | | // than bool, and VQ is either volatile or empty, there exist |
8907 | | // candidate operator functions of the form |
8908 | | // |
8909 | | // VQ T& operator++(VQ T&); |
8910 | | // T operator++(VQ T&, int); |
8911 | | // |
8912 | | // C++ [over.built]p4: |
8913 | | // |
8914 | | // For every pair (T, VQ), where T is an arithmetic type other |
8915 | | // than bool, and VQ is either volatile or empty, there exist |
8916 | | // candidate operator functions of the form |
8917 | | // |
8918 | | // VQ T& operator--(VQ T&); |
8919 | | // T operator--(VQ T&, int); |
8920 | 0 | void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { |
8921 | 0 | if (!HasArithmeticOrEnumeralCandidateType) |
8922 | 0 | return; |
8923 | | |
8924 | 0 | for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { |
8925 | 0 | const auto TypeOfT = ArithmeticTypes[Arith]; |
8926 | 0 | if (TypeOfT == S.Context.BoolTy) { |
8927 | 0 | if (Op == OO_MinusMinus) |
8928 | 0 | continue; |
8929 | 0 | if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) |
8930 | 0 | continue; |
8931 | 0 | } |
8932 | 0 | addPlusPlusMinusMinusStyleOverloads( |
8933 | 0 | TypeOfT, |
8934 | 0 | VisibleTypeConversionsQuals.hasVolatile(), |
8935 | 0 | VisibleTypeConversionsQuals.hasRestrict()); |
8936 | 0 | } |
8937 | 0 | } |
8938 | | |
8939 | | // C++ [over.built]p5: |
8940 | | // |
8941 | | // For every pair (T, VQ), where T is a cv-qualified or |
8942 | | // cv-unqualified object type, and VQ is either volatile or |
8943 | | // empty, there exist candidate operator functions of the form |
8944 | | // |
8945 | | // T*VQ& operator++(T*VQ&); |
8946 | | // T*VQ& operator--(T*VQ&); |
8947 | | // T* operator++(T*VQ&, int); |
8948 | | // T* operator--(T*VQ&, int); |
8949 | 0 | void addPlusPlusMinusMinusPointerOverloads() { |
8950 | 0 | for (QualType PtrTy : CandidateTypes[0].pointer_types()) { |
8951 | | // Skip pointer types that aren't pointers to object types. |
8952 | 0 | if (!PtrTy->getPointeeType()->isObjectType()) |
8953 | 0 | continue; |
8954 | | |
8955 | 0 | addPlusPlusMinusMinusStyleOverloads( |
8956 | 0 | PtrTy, |
8957 | 0 | (!PtrTy.isVolatileQualified() && |
8958 | 0 | VisibleTypeConversionsQuals.hasVolatile()), |
8959 | 0 | (!PtrTy.isRestrictQualified() && |
8960 | 0 | VisibleTypeConversionsQuals.hasRestrict())); |
8961 | 0 | } |
8962 | 0 | } |
8963 | | |
8964 | | // C++ [over.built]p6: |
8965 | | // For every cv-qualified or cv-unqualified object type T, there |
8966 | | // exist candidate operator functions of the form |
8967 | | // |
8968 | | // T& operator*(T*); |
8969 | | // |
8970 | | // C++ [over.built]p7: |
8971 | | // For every function type T that does not have cv-qualifiers or a |
8972 | | // ref-qualifier, there exist candidate operator functions of the form |
8973 | | // T& operator*(T*); |
8974 | 0 | void addUnaryStarPointerOverloads() { |
8975 | 0 | for (QualType ParamTy : CandidateTypes[0].pointer_types()) { |
8976 | 0 | QualType PointeeTy = ParamTy->getPointeeType(); |
8977 | 0 | if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) |
8978 | 0 | continue; |
8979 | | |
8980 | 0 | if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) |
8981 | 0 | if (Proto->getMethodQuals() || Proto->getRefQualifier()) |
8982 | 0 | continue; |
8983 | | |
8984 | 0 | S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); |
8985 | 0 | } |
8986 | 0 | } |
8987 | | |
8988 | | // C++ [over.built]p9: |
8989 | | // For every promoted arithmetic type T, there exist candidate |
8990 | | // operator functions of the form |
8991 | | // |
8992 | | // T operator+(T); |
8993 | | // T operator-(T); |
8994 | 0 | void addUnaryPlusOrMinusArithmeticOverloads() { |
8995 | 0 | if (!HasArithmeticOrEnumeralCandidateType) |
8996 | 0 | return; |
8997 | | |
8998 | 0 | for (unsigned Arith = FirstPromotedArithmeticType; |
8999 | 0 | Arith < LastPromotedArithmeticType; ++Arith) { |
9000 | 0 | QualType ArithTy = ArithmeticTypes[Arith]; |
9001 | 0 | S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); |
9002 | 0 | } |
9003 | | |
9004 | | // Extension: We also add these operators for vector types. |
9005 | 0 | for (QualType VecTy : CandidateTypes[0].vector_types()) |
9006 | 0 | S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); |
9007 | 0 | } |
9008 | | |
9009 | | // C++ [over.built]p8: |
9010 | | // For every type T, there exist candidate operator functions of |
9011 | | // the form |
9012 | | // |
9013 | | // T* operator+(T*); |
9014 | 0 | void addUnaryPlusPointerOverloads() { |
9015 | 0 | for (QualType ParamTy : CandidateTypes[0].pointer_types()) |
9016 | 0 | S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); |
9017 | 0 | } |
9018 | | |
9019 | | // C++ [over.built]p10: |
9020 | | // For every promoted integral type T, there exist candidate |
9021 | | // operator functions of the form |
9022 | | // |
9023 | | // T operator~(T); |
9024 | 0 | void addUnaryTildePromotedIntegralOverloads() { |
9025 | 0 | if (!HasArithmeticOrEnumeralCandidateType) |
9026 | 0 | return; |
9027 | | |
9028 | 0 | for (unsigned Int = FirstPromotedIntegralType; |
9029 | 0 | Int < LastPromotedIntegralType; ++Int) { |
9030 | 0 | QualType IntTy = ArithmeticTypes[Int]; |
9031 | 0 | S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); |
9032 | 0 | } |
9033 | | |
9034 | | // Extension: We also add this operator for vector types. |
9035 | 0 | for (QualType VecTy : CandidateTypes[0].vector_types()) |
9036 | 0 | S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); |
9037 | 0 | } |
9038 | | |
9039 | | // C++ [over.match.oper]p16: |
9040 | | // For every pointer to member type T or type std::nullptr_t, there |
9041 | | // exist candidate operator functions of the form |
9042 | | // |
9043 | | // bool operator==(T,T); |
9044 | | // bool operator!=(T,T); |
9045 | 0 | void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { |
9046 | | /// Set of (canonical) types that we've already handled. |
9047 | 0 | llvm::SmallPtrSet<QualType, 8> AddedTypes; |
9048 | |
|
9049 | 0 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
9050 | 0 | for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { |
9051 | | // Don't add the same builtin candidate twice. |
9052 | 0 | if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) |
9053 | 0 | continue; |
9054 | | |
9055 | 0 | QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; |
9056 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
9057 | 0 | } |
9058 | |
|
9059 | 0 | if (CandidateTypes[ArgIdx].hasNullPtrType()) { |
9060 | 0 | CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); |
9061 | 0 | if (AddedTypes.insert(NullPtrTy).second) { |
9062 | 0 | QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; |
9063 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
9064 | 0 | } |
9065 | 0 | } |
9066 | 0 | } |
9067 | 0 | } |
9068 | | |
9069 | | // C++ [over.built]p15: |
9070 | | // |
9071 | | // For every T, where T is an enumeration type or a pointer type, |
9072 | | // there exist candidate operator functions of the form |
9073 | | // |
9074 | | // bool operator<(T, T); |
9075 | | // bool operator>(T, T); |
9076 | | // bool operator<=(T, T); |
9077 | | // bool operator>=(T, T); |
9078 | | // bool operator==(T, T); |
9079 | | // bool operator!=(T, T); |
9080 | | // R operator<=>(T, T) |
9081 | 0 | void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) { |
9082 | | // C++ [over.match.oper]p3: |
9083 | | // [...]the built-in candidates include all of the candidate operator |
9084 | | // functions defined in 13.6 that, compared to the given operator, [...] |
9085 | | // do not have the same parameter-type-list as any non-template non-member |
9086 | | // candidate. |
9087 | | // |
9088 | | // Note that in practice, this only affects enumeration types because there |
9089 | | // aren't any built-in candidates of record type, and a user-defined operator |
9090 | | // must have an operand of record or enumeration type. Also, the only other |
9091 | | // overloaded operator with enumeration arguments, operator=, |
9092 | | // cannot be overloaded for enumeration types, so this is the only place |
9093 | | // where we must suppress candidates like this. |
9094 | 0 | llvm::DenseSet<std::pair<CanQualType, CanQualType> > |
9095 | 0 | UserDefinedBinaryOperators; |
9096 | |
|
9097 | 0 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
9098 | 0 | if (!CandidateTypes[ArgIdx].enumeration_types().empty()) { |
9099 | 0 | for (OverloadCandidateSet::iterator C = CandidateSet.begin(), |
9100 | 0 | CEnd = CandidateSet.end(); |
9101 | 0 | C != CEnd; ++C) { |
9102 | 0 | if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) |
9103 | 0 | continue; |
9104 | | |
9105 | 0 | if (C->Function->isFunctionTemplateSpecialization()) |
9106 | 0 | continue; |
9107 | | |
9108 | | // We interpret "same parameter-type-list" as applying to the |
9109 | | // "synthesized candidate, with the order of the two parameters |
9110 | | // reversed", not to the original function. |
9111 | 0 | bool Reversed = C->isReversed(); |
9112 | 0 | QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) |
9113 | 0 | ->getType() |
9114 | 0 | .getUnqualifiedType(); |
9115 | 0 | QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) |
9116 | 0 | ->getType() |
9117 | 0 | .getUnqualifiedType(); |
9118 | | |
9119 | | // Skip if either parameter isn't of enumeral type. |
9120 | 0 | if (!FirstParamType->isEnumeralType() || |
9121 | 0 | !SecondParamType->isEnumeralType()) |
9122 | 0 | continue; |
9123 | | |
9124 | | // Add this operator to the set of known user-defined operators. |
9125 | 0 | UserDefinedBinaryOperators.insert( |
9126 | 0 | std::make_pair(S.Context.getCanonicalType(FirstParamType), |
9127 | 0 | S.Context.getCanonicalType(SecondParamType))); |
9128 | 0 | } |
9129 | 0 | } |
9130 | 0 | } |
9131 | | |
9132 | | /// Set of (canonical) types that we've already handled. |
9133 | 0 | llvm::SmallPtrSet<QualType, 8> AddedTypes; |
9134 | |
|
9135 | 0 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
9136 | 0 | for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { |
9137 | | // Don't add the same builtin candidate twice. |
9138 | 0 | if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) |
9139 | 0 | continue; |
9140 | 0 | if (IsSpaceship && PtrTy->isFunctionPointerType()) |
9141 | 0 | continue; |
9142 | | |
9143 | 0 | QualType ParamTypes[2] = {PtrTy, PtrTy}; |
9144 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
9145 | 0 | } |
9146 | 0 | for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { |
9147 | 0 | CanQualType CanonType = S.Context.getCanonicalType(EnumTy); |
9148 | | |
9149 | | // Don't add the same builtin candidate twice, or if a user defined |
9150 | | // candidate exists. |
9151 | 0 | if (!AddedTypes.insert(CanonType).second || |
9152 | 0 | UserDefinedBinaryOperators.count(std::make_pair(CanonType, |
9153 | 0 | CanonType))) |
9154 | 0 | continue; |
9155 | 0 | QualType ParamTypes[2] = {EnumTy, EnumTy}; |
9156 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
9157 | 0 | } |
9158 | 0 | } |
9159 | 0 | } |
9160 | | |
9161 | | // C++ [over.built]p13: |
9162 | | // |
9163 | | // For every cv-qualified or cv-unqualified object type T |
9164 | | // there exist candidate operator functions of the form |
9165 | | // |
9166 | | // T* operator+(T*, ptrdiff_t); |
9167 | | // T& operator[](T*, ptrdiff_t); [BELOW] |
9168 | | // T* operator-(T*, ptrdiff_t); |
9169 | | // T* operator+(ptrdiff_t, T*); |
9170 | | // T& operator[](ptrdiff_t, T*); [BELOW] |
9171 | | // |
9172 | | // C++ [over.built]p14: |
9173 | | // |
9174 | | // For every T, where T is a pointer to object type, there |
9175 | | // exist candidate operator functions of the form |
9176 | | // |
9177 | | // ptrdiff_t operator-(T, T); |
9178 | 0 | void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { |
9179 | | /// Set of (canonical) types that we've already handled. |
9180 | 0 | llvm::SmallPtrSet<QualType, 8> AddedTypes; |
9181 | |
|
9182 | 0 | for (int Arg = 0; Arg < 2; ++Arg) { |
9183 | 0 | QualType AsymmetricParamTypes[2] = { |
9184 | 0 | S.Context.getPointerDiffType(), |
9185 | 0 | S.Context.getPointerDiffType(), |
9186 | 0 | }; |
9187 | 0 | for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) { |
9188 | 0 | QualType PointeeTy = PtrTy->getPointeeType(); |
9189 | 0 | if (!PointeeTy->isObjectType()) |
9190 | 0 | continue; |
9191 | | |
9192 | 0 | AsymmetricParamTypes[Arg] = PtrTy; |
9193 | 0 | if (Arg == 0 || Op == OO_Plus) { |
9194 | | // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) |
9195 | | // T* operator+(ptrdiff_t, T*); |
9196 | 0 | S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); |
9197 | 0 | } |
9198 | 0 | if (Op == OO_Minus) { |
9199 | | // ptrdiff_t operator-(T, T); |
9200 | 0 | if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) |
9201 | 0 | continue; |
9202 | | |
9203 | 0 | QualType ParamTypes[2] = {PtrTy, PtrTy}; |
9204 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
9205 | 0 | } |
9206 | 0 | } |
9207 | 0 | } |
9208 | 0 | } |
9209 | | |
9210 | | // C++ [over.built]p12: |
9211 | | // |
9212 | | // For every pair of promoted arithmetic types L and R, there |
9213 | | // exist candidate operator functions of the form |
9214 | | // |
9215 | | // LR operator*(L, R); |
9216 | | // LR operator/(L, R); |
9217 | | // LR operator+(L, R); |
9218 | | // LR operator-(L, R); |
9219 | | // bool operator<(L, R); |
9220 | | // bool operator>(L, R); |
9221 | | // bool operator<=(L, R); |
9222 | | // bool operator>=(L, R); |
9223 | | // bool operator==(L, R); |
9224 | | // bool operator!=(L, R); |
9225 | | // |
9226 | | // where LR is the result of the usual arithmetic conversions |
9227 | | // between types L and R. |
9228 | | // |
9229 | | // C++ [over.built]p24: |
9230 | | // |
9231 | | // For every pair of promoted arithmetic types L and R, there exist |
9232 | | // candidate operator functions of the form |
9233 | | // |
9234 | | // LR operator?(bool, L, R); |
9235 | | // |
9236 | | // where LR is the result of the usual arithmetic conversions |
9237 | | // between types L and R. |
9238 | | // Our candidates ignore the first parameter. |
9239 | 0 | void addGenericBinaryArithmeticOverloads() { |
9240 | 0 | if (!HasArithmeticOrEnumeralCandidateType) |
9241 | 0 | return; |
9242 | | |
9243 | 0 | for (unsigned Left = FirstPromotedArithmeticType; |
9244 | 0 | Left < LastPromotedArithmeticType; ++Left) { |
9245 | 0 | for (unsigned Right = FirstPromotedArithmeticType; |
9246 | 0 | Right < LastPromotedArithmeticType; ++Right) { |
9247 | 0 | QualType LandR[2] = { ArithmeticTypes[Left], |
9248 | 0 | ArithmeticTypes[Right] }; |
9249 | 0 | S.AddBuiltinCandidate(LandR, Args, CandidateSet); |
9250 | 0 | } |
9251 | 0 | } |
9252 | | |
9253 | | // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the |
9254 | | // conditional operator for vector types. |
9255 | 0 | for (QualType Vec1Ty : CandidateTypes[0].vector_types()) |
9256 | 0 | for (QualType Vec2Ty : CandidateTypes[1].vector_types()) { |
9257 | 0 | QualType LandR[2] = {Vec1Ty, Vec2Ty}; |
9258 | 0 | S.AddBuiltinCandidate(LandR, Args, CandidateSet); |
9259 | 0 | } |
9260 | 0 | } |
9261 | | |
9262 | | /// Add binary operator overloads for each candidate matrix type M1, M2: |
9263 | | /// * (M1, M1) -> M1 |
9264 | | /// * (M1, M1.getElementType()) -> M1 |
9265 | | /// * (M2.getElementType(), M2) -> M2 |
9266 | | /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0]. |
9267 | 0 | void addMatrixBinaryArithmeticOverloads() { |
9268 | 0 | if (!HasArithmeticOrEnumeralCandidateType) |
9269 | 0 | return; |
9270 | | |
9271 | 0 | for (QualType M1 : CandidateTypes[0].matrix_types()) { |
9272 | 0 | AddCandidate(M1, cast<MatrixType>(M1)->getElementType()); |
9273 | 0 | AddCandidate(M1, M1); |
9274 | 0 | } |
9275 | |
|
9276 | 0 | for (QualType M2 : CandidateTypes[1].matrix_types()) { |
9277 | 0 | AddCandidate(cast<MatrixType>(M2)->getElementType(), M2); |
9278 | 0 | if (!CandidateTypes[0].containsMatrixType(M2)) |
9279 | 0 | AddCandidate(M2, M2); |
9280 | 0 | } |
9281 | 0 | } |
9282 | | |
9283 | | // C++2a [over.built]p14: |
9284 | | // |
9285 | | // For every integral type T there exists a candidate operator function |
9286 | | // of the form |
9287 | | // |
9288 | | // std::strong_ordering operator<=>(T, T) |
9289 | | // |
9290 | | // C++2a [over.built]p15: |
9291 | | // |
9292 | | // For every pair of floating-point types L and R, there exists a candidate |
9293 | | // operator function of the form |
9294 | | // |
9295 | | // std::partial_ordering operator<=>(L, R); |
9296 | | // |
9297 | | // FIXME: The current specification for integral types doesn't play nice with |
9298 | | // the direction of p0946r0, which allows mixed integral and unscoped-enum |
9299 | | // comparisons. Under the current spec this can lead to ambiguity during |
9300 | | // overload resolution. For example: |
9301 | | // |
9302 | | // enum A : int {a}; |
9303 | | // auto x = (a <=> (long)42); |
9304 | | // |
9305 | | // error: call is ambiguous for arguments 'A' and 'long'. |
9306 | | // note: candidate operator<=>(int, int) |
9307 | | // note: candidate operator<=>(long, long) |
9308 | | // |
9309 | | // To avoid this error, this function deviates from the specification and adds |
9310 | | // the mixed overloads `operator<=>(L, R)` where L and R are promoted |
9311 | | // arithmetic types (the same as the generic relational overloads). |
9312 | | // |
9313 | | // For now this function acts as a placeholder. |
9314 | 0 | void addThreeWayArithmeticOverloads() { |
9315 | 0 | addGenericBinaryArithmeticOverloads(); |
9316 | 0 | } |
9317 | | |
9318 | | // C++ [over.built]p17: |
9319 | | // |
9320 | | // For every pair of promoted integral types L and R, there |
9321 | | // exist candidate operator functions of the form |
9322 | | // |
9323 | | // LR operator%(L, R); |
9324 | | // LR operator&(L, R); |
9325 | | // LR operator^(L, R); |
9326 | | // LR operator|(L, R); |
9327 | | // L operator<<(L, R); |
9328 | | // L operator>>(L, R); |
9329 | | // |
9330 | | // where LR is the result of the usual arithmetic conversions |
9331 | | // between types L and R. |
9332 | 0 | void addBinaryBitwiseArithmeticOverloads() { |
9333 | 0 | if (!HasArithmeticOrEnumeralCandidateType) |
9334 | 0 | return; |
9335 | | |
9336 | 0 | for (unsigned Left = FirstPromotedIntegralType; |
9337 | 0 | Left < LastPromotedIntegralType; ++Left) { |
9338 | 0 | for (unsigned Right = FirstPromotedIntegralType; |
9339 | 0 | Right < LastPromotedIntegralType; ++Right) { |
9340 | 0 | QualType LandR[2] = { ArithmeticTypes[Left], |
9341 | 0 | ArithmeticTypes[Right] }; |
9342 | 0 | S.AddBuiltinCandidate(LandR, Args, CandidateSet); |
9343 | 0 | } |
9344 | 0 | } |
9345 | 0 | } |
9346 | | |
9347 | | // C++ [over.built]p20: |
9348 | | // |
9349 | | // For every pair (T, VQ), where T is an enumeration or |
9350 | | // pointer to member type and VQ is either volatile or |
9351 | | // empty, there exist candidate operator functions of the form |
9352 | | // |
9353 | | // VQ T& operator=(VQ T&, T); |
9354 | 0 | void addAssignmentMemberPointerOrEnumeralOverloads() { |
9355 | | /// Set of (canonical) types that we've already handled. |
9356 | 0 | llvm::SmallPtrSet<QualType, 8> AddedTypes; |
9357 | |
|
9358 | 0 | for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { |
9359 | 0 | for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { |
9360 | 0 | if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) |
9361 | 0 | continue; |
9362 | | |
9363 | 0 | AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet); |
9364 | 0 | } |
9365 | |
|
9366 | 0 | for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { |
9367 | 0 | if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) |
9368 | 0 | continue; |
9369 | | |
9370 | 0 | AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet); |
9371 | 0 | } |
9372 | 0 | } |
9373 | 0 | } |
9374 | | |
9375 | | // C++ [over.built]p19: |
9376 | | // |
9377 | | // For every pair (T, VQ), where T is any type and VQ is either |
9378 | | // volatile or empty, there exist candidate operator functions |
9379 | | // of the form |
9380 | | // |
9381 | | // T*VQ& operator=(T*VQ&, T*); |
9382 | | // |
9383 | | // C++ [over.built]p21: |
9384 | | // |
9385 | | // For every pair (T, VQ), where T is a cv-qualified or |
9386 | | // cv-unqualified object type and VQ is either volatile or |
9387 | | // empty, there exist candidate operator functions of the form |
9388 | | // |
9389 | | // T*VQ& operator+=(T*VQ&, ptrdiff_t); |
9390 | | // T*VQ& operator-=(T*VQ&, ptrdiff_t); |
9391 | 0 | void addAssignmentPointerOverloads(bool isEqualOp) { |
9392 | | /// Set of (canonical) types that we've already handled. |
9393 | 0 | llvm::SmallPtrSet<QualType, 8> AddedTypes; |
9394 | |
|
9395 | 0 | for (QualType PtrTy : CandidateTypes[0].pointer_types()) { |
9396 | | // If this is operator=, keep track of the builtin candidates we added. |
9397 | 0 | if (isEqualOp) |
9398 | 0 | AddedTypes.insert(S.Context.getCanonicalType(PtrTy)); |
9399 | 0 | else if (!PtrTy->getPointeeType()->isObjectType()) |
9400 | 0 | continue; |
9401 | | |
9402 | | // non-volatile version |
9403 | 0 | QualType ParamTypes[2] = { |
9404 | 0 | S.Context.getLValueReferenceType(PtrTy), |
9405 | 0 | isEqualOp ? PtrTy : S.Context.getPointerDiffType(), |
9406 | 0 | }; |
9407 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
9408 | 0 | /*IsAssignmentOperator=*/ isEqualOp); |
9409 | |
|
9410 | 0 | bool NeedVolatile = !PtrTy.isVolatileQualified() && |
9411 | 0 | VisibleTypeConversionsQuals.hasVolatile(); |
9412 | 0 | if (NeedVolatile) { |
9413 | | // volatile version |
9414 | 0 | ParamTypes[0] = |
9415 | 0 | S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy)); |
9416 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
9417 | 0 | /*IsAssignmentOperator=*/isEqualOp); |
9418 | 0 | } |
9419 | |
|
9420 | 0 | if (!PtrTy.isRestrictQualified() && |
9421 | 0 | VisibleTypeConversionsQuals.hasRestrict()) { |
9422 | | // restrict version |
9423 | 0 | ParamTypes[0] = |
9424 | 0 | S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy)); |
9425 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
9426 | 0 | /*IsAssignmentOperator=*/isEqualOp); |
9427 | |
|
9428 | 0 | if (NeedVolatile) { |
9429 | | // volatile restrict version |
9430 | 0 | ParamTypes[0] = |
9431 | 0 | S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( |
9432 | 0 | PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); |
9433 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
9434 | 0 | /*IsAssignmentOperator=*/isEqualOp); |
9435 | 0 | } |
9436 | 0 | } |
9437 | 0 | } |
9438 | |
|
9439 | 0 | if (isEqualOp) { |
9440 | 0 | for (QualType PtrTy : CandidateTypes[1].pointer_types()) { |
9441 | | // Make sure we don't add the same candidate twice. |
9442 | 0 | if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) |
9443 | 0 | continue; |
9444 | | |
9445 | 0 | QualType ParamTypes[2] = { |
9446 | 0 | S.Context.getLValueReferenceType(PtrTy), |
9447 | 0 | PtrTy, |
9448 | 0 | }; |
9449 | | |
9450 | | // non-volatile version |
9451 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
9452 | 0 | /*IsAssignmentOperator=*/true); |
9453 | |
|
9454 | 0 | bool NeedVolatile = !PtrTy.isVolatileQualified() && |
9455 | 0 | VisibleTypeConversionsQuals.hasVolatile(); |
9456 | 0 | if (NeedVolatile) { |
9457 | | // volatile version |
9458 | 0 | ParamTypes[0] = S.Context.getLValueReferenceType( |
9459 | 0 | S.Context.getVolatileType(PtrTy)); |
9460 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
9461 | 0 | /*IsAssignmentOperator=*/true); |
9462 | 0 | } |
9463 | |
|
9464 | 0 | if (!PtrTy.isRestrictQualified() && |
9465 | 0 | VisibleTypeConversionsQuals.hasRestrict()) { |
9466 | | // restrict version |
9467 | 0 | ParamTypes[0] = S.Context.getLValueReferenceType( |
9468 | 0 | S.Context.getRestrictType(PtrTy)); |
9469 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
9470 | 0 | /*IsAssignmentOperator=*/true); |
9471 | |
|
9472 | 0 | if (NeedVolatile) { |
9473 | | // volatile restrict version |
9474 | 0 | ParamTypes[0] = |
9475 | 0 | S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( |
9476 | 0 | PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); |
9477 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
9478 | 0 | /*IsAssignmentOperator=*/true); |
9479 | 0 | } |
9480 | 0 | } |
9481 | 0 | } |
9482 | 0 | } |
9483 | 0 | } |
9484 | | |
9485 | | // C++ [over.built]p18: |
9486 | | // |
9487 | | // For every triple (L, VQ, R), where L is an arithmetic type, |
9488 | | // VQ is either volatile or empty, and R is a promoted |
9489 | | // arithmetic type, there exist candidate operator functions of |
9490 | | // the form |
9491 | | // |
9492 | | // VQ L& operator=(VQ L&, R); |
9493 | | // VQ L& operator*=(VQ L&, R); |
9494 | | // VQ L& operator/=(VQ L&, R); |
9495 | | // VQ L& operator+=(VQ L&, R); |
9496 | | // VQ L& operator-=(VQ L&, R); |
9497 | 0 | void addAssignmentArithmeticOverloads(bool isEqualOp) { |
9498 | 0 | if (!HasArithmeticOrEnumeralCandidateType) |
9499 | 0 | return; |
9500 | | |
9501 | 0 | for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { |
9502 | 0 | for (unsigned Right = FirstPromotedArithmeticType; |
9503 | 0 | Right < LastPromotedArithmeticType; ++Right) { |
9504 | 0 | QualType ParamTypes[2]; |
9505 | 0 | ParamTypes[1] = ArithmeticTypes[Right]; |
9506 | 0 | auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( |
9507 | 0 | S, ArithmeticTypes[Left], Args[0]); |
9508 | |
|
9509 | 0 | forAllQualifierCombinations( |
9510 | 0 | VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) { |
9511 | 0 | ParamTypes[0] = |
9512 | 0 | makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S); |
9513 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
9514 | 0 | /*IsAssignmentOperator=*/isEqualOp); |
9515 | 0 | }); |
9516 | 0 | } |
9517 | 0 | } |
9518 | | |
9519 | | // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. |
9520 | 0 | for (QualType Vec1Ty : CandidateTypes[0].vector_types()) |
9521 | 0 | for (QualType Vec2Ty : CandidateTypes[0].vector_types()) { |
9522 | 0 | QualType ParamTypes[2]; |
9523 | 0 | ParamTypes[1] = Vec2Ty; |
9524 | | // Add this built-in operator as a candidate (VQ is empty). |
9525 | 0 | ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty); |
9526 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
9527 | 0 | /*IsAssignmentOperator=*/isEqualOp); |
9528 | | |
9529 | | // Add this built-in operator as a candidate (VQ is 'volatile'). |
9530 | 0 | if (VisibleTypeConversionsQuals.hasVolatile()) { |
9531 | 0 | ParamTypes[0] = S.Context.getVolatileType(Vec1Ty); |
9532 | 0 | ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); |
9533 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
9534 | 0 | /*IsAssignmentOperator=*/isEqualOp); |
9535 | 0 | } |
9536 | 0 | } |
9537 | 0 | } |
9538 | | |
9539 | | // C++ [over.built]p22: |
9540 | | // |
9541 | | // For every triple (L, VQ, R), where L is an integral type, VQ |
9542 | | // is either volatile or empty, and R is a promoted integral |
9543 | | // type, there exist candidate operator functions of the form |
9544 | | // |
9545 | | // VQ L& operator%=(VQ L&, R); |
9546 | | // VQ L& operator<<=(VQ L&, R); |
9547 | | // VQ L& operator>>=(VQ L&, R); |
9548 | | // VQ L& operator&=(VQ L&, R); |
9549 | | // VQ L& operator^=(VQ L&, R); |
9550 | | // VQ L& operator|=(VQ L&, R); |
9551 | 0 | void addAssignmentIntegralOverloads() { |
9552 | 0 | if (!HasArithmeticOrEnumeralCandidateType) |
9553 | 0 | return; |
9554 | | |
9555 | 0 | for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { |
9556 | 0 | for (unsigned Right = FirstPromotedIntegralType; |
9557 | 0 | Right < LastPromotedIntegralType; ++Right) { |
9558 | 0 | QualType ParamTypes[2]; |
9559 | 0 | ParamTypes[1] = ArithmeticTypes[Right]; |
9560 | 0 | auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( |
9561 | 0 | S, ArithmeticTypes[Left], Args[0]); |
9562 | |
|
9563 | 0 | forAllQualifierCombinations( |
9564 | 0 | VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) { |
9565 | 0 | ParamTypes[0] = |
9566 | 0 | makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S); |
9567 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
9568 | 0 | }); |
9569 | 0 | } |
9570 | 0 | } |
9571 | 0 | } |
9572 | | |
9573 | | // C++ [over.operator]p23: |
9574 | | // |
9575 | | // There also exist candidate operator functions of the form |
9576 | | // |
9577 | | // bool operator!(bool); |
9578 | | // bool operator&&(bool, bool); |
9579 | | // bool operator||(bool, bool); |
9580 | 0 | void addExclaimOverload() { |
9581 | 0 | QualType ParamTy = S.Context.BoolTy; |
9582 | 0 | S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, |
9583 | 0 | /*IsAssignmentOperator=*/false, |
9584 | 0 | /*NumContextualBoolArguments=*/1); |
9585 | 0 | } |
9586 | 0 | void addAmpAmpOrPipePipeOverload() { |
9587 | 0 | QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; |
9588 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, |
9589 | 0 | /*IsAssignmentOperator=*/false, |
9590 | 0 | /*NumContextualBoolArguments=*/2); |
9591 | 0 | } |
9592 | | |
9593 | | // C++ [over.built]p13: |
9594 | | // |
9595 | | // For every cv-qualified or cv-unqualified object type T there |
9596 | | // exist candidate operator functions of the form |
9597 | | // |
9598 | | // T* operator+(T*, ptrdiff_t); [ABOVE] |
9599 | | // T& operator[](T*, ptrdiff_t); |
9600 | | // T* operator-(T*, ptrdiff_t); [ABOVE] |
9601 | | // T* operator+(ptrdiff_t, T*); [ABOVE] |
9602 | | // T& operator[](ptrdiff_t, T*); |
9603 | 0 | void addSubscriptOverloads() { |
9604 | 0 | for (QualType PtrTy : CandidateTypes[0].pointer_types()) { |
9605 | 0 | QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()}; |
9606 | 0 | QualType PointeeType = PtrTy->getPointeeType(); |
9607 | 0 | if (!PointeeType->isObjectType()) |
9608 | 0 | continue; |
9609 | | |
9610 | | // T& operator[](T*, ptrdiff_t) |
9611 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
9612 | 0 | } |
9613 | |
|
9614 | 0 | for (QualType PtrTy : CandidateTypes[1].pointer_types()) { |
9615 | 0 | QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy}; |
9616 | 0 | QualType PointeeType = PtrTy->getPointeeType(); |
9617 | 0 | if (!PointeeType->isObjectType()) |
9618 | 0 | continue; |
9619 | | |
9620 | | // T& operator[](ptrdiff_t, T*) |
9621 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
9622 | 0 | } |
9623 | 0 | } |
9624 | | |
9625 | | // C++ [over.built]p11: |
9626 | | // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, |
9627 | | // C1 is the same type as C2 or is a derived class of C2, T is an object |
9628 | | // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, |
9629 | | // there exist candidate operator functions of the form |
9630 | | // |
9631 | | // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); |
9632 | | // |
9633 | | // where CV12 is the union of CV1 and CV2. |
9634 | 0 | void addArrowStarOverloads() { |
9635 | 0 | for (QualType PtrTy : CandidateTypes[0].pointer_types()) { |
9636 | 0 | QualType C1Ty = PtrTy; |
9637 | 0 | QualType C1; |
9638 | 0 | QualifierCollector Q1; |
9639 | 0 | C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); |
9640 | 0 | if (!isa<RecordType>(C1)) |
9641 | 0 | continue; |
9642 | | // heuristic to reduce number of builtin candidates in the set. |
9643 | | // Add volatile/restrict version only if there are conversions to a |
9644 | | // volatile/restrict type. |
9645 | 0 | if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) |
9646 | 0 | continue; |
9647 | 0 | if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) |
9648 | 0 | continue; |
9649 | 0 | for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) { |
9650 | 0 | const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy); |
9651 | 0 | QualType C2 = QualType(mptr->getClass(), 0); |
9652 | 0 | C2 = C2.getUnqualifiedType(); |
9653 | 0 | if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) |
9654 | 0 | break; |
9655 | 0 | QualType ParamTypes[2] = {PtrTy, MemPtrTy}; |
9656 | | // build CV12 T& |
9657 | 0 | QualType T = mptr->getPointeeType(); |
9658 | 0 | if (!VisibleTypeConversionsQuals.hasVolatile() && |
9659 | 0 | T.isVolatileQualified()) |
9660 | 0 | continue; |
9661 | 0 | if (!VisibleTypeConversionsQuals.hasRestrict() && |
9662 | 0 | T.isRestrictQualified()) |
9663 | 0 | continue; |
9664 | 0 | T = Q1.apply(S.Context, T); |
9665 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
9666 | 0 | } |
9667 | 0 | } |
9668 | 0 | } |
9669 | | |
9670 | | // Note that we don't consider the first argument, since it has been |
9671 | | // contextually converted to bool long ago. The candidates below are |
9672 | | // therefore added as binary. |
9673 | | // |
9674 | | // C++ [over.built]p25: |
9675 | | // For every type T, where T is a pointer, pointer-to-member, or scoped |
9676 | | // enumeration type, there exist candidate operator functions of the form |
9677 | | // |
9678 | | // T operator?(bool, T, T); |
9679 | | // |
9680 | 0 | void addConditionalOperatorOverloads() { |
9681 | | /// Set of (canonical) types that we've already handled. |
9682 | 0 | llvm::SmallPtrSet<QualType, 8> AddedTypes; |
9683 | |
|
9684 | 0 | for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { |
9685 | 0 | for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { |
9686 | 0 | if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) |
9687 | 0 | continue; |
9688 | | |
9689 | 0 | QualType ParamTypes[2] = {PtrTy, PtrTy}; |
9690 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
9691 | 0 | } |
9692 | |
|
9693 | 0 | for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { |
9694 | 0 | if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) |
9695 | 0 | continue; |
9696 | | |
9697 | 0 | QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; |
9698 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
9699 | 0 | } |
9700 | |
|
9701 | 0 | if (S.getLangOpts().CPlusPlus11) { |
9702 | 0 | for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { |
9703 | 0 | if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped()) |
9704 | 0 | continue; |
9705 | | |
9706 | 0 | if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) |
9707 | 0 | continue; |
9708 | | |
9709 | 0 | QualType ParamTypes[2] = {EnumTy, EnumTy}; |
9710 | 0 | S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); |
9711 | 0 | } |
9712 | 0 | } |
9713 | 0 | } |
9714 | 0 | } |
9715 | | }; |
9716 | | |
9717 | | } // end anonymous namespace |
9718 | | |
9719 | | /// AddBuiltinOperatorCandidates - Add the appropriate built-in |
9720 | | /// operator overloads to the candidate set (C++ [over.built]), based |
9721 | | /// on the operator @p Op and the arguments given. For example, if the |
9722 | | /// operator is a binary '+', this routine might add "int |
9723 | | /// operator+(int, int)" to cover integer addition. |
9724 | | void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, |
9725 | | SourceLocation OpLoc, |
9726 | | ArrayRef<Expr *> Args, |
9727 | 0 | OverloadCandidateSet &CandidateSet) { |
9728 | | // Find all of the types that the arguments can convert to, but only |
9729 | | // if the operator we're looking at has built-in operator candidates |
9730 | | // that make use of these types. Also record whether we encounter non-record |
9731 | | // candidate types or either arithmetic or enumeral candidate types. |
9732 | 0 | QualifiersAndAtomic VisibleTypeConversionsQuals; |
9733 | 0 | VisibleTypeConversionsQuals.addConst(); |
9734 | 0 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
9735 | 0 | VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); |
9736 | 0 | if (Args[ArgIdx]->getType()->isAtomicType()) |
9737 | 0 | VisibleTypeConversionsQuals.addAtomic(); |
9738 | 0 | } |
9739 | |
|
9740 | 0 | bool HasNonRecordCandidateType = false; |
9741 | 0 | bool HasArithmeticOrEnumeralCandidateType = false; |
9742 | 0 | SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; |
9743 | 0 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
9744 | 0 | CandidateTypes.emplace_back(*this); |
9745 | 0 | CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), |
9746 | 0 | OpLoc, |
9747 | 0 | true, |
9748 | 0 | (Op == OO_Exclaim || |
9749 | 0 | Op == OO_AmpAmp || |
9750 | 0 | Op == OO_PipePipe), |
9751 | 0 | VisibleTypeConversionsQuals); |
9752 | 0 | HasNonRecordCandidateType = HasNonRecordCandidateType || |
9753 | 0 | CandidateTypes[ArgIdx].hasNonRecordTypes(); |
9754 | 0 | HasArithmeticOrEnumeralCandidateType = |
9755 | 0 | HasArithmeticOrEnumeralCandidateType || |
9756 | 0 | CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); |
9757 | 0 | } |
9758 | | |
9759 | | // Exit early when no non-record types have been added to the candidate set |
9760 | | // for any of the arguments to the operator. |
9761 | | // |
9762 | | // We can't exit early for !, ||, or &&, since there we have always have |
9763 | | // 'bool' overloads. |
9764 | 0 | if (!HasNonRecordCandidateType && |
9765 | 0 | !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) |
9766 | 0 | return; |
9767 | | |
9768 | | // Setup an object to manage the common state for building overloads. |
9769 | 0 | BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, |
9770 | 0 | VisibleTypeConversionsQuals, |
9771 | 0 | HasArithmeticOrEnumeralCandidateType, |
9772 | 0 | CandidateTypes, CandidateSet); |
9773 | | |
9774 | | // Dispatch over the operation to add in only those overloads which apply. |
9775 | 0 | switch (Op) { |
9776 | 0 | case OO_None: |
9777 | 0 | case NUM_OVERLOADED_OPERATORS: |
9778 | 0 | llvm_unreachable("Expected an overloaded operator"); |
9779 | |
|
9780 | 0 | case OO_New: |
9781 | 0 | case OO_Delete: |
9782 | 0 | case OO_Array_New: |
9783 | 0 | case OO_Array_Delete: |
9784 | 0 | case OO_Call: |
9785 | 0 | llvm_unreachable( |
9786 | 0 | "Special operators don't use AddBuiltinOperatorCandidates"); |
9787 | |
|
9788 | 0 | case OO_Comma: |
9789 | 0 | case OO_Arrow: |
9790 | 0 | case OO_Coawait: |
9791 | | // C++ [over.match.oper]p3: |
9792 | | // -- For the operator ',', the unary operator '&', the |
9793 | | // operator '->', or the operator 'co_await', the |
9794 | | // built-in candidates set is empty. |
9795 | 0 | break; |
9796 | | |
9797 | 0 | case OO_Plus: // '+' is either unary or binary |
9798 | 0 | if (Args.size() == 1) |
9799 | 0 | OpBuilder.addUnaryPlusPointerOverloads(); |
9800 | 0 | [[fallthrough]]; |
9801 | |
|
9802 | 0 | case OO_Minus: // '-' is either unary or binary |
9803 | 0 | if (Args.size() == 1) { |
9804 | 0 | OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); |
9805 | 0 | } else { |
9806 | 0 | OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); |
9807 | 0 | OpBuilder.addGenericBinaryArithmeticOverloads(); |
9808 | 0 | OpBuilder.addMatrixBinaryArithmeticOverloads(); |
9809 | 0 | } |
9810 | 0 | break; |
9811 | | |
9812 | 0 | case OO_Star: // '*' is either unary or binary |
9813 | 0 | if (Args.size() == 1) |
9814 | 0 | OpBuilder.addUnaryStarPointerOverloads(); |
9815 | 0 | else { |
9816 | 0 | OpBuilder.addGenericBinaryArithmeticOverloads(); |
9817 | 0 | OpBuilder.addMatrixBinaryArithmeticOverloads(); |
9818 | 0 | } |
9819 | 0 | break; |
9820 | | |
9821 | 0 | case OO_Slash: |
9822 | 0 | OpBuilder.addGenericBinaryArithmeticOverloads(); |
9823 | 0 | break; |
9824 | | |
9825 | 0 | case OO_PlusPlus: |
9826 | 0 | case OO_MinusMinus: |
9827 | 0 | OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); |
9828 | 0 | OpBuilder.addPlusPlusMinusMinusPointerOverloads(); |
9829 | 0 | break; |
9830 | | |
9831 | 0 | case OO_EqualEqual: |
9832 | 0 | case OO_ExclaimEqual: |
9833 | 0 | OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); |
9834 | 0 | OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); |
9835 | 0 | OpBuilder.addGenericBinaryArithmeticOverloads(); |
9836 | 0 | break; |
9837 | | |
9838 | 0 | case OO_Less: |
9839 | 0 | case OO_Greater: |
9840 | 0 | case OO_LessEqual: |
9841 | 0 | case OO_GreaterEqual: |
9842 | 0 | OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); |
9843 | 0 | OpBuilder.addGenericBinaryArithmeticOverloads(); |
9844 | 0 | break; |
9845 | | |
9846 | 0 | case OO_Spaceship: |
9847 | 0 | OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true); |
9848 | 0 | OpBuilder.addThreeWayArithmeticOverloads(); |
9849 | 0 | break; |
9850 | | |
9851 | 0 | case OO_Percent: |
9852 | 0 | case OO_Caret: |
9853 | 0 | case OO_Pipe: |
9854 | 0 | case OO_LessLess: |
9855 | 0 | case OO_GreaterGreater: |
9856 | 0 | OpBuilder.addBinaryBitwiseArithmeticOverloads(); |
9857 | 0 | break; |
9858 | | |
9859 | 0 | case OO_Amp: // '&' is either unary or binary |
9860 | 0 | if (Args.size() == 1) |
9861 | | // C++ [over.match.oper]p3: |
9862 | | // -- For the operator ',', the unary operator '&', or the |
9863 | | // operator '->', the built-in candidates set is empty. |
9864 | 0 | break; |
9865 | | |
9866 | 0 | OpBuilder.addBinaryBitwiseArithmeticOverloads(); |
9867 | 0 | break; |
9868 | | |
9869 | 0 | case OO_Tilde: |
9870 | 0 | OpBuilder.addUnaryTildePromotedIntegralOverloads(); |
9871 | 0 | break; |
9872 | | |
9873 | 0 | case OO_Equal: |
9874 | 0 | OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); |
9875 | 0 | [[fallthrough]]; |
9876 | |
|
9877 | 0 | case OO_PlusEqual: |
9878 | 0 | case OO_MinusEqual: |
9879 | 0 | OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); |
9880 | 0 | [[fallthrough]]; |
9881 | |
|
9882 | 0 | case OO_StarEqual: |
9883 | 0 | case OO_SlashEqual: |
9884 | 0 | OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); |
9885 | 0 | break; |
9886 | | |
9887 | 0 | case OO_PercentEqual: |
9888 | 0 | case OO_LessLessEqual: |
9889 | 0 | case OO_GreaterGreaterEqual: |
9890 | 0 | case OO_AmpEqual: |
9891 | 0 | case OO_CaretEqual: |
9892 | 0 | case OO_PipeEqual: |
9893 | 0 | OpBuilder.addAssignmentIntegralOverloads(); |
9894 | 0 | break; |
9895 | | |
9896 | 0 | case OO_Exclaim: |
9897 | 0 | OpBuilder.addExclaimOverload(); |
9898 | 0 | break; |
9899 | | |
9900 | 0 | case OO_AmpAmp: |
9901 | 0 | case OO_PipePipe: |
9902 | 0 | OpBuilder.addAmpAmpOrPipePipeOverload(); |
9903 | 0 | break; |
9904 | | |
9905 | 0 | case OO_Subscript: |
9906 | 0 | if (Args.size() == 2) |
9907 | 0 | OpBuilder.addSubscriptOverloads(); |
9908 | 0 | break; |
9909 | | |
9910 | 0 | case OO_ArrowStar: |
9911 | 0 | OpBuilder.addArrowStarOverloads(); |
9912 | 0 | break; |
9913 | | |
9914 | 0 | case OO_Conditional: |
9915 | 0 | OpBuilder.addConditionalOperatorOverloads(); |
9916 | 0 | OpBuilder.addGenericBinaryArithmeticOverloads(); |
9917 | 0 | break; |
9918 | 0 | } |
9919 | 0 | } |
9920 | | |
9921 | | /// Add function candidates found via argument-dependent lookup |
9922 | | /// to the set of overloading candidates. |
9923 | | /// |
9924 | | /// This routine performs argument-dependent name lookup based on the |
9925 | | /// given function name (which may also be an operator name) and adds |
9926 | | /// all of the overload candidates found by ADL to the overload |
9927 | | /// candidate set (C++ [basic.lookup.argdep]). |
9928 | | void |
9929 | | Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, |
9930 | | SourceLocation Loc, |
9931 | | ArrayRef<Expr *> Args, |
9932 | | TemplateArgumentListInfo *ExplicitTemplateArgs, |
9933 | | OverloadCandidateSet& CandidateSet, |
9934 | 0 | bool PartialOverloading) { |
9935 | 0 | ADLResult Fns; |
9936 | | |
9937 | | // FIXME: This approach for uniquing ADL results (and removing |
9938 | | // redundant candidates from the set) relies on pointer-equality, |
9939 | | // which means we need to key off the canonical decl. However, |
9940 | | // always going back to the canonical decl might not get us the |
9941 | | // right set of default arguments. What default arguments are |
9942 | | // we supposed to consider on ADL candidates, anyway? |
9943 | | |
9944 | | // FIXME: Pass in the explicit template arguments? |
9945 | 0 | ArgumentDependentLookup(Name, Loc, Args, Fns); |
9946 | | |
9947 | | // Erase all of the candidates we already knew about. |
9948 | 0 | for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), |
9949 | 0 | CandEnd = CandidateSet.end(); |
9950 | 0 | Cand != CandEnd; ++Cand) |
9951 | 0 | if (Cand->Function) { |
9952 | 0 | Fns.erase(Cand->Function); |
9953 | 0 | if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) |
9954 | 0 | Fns.erase(FunTmpl); |
9955 | 0 | } |
9956 | | |
9957 | | // For each of the ADL candidates we found, add it to the overload |
9958 | | // set. |
9959 | 0 | for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { |
9960 | 0 | DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); |
9961 | |
|
9962 | 0 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { |
9963 | 0 | if (ExplicitTemplateArgs) |
9964 | 0 | continue; |
9965 | | |
9966 | 0 | AddOverloadCandidate( |
9967 | 0 | FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false, |
9968 | 0 | PartialOverloading, /*AllowExplicit=*/true, |
9969 | 0 | /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL); |
9970 | 0 | if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) { |
9971 | 0 | AddOverloadCandidate( |
9972 | 0 | FD, FoundDecl, {Args[1], Args[0]}, CandidateSet, |
9973 | 0 | /*SuppressUserConversions=*/false, PartialOverloading, |
9974 | 0 | /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false, |
9975 | 0 | ADLCallKind::UsesADL, std::nullopt, |
9976 | 0 | OverloadCandidateParamOrder::Reversed); |
9977 | 0 | } |
9978 | 0 | } else { |
9979 | 0 | auto *FTD = cast<FunctionTemplateDecl>(*I); |
9980 | 0 | AddTemplateOverloadCandidate( |
9981 | 0 | FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet, |
9982 | 0 | /*SuppressUserConversions=*/false, PartialOverloading, |
9983 | 0 | /*AllowExplicit=*/true, ADLCallKind::UsesADL); |
9984 | 0 | if (CandidateSet.getRewriteInfo().shouldAddReversed( |
9985 | 0 | *this, Args, FTD->getTemplatedDecl())) { |
9986 | 0 | AddTemplateOverloadCandidate( |
9987 | 0 | FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]}, |
9988 | 0 | CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading, |
9989 | 0 | /*AllowExplicit=*/true, ADLCallKind::UsesADL, |
9990 | 0 | OverloadCandidateParamOrder::Reversed); |
9991 | 0 | } |
9992 | 0 | } |
9993 | 0 | } |
9994 | 0 | } |
9995 | | |
9996 | | namespace { |
9997 | | enum class Comparison { Equal, Better, Worse }; |
9998 | | } |
9999 | | |
10000 | | /// Compares the enable_if attributes of two FunctionDecls, for the purposes of |
10001 | | /// overload resolution. |
10002 | | /// |
10003 | | /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff |
10004 | | /// Cand1's first N enable_if attributes have precisely the same conditions as |
10005 | | /// Cand2's first N enable_if attributes (where N = the number of enable_if |
10006 | | /// attributes on Cand2), and Cand1 has more than N enable_if attributes. |
10007 | | /// |
10008 | | /// Note that you can have a pair of candidates such that Cand1's enable_if |
10009 | | /// attributes are worse than Cand2's, and Cand2's enable_if attributes are |
10010 | | /// worse than Cand1's. |
10011 | | static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, |
10012 | 0 | const FunctionDecl *Cand2) { |
10013 | | // Common case: One (or both) decls don't have enable_if attrs. |
10014 | 0 | bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); |
10015 | 0 | bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); |
10016 | 0 | if (!Cand1Attr || !Cand2Attr) { |
10017 | 0 | if (Cand1Attr == Cand2Attr) |
10018 | 0 | return Comparison::Equal; |
10019 | 0 | return Cand1Attr ? Comparison::Better : Comparison::Worse; |
10020 | 0 | } |
10021 | | |
10022 | 0 | auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); |
10023 | 0 | auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); |
10024 | |
|
10025 | 0 | llvm::FoldingSetNodeID Cand1ID, Cand2ID; |
10026 | 0 | for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { |
10027 | 0 | std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); |
10028 | 0 | std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); |
10029 | | |
10030 | | // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 |
10031 | | // has fewer enable_if attributes than Cand2, and vice versa. |
10032 | 0 | if (!Cand1A) |
10033 | 0 | return Comparison::Worse; |
10034 | 0 | if (!Cand2A) |
10035 | 0 | return Comparison::Better; |
10036 | | |
10037 | 0 | Cand1ID.clear(); |
10038 | 0 | Cand2ID.clear(); |
10039 | |
|
10040 | 0 | (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); |
10041 | 0 | (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); |
10042 | 0 | if (Cand1ID != Cand2ID) |
10043 | 0 | return Comparison::Worse; |
10044 | 0 | } |
10045 | | |
10046 | 0 | return Comparison::Equal; |
10047 | 0 | } |
10048 | | |
10049 | | static Comparison |
10050 | | isBetterMultiversionCandidate(const OverloadCandidate &Cand1, |
10051 | 0 | const OverloadCandidate &Cand2) { |
10052 | 0 | if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || |
10053 | 0 | !Cand2.Function->isMultiVersion()) |
10054 | 0 | return Comparison::Equal; |
10055 | | |
10056 | | // If both are invalid, they are equal. If one of them is invalid, the other |
10057 | | // is better. |
10058 | 0 | if (Cand1.Function->isInvalidDecl()) { |
10059 | 0 | if (Cand2.Function->isInvalidDecl()) |
10060 | 0 | return Comparison::Equal; |
10061 | 0 | return Comparison::Worse; |
10062 | 0 | } |
10063 | 0 | if (Cand2.Function->isInvalidDecl()) |
10064 | 0 | return Comparison::Better; |
10065 | | |
10066 | | // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer |
10067 | | // cpu_dispatch, else arbitrarily based on the identifiers. |
10068 | 0 | bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); |
10069 | 0 | bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); |
10070 | 0 | const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); |
10071 | 0 | const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); |
10072 | |
|
10073 | 0 | if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) |
10074 | 0 | return Comparison::Equal; |
10075 | | |
10076 | 0 | if (Cand1CPUDisp && !Cand2CPUDisp) |
10077 | 0 | return Comparison::Better; |
10078 | 0 | if (Cand2CPUDisp && !Cand1CPUDisp) |
10079 | 0 | return Comparison::Worse; |
10080 | | |
10081 | 0 | if (Cand1CPUSpec && Cand2CPUSpec) { |
10082 | 0 | if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) |
10083 | 0 | return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size() |
10084 | 0 | ? Comparison::Better |
10085 | 0 | : Comparison::Worse; |
10086 | | |
10087 | 0 | std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> |
10088 | 0 | FirstDiff = std::mismatch( |
10089 | 0 | Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), |
10090 | 0 | Cand2CPUSpec->cpus_begin(), |
10091 | 0 | [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { |
10092 | 0 | return LHS->getName() == RHS->getName(); |
10093 | 0 | }); |
10094 | |
|
10095 | 0 | assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && |
10096 | 0 | "Two different cpu-specific versions should not have the same " |
10097 | 0 | "identifier list, otherwise they'd be the same decl!"); |
10098 | 0 | return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName() |
10099 | 0 | ? Comparison::Better |
10100 | 0 | : Comparison::Worse; |
10101 | 0 | } |
10102 | 0 | llvm_unreachable("No way to get here unless both had cpu_dispatch"); |
10103 | 0 | } |
10104 | | |
10105 | | /// Compute the type of the implicit object parameter for the given function, |
10106 | | /// if any. Returns std::nullopt if there is no implicit object parameter, and a |
10107 | | /// null QualType if there is a 'matches anything' implicit object parameter. |
10108 | | static std::optional<QualType> |
10109 | 0 | getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) { |
10110 | 0 | if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F)) |
10111 | 0 | return std::nullopt; |
10112 | | |
10113 | 0 | auto *M = cast<CXXMethodDecl>(F); |
10114 | | // Static member functions' object parameters match all types. |
10115 | 0 | if (M->isStatic()) |
10116 | 0 | return QualType(); |
10117 | 0 | return M->getFunctionObjectParameterReferenceType(); |
10118 | 0 | } |
10119 | | |
10120 | | // As a Clang extension, allow ambiguity among F1 and F2 if they represent |
10121 | | // represent the same entity. |
10122 | | static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1, |
10123 | 0 | const FunctionDecl *F2) { |
10124 | 0 | if (declaresSameEntity(F1, F2)) |
10125 | 0 | return true; |
10126 | 0 | auto PT1 = F1->getPrimaryTemplate(); |
10127 | 0 | auto PT2 = F2->getPrimaryTemplate(); |
10128 | 0 | if (PT1 && PT2) { |
10129 | 0 | if (declaresSameEntity(PT1, PT2) || |
10130 | 0 | declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(), |
10131 | 0 | PT2->getInstantiatedFromMemberTemplate())) |
10132 | 0 | return true; |
10133 | 0 | } |
10134 | | // TODO: It is not clear whether comparing parameters is necessary (i.e. |
10135 | | // different functions with same params). Consider removing this (as no test |
10136 | | // fail w/o it). |
10137 | 0 | auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) { |
10138 | 0 | if (First) { |
10139 | 0 | if (std::optional<QualType> T = getImplicitObjectParamType(Context, F)) |
10140 | 0 | return *T; |
10141 | 0 | } |
10142 | 0 | assert(I < F->getNumParams()); |
10143 | 0 | return F->getParamDecl(I++)->getType(); |
10144 | 0 | }; |
10145 | |
|
10146 | 0 | unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1); |
10147 | 0 | unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2); |
10148 | |
|
10149 | 0 | if (F1NumParams != F2NumParams) |
10150 | 0 | return false; |
10151 | | |
10152 | 0 | unsigned I1 = 0, I2 = 0; |
10153 | 0 | for (unsigned I = 0; I != F1NumParams; ++I) { |
10154 | 0 | QualType T1 = NextParam(F1, I1, I == 0); |
10155 | 0 | QualType T2 = NextParam(F2, I2, I == 0); |
10156 | 0 | assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types"); |
10157 | 0 | if (!Context.hasSameUnqualifiedType(T1, T2)) |
10158 | 0 | return false; |
10159 | 0 | } |
10160 | 0 | return true; |
10161 | 0 | } |
10162 | | |
10163 | | /// We're allowed to use constraints partial ordering only if the candidates |
10164 | | /// have the same parameter types: |
10165 | | /// [over.match.best.general]p2.6 |
10166 | | /// F1 and F2 are non-template functions with the same |
10167 | | /// non-object-parameter-type-lists, and F1 is more constrained than F2 [...] |
10168 | | static bool sameFunctionParameterTypeLists(Sema &S, |
10169 | | const OverloadCandidate &Cand1, |
10170 | 0 | const OverloadCandidate &Cand2) { |
10171 | 0 | if (!Cand1.Function || !Cand2.Function) |
10172 | 0 | return false; |
10173 | | |
10174 | 0 | FunctionDecl *Fn1 = Cand1.Function; |
10175 | 0 | FunctionDecl *Fn2 = Cand2.Function; |
10176 | |
|
10177 | 0 | if (Fn1->isVariadic() != Fn1->isVariadic()) |
10178 | 0 | return false; |
10179 | | |
10180 | 0 | if (!S.FunctionNonObjectParamTypesAreEqual( |
10181 | 0 | Fn1, Fn2, nullptr, Cand1.isReversed() ^ Cand2.isReversed())) |
10182 | 0 | return false; |
10183 | | |
10184 | 0 | auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1); |
10185 | 0 | auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2); |
10186 | 0 | if (Mem1 && Mem2) { |
10187 | | // if they are member functions, both are direct members of the same class, |
10188 | | // and |
10189 | 0 | if (Mem1->getParent() != Mem2->getParent()) |
10190 | 0 | return false; |
10191 | | // if both are non-static member functions, they have the same types for |
10192 | | // their object parameters |
10193 | 0 | if (Mem1->isInstance() && Mem2->isInstance() && |
10194 | 0 | !S.getASTContext().hasSameType( |
10195 | 0 | Mem1->getFunctionObjectParameterReferenceType(), |
10196 | 0 | Mem1->getFunctionObjectParameterReferenceType())) |
10197 | 0 | return false; |
10198 | 0 | } |
10199 | 0 | return true; |
10200 | 0 | } |
10201 | | |
10202 | | /// isBetterOverloadCandidate - Determines whether the first overload |
10203 | | /// candidate is a better candidate than the second (C++ 13.3.3p1). |
10204 | | bool clang::isBetterOverloadCandidate( |
10205 | | Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, |
10206 | 0 | SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { |
10207 | | // Define viable functions to be better candidates than non-viable |
10208 | | // functions. |
10209 | 0 | if (!Cand2.Viable) |
10210 | 0 | return Cand1.Viable; |
10211 | 0 | else if (!Cand1.Viable) |
10212 | 0 | return false; |
10213 | | |
10214 | | // [CUDA] A function with 'never' preference is marked not viable, therefore |
10215 | | // is never shown up here. The worst preference shown up here is 'wrong side', |
10216 | | // e.g. an H function called by a HD function in device compilation. This is |
10217 | | // valid AST as long as the HD function is not emitted, e.g. it is an inline |
10218 | | // function which is called only by an H function. A deferred diagnostic will |
10219 | | // be triggered if it is emitted. However a wrong-sided function is still |
10220 | | // a viable candidate here. |
10221 | | // |
10222 | | // If Cand1 can be emitted and Cand2 cannot be emitted in the current |
10223 | | // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2 |
10224 | | // can be emitted, Cand1 is not better than Cand2. This rule should have |
10225 | | // precedence over other rules. |
10226 | | // |
10227 | | // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then |
10228 | | // other rules should be used to determine which is better. This is because |
10229 | | // host/device based overloading resolution is mostly for determining |
10230 | | // viability of a function. If two functions are both viable, other factors |
10231 | | // should take precedence in preference, e.g. the standard-defined preferences |
10232 | | // like argument conversion ranks or enable_if partial-ordering. The |
10233 | | // preference for pass-object-size parameters is probably most similar to a |
10234 | | // type-based-overloading decision and so should take priority. |
10235 | | // |
10236 | | // If other rules cannot determine which is better, CUDA preference will be |
10237 | | // used again to determine which is better. |
10238 | | // |
10239 | | // TODO: Currently IdentifyCUDAPreference does not return correct values |
10240 | | // for functions called in global variable initializers due to missing |
10241 | | // correct context about device/host. Therefore we can only enforce this |
10242 | | // rule when there is a caller. We should enforce this rule for functions |
10243 | | // in global variable initializers once proper context is added. |
10244 | | // |
10245 | | // TODO: We can only enable the hostness based overloading resolution when |
10246 | | // -fgpu-exclude-wrong-side-overloads is on since this requires deferring |
10247 | | // overloading resolution diagnostics. |
10248 | 0 | if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function && |
10249 | 0 | S.getLangOpts().GPUExcludeWrongSideOverloads) { |
10250 | 0 | if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) { |
10251 | 0 | bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller); |
10252 | 0 | bool IsCand1ImplicitHD = |
10253 | 0 | Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function); |
10254 | 0 | bool IsCand2ImplicitHD = |
10255 | 0 | Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function); |
10256 | 0 | auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function); |
10257 | 0 | auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function); |
10258 | 0 | assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never); |
10259 | | // The implicit HD function may be a function in a system header which |
10260 | | // is forced by pragma. In device compilation, if we prefer HD candidates |
10261 | | // over wrong-sided candidates, overloading resolution may change, which |
10262 | | // may result in non-deferrable diagnostics. As a workaround, we let |
10263 | | // implicit HD candidates take equal preference as wrong-sided candidates. |
10264 | | // This will preserve the overloading resolution. |
10265 | | // TODO: We still need special handling of implicit HD functions since |
10266 | | // they may incur other diagnostics to be deferred. We should make all |
10267 | | // host/device related diagnostics deferrable and remove special handling |
10268 | | // of implicit HD functions. |
10269 | 0 | auto EmitThreshold = |
10270 | 0 | (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD && |
10271 | 0 | (IsCand1ImplicitHD || IsCand2ImplicitHD)) |
10272 | 0 | ? Sema::CFP_Never |
10273 | 0 | : Sema::CFP_WrongSide; |
10274 | 0 | auto Cand1Emittable = P1 > EmitThreshold; |
10275 | 0 | auto Cand2Emittable = P2 > EmitThreshold; |
10276 | 0 | if (Cand1Emittable && !Cand2Emittable) |
10277 | 0 | return true; |
10278 | 0 | if (!Cand1Emittable && Cand2Emittable) |
10279 | 0 | return false; |
10280 | 0 | } |
10281 | 0 | } |
10282 | | |
10283 | | // C++ [over.match.best]p1: (Changed in C++23) |
10284 | | // |
10285 | | // -- if F is a static member function, ICS1(F) is defined such |
10286 | | // that ICS1(F) is neither better nor worse than ICS1(G) for |
10287 | | // any function G, and, symmetrically, ICS1(G) is neither |
10288 | | // better nor worse than ICS1(F). |
10289 | 0 | unsigned StartArg = 0; |
10290 | 0 | if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) |
10291 | 0 | StartArg = 1; |
10292 | |
|
10293 | 0 | auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { |
10294 | | // We don't allow incompatible pointer conversions in C++. |
10295 | 0 | if (!S.getLangOpts().CPlusPlus) |
10296 | 0 | return ICS.isStandard() && |
10297 | 0 | ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; |
10298 | | |
10299 | | // The only ill-formed conversion we allow in C++ is the string literal to |
10300 | | // char* conversion, which is only considered ill-formed after C++11. |
10301 | 0 | return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && |
10302 | 0 | hasDeprecatedStringLiteralToCharPtrConversion(ICS); |
10303 | 0 | }; |
10304 | | |
10305 | | // Define functions that don't require ill-formed conversions for a given |
10306 | | // argument to be better candidates than functions that do. |
10307 | 0 | unsigned NumArgs = Cand1.Conversions.size(); |
10308 | 0 | assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); |
10309 | 0 | bool HasBetterConversion = false; |
10310 | 0 | for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { |
10311 | 0 | bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); |
10312 | 0 | bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); |
10313 | 0 | if (Cand1Bad != Cand2Bad) { |
10314 | 0 | if (Cand1Bad) |
10315 | 0 | return false; |
10316 | 0 | HasBetterConversion = true; |
10317 | 0 | } |
10318 | 0 | } |
10319 | | |
10320 | 0 | if (HasBetterConversion) |
10321 | 0 | return true; |
10322 | | |
10323 | | // C++ [over.match.best]p1: |
10324 | | // A viable function F1 is defined to be a better function than another |
10325 | | // viable function F2 if for all arguments i, ICSi(F1) is not a worse |
10326 | | // conversion sequence than ICSi(F2), and then... |
10327 | 0 | bool HasWorseConversion = false; |
10328 | 0 | for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { |
10329 | 0 | switch (CompareImplicitConversionSequences(S, Loc, |
10330 | 0 | Cand1.Conversions[ArgIdx], |
10331 | 0 | Cand2.Conversions[ArgIdx])) { |
10332 | 0 | case ImplicitConversionSequence::Better: |
10333 | | // Cand1 has a better conversion sequence. |
10334 | 0 | HasBetterConversion = true; |
10335 | 0 | break; |
10336 | | |
10337 | 0 | case ImplicitConversionSequence::Worse: |
10338 | 0 | if (Cand1.Function && Cand2.Function && |
10339 | 0 | Cand1.isReversed() != Cand2.isReversed() && |
10340 | 0 | allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) { |
10341 | | // Work around large-scale breakage caused by considering reversed |
10342 | | // forms of operator== in C++20: |
10343 | | // |
10344 | | // When comparing a function against a reversed function, if we have a |
10345 | | // better conversion for one argument and a worse conversion for the |
10346 | | // other, the implicit conversion sequences are treated as being equally |
10347 | | // good. |
10348 | | // |
10349 | | // This prevents a comparison function from being considered ambiguous |
10350 | | // with a reversed form that is written in the same way. |
10351 | | // |
10352 | | // We diagnose this as an extension from CreateOverloadedBinOp. |
10353 | 0 | HasWorseConversion = true; |
10354 | 0 | break; |
10355 | 0 | } |
10356 | | |
10357 | | // Cand1 can't be better than Cand2. |
10358 | 0 | return false; |
10359 | | |
10360 | 0 | case ImplicitConversionSequence::Indistinguishable: |
10361 | | // Do nothing. |
10362 | 0 | break; |
10363 | 0 | } |
10364 | 0 | } |
10365 | | |
10366 | | // -- for some argument j, ICSj(F1) is a better conversion sequence than |
10367 | | // ICSj(F2), or, if not that, |
10368 | 0 | if (HasBetterConversion && !HasWorseConversion) |
10369 | 0 | return true; |
10370 | | |
10371 | | // -- the context is an initialization by user-defined conversion |
10372 | | // (see 8.5, 13.3.1.5) and the standard conversion sequence |
10373 | | // from the return type of F1 to the destination type (i.e., |
10374 | | // the type of the entity being initialized) is a better |
10375 | | // conversion sequence than the standard conversion sequence |
10376 | | // from the return type of F2 to the destination type. |
10377 | 0 | if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && |
10378 | 0 | Cand1.Function && Cand2.Function && |
10379 | 0 | isa<CXXConversionDecl>(Cand1.Function) && |
10380 | 0 | isa<CXXConversionDecl>(Cand2.Function)) { |
10381 | | // First check whether we prefer one of the conversion functions over the |
10382 | | // other. This only distinguishes the results in non-standard, extension |
10383 | | // cases such as the conversion from a lambda closure type to a function |
10384 | | // pointer or block. |
10385 | 0 | ImplicitConversionSequence::CompareKind Result = |
10386 | 0 | compareConversionFunctions(S, Cand1.Function, Cand2.Function); |
10387 | 0 | if (Result == ImplicitConversionSequence::Indistinguishable) |
10388 | 0 | Result = CompareStandardConversionSequences(S, Loc, |
10389 | 0 | Cand1.FinalConversion, |
10390 | 0 | Cand2.FinalConversion); |
10391 | |
|
10392 | 0 | if (Result != ImplicitConversionSequence::Indistinguishable) |
10393 | 0 | return Result == ImplicitConversionSequence::Better; |
10394 | | |
10395 | | // FIXME: Compare kind of reference binding if conversion functions |
10396 | | // convert to a reference type used in direct reference binding, per |
10397 | | // C++14 [over.match.best]p1 section 2 bullet 3. |
10398 | 0 | } |
10399 | | |
10400 | | // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, |
10401 | | // as combined with the resolution to CWG issue 243. |
10402 | | // |
10403 | | // When the context is initialization by constructor ([over.match.ctor] or |
10404 | | // either phase of [over.match.list]), a constructor is preferred over |
10405 | | // a conversion function. |
10406 | 0 | if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && |
10407 | 0 | Cand1.Function && Cand2.Function && |
10408 | 0 | isa<CXXConstructorDecl>(Cand1.Function) != |
10409 | 0 | isa<CXXConstructorDecl>(Cand2.Function)) |
10410 | 0 | return isa<CXXConstructorDecl>(Cand1.Function); |
10411 | | |
10412 | | // -- F1 is a non-template function and F2 is a function template |
10413 | | // specialization, or, if not that, |
10414 | 0 | bool Cand1IsSpecialization = Cand1.Function && |
10415 | 0 | Cand1.Function->getPrimaryTemplate(); |
10416 | 0 | bool Cand2IsSpecialization = Cand2.Function && |
10417 | 0 | Cand2.Function->getPrimaryTemplate(); |
10418 | 0 | if (Cand1IsSpecialization != Cand2IsSpecialization) |
10419 | 0 | return Cand2IsSpecialization; |
10420 | | |
10421 | | // -- F1 and F2 are function template specializations, and the function |
10422 | | // template for F1 is more specialized than the template for F2 |
10423 | | // according to the partial ordering rules described in 14.5.5.2, or, |
10424 | | // if not that, |
10425 | 0 | if (Cand1IsSpecialization && Cand2IsSpecialization) { |
10426 | 0 | if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate( |
10427 | 0 | Cand1.Function->getPrimaryTemplate(), |
10428 | 0 | Cand2.Function->getPrimaryTemplate(), Loc, |
10429 | 0 | isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion |
10430 | 0 | : TPOC_Call, |
10431 | 0 | Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments, |
10432 | 0 | Cand1.isReversed() ^ Cand2.isReversed())) |
10433 | 0 | return BetterTemplate == Cand1.Function->getPrimaryTemplate(); |
10434 | 0 | } |
10435 | | |
10436 | | // -— F1 and F2 are non-template functions with the same |
10437 | | // parameter-type-lists, and F1 is more constrained than F2 [...], |
10438 | 0 | if (!Cand1IsSpecialization && !Cand2IsSpecialization && |
10439 | 0 | sameFunctionParameterTypeLists(S, Cand1, Cand2)) { |
10440 | 0 | FunctionDecl *Function1 = Cand1.Function; |
10441 | 0 | FunctionDecl *Function2 = Cand2.Function; |
10442 | 0 | if (FunctionDecl *MF = Function1->getInstantiatedFromMemberFunction()) |
10443 | 0 | Function1 = MF; |
10444 | 0 | if (FunctionDecl *MF = Function2->getInstantiatedFromMemberFunction()) |
10445 | 0 | Function2 = MF; |
10446 | |
|
10447 | 0 | const Expr *RC1 = Function1->getTrailingRequiresClause(); |
10448 | 0 | const Expr *RC2 = Function2->getTrailingRequiresClause(); |
10449 | 0 | if (RC1 && RC2) { |
10450 | 0 | bool AtLeastAsConstrained1, AtLeastAsConstrained2; |
10451 | 0 | if (S.IsAtLeastAsConstrained(Function1, RC1, Function2, RC2, |
10452 | 0 | AtLeastAsConstrained1) || |
10453 | 0 | S.IsAtLeastAsConstrained(Function2, RC2, Function1, RC1, |
10454 | 0 | AtLeastAsConstrained2)) |
10455 | 0 | return false; |
10456 | 0 | if (AtLeastAsConstrained1 != AtLeastAsConstrained2) |
10457 | 0 | return AtLeastAsConstrained1; |
10458 | 0 | } else if (RC1 || RC2) { |
10459 | 0 | return RC1 != nullptr; |
10460 | 0 | } |
10461 | 0 | } |
10462 | | |
10463 | | // -- F1 is a constructor for a class D, F2 is a constructor for a base |
10464 | | // class B of D, and for all arguments the corresponding parameters of |
10465 | | // F1 and F2 have the same type. |
10466 | | // FIXME: Implement the "all parameters have the same type" check. |
10467 | 0 | bool Cand1IsInherited = |
10468 | 0 | isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); |
10469 | 0 | bool Cand2IsInherited = |
10470 | 0 | isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); |
10471 | 0 | if (Cand1IsInherited != Cand2IsInherited) |
10472 | 0 | return Cand2IsInherited; |
10473 | 0 | else if (Cand1IsInherited) { |
10474 | 0 | assert(Cand2IsInherited); |
10475 | 0 | auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); |
10476 | 0 | auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); |
10477 | 0 | if (Cand1Class->isDerivedFrom(Cand2Class)) |
10478 | 0 | return true; |
10479 | 0 | if (Cand2Class->isDerivedFrom(Cand1Class)) |
10480 | 0 | return false; |
10481 | | // Inherited from sibling base classes: still ambiguous. |
10482 | 0 | } |
10483 | | |
10484 | | // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not |
10485 | | // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate |
10486 | | // with reversed order of parameters and F1 is not |
10487 | | // |
10488 | | // We rank reversed + different operator as worse than just reversed, but |
10489 | | // that comparison can never happen, because we only consider reversing for |
10490 | | // the maximally-rewritten operator (== or <=>). |
10491 | 0 | if (Cand1.RewriteKind != Cand2.RewriteKind) |
10492 | 0 | return Cand1.RewriteKind < Cand2.RewriteKind; |
10493 | | |
10494 | | // Check C++17 tie-breakers for deduction guides. |
10495 | 0 | { |
10496 | 0 | auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); |
10497 | 0 | auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); |
10498 | 0 | if (Guide1 && Guide2) { |
10499 | | // -- F1 is generated from a deduction-guide and F2 is not |
10500 | 0 | if (Guide1->isImplicit() != Guide2->isImplicit()) |
10501 | 0 | return Guide2->isImplicit(); |
10502 | | |
10503 | | // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not |
10504 | 0 | if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy) |
10505 | 0 | return true; |
10506 | 0 | if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy) |
10507 | 0 | return false; |
10508 | | |
10509 | | // --F1 is generated from a non-template constructor and F2 is generated |
10510 | | // from a constructor template |
10511 | 0 | const auto *Constructor1 = Guide1->getCorrespondingConstructor(); |
10512 | 0 | const auto *Constructor2 = Guide2->getCorrespondingConstructor(); |
10513 | 0 | if (Constructor1 && Constructor2) { |
10514 | 0 | bool isC1Templated = Constructor1->getTemplatedKind() != |
10515 | 0 | FunctionDecl::TemplatedKind::TK_NonTemplate; |
10516 | 0 | bool isC2Templated = Constructor2->getTemplatedKind() != |
10517 | 0 | FunctionDecl::TemplatedKind::TK_NonTemplate; |
10518 | 0 | if (isC1Templated != isC2Templated) |
10519 | 0 | return isC2Templated; |
10520 | 0 | } |
10521 | 0 | } |
10522 | 0 | } |
10523 | | |
10524 | | // Check for enable_if value-based overload resolution. |
10525 | 0 | if (Cand1.Function && Cand2.Function) { |
10526 | 0 | Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); |
10527 | 0 | if (Cmp != Comparison::Equal) |
10528 | 0 | return Cmp == Comparison::Better; |
10529 | 0 | } |
10530 | | |
10531 | 0 | bool HasPS1 = Cand1.Function != nullptr && |
10532 | 0 | functionHasPassObjectSizeParams(Cand1.Function); |
10533 | 0 | bool HasPS2 = Cand2.Function != nullptr && |
10534 | 0 | functionHasPassObjectSizeParams(Cand2.Function); |
10535 | 0 | if (HasPS1 != HasPS2 && HasPS1) |
10536 | 0 | return true; |
10537 | | |
10538 | 0 | auto MV = isBetterMultiversionCandidate(Cand1, Cand2); |
10539 | 0 | if (MV == Comparison::Better) |
10540 | 0 | return true; |
10541 | 0 | if (MV == Comparison::Worse) |
10542 | 0 | return false; |
10543 | | |
10544 | | // If other rules cannot determine which is better, CUDA preference is used |
10545 | | // to determine which is better. |
10546 | 0 | if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { |
10547 | 0 | FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); |
10548 | 0 | return S.IdentifyCUDAPreference(Caller, Cand1.Function) > |
10549 | 0 | S.IdentifyCUDAPreference(Caller, Cand2.Function); |
10550 | 0 | } |
10551 | | |
10552 | | // General member function overloading is handled above, so this only handles |
10553 | | // constructors with address spaces. |
10554 | | // This only handles address spaces since C++ has no other |
10555 | | // qualifier that can be used with constructors. |
10556 | 0 | const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function); |
10557 | 0 | const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function); |
10558 | 0 | if (CD1 && CD2) { |
10559 | 0 | LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace(); |
10560 | 0 | LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace(); |
10561 | 0 | if (AS1 != AS2) { |
10562 | 0 | if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1)) |
10563 | 0 | return true; |
10564 | 0 | if (Qualifiers::isAddressSpaceSupersetOf(AS1, AS2)) |
10565 | 0 | return false; |
10566 | 0 | } |
10567 | 0 | } |
10568 | | |
10569 | 0 | return false; |
10570 | 0 | } |
10571 | | |
10572 | | /// Determine whether two declarations are "equivalent" for the purposes of |
10573 | | /// name lookup and overload resolution. This applies when the same internal/no |
10574 | | /// linkage entity is defined by two modules (probably by textually including |
10575 | | /// the same header). In such a case, we don't consider the declarations to |
10576 | | /// declare the same entity, but we also don't want lookups with both |
10577 | | /// declarations visible to be ambiguous in some cases (this happens when using |
10578 | | /// a modularized libstdc++). |
10579 | | bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, |
10580 | 0 | const NamedDecl *B) { |
10581 | 0 | auto *VA = dyn_cast_or_null<ValueDecl>(A); |
10582 | 0 | auto *VB = dyn_cast_or_null<ValueDecl>(B); |
10583 | 0 | if (!VA || !VB) |
10584 | 0 | return false; |
10585 | | |
10586 | | // The declarations must be declaring the same name as an internal linkage |
10587 | | // entity in different modules. |
10588 | 0 | if (!VA->getDeclContext()->getRedeclContext()->Equals( |
10589 | 0 | VB->getDeclContext()->getRedeclContext()) || |
10590 | 0 | getOwningModule(VA) == getOwningModule(VB) || |
10591 | 0 | VA->isExternallyVisible() || VB->isExternallyVisible()) |
10592 | 0 | return false; |
10593 | | |
10594 | | // Check that the declarations appear to be equivalent. |
10595 | | // |
10596 | | // FIXME: Checking the type isn't really enough to resolve the ambiguity. |
10597 | | // For constants and functions, we should check the initializer or body is |
10598 | | // the same. For non-constant variables, we shouldn't allow it at all. |
10599 | 0 | if (Context.hasSameType(VA->getType(), VB->getType())) |
10600 | 0 | return true; |
10601 | | |
10602 | | // Enum constants within unnamed enumerations will have different types, but |
10603 | | // may still be similar enough to be interchangeable for our purposes. |
10604 | 0 | if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { |
10605 | 0 | if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { |
10606 | | // Only handle anonymous enums. If the enumerations were named and |
10607 | | // equivalent, they would have been merged to the same type. |
10608 | 0 | auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); |
10609 | 0 | auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); |
10610 | 0 | if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || |
10611 | 0 | !Context.hasSameType(EnumA->getIntegerType(), |
10612 | 0 | EnumB->getIntegerType())) |
10613 | 0 | return false; |
10614 | | // Allow this only if the value is the same for both enumerators. |
10615 | 0 | return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); |
10616 | 0 | } |
10617 | 0 | } |
10618 | | |
10619 | | // Nothing else is sufficiently similar. |
10620 | 0 | return false; |
10621 | 0 | } |
10622 | | |
10623 | | void Sema::diagnoseEquivalentInternalLinkageDeclarations( |
10624 | 0 | SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { |
10625 | 0 | assert(D && "Unknown declaration"); |
10626 | 0 | Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; |
10627 | |
|
10628 | 0 | Module *M = getOwningModule(D); |
10629 | 0 | Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) |
10630 | 0 | << !M << (M ? M->getFullModuleName() : ""); |
10631 | |
|
10632 | 0 | for (auto *E : Equiv) { |
10633 | 0 | Module *M = getOwningModule(E); |
10634 | 0 | Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) |
10635 | 0 | << !M << (M ? M->getFullModuleName() : ""); |
10636 | 0 | } |
10637 | 0 | } |
10638 | | |
10639 | 0 | bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const { |
10640 | 0 | return FailureKind == ovl_fail_bad_deduction && |
10641 | 0 | DeductionFailure.Result == Sema::TDK_ConstraintsNotSatisfied && |
10642 | 0 | static_cast<CNSInfo *>(DeductionFailure.Data) |
10643 | 0 | ->Satisfaction.ContainsErrors; |
10644 | 0 | } |
10645 | | |
10646 | | /// Computes the best viable function (C++ 13.3.3) |
10647 | | /// within an overload candidate set. |
10648 | | /// |
10649 | | /// \param Loc The location of the function name (or operator symbol) for |
10650 | | /// which overload resolution occurs. |
10651 | | /// |
10652 | | /// \param Best If overload resolution was successful or found a deleted |
10653 | | /// function, \p Best points to the candidate function found. |
10654 | | /// |
10655 | | /// \returns The result of overload resolution. |
10656 | | OverloadingResult |
10657 | | OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, |
10658 | 2 | iterator &Best) { |
10659 | 2 | llvm::SmallVector<OverloadCandidate *, 16> Candidates; |
10660 | 2 | std::transform(begin(), end(), std::back_inserter(Candidates), |
10661 | 2 | [](OverloadCandidate &Cand) { return &Cand; }); |
10662 | | |
10663 | | // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but |
10664 | | // are accepted by both clang and NVCC. However, during a particular |
10665 | | // compilation mode only one call variant is viable. We need to |
10666 | | // exclude non-viable overload candidates from consideration based |
10667 | | // only on their host/device attributes. Specifically, if one |
10668 | | // candidate call is WrongSide and the other is SameSide, we ignore |
10669 | | // the WrongSide candidate. |
10670 | | // We only need to remove wrong-sided candidates here if |
10671 | | // -fgpu-exclude-wrong-side-overloads is off. When |
10672 | | // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared |
10673 | | // uniformly in isBetterOverloadCandidate. |
10674 | 2 | if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) { |
10675 | 0 | const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); |
10676 | 0 | bool ContainsSameSideCandidate = |
10677 | 0 | llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { |
10678 | | // Check viable function only. |
10679 | 0 | return Cand->Viable && Cand->Function && |
10680 | 0 | S.IdentifyCUDAPreference(Caller, Cand->Function) == |
10681 | 0 | Sema::CFP_SameSide; |
10682 | 0 | }); |
10683 | 0 | if (ContainsSameSideCandidate) { |
10684 | 0 | auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { |
10685 | | // Check viable function only to avoid unnecessary data copying/moving. |
10686 | 0 | return Cand->Viable && Cand->Function && |
10687 | 0 | S.IdentifyCUDAPreference(Caller, Cand->Function) == |
10688 | 0 | Sema::CFP_WrongSide; |
10689 | 0 | }; |
10690 | 0 | llvm::erase_if(Candidates, IsWrongSideCandidate); |
10691 | 0 | } |
10692 | 0 | } |
10693 | | |
10694 | | // Find the best viable function. |
10695 | 2 | Best = end(); |
10696 | 2 | for (auto *Cand : Candidates) { |
10697 | 0 | Cand->Best = false; |
10698 | 0 | if (Cand->Viable) { |
10699 | 0 | if (Best == end() || |
10700 | 0 | isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) |
10701 | 0 | Best = Cand; |
10702 | 0 | } else if (Cand->NotValidBecauseConstraintExprHasError()) { |
10703 | | // This candidate has constraint that we were unable to evaluate because |
10704 | | // it referenced an expression that contained an error. Rather than fall |
10705 | | // back onto a potentially unintended candidate (made worse by |
10706 | | // subsuming constraints), treat this as 'no viable candidate'. |
10707 | 0 | Best = end(); |
10708 | 0 | return OR_No_Viable_Function; |
10709 | 0 | } |
10710 | 0 | } |
10711 | | |
10712 | | // If we didn't find any viable functions, abort. |
10713 | 2 | if (Best == end()) |
10714 | 2 | return OR_No_Viable_Function; |
10715 | | |
10716 | 0 | llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; |
10717 | |
|
10718 | 0 | llvm::SmallVector<OverloadCandidate*, 4> PendingBest; |
10719 | 0 | PendingBest.push_back(&*Best); |
10720 | 0 | Best->Best = true; |
10721 | | |
10722 | | // Make sure that this function is better than every other viable |
10723 | | // function. If not, we have an ambiguity. |
10724 | 0 | while (!PendingBest.empty()) { |
10725 | 0 | auto *Curr = PendingBest.pop_back_val(); |
10726 | 0 | for (auto *Cand : Candidates) { |
10727 | 0 | if (Cand->Viable && !Cand->Best && |
10728 | 0 | !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { |
10729 | 0 | PendingBest.push_back(Cand); |
10730 | 0 | Cand->Best = true; |
10731 | |
|
10732 | 0 | if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, |
10733 | 0 | Curr->Function)) |
10734 | 0 | EquivalentCands.push_back(Cand->Function); |
10735 | 0 | else |
10736 | 0 | Best = end(); |
10737 | 0 | } |
10738 | 0 | } |
10739 | 0 | } |
10740 | | |
10741 | | // If we found more than one best candidate, this is ambiguous. |
10742 | 0 | if (Best == end()) |
10743 | 0 | return OR_Ambiguous; |
10744 | | |
10745 | | // Best is the best viable function. |
10746 | 0 | if (Best->Function && Best->Function->isDeleted()) |
10747 | 0 | return OR_Deleted; |
10748 | | |
10749 | 0 | if (!EquivalentCands.empty()) |
10750 | 0 | S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, |
10751 | 0 | EquivalentCands); |
10752 | |
|
10753 | 0 | return OR_Success; |
10754 | 0 | } |
10755 | | |
10756 | | namespace { |
10757 | | |
10758 | | enum OverloadCandidateKind { |
10759 | | oc_function, |
10760 | | oc_method, |
10761 | | oc_reversed_binary_operator, |
10762 | | oc_constructor, |
10763 | | oc_implicit_default_constructor, |
10764 | | oc_implicit_copy_constructor, |
10765 | | oc_implicit_move_constructor, |
10766 | | oc_implicit_copy_assignment, |
10767 | | oc_implicit_move_assignment, |
10768 | | oc_implicit_equality_comparison, |
10769 | | oc_inherited_constructor |
10770 | | }; |
10771 | | |
10772 | | enum OverloadCandidateSelect { |
10773 | | ocs_non_template, |
10774 | | ocs_template, |
10775 | | ocs_described_template, |
10776 | | }; |
10777 | | |
10778 | | static std::pair<OverloadCandidateKind, OverloadCandidateSelect> |
10779 | | ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found, |
10780 | | const FunctionDecl *Fn, |
10781 | | OverloadCandidateRewriteKind CRK, |
10782 | 0 | std::string &Description) { |
10783 | |
|
10784 | 0 | bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); |
10785 | 0 | if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { |
10786 | 0 | isTemplate = true; |
10787 | 0 | Description = S.getTemplateArgumentBindingsText( |
10788 | 0 | FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); |
10789 | 0 | } |
10790 | |
|
10791 | 0 | OverloadCandidateSelect Select = [&]() { |
10792 | 0 | if (!Description.empty()) |
10793 | 0 | return ocs_described_template; |
10794 | 0 | return isTemplate ? ocs_template : ocs_non_template; |
10795 | 0 | }(); |
10796 | |
|
10797 | 0 | OverloadCandidateKind Kind = [&]() { |
10798 | 0 | if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) |
10799 | 0 | return oc_implicit_equality_comparison; |
10800 | | |
10801 | 0 | if (CRK & CRK_Reversed) |
10802 | 0 | return oc_reversed_binary_operator; |
10803 | | |
10804 | 0 | if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { |
10805 | 0 | if (!Ctor->isImplicit()) { |
10806 | 0 | if (isa<ConstructorUsingShadowDecl>(Found)) |
10807 | 0 | return oc_inherited_constructor; |
10808 | 0 | else |
10809 | 0 | return oc_constructor; |
10810 | 0 | } |
10811 | | |
10812 | 0 | if (Ctor->isDefaultConstructor()) |
10813 | 0 | return oc_implicit_default_constructor; |
10814 | | |
10815 | 0 | if (Ctor->isMoveConstructor()) |
10816 | 0 | return oc_implicit_move_constructor; |
10817 | | |
10818 | 0 | assert(Ctor->isCopyConstructor() && |
10819 | 0 | "unexpected sort of implicit constructor"); |
10820 | 0 | return oc_implicit_copy_constructor; |
10821 | 0 | } |
10822 | | |
10823 | 0 | if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) { |
10824 | | // This actually gets spelled 'candidate function' for now, but |
10825 | | // it doesn't hurt to split it out. |
10826 | 0 | if (!Meth->isImplicit()) |
10827 | 0 | return oc_method; |
10828 | | |
10829 | 0 | if (Meth->isMoveAssignmentOperator()) |
10830 | 0 | return oc_implicit_move_assignment; |
10831 | | |
10832 | 0 | if (Meth->isCopyAssignmentOperator()) |
10833 | 0 | return oc_implicit_copy_assignment; |
10834 | | |
10835 | 0 | assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); |
10836 | 0 | return oc_method; |
10837 | 0 | } |
10838 | | |
10839 | 0 | return oc_function; |
10840 | 0 | }(); |
10841 | |
|
10842 | 0 | return std::make_pair(Kind, Select); |
10843 | 0 | } |
10844 | | |
10845 | 0 | void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) { |
10846 | | // FIXME: It'd be nice to only emit a note once per using-decl per overload |
10847 | | // set. |
10848 | 0 | if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) |
10849 | 0 | S.Diag(FoundDecl->getLocation(), |
10850 | 0 | diag::note_ovl_candidate_inherited_constructor) |
10851 | 0 | << Shadow->getNominatedBaseClass(); |
10852 | 0 | } |
10853 | | |
10854 | | } // end anonymous namespace |
10855 | | |
10856 | | static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, |
10857 | 0 | const FunctionDecl *FD) { |
10858 | 0 | for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { |
10859 | 0 | bool AlwaysTrue; |
10860 | 0 | if (EnableIf->getCond()->isValueDependent() || |
10861 | 0 | !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) |
10862 | 0 | return false; |
10863 | 0 | if (!AlwaysTrue) |
10864 | 0 | return false; |
10865 | 0 | } |
10866 | 0 | return true; |
10867 | 0 | } |
10868 | | |
10869 | | /// Returns true if we can take the address of the function. |
10870 | | /// |
10871 | | /// \param Complain - If true, we'll emit a diagnostic |
10872 | | /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are |
10873 | | /// we in overload resolution? |
10874 | | /// \param Loc - The location of the statement we're complaining about. Ignored |
10875 | | /// if we're not complaining, or if we're in overload resolution. |
10876 | | static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, |
10877 | | bool Complain, |
10878 | | bool InOverloadResolution, |
10879 | 0 | SourceLocation Loc) { |
10880 | 0 | if (!isFunctionAlwaysEnabled(S.Context, FD)) { |
10881 | 0 | if (Complain) { |
10882 | 0 | if (InOverloadResolution) |
10883 | 0 | S.Diag(FD->getBeginLoc(), |
10884 | 0 | diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); |
10885 | 0 | else |
10886 | 0 | S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; |
10887 | 0 | } |
10888 | 0 | return false; |
10889 | 0 | } |
10890 | | |
10891 | 0 | if (FD->getTrailingRequiresClause()) { |
10892 | 0 | ConstraintSatisfaction Satisfaction; |
10893 | 0 | if (S.CheckFunctionConstraints(FD, Satisfaction, Loc)) |
10894 | 0 | return false; |
10895 | 0 | if (!Satisfaction.IsSatisfied) { |
10896 | 0 | if (Complain) { |
10897 | 0 | if (InOverloadResolution) { |
10898 | 0 | SmallString<128> TemplateArgString; |
10899 | 0 | if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) { |
10900 | 0 | TemplateArgString += " "; |
10901 | 0 | TemplateArgString += S.getTemplateArgumentBindingsText( |
10902 | 0 | FunTmpl->getTemplateParameters(), |
10903 | 0 | *FD->getTemplateSpecializationArgs()); |
10904 | 0 | } |
10905 | |
|
10906 | 0 | S.Diag(FD->getBeginLoc(), |
10907 | 0 | diag::note_ovl_candidate_unsatisfied_constraints) |
10908 | 0 | << TemplateArgString; |
10909 | 0 | } else |
10910 | 0 | S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied) |
10911 | 0 | << FD; |
10912 | 0 | S.DiagnoseUnsatisfiedConstraint(Satisfaction); |
10913 | 0 | } |
10914 | 0 | return false; |
10915 | 0 | } |
10916 | 0 | } |
10917 | | |
10918 | 0 | auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { |
10919 | 0 | return P->hasAttr<PassObjectSizeAttr>(); |
10920 | 0 | }); |
10921 | 0 | if (I == FD->param_end()) |
10922 | 0 | return true; |
10923 | | |
10924 | 0 | if (Complain) { |
10925 | | // Add one to ParamNo because it's user-facing |
10926 | 0 | unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; |
10927 | 0 | if (InOverloadResolution) |
10928 | 0 | S.Diag(FD->getLocation(), |
10929 | 0 | diag::note_ovl_candidate_has_pass_object_size_params) |
10930 | 0 | << ParamNo; |
10931 | 0 | else |
10932 | 0 | S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) |
10933 | 0 | << FD << ParamNo; |
10934 | 0 | } |
10935 | 0 | return false; |
10936 | 0 | } |
10937 | | |
10938 | | static bool checkAddressOfCandidateIsAvailable(Sema &S, |
10939 | 0 | const FunctionDecl *FD) { |
10940 | 0 | return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, |
10941 | 0 | /*InOverloadResolution=*/true, |
10942 | 0 | /*Loc=*/SourceLocation()); |
10943 | 0 | } |
10944 | | |
10945 | | bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, |
10946 | | bool Complain, |
10947 | 0 | SourceLocation Loc) { |
10948 | 0 | return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, |
10949 | 0 | /*InOverloadResolution=*/false, |
10950 | 0 | Loc); |
10951 | 0 | } |
10952 | | |
10953 | | // Don't print candidates other than the one that matches the calling |
10954 | | // convention of the call operator, since that is guaranteed to exist. |
10955 | 0 | static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) { |
10956 | 0 | const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn); |
10957 | |
|
10958 | 0 | if (!ConvD) |
10959 | 0 | return false; |
10960 | 0 | const auto *RD = cast<CXXRecordDecl>(Fn->getParent()); |
10961 | 0 | if (!RD->isLambda()) |
10962 | 0 | return false; |
10963 | | |
10964 | 0 | CXXMethodDecl *CallOp = RD->getLambdaCallOperator(); |
10965 | 0 | CallingConv CallOpCC = |
10966 | 0 | CallOp->getType()->castAs<FunctionType>()->getCallConv(); |
10967 | 0 | QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType(); |
10968 | 0 | CallingConv ConvToCC = |
10969 | 0 | ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv(); |
10970 | |
|
10971 | 0 | return ConvToCC != CallOpCC; |
10972 | 0 | } |
10973 | | |
10974 | | // Notes the location of an overload candidate. |
10975 | | void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, |
10976 | | OverloadCandidateRewriteKind RewriteKind, |
10977 | 0 | QualType DestType, bool TakingAddress) { |
10978 | 0 | if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) |
10979 | 0 | return; |
10980 | 0 | if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && |
10981 | 0 | !Fn->getAttr<TargetAttr>()->isDefaultVersion()) |
10982 | 0 | return; |
10983 | 0 | if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() && |
10984 | 0 | !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion()) |
10985 | 0 | return; |
10986 | 0 | if (shouldSkipNotingLambdaConversionDecl(Fn)) |
10987 | 0 | return; |
10988 | | |
10989 | 0 | std::string FnDesc; |
10990 | 0 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = |
10991 | 0 | ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); |
10992 | 0 | PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) |
10993 | 0 | << (unsigned)KSPair.first << (unsigned)KSPair.second |
10994 | 0 | << Fn << FnDesc; |
10995 | |
|
10996 | 0 | HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); |
10997 | 0 | Diag(Fn->getLocation(), PD); |
10998 | 0 | MaybeEmitInheritedConstructorNote(*this, Found); |
10999 | 0 | } |
11000 | | |
11001 | | static void |
11002 | 0 | MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) { |
11003 | | // Perhaps the ambiguity was caused by two atomic constraints that are |
11004 | | // 'identical' but not equivalent: |
11005 | | // |
11006 | | // void foo() requires (sizeof(T) > 4) { } // #1 |
11007 | | // void foo() requires (sizeof(T) > 4) && T::value { } // #2 |
11008 | | // |
11009 | | // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause |
11010 | | // #2 to subsume #1, but these constraint are not considered equivalent |
11011 | | // according to the subsumption rules because they are not the same |
11012 | | // source-level construct. This behavior is quite confusing and we should try |
11013 | | // to help the user figure out what happened. |
11014 | |
|
11015 | 0 | SmallVector<const Expr *, 3> FirstAC, SecondAC; |
11016 | 0 | FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr; |
11017 | 0 | for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) { |
11018 | 0 | if (!I->Function) |
11019 | 0 | continue; |
11020 | 0 | SmallVector<const Expr *, 3> AC; |
11021 | 0 | if (auto *Template = I->Function->getPrimaryTemplate()) |
11022 | 0 | Template->getAssociatedConstraints(AC); |
11023 | 0 | else |
11024 | 0 | I->Function->getAssociatedConstraints(AC); |
11025 | 0 | if (AC.empty()) |
11026 | 0 | continue; |
11027 | 0 | if (FirstCand == nullptr) { |
11028 | 0 | FirstCand = I->Function; |
11029 | 0 | FirstAC = AC; |
11030 | 0 | } else if (SecondCand == nullptr) { |
11031 | 0 | SecondCand = I->Function; |
11032 | 0 | SecondAC = AC; |
11033 | 0 | } else { |
11034 | | // We have more than one pair of constrained functions - this check is |
11035 | | // expensive and we'd rather not try to diagnose it. |
11036 | 0 | return; |
11037 | 0 | } |
11038 | 0 | } |
11039 | 0 | if (!SecondCand) |
11040 | 0 | return; |
11041 | | // The diagnostic can only happen if there are associated constraints on |
11042 | | // both sides (there needs to be some identical atomic constraint). |
11043 | 0 | if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC, |
11044 | 0 | SecondCand, SecondAC)) |
11045 | | // Just show the user one diagnostic, they'll probably figure it out |
11046 | | // from here. |
11047 | 0 | return; |
11048 | 0 | } |
11049 | | |
11050 | | // Notes the location of all overload candidates designated through |
11051 | | // OverloadedExpr |
11052 | | void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, |
11053 | 0 | bool TakingAddress) { |
11054 | 0 | assert(OverloadedExpr->getType() == Context.OverloadTy); |
11055 | | |
11056 | 0 | OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); |
11057 | 0 | OverloadExpr *OvlExpr = Ovl.Expression; |
11058 | |
|
11059 | 0 | for (UnresolvedSetIterator I = OvlExpr->decls_begin(), |
11060 | 0 | IEnd = OvlExpr->decls_end(); |
11061 | 0 | I != IEnd; ++I) { |
11062 | 0 | if (FunctionTemplateDecl *FunTmpl = |
11063 | 0 | dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { |
11064 | 0 | NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, |
11065 | 0 | TakingAddress); |
11066 | 0 | } else if (FunctionDecl *Fun |
11067 | 0 | = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { |
11068 | 0 | NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); |
11069 | 0 | } |
11070 | 0 | } |
11071 | 0 | } |
11072 | | |
11073 | | /// Diagnoses an ambiguous conversion. The partial diagnostic is the |
11074 | | /// "lead" diagnostic; it will be given two arguments, the source and |
11075 | | /// target types of the conversion. |
11076 | | void ImplicitConversionSequence::DiagnoseAmbiguousConversion( |
11077 | | Sema &S, |
11078 | | SourceLocation CaretLoc, |
11079 | 0 | const PartialDiagnostic &PDiag) const { |
11080 | 0 | S.Diag(CaretLoc, PDiag) |
11081 | 0 | << Ambiguous.getFromType() << Ambiguous.getToType(); |
11082 | 0 | unsigned CandsShown = 0; |
11083 | 0 | AmbiguousConversionSequence::const_iterator I, E; |
11084 | 0 | for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { |
11085 | 0 | if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow()) |
11086 | 0 | break; |
11087 | 0 | ++CandsShown; |
11088 | 0 | S.NoteOverloadCandidate(I->first, I->second); |
11089 | 0 | } |
11090 | 0 | S.Diags.overloadCandidatesShown(CandsShown); |
11091 | 0 | if (I != E) |
11092 | 0 | S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); |
11093 | 0 | } |
11094 | | |
11095 | | static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, |
11096 | 0 | unsigned I, bool TakingCandidateAddress) { |
11097 | 0 | const ImplicitConversionSequence &Conv = Cand->Conversions[I]; |
11098 | 0 | assert(Conv.isBad()); |
11099 | 0 | assert(Cand->Function && "for now, candidate must be a function"); |
11100 | 0 | FunctionDecl *Fn = Cand->Function; |
11101 | | |
11102 | | // There's a conversion slot for the object argument if this is a |
11103 | | // non-constructor method. Note that 'I' corresponds the |
11104 | | // conversion-slot index. |
11105 | 0 | bool isObjectArgument = false; |
11106 | 0 | if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { |
11107 | 0 | if (I == 0) |
11108 | 0 | isObjectArgument = true; |
11109 | 0 | else |
11110 | 0 | I--; |
11111 | 0 | } |
11112 | |
|
11113 | 0 | std::string FnDesc; |
11114 | 0 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = |
11115 | 0 | ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), |
11116 | 0 | FnDesc); |
11117 | |
|
11118 | 0 | Expr *FromExpr = Conv.Bad.FromExpr; |
11119 | 0 | QualType FromTy = Conv.Bad.getFromType(); |
11120 | 0 | QualType ToTy = Conv.Bad.getToType(); |
11121 | 0 | SourceRange ToParamRange = |
11122 | 0 | !isObjectArgument ? Fn->getParamDecl(I)->getSourceRange() : SourceRange(); |
11123 | |
|
11124 | 0 | if (FromTy == S.Context.OverloadTy) { |
11125 | 0 | assert(FromExpr && "overload set argument came from implicit argument?"); |
11126 | 0 | Expr *E = FromExpr->IgnoreParens(); |
11127 | 0 | if (isa<UnaryOperator>(E)) |
11128 | 0 | E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); |
11129 | 0 | DeclarationName Name = cast<OverloadExpr>(E)->getName(); |
11130 | |
|
11131 | 0 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) |
11132 | 0 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
11133 | 0 | << ToParamRange << ToTy << Name << I + 1; |
11134 | 0 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11135 | 0 | return; |
11136 | 0 | } |
11137 | | |
11138 | | // Do some hand-waving analysis to see if the non-viability is due |
11139 | | // to a qualifier mismatch. |
11140 | 0 | CanQualType CFromTy = S.Context.getCanonicalType(FromTy); |
11141 | 0 | CanQualType CToTy = S.Context.getCanonicalType(ToTy); |
11142 | 0 | if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) |
11143 | 0 | CToTy = RT->getPointeeType(); |
11144 | 0 | else { |
11145 | | // TODO: detect and diagnose the full richness of const mismatches. |
11146 | 0 | if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) |
11147 | 0 | if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { |
11148 | 0 | CFromTy = FromPT->getPointeeType(); |
11149 | 0 | CToTy = ToPT->getPointeeType(); |
11150 | 0 | } |
11151 | 0 | } |
11152 | |
|
11153 | 0 | if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && |
11154 | 0 | !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { |
11155 | 0 | Qualifiers FromQs = CFromTy.getQualifiers(); |
11156 | 0 | Qualifiers ToQs = CToTy.getQualifiers(); |
11157 | |
|
11158 | 0 | if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { |
11159 | 0 | if (isObjectArgument) |
11160 | 0 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) |
11161 | 0 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second |
11162 | 0 | << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace(); |
11163 | 0 | else |
11164 | 0 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) |
11165 | 0 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second |
11166 | 0 | << FnDesc << ToParamRange << FromQs.getAddressSpace() |
11167 | 0 | << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1; |
11168 | 0 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11169 | 0 | return; |
11170 | 0 | } |
11171 | | |
11172 | 0 | if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { |
11173 | 0 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) |
11174 | 0 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
11175 | 0 | << ToParamRange << FromTy << FromQs.getObjCLifetime() |
11176 | 0 | << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1; |
11177 | 0 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11178 | 0 | return; |
11179 | 0 | } |
11180 | | |
11181 | 0 | if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { |
11182 | 0 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) |
11183 | 0 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
11184 | 0 | << ToParamRange << FromTy << FromQs.getObjCGCAttr() |
11185 | 0 | << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1; |
11186 | 0 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11187 | 0 | return; |
11188 | 0 | } |
11189 | | |
11190 | 0 | unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); |
11191 | 0 | assert(CVR && "expected qualifiers mismatch"); |
11192 | | |
11193 | 0 | if (isObjectArgument) { |
11194 | 0 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) |
11195 | 0 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
11196 | 0 | << FromTy << (CVR - 1); |
11197 | 0 | } else { |
11198 | 0 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) |
11199 | 0 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
11200 | 0 | << ToParamRange << FromTy << (CVR - 1) << I + 1; |
11201 | 0 | } |
11202 | 0 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11203 | 0 | return; |
11204 | 0 | } |
11205 | | |
11206 | 0 | if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue || |
11207 | 0 | Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) { |
11208 | 0 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category) |
11209 | 0 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
11210 | 0 | << (unsigned)isObjectArgument << I + 1 |
11211 | 0 | << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) |
11212 | 0 | << ToParamRange; |
11213 | 0 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11214 | 0 | return; |
11215 | 0 | } |
11216 | | |
11217 | | // Special diagnostic for failure to convert an initializer list, since |
11218 | | // telling the user that it has type void is not useful. |
11219 | 0 | if (FromExpr && isa<InitListExpr>(FromExpr)) { |
11220 | 0 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) |
11221 | 0 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
11222 | 0 | << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1 |
11223 | 0 | << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1 |
11224 | 0 | : Conv.Bad.Kind == BadConversionSequence::too_many_initializers |
11225 | 0 | ? 2 |
11226 | 0 | : 0); |
11227 | 0 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11228 | 0 | return; |
11229 | 0 | } |
11230 | | |
11231 | | // Diagnose references or pointers to incomplete types differently, |
11232 | | // since it's far from impossible that the incompleteness triggered |
11233 | | // the failure. |
11234 | 0 | QualType TempFromTy = FromTy.getNonReferenceType(); |
11235 | 0 | if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) |
11236 | 0 | TempFromTy = PTy->getPointeeType(); |
11237 | 0 | if (TempFromTy->isIncompleteType()) { |
11238 | | // Emit the generic diagnostic and, optionally, add the hints to it. |
11239 | 0 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) |
11240 | 0 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
11241 | 0 | << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1 |
11242 | 0 | << (unsigned)(Cand->Fix.Kind); |
11243 | |
|
11244 | 0 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11245 | 0 | return; |
11246 | 0 | } |
11247 | | |
11248 | | // Diagnose base -> derived pointer conversions. |
11249 | 0 | unsigned BaseToDerivedConversion = 0; |
11250 | 0 | if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { |
11251 | 0 | if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { |
11252 | 0 | if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( |
11253 | 0 | FromPtrTy->getPointeeType()) && |
11254 | 0 | !FromPtrTy->getPointeeType()->isIncompleteType() && |
11255 | 0 | !ToPtrTy->getPointeeType()->isIncompleteType() && |
11256 | 0 | S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), |
11257 | 0 | FromPtrTy->getPointeeType())) |
11258 | 0 | BaseToDerivedConversion = 1; |
11259 | 0 | } |
11260 | 0 | } else if (const ObjCObjectPointerType *FromPtrTy |
11261 | 0 | = FromTy->getAs<ObjCObjectPointerType>()) { |
11262 | 0 | if (const ObjCObjectPointerType *ToPtrTy |
11263 | 0 | = ToTy->getAs<ObjCObjectPointerType>()) |
11264 | 0 | if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) |
11265 | 0 | if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) |
11266 | 0 | if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( |
11267 | 0 | FromPtrTy->getPointeeType()) && |
11268 | 0 | FromIface->isSuperClassOf(ToIface)) |
11269 | 0 | BaseToDerivedConversion = 2; |
11270 | 0 | } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { |
11271 | 0 | if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && |
11272 | 0 | !FromTy->isIncompleteType() && |
11273 | 0 | !ToRefTy->getPointeeType()->isIncompleteType() && |
11274 | 0 | S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { |
11275 | 0 | BaseToDerivedConversion = 3; |
11276 | 0 | } |
11277 | 0 | } |
11278 | |
|
11279 | 0 | if (BaseToDerivedConversion) { |
11280 | 0 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) |
11281 | 0 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
11282 | 0 | << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy |
11283 | 0 | << I + 1; |
11284 | 0 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11285 | 0 | return; |
11286 | 0 | } |
11287 | | |
11288 | 0 | if (isa<ObjCObjectPointerType>(CFromTy) && |
11289 | 0 | isa<PointerType>(CToTy)) { |
11290 | 0 | Qualifiers FromQs = CFromTy.getQualifiers(); |
11291 | 0 | Qualifiers ToQs = CToTy.getQualifiers(); |
11292 | 0 | if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { |
11293 | 0 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) |
11294 | 0 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
11295 | 0 | << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument |
11296 | 0 | << I + 1; |
11297 | 0 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11298 | 0 | return; |
11299 | 0 | } |
11300 | 0 | } |
11301 | | |
11302 | 0 | if (TakingCandidateAddress && |
11303 | 0 | !checkAddressOfCandidateIsAvailable(S, Cand->Function)) |
11304 | 0 | return; |
11305 | | |
11306 | | // Emit the generic diagnostic and, optionally, add the hints to it. |
11307 | 0 | PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); |
11308 | 0 | FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
11309 | 0 | << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1 |
11310 | 0 | << (unsigned)(Cand->Fix.Kind); |
11311 | | |
11312 | | // Check that location of Fn is not in system header. |
11313 | 0 | if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) { |
11314 | | // If we can fix the conversion, suggest the FixIts. |
11315 | 0 | for (const FixItHint &HI : Cand->Fix.Hints) |
11316 | 0 | FDiag << HI; |
11317 | 0 | } |
11318 | |
|
11319 | 0 | S.Diag(Fn->getLocation(), FDiag); |
11320 | |
|
11321 | 0 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11322 | 0 | } |
11323 | | |
11324 | | /// Additional arity mismatch diagnosis specific to a function overload |
11325 | | /// candidates. This is not covered by the more general DiagnoseArityMismatch() |
11326 | | /// over a candidate in any candidate set. |
11327 | | static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, |
11328 | 0 | unsigned NumArgs) { |
11329 | 0 | FunctionDecl *Fn = Cand->Function; |
11330 | 0 | unsigned MinParams = Fn->getMinRequiredArguments(); |
11331 | | |
11332 | | // With invalid overloaded operators, it's possible that we think we |
11333 | | // have an arity mismatch when in fact it looks like we have the |
11334 | | // right number of arguments, because only overloaded operators have |
11335 | | // the weird behavior of overloading member and non-member functions. |
11336 | | // Just don't report anything. |
11337 | 0 | if (Fn->isInvalidDecl() && |
11338 | 0 | Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) |
11339 | 0 | return true; |
11340 | | |
11341 | 0 | if (NumArgs < MinParams) { |
11342 | 0 | assert((Cand->FailureKind == ovl_fail_too_few_arguments) || |
11343 | 0 | (Cand->FailureKind == ovl_fail_bad_deduction && |
11344 | 0 | Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); |
11345 | 0 | } else { |
11346 | 0 | assert((Cand->FailureKind == ovl_fail_too_many_arguments) || |
11347 | 0 | (Cand->FailureKind == ovl_fail_bad_deduction && |
11348 | 0 | Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); |
11349 | 0 | } |
11350 | | |
11351 | 0 | return false; |
11352 | 0 | } |
11353 | | |
11354 | | /// General arity mismatch diagnosis over a candidate in a candidate set. |
11355 | | static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, |
11356 | 0 | unsigned NumFormalArgs) { |
11357 | 0 | assert(isa<FunctionDecl>(D) && |
11358 | 0 | "The templated declaration should at least be a function" |
11359 | 0 | " when diagnosing bad template argument deduction due to too many" |
11360 | 0 | " or too few arguments"); |
11361 | | |
11362 | 0 | FunctionDecl *Fn = cast<FunctionDecl>(D); |
11363 | | |
11364 | | // TODO: treat calls to a missing default constructor as a special case |
11365 | 0 | const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>(); |
11366 | 0 | unsigned MinParams = Fn->getMinRequiredExplicitArguments(); |
11367 | | |
11368 | | // at least / at most / exactly |
11369 | 0 | bool HasExplicitObjectParam = Fn->hasCXXExplicitFunctionObjectParameter(); |
11370 | 0 | unsigned ParamCount = FnTy->getNumParams() - (HasExplicitObjectParam ? 1 : 0); |
11371 | 0 | unsigned mode, modeCount; |
11372 | 0 | if (NumFormalArgs < MinParams) { |
11373 | 0 | if (MinParams != ParamCount || FnTy->isVariadic() || |
11374 | 0 | FnTy->isTemplateVariadic()) |
11375 | 0 | mode = 0; // "at least" |
11376 | 0 | else |
11377 | 0 | mode = 2; // "exactly" |
11378 | 0 | modeCount = MinParams; |
11379 | 0 | } else { |
11380 | 0 | if (MinParams != ParamCount) |
11381 | 0 | mode = 1; // "at most" |
11382 | 0 | else |
11383 | 0 | mode = 2; // "exactly" |
11384 | 0 | modeCount = ParamCount; |
11385 | 0 | } |
11386 | |
|
11387 | 0 | std::string Description; |
11388 | 0 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = |
11389 | 0 | ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); |
11390 | |
|
11391 | 0 | if (modeCount == 1 && |
11392 | 0 | Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName()) |
11393 | 0 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) |
11394 | 0 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second |
11395 | 0 | << Description << mode |
11396 | 0 | << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs |
11397 | 0 | << HasExplicitObjectParam << Fn->getParametersSourceRange(); |
11398 | 0 | else |
11399 | 0 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) |
11400 | 0 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second |
11401 | 0 | << Description << mode << modeCount << NumFormalArgs |
11402 | 0 | << HasExplicitObjectParam << Fn->getParametersSourceRange(); |
11403 | |
|
11404 | 0 | MaybeEmitInheritedConstructorNote(S, Found); |
11405 | 0 | } |
11406 | | |
11407 | | /// Arity mismatch diagnosis specific to a function overload candidate. |
11408 | | static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, |
11409 | 0 | unsigned NumFormalArgs) { |
11410 | 0 | if (!CheckArityMismatch(S, Cand, NumFormalArgs)) |
11411 | 0 | DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); |
11412 | 0 | } |
11413 | | |
11414 | 0 | static TemplateDecl *getDescribedTemplate(Decl *Templated) { |
11415 | 0 | if (TemplateDecl *TD = Templated->getDescribedTemplate()) |
11416 | 0 | return TD; |
11417 | 0 | llvm_unreachable("Unsupported: Getting the described template declaration" |
11418 | 0 | " for bad deduction diagnosis"); |
11419 | 0 | } |
11420 | | |
11421 | | /// Diagnose a failed template-argument deduction. |
11422 | | static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, |
11423 | | DeductionFailureInfo &DeductionFailure, |
11424 | | unsigned NumArgs, |
11425 | 0 | bool TakingCandidateAddress) { |
11426 | 0 | TemplateParameter Param = DeductionFailure.getTemplateParameter(); |
11427 | 0 | NamedDecl *ParamD; |
11428 | 0 | (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || |
11429 | 0 | (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || |
11430 | 0 | (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); |
11431 | 0 | switch (DeductionFailure.Result) { |
11432 | 0 | case Sema::TDK_Success: |
11433 | 0 | llvm_unreachable("TDK_success while diagnosing bad deduction"); |
11434 | |
|
11435 | 0 | case Sema::TDK_Incomplete: { |
11436 | 0 | assert(ParamD && "no parameter found for incomplete deduction result"); |
11437 | 0 | S.Diag(Templated->getLocation(), |
11438 | 0 | diag::note_ovl_candidate_incomplete_deduction) |
11439 | 0 | << ParamD->getDeclName(); |
11440 | 0 | MaybeEmitInheritedConstructorNote(S, Found); |
11441 | 0 | return; |
11442 | 0 | } |
11443 | | |
11444 | 0 | case Sema::TDK_IncompletePack: { |
11445 | 0 | assert(ParamD && "no parameter found for incomplete deduction result"); |
11446 | 0 | S.Diag(Templated->getLocation(), |
11447 | 0 | diag::note_ovl_candidate_incomplete_deduction_pack) |
11448 | 0 | << ParamD->getDeclName() |
11449 | 0 | << (DeductionFailure.getFirstArg()->pack_size() + 1) |
11450 | 0 | << *DeductionFailure.getFirstArg(); |
11451 | 0 | MaybeEmitInheritedConstructorNote(S, Found); |
11452 | 0 | return; |
11453 | 0 | } |
11454 | | |
11455 | 0 | case Sema::TDK_Underqualified: { |
11456 | 0 | assert(ParamD && "no parameter found for bad qualifiers deduction result"); |
11457 | 0 | TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); |
11458 | |
|
11459 | 0 | QualType Param = DeductionFailure.getFirstArg()->getAsType(); |
11460 | | |
11461 | | // Param will have been canonicalized, but it should just be a |
11462 | | // qualified version of ParamD, so move the qualifiers to that. |
11463 | 0 | QualifierCollector Qs; |
11464 | 0 | Qs.strip(Param); |
11465 | 0 | QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); |
11466 | 0 | assert(S.Context.hasSameType(Param, NonCanonParam)); |
11467 | | |
11468 | | // Arg has also been canonicalized, but there's nothing we can do |
11469 | | // about that. It also doesn't matter as much, because it won't |
11470 | | // have any template parameters in it (because deduction isn't |
11471 | | // done on dependent types). |
11472 | 0 | QualType Arg = DeductionFailure.getSecondArg()->getAsType(); |
11473 | |
|
11474 | 0 | S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) |
11475 | 0 | << ParamD->getDeclName() << Arg << NonCanonParam; |
11476 | 0 | MaybeEmitInheritedConstructorNote(S, Found); |
11477 | 0 | return; |
11478 | 0 | } |
11479 | | |
11480 | 0 | case Sema::TDK_Inconsistent: { |
11481 | 0 | assert(ParamD && "no parameter found for inconsistent deduction result"); |
11482 | 0 | int which = 0; |
11483 | 0 | if (isa<TemplateTypeParmDecl>(ParamD)) |
11484 | 0 | which = 0; |
11485 | 0 | else if (isa<NonTypeTemplateParmDecl>(ParamD)) { |
11486 | | // Deduction might have failed because we deduced arguments of two |
11487 | | // different types for a non-type template parameter. |
11488 | | // FIXME: Use a different TDK value for this. |
11489 | 0 | QualType T1 = |
11490 | 0 | DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); |
11491 | 0 | QualType T2 = |
11492 | 0 | DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); |
11493 | 0 | if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { |
11494 | 0 | S.Diag(Templated->getLocation(), |
11495 | 0 | diag::note_ovl_candidate_inconsistent_deduction_types) |
11496 | 0 | << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 |
11497 | 0 | << *DeductionFailure.getSecondArg() << T2; |
11498 | 0 | MaybeEmitInheritedConstructorNote(S, Found); |
11499 | 0 | return; |
11500 | 0 | } |
11501 | | |
11502 | 0 | which = 1; |
11503 | 0 | } else { |
11504 | 0 | which = 2; |
11505 | 0 | } |
11506 | | |
11507 | | // Tweak the diagnostic if the problem is that we deduced packs of |
11508 | | // different arities. We'll print the actual packs anyway in case that |
11509 | | // includes additional useful information. |
11510 | 0 | if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && |
11511 | 0 | DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && |
11512 | 0 | DeductionFailure.getFirstArg()->pack_size() != |
11513 | 0 | DeductionFailure.getSecondArg()->pack_size()) { |
11514 | 0 | which = 3; |
11515 | 0 | } |
11516 | |
|
11517 | 0 | S.Diag(Templated->getLocation(), |
11518 | 0 | diag::note_ovl_candidate_inconsistent_deduction) |
11519 | 0 | << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() |
11520 | 0 | << *DeductionFailure.getSecondArg(); |
11521 | 0 | MaybeEmitInheritedConstructorNote(S, Found); |
11522 | 0 | return; |
11523 | 0 | } |
11524 | | |
11525 | 0 | case Sema::TDK_InvalidExplicitArguments: |
11526 | 0 | assert(ParamD && "no parameter found for invalid explicit arguments"); |
11527 | 0 | if (ParamD->getDeclName()) |
11528 | 0 | S.Diag(Templated->getLocation(), |
11529 | 0 | diag::note_ovl_candidate_explicit_arg_mismatch_named) |
11530 | 0 | << ParamD->getDeclName(); |
11531 | 0 | else { |
11532 | 0 | int index = 0; |
11533 | 0 | if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) |
11534 | 0 | index = TTP->getIndex(); |
11535 | 0 | else if (NonTypeTemplateParmDecl *NTTP |
11536 | 0 | = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) |
11537 | 0 | index = NTTP->getIndex(); |
11538 | 0 | else |
11539 | 0 | index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); |
11540 | 0 | S.Diag(Templated->getLocation(), |
11541 | 0 | diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) |
11542 | 0 | << (index + 1); |
11543 | 0 | } |
11544 | 0 | MaybeEmitInheritedConstructorNote(S, Found); |
11545 | 0 | return; |
11546 | | |
11547 | 0 | case Sema::TDK_ConstraintsNotSatisfied: { |
11548 | | // Format the template argument list into the argument string. |
11549 | 0 | SmallString<128> TemplateArgString; |
11550 | 0 | TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); |
11551 | 0 | TemplateArgString = " "; |
11552 | 0 | TemplateArgString += S.getTemplateArgumentBindingsText( |
11553 | 0 | getDescribedTemplate(Templated)->getTemplateParameters(), *Args); |
11554 | 0 | if (TemplateArgString.size() == 1) |
11555 | 0 | TemplateArgString.clear(); |
11556 | 0 | S.Diag(Templated->getLocation(), |
11557 | 0 | diag::note_ovl_candidate_unsatisfied_constraints) |
11558 | 0 | << TemplateArgString; |
11559 | |
|
11560 | 0 | S.DiagnoseUnsatisfiedConstraint( |
11561 | 0 | static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); |
11562 | 0 | return; |
11563 | 0 | } |
11564 | 0 | case Sema::TDK_TooManyArguments: |
11565 | 0 | case Sema::TDK_TooFewArguments: |
11566 | 0 | DiagnoseArityMismatch(S, Found, Templated, NumArgs); |
11567 | 0 | return; |
11568 | | |
11569 | 0 | case Sema::TDK_InstantiationDepth: |
11570 | 0 | S.Diag(Templated->getLocation(), |
11571 | 0 | diag::note_ovl_candidate_instantiation_depth); |
11572 | 0 | MaybeEmitInheritedConstructorNote(S, Found); |
11573 | 0 | return; |
11574 | | |
11575 | 0 | case Sema::TDK_SubstitutionFailure: { |
11576 | | // Format the template argument list into the argument string. |
11577 | 0 | SmallString<128> TemplateArgString; |
11578 | 0 | if (TemplateArgumentList *Args = |
11579 | 0 | DeductionFailure.getTemplateArgumentList()) { |
11580 | 0 | TemplateArgString = " "; |
11581 | 0 | TemplateArgString += S.getTemplateArgumentBindingsText( |
11582 | 0 | getDescribedTemplate(Templated)->getTemplateParameters(), *Args); |
11583 | 0 | if (TemplateArgString.size() == 1) |
11584 | 0 | TemplateArgString.clear(); |
11585 | 0 | } |
11586 | | |
11587 | | // If this candidate was disabled by enable_if, say so. |
11588 | 0 | PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); |
11589 | 0 | if (PDiag && PDiag->second.getDiagID() == |
11590 | 0 | diag::err_typename_nested_not_found_enable_if) { |
11591 | | // FIXME: Use the source range of the condition, and the fully-qualified |
11592 | | // name of the enable_if template. These are both present in PDiag. |
11593 | 0 | S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) |
11594 | 0 | << "'enable_if'" << TemplateArgString; |
11595 | 0 | return; |
11596 | 0 | } |
11597 | | |
11598 | | // We found a specific requirement that disabled the enable_if. |
11599 | 0 | if (PDiag && PDiag->second.getDiagID() == |
11600 | 0 | diag::err_typename_nested_not_found_requirement) { |
11601 | 0 | S.Diag(Templated->getLocation(), |
11602 | 0 | diag::note_ovl_candidate_disabled_by_requirement) |
11603 | 0 | << PDiag->second.getStringArg(0) << TemplateArgString; |
11604 | 0 | return; |
11605 | 0 | } |
11606 | | |
11607 | | // Format the SFINAE diagnostic into the argument string. |
11608 | | // FIXME: Add a general mechanism to include a PartialDiagnostic *'s |
11609 | | // formatted message in another diagnostic. |
11610 | 0 | SmallString<128> SFINAEArgString; |
11611 | 0 | SourceRange R; |
11612 | 0 | if (PDiag) { |
11613 | 0 | SFINAEArgString = ": "; |
11614 | 0 | R = SourceRange(PDiag->first, PDiag->first); |
11615 | 0 | PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); |
11616 | 0 | } |
11617 | |
|
11618 | 0 | S.Diag(Templated->getLocation(), |
11619 | 0 | diag::note_ovl_candidate_substitution_failure) |
11620 | 0 | << TemplateArgString << SFINAEArgString << R; |
11621 | 0 | MaybeEmitInheritedConstructorNote(S, Found); |
11622 | 0 | return; |
11623 | 0 | } |
11624 | | |
11625 | 0 | case Sema::TDK_DeducedMismatch: |
11626 | 0 | case Sema::TDK_DeducedMismatchNested: { |
11627 | | // Format the template argument list into the argument string. |
11628 | 0 | SmallString<128> TemplateArgString; |
11629 | 0 | if (TemplateArgumentList *Args = |
11630 | 0 | DeductionFailure.getTemplateArgumentList()) { |
11631 | 0 | TemplateArgString = " "; |
11632 | 0 | TemplateArgString += S.getTemplateArgumentBindingsText( |
11633 | 0 | getDescribedTemplate(Templated)->getTemplateParameters(), *Args); |
11634 | 0 | if (TemplateArgString.size() == 1) |
11635 | 0 | TemplateArgString.clear(); |
11636 | 0 | } |
11637 | |
|
11638 | 0 | S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) |
11639 | 0 | << (*DeductionFailure.getCallArgIndex() + 1) |
11640 | 0 | << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() |
11641 | 0 | << TemplateArgString |
11642 | 0 | << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); |
11643 | 0 | break; |
11644 | 0 | } |
11645 | | |
11646 | 0 | case Sema::TDK_NonDeducedMismatch: { |
11647 | | // FIXME: Provide a source location to indicate what we couldn't match. |
11648 | 0 | TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); |
11649 | 0 | TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); |
11650 | 0 | if (FirstTA.getKind() == TemplateArgument::Template && |
11651 | 0 | SecondTA.getKind() == TemplateArgument::Template) { |
11652 | 0 | TemplateName FirstTN = FirstTA.getAsTemplate(); |
11653 | 0 | TemplateName SecondTN = SecondTA.getAsTemplate(); |
11654 | 0 | if (FirstTN.getKind() == TemplateName::Template && |
11655 | 0 | SecondTN.getKind() == TemplateName::Template) { |
11656 | 0 | if (FirstTN.getAsTemplateDecl()->getName() == |
11657 | 0 | SecondTN.getAsTemplateDecl()->getName()) { |
11658 | | // FIXME: This fixes a bad diagnostic where both templates are named |
11659 | | // the same. This particular case is a bit difficult since: |
11660 | | // 1) It is passed as a string to the diagnostic printer. |
11661 | | // 2) The diagnostic printer only attempts to find a better |
11662 | | // name for types, not decls. |
11663 | | // Ideally, this should folded into the diagnostic printer. |
11664 | 0 | S.Diag(Templated->getLocation(), |
11665 | 0 | diag::note_ovl_candidate_non_deduced_mismatch_qualified) |
11666 | 0 | << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); |
11667 | 0 | return; |
11668 | 0 | } |
11669 | 0 | } |
11670 | 0 | } |
11671 | | |
11672 | 0 | if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && |
11673 | 0 | !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) |
11674 | 0 | return; |
11675 | | |
11676 | | // FIXME: For generic lambda parameters, check if the function is a lambda |
11677 | | // call operator, and if so, emit a prettier and more informative |
11678 | | // diagnostic that mentions 'auto' and lambda in addition to |
11679 | | // (or instead of?) the canonical template type parameters. |
11680 | 0 | S.Diag(Templated->getLocation(), |
11681 | 0 | diag::note_ovl_candidate_non_deduced_mismatch) |
11682 | 0 | << FirstTA << SecondTA; |
11683 | 0 | return; |
11684 | 0 | } |
11685 | | // TODO: diagnose these individually, then kill off |
11686 | | // note_ovl_candidate_bad_deduction, which is uselessly vague. |
11687 | 0 | case Sema::TDK_MiscellaneousDeductionFailure: |
11688 | 0 | S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); |
11689 | 0 | MaybeEmitInheritedConstructorNote(S, Found); |
11690 | 0 | return; |
11691 | 0 | case Sema::TDK_CUDATargetMismatch: |
11692 | 0 | S.Diag(Templated->getLocation(), |
11693 | 0 | diag::note_cuda_ovl_candidate_target_mismatch); |
11694 | 0 | return; |
11695 | 0 | } |
11696 | 0 | } |
11697 | | |
11698 | | /// Diagnose a failed template-argument deduction, for function calls. |
11699 | | static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, |
11700 | | unsigned NumArgs, |
11701 | 0 | bool TakingCandidateAddress) { |
11702 | 0 | unsigned TDK = Cand->DeductionFailure.Result; |
11703 | 0 | if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { |
11704 | 0 | if (CheckArityMismatch(S, Cand, NumArgs)) |
11705 | 0 | return; |
11706 | 0 | } |
11707 | 0 | DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern |
11708 | 0 | Cand->DeductionFailure, NumArgs, TakingCandidateAddress); |
11709 | 0 | } |
11710 | | |
11711 | | /// CUDA: diagnose an invalid call across targets. |
11712 | 0 | static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { |
11713 | 0 | FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); |
11714 | 0 | FunctionDecl *Callee = Cand->Function; |
11715 | |
|
11716 | 0 | Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), |
11717 | 0 | CalleeTarget = S.IdentifyCUDATarget(Callee); |
11718 | |
|
11719 | 0 | std::string FnDesc; |
11720 | 0 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = |
11721 | 0 | ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, |
11722 | 0 | Cand->getRewriteKind(), FnDesc); |
11723 | |
|
11724 | 0 | S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) |
11725 | 0 | << (unsigned)FnKindPair.first << (unsigned)ocs_non_template |
11726 | 0 | << FnDesc /* Ignored */ |
11727 | 0 | << CalleeTarget << CallerTarget; |
11728 | | |
11729 | | // This could be an implicit constructor for which we could not infer the |
11730 | | // target due to a collsion. Diagnose that case. |
11731 | 0 | CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); |
11732 | 0 | if (Meth != nullptr && Meth->isImplicit()) { |
11733 | 0 | CXXRecordDecl *ParentClass = Meth->getParent(); |
11734 | 0 | Sema::CXXSpecialMember CSM; |
11735 | |
|
11736 | 0 | switch (FnKindPair.first) { |
11737 | 0 | default: |
11738 | 0 | return; |
11739 | 0 | case oc_implicit_default_constructor: |
11740 | 0 | CSM = Sema::CXXDefaultConstructor; |
11741 | 0 | break; |
11742 | 0 | case oc_implicit_copy_constructor: |
11743 | 0 | CSM = Sema::CXXCopyConstructor; |
11744 | 0 | break; |
11745 | 0 | case oc_implicit_move_constructor: |
11746 | 0 | CSM = Sema::CXXMoveConstructor; |
11747 | 0 | break; |
11748 | 0 | case oc_implicit_copy_assignment: |
11749 | 0 | CSM = Sema::CXXCopyAssignment; |
11750 | 0 | break; |
11751 | 0 | case oc_implicit_move_assignment: |
11752 | 0 | CSM = Sema::CXXMoveAssignment; |
11753 | 0 | break; |
11754 | 0 | }; |
11755 | |
|
11756 | 0 | bool ConstRHS = false; |
11757 | 0 | if (Meth->getNumParams()) { |
11758 | 0 | if (const ReferenceType *RT = |
11759 | 0 | Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { |
11760 | 0 | ConstRHS = RT->getPointeeType().isConstQualified(); |
11761 | 0 | } |
11762 | 0 | } |
11763 | |
|
11764 | 0 | S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, |
11765 | 0 | /* ConstRHS */ ConstRHS, |
11766 | 0 | /* Diagnose */ true); |
11767 | 0 | } |
11768 | 0 | } |
11769 | | |
11770 | 0 | static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { |
11771 | 0 | FunctionDecl *Callee = Cand->Function; |
11772 | 0 | EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); |
11773 | |
|
11774 | 0 | S.Diag(Callee->getLocation(), |
11775 | 0 | diag::note_ovl_candidate_disabled_by_function_cond_attr) |
11776 | 0 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); |
11777 | 0 | } |
11778 | | |
11779 | 0 | static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { |
11780 | 0 | ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function); |
11781 | 0 | assert(ES.isExplicit() && "not an explicit candidate"); |
11782 | | |
11783 | 0 | unsigned Kind; |
11784 | 0 | switch (Cand->Function->getDeclKind()) { |
11785 | 0 | case Decl::Kind::CXXConstructor: |
11786 | 0 | Kind = 0; |
11787 | 0 | break; |
11788 | 0 | case Decl::Kind::CXXConversion: |
11789 | 0 | Kind = 1; |
11790 | 0 | break; |
11791 | 0 | case Decl::Kind::CXXDeductionGuide: |
11792 | 0 | Kind = Cand->Function->isImplicit() ? 0 : 2; |
11793 | 0 | break; |
11794 | 0 | default: |
11795 | 0 | llvm_unreachable("invalid Decl"); |
11796 | 0 | } |
11797 | | |
11798 | | // Note the location of the first (in-class) declaration; a redeclaration |
11799 | | // (particularly an out-of-class definition) will typically lack the |
11800 | | // 'explicit' specifier. |
11801 | | // FIXME: This is probably a good thing to do for all 'candidate' notes. |
11802 | 0 | FunctionDecl *First = Cand->Function->getFirstDecl(); |
11803 | 0 | if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) |
11804 | 0 | First = Pattern->getFirstDecl(); |
11805 | |
|
11806 | 0 | S.Diag(First->getLocation(), |
11807 | 0 | diag::note_ovl_candidate_explicit) |
11808 | 0 | << Kind << (ES.getExpr() ? 1 : 0) |
11809 | 0 | << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); |
11810 | 0 | } |
11811 | | |
11812 | | /// Generates a 'note' diagnostic for an overload candidate. We've |
11813 | | /// already generated a primary error at the call site. |
11814 | | /// |
11815 | | /// It really does need to be a single diagnostic with its caret |
11816 | | /// pointed at the candidate declaration. Yes, this creates some |
11817 | | /// major challenges of technical writing. Yes, this makes pointing |
11818 | | /// out problems with specific arguments quite awkward. It's still |
11819 | | /// better than generating twenty screens of text for every failed |
11820 | | /// overload. |
11821 | | /// |
11822 | | /// It would be great to be able to express per-candidate problems |
11823 | | /// more richly for those diagnostic clients that cared, but we'd |
11824 | | /// still have to be just as careful with the default diagnostics. |
11825 | | /// \param CtorDestAS Addr space of object being constructed (for ctor |
11826 | | /// candidates only). |
11827 | | static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, |
11828 | | unsigned NumArgs, |
11829 | | bool TakingCandidateAddress, |
11830 | 0 | LangAS CtorDestAS = LangAS::Default) { |
11831 | 0 | FunctionDecl *Fn = Cand->Function; |
11832 | 0 | if (shouldSkipNotingLambdaConversionDecl(Fn)) |
11833 | 0 | return; |
11834 | | |
11835 | | // There is no physical candidate declaration to point to for OpenCL builtins. |
11836 | | // Except for failed conversions, the notes are identical for each candidate, |
11837 | | // so do not generate such notes. |
11838 | 0 | if (S.getLangOpts().OpenCL && Fn->isImplicit() && |
11839 | 0 | Cand->FailureKind != ovl_fail_bad_conversion) |
11840 | 0 | return; |
11841 | | |
11842 | | // Note deleted candidates, but only if they're viable. |
11843 | 0 | if (Cand->Viable) { |
11844 | 0 | if (Fn->isDeleted()) { |
11845 | 0 | std::string FnDesc; |
11846 | 0 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = |
11847 | 0 | ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, |
11848 | 0 | Cand->getRewriteKind(), FnDesc); |
11849 | |
|
11850 | 0 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) |
11851 | 0 | << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc |
11852 | 0 | << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); |
11853 | 0 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11854 | 0 | return; |
11855 | 0 | } |
11856 | | |
11857 | | // We don't really have anything else to say about viable candidates. |
11858 | 0 | S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); |
11859 | 0 | return; |
11860 | 0 | } |
11861 | | |
11862 | 0 | switch (Cand->FailureKind) { |
11863 | 0 | case ovl_fail_too_many_arguments: |
11864 | 0 | case ovl_fail_too_few_arguments: |
11865 | 0 | return DiagnoseArityMismatch(S, Cand, NumArgs); |
11866 | | |
11867 | 0 | case ovl_fail_bad_deduction: |
11868 | 0 | return DiagnoseBadDeduction(S, Cand, NumArgs, |
11869 | 0 | TakingCandidateAddress); |
11870 | | |
11871 | 0 | case ovl_fail_illegal_constructor: { |
11872 | 0 | S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) |
11873 | 0 | << (Fn->getPrimaryTemplate() ? 1 : 0); |
11874 | 0 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11875 | 0 | return; |
11876 | 0 | } |
11877 | | |
11878 | 0 | case ovl_fail_object_addrspace_mismatch: { |
11879 | 0 | Qualifiers QualsForPrinting; |
11880 | 0 | QualsForPrinting.setAddressSpace(CtorDestAS); |
11881 | 0 | S.Diag(Fn->getLocation(), |
11882 | 0 | diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) |
11883 | 0 | << QualsForPrinting; |
11884 | 0 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11885 | 0 | return; |
11886 | 0 | } |
11887 | | |
11888 | 0 | case ovl_fail_trivial_conversion: |
11889 | 0 | case ovl_fail_bad_final_conversion: |
11890 | 0 | case ovl_fail_final_conversion_not_exact: |
11891 | 0 | return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); |
11892 | | |
11893 | 0 | case ovl_fail_bad_conversion: { |
11894 | 0 | unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); |
11895 | 0 | for (unsigned N = Cand->Conversions.size(); I != N; ++I) |
11896 | 0 | if (Cand->Conversions[I].isBad()) |
11897 | 0 | return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); |
11898 | | |
11899 | | // FIXME: this currently happens when we're called from SemaInit |
11900 | | // when user-conversion overload fails. Figure out how to handle |
11901 | | // those conditions and diagnose them well. |
11902 | 0 | return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); |
11903 | 0 | } |
11904 | | |
11905 | 0 | case ovl_fail_bad_target: |
11906 | 0 | return DiagnoseBadTarget(S, Cand); |
11907 | | |
11908 | 0 | case ovl_fail_enable_if: |
11909 | 0 | return DiagnoseFailedEnableIfAttr(S, Cand); |
11910 | | |
11911 | 0 | case ovl_fail_explicit: |
11912 | 0 | return DiagnoseFailedExplicitSpec(S, Cand); |
11913 | | |
11914 | 0 | case ovl_fail_inhctor_slice: |
11915 | | // It's generally not interesting to note copy/move constructors here. |
11916 | 0 | if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) |
11917 | 0 | return; |
11918 | 0 | S.Diag(Fn->getLocation(), |
11919 | 0 | diag::note_ovl_candidate_inherited_constructor_slice) |
11920 | 0 | << (Fn->getPrimaryTemplate() ? 1 : 0) |
11921 | 0 | << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); |
11922 | 0 | MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); |
11923 | 0 | return; |
11924 | | |
11925 | 0 | case ovl_fail_addr_not_available: { |
11926 | 0 | bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); |
11927 | 0 | (void)Available; |
11928 | 0 | assert(!Available); |
11929 | 0 | break; |
11930 | 0 | } |
11931 | 0 | case ovl_non_default_multiversion_function: |
11932 | | // Do nothing, these should simply be ignored. |
11933 | 0 | break; |
11934 | | |
11935 | 0 | case ovl_fail_constraints_not_satisfied: { |
11936 | 0 | std::string FnDesc; |
11937 | 0 | std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = |
11938 | 0 | ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, |
11939 | 0 | Cand->getRewriteKind(), FnDesc); |
11940 | |
|
11941 | 0 | S.Diag(Fn->getLocation(), |
11942 | 0 | diag::note_ovl_candidate_constraints_not_satisfied) |
11943 | 0 | << (unsigned)FnKindPair.first << (unsigned)ocs_non_template |
11944 | 0 | << FnDesc /* Ignored */; |
11945 | 0 | ConstraintSatisfaction Satisfaction; |
11946 | 0 | if (S.CheckFunctionConstraints(Fn, Satisfaction)) |
11947 | 0 | break; |
11948 | 0 | S.DiagnoseUnsatisfiedConstraint(Satisfaction); |
11949 | 0 | } |
11950 | 0 | } |
11951 | 0 | } |
11952 | | |
11953 | 0 | static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { |
11954 | 0 | if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate)) |
11955 | 0 | return; |
11956 | | |
11957 | | // Desugar the type of the surrogate down to a function type, |
11958 | | // retaining as many typedefs as possible while still showing |
11959 | | // the function type (and, therefore, its parameter types). |
11960 | 0 | QualType FnType = Cand->Surrogate->getConversionType(); |
11961 | 0 | bool isLValueReference = false; |
11962 | 0 | bool isRValueReference = false; |
11963 | 0 | bool isPointer = false; |
11964 | 0 | if (const LValueReferenceType *FnTypeRef = |
11965 | 0 | FnType->getAs<LValueReferenceType>()) { |
11966 | 0 | FnType = FnTypeRef->getPointeeType(); |
11967 | 0 | isLValueReference = true; |
11968 | 0 | } else if (const RValueReferenceType *FnTypeRef = |
11969 | 0 | FnType->getAs<RValueReferenceType>()) { |
11970 | 0 | FnType = FnTypeRef->getPointeeType(); |
11971 | 0 | isRValueReference = true; |
11972 | 0 | } |
11973 | 0 | if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { |
11974 | 0 | FnType = FnTypePtr->getPointeeType(); |
11975 | 0 | isPointer = true; |
11976 | 0 | } |
11977 | | // Desugar down to a function type. |
11978 | 0 | FnType = QualType(FnType->getAs<FunctionType>(), 0); |
11979 | | // Reconstruct the pointer/reference as appropriate. |
11980 | 0 | if (isPointer) FnType = S.Context.getPointerType(FnType); |
11981 | 0 | if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); |
11982 | 0 | if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); |
11983 | |
|
11984 | 0 | if (!Cand->Viable && |
11985 | 0 | Cand->FailureKind == ovl_fail_constraints_not_satisfied) { |
11986 | 0 | S.Diag(Cand->Surrogate->getLocation(), |
11987 | 0 | diag::note_ovl_surrogate_constraints_not_satisfied) |
11988 | 0 | << Cand->Surrogate; |
11989 | 0 | ConstraintSatisfaction Satisfaction; |
11990 | 0 | if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction)) |
11991 | 0 | S.DiagnoseUnsatisfiedConstraint(Satisfaction); |
11992 | 0 | } else { |
11993 | 0 | S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) |
11994 | 0 | << FnType; |
11995 | 0 | } |
11996 | 0 | } |
11997 | | |
11998 | | static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, |
11999 | | SourceLocation OpLoc, |
12000 | 0 | OverloadCandidate *Cand) { |
12001 | 0 | assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); |
12002 | 0 | std::string TypeStr("operator"); |
12003 | 0 | TypeStr += Opc; |
12004 | 0 | TypeStr += "("; |
12005 | 0 | TypeStr += Cand->BuiltinParamTypes[0].getAsString(); |
12006 | 0 | if (Cand->Conversions.size() == 1) { |
12007 | 0 | TypeStr += ")"; |
12008 | 0 | S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; |
12009 | 0 | } else { |
12010 | 0 | TypeStr += ", "; |
12011 | 0 | TypeStr += Cand->BuiltinParamTypes[1].getAsString(); |
12012 | 0 | TypeStr += ")"; |
12013 | 0 | S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; |
12014 | 0 | } |
12015 | 0 | } |
12016 | | |
12017 | | static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, |
12018 | 0 | OverloadCandidate *Cand) { |
12019 | 0 | for (const ImplicitConversionSequence &ICS : Cand->Conversions) { |
12020 | 0 | if (ICS.isBad()) break; // all meaningless after first invalid |
12021 | 0 | if (!ICS.isAmbiguous()) continue; |
12022 | | |
12023 | 0 | ICS.DiagnoseAmbiguousConversion( |
12024 | 0 | S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); |
12025 | 0 | } |
12026 | 0 | } |
12027 | | |
12028 | 0 | static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { |
12029 | 0 | if (Cand->Function) |
12030 | 0 | return Cand->Function->getLocation(); |
12031 | 0 | if (Cand->IsSurrogate) |
12032 | 0 | return Cand->Surrogate->getLocation(); |
12033 | 0 | return SourceLocation(); |
12034 | 0 | } |
12035 | | |
12036 | 0 | static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { |
12037 | 0 | switch ((Sema::TemplateDeductionResult)DFI.Result) { |
12038 | 0 | case Sema::TDK_Success: |
12039 | 0 | case Sema::TDK_NonDependentConversionFailure: |
12040 | 0 | case Sema::TDK_AlreadyDiagnosed: |
12041 | 0 | llvm_unreachable("non-deduction failure while diagnosing bad deduction"); |
12042 | |
|
12043 | 0 | case Sema::TDK_Invalid: |
12044 | 0 | case Sema::TDK_Incomplete: |
12045 | 0 | case Sema::TDK_IncompletePack: |
12046 | 0 | return 1; |
12047 | | |
12048 | 0 | case Sema::TDK_Underqualified: |
12049 | 0 | case Sema::TDK_Inconsistent: |
12050 | 0 | return 2; |
12051 | | |
12052 | 0 | case Sema::TDK_SubstitutionFailure: |
12053 | 0 | case Sema::TDK_DeducedMismatch: |
12054 | 0 | case Sema::TDK_ConstraintsNotSatisfied: |
12055 | 0 | case Sema::TDK_DeducedMismatchNested: |
12056 | 0 | case Sema::TDK_NonDeducedMismatch: |
12057 | 0 | case Sema::TDK_MiscellaneousDeductionFailure: |
12058 | 0 | case Sema::TDK_CUDATargetMismatch: |
12059 | 0 | return 3; |
12060 | | |
12061 | 0 | case Sema::TDK_InstantiationDepth: |
12062 | 0 | return 4; |
12063 | | |
12064 | 0 | case Sema::TDK_InvalidExplicitArguments: |
12065 | 0 | return 5; |
12066 | | |
12067 | 0 | case Sema::TDK_TooManyArguments: |
12068 | 0 | case Sema::TDK_TooFewArguments: |
12069 | 0 | return 6; |
12070 | 0 | } |
12071 | 0 | llvm_unreachable("Unhandled deduction result"); |
12072 | 0 | } |
12073 | | |
12074 | | namespace { |
12075 | | |
12076 | | struct CompareOverloadCandidatesForDisplay { |
12077 | | Sema &S; |
12078 | | SourceLocation Loc; |
12079 | | size_t NumArgs; |
12080 | | OverloadCandidateSet::CandidateSetKind CSK; |
12081 | | |
12082 | | CompareOverloadCandidatesForDisplay( |
12083 | | Sema &S, SourceLocation Loc, size_t NArgs, |
12084 | | OverloadCandidateSet::CandidateSetKind CSK) |
12085 | 0 | : S(S), NumArgs(NArgs), CSK(CSK) {} |
12086 | | |
12087 | 0 | OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { |
12088 | | // If there are too many or too few arguments, that's the high-order bit we |
12089 | | // want to sort by, even if the immediate failure kind was something else. |
12090 | 0 | if (C->FailureKind == ovl_fail_too_many_arguments || |
12091 | 0 | C->FailureKind == ovl_fail_too_few_arguments) |
12092 | 0 | return static_cast<OverloadFailureKind>(C->FailureKind); |
12093 | | |
12094 | 0 | if (C->Function) { |
12095 | 0 | if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) |
12096 | 0 | return ovl_fail_too_many_arguments; |
12097 | 0 | if (NumArgs < C->Function->getMinRequiredArguments()) |
12098 | 0 | return ovl_fail_too_few_arguments; |
12099 | 0 | } |
12100 | | |
12101 | 0 | return static_cast<OverloadFailureKind>(C->FailureKind); |
12102 | 0 | } |
12103 | | |
12104 | | bool operator()(const OverloadCandidate *L, |
12105 | 0 | const OverloadCandidate *R) { |
12106 | | // Fast-path this check. |
12107 | 0 | if (L == R) return false; |
12108 | | |
12109 | | // Order first by viability. |
12110 | 0 | if (L->Viable) { |
12111 | 0 | if (!R->Viable) return true; |
12112 | | |
12113 | 0 | if (int Ord = CompareConversions(*L, *R)) |
12114 | 0 | return Ord < 0; |
12115 | | // Use other tie breakers. |
12116 | 0 | } else if (R->Viable) |
12117 | 0 | return false; |
12118 | | |
12119 | 0 | assert(L->Viable == R->Viable); |
12120 | | |
12121 | | // Criteria by which we can sort non-viable candidates: |
12122 | 0 | if (!L->Viable) { |
12123 | 0 | OverloadFailureKind LFailureKind = EffectiveFailureKind(L); |
12124 | 0 | OverloadFailureKind RFailureKind = EffectiveFailureKind(R); |
12125 | | |
12126 | | // 1. Arity mismatches come after other candidates. |
12127 | 0 | if (LFailureKind == ovl_fail_too_many_arguments || |
12128 | 0 | LFailureKind == ovl_fail_too_few_arguments) { |
12129 | 0 | if (RFailureKind == ovl_fail_too_many_arguments || |
12130 | 0 | RFailureKind == ovl_fail_too_few_arguments) { |
12131 | 0 | int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); |
12132 | 0 | int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); |
12133 | 0 | if (LDist == RDist) { |
12134 | 0 | if (LFailureKind == RFailureKind) |
12135 | | // Sort non-surrogates before surrogates. |
12136 | 0 | return !L->IsSurrogate && R->IsSurrogate; |
12137 | | // Sort candidates requiring fewer parameters than there were |
12138 | | // arguments given after candidates requiring more parameters |
12139 | | // than there were arguments given. |
12140 | 0 | return LFailureKind == ovl_fail_too_many_arguments; |
12141 | 0 | } |
12142 | 0 | return LDist < RDist; |
12143 | 0 | } |
12144 | 0 | return false; |
12145 | 0 | } |
12146 | 0 | if (RFailureKind == ovl_fail_too_many_arguments || |
12147 | 0 | RFailureKind == ovl_fail_too_few_arguments) |
12148 | 0 | return true; |
12149 | | |
12150 | | // 2. Bad conversions come first and are ordered by the number |
12151 | | // of bad conversions and quality of good conversions. |
12152 | 0 | if (LFailureKind == ovl_fail_bad_conversion) { |
12153 | 0 | if (RFailureKind != ovl_fail_bad_conversion) |
12154 | 0 | return true; |
12155 | | |
12156 | | // The conversion that can be fixed with a smaller number of changes, |
12157 | | // comes first. |
12158 | 0 | unsigned numLFixes = L->Fix.NumConversionsFixed; |
12159 | 0 | unsigned numRFixes = R->Fix.NumConversionsFixed; |
12160 | 0 | numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; |
12161 | 0 | numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; |
12162 | 0 | if (numLFixes != numRFixes) { |
12163 | 0 | return numLFixes < numRFixes; |
12164 | 0 | } |
12165 | | |
12166 | | // If there's any ordering between the defined conversions... |
12167 | 0 | if (int Ord = CompareConversions(*L, *R)) |
12168 | 0 | return Ord < 0; |
12169 | 0 | } else if (RFailureKind == ovl_fail_bad_conversion) |
12170 | 0 | return false; |
12171 | | |
12172 | 0 | if (LFailureKind == ovl_fail_bad_deduction) { |
12173 | 0 | if (RFailureKind != ovl_fail_bad_deduction) |
12174 | 0 | return true; |
12175 | | |
12176 | 0 | if (L->DeductionFailure.Result != R->DeductionFailure.Result) { |
12177 | 0 | unsigned LRank = RankDeductionFailure(L->DeductionFailure); |
12178 | 0 | unsigned RRank = RankDeductionFailure(R->DeductionFailure); |
12179 | 0 | if (LRank != RRank) |
12180 | 0 | return LRank < RRank; |
12181 | 0 | } |
12182 | 0 | } else if (RFailureKind == ovl_fail_bad_deduction) |
12183 | 0 | return false; |
12184 | | |
12185 | | // TODO: others? |
12186 | 0 | } |
12187 | | |
12188 | | // Sort everything else by location. |
12189 | 0 | SourceLocation LLoc = GetLocationForCandidate(L); |
12190 | 0 | SourceLocation RLoc = GetLocationForCandidate(R); |
12191 | | |
12192 | | // Put candidates without locations (e.g. builtins) at the end. |
12193 | 0 | if (LLoc.isValid() && RLoc.isValid()) |
12194 | 0 | return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); |
12195 | 0 | if (LLoc.isValid() && !RLoc.isValid()) |
12196 | 0 | return true; |
12197 | 0 | if (RLoc.isValid() && !LLoc.isValid()) |
12198 | 0 | return false; |
12199 | 0 | assert(!LLoc.isValid() && !RLoc.isValid()); |
12200 | | // For builtins and other functions without locations, fallback to the order |
12201 | | // in which they were added into the candidate set. |
12202 | 0 | return L < R; |
12203 | 0 | } |
12204 | | |
12205 | | private: |
12206 | | struct ConversionSignals { |
12207 | | unsigned KindRank = 0; |
12208 | | ImplicitConversionRank Rank = ICR_Exact_Match; |
12209 | | |
12210 | 0 | static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) { |
12211 | 0 | ConversionSignals Sig; |
12212 | 0 | Sig.KindRank = Seq.getKindRank(); |
12213 | 0 | if (Seq.isStandard()) |
12214 | 0 | Sig.Rank = Seq.Standard.getRank(); |
12215 | 0 | else if (Seq.isUserDefined()) |
12216 | 0 | Sig.Rank = Seq.UserDefined.After.getRank(); |
12217 | | // We intend StaticObjectArgumentConversion to compare the same as |
12218 | | // StandardConversion with ICR_ExactMatch rank. |
12219 | 0 | return Sig; |
12220 | 0 | } |
12221 | | |
12222 | 0 | static ConversionSignals ForObjectArgument() { |
12223 | | // We intend StaticObjectArgumentConversion to compare the same as |
12224 | | // StandardConversion with ICR_ExactMatch rank. Default give us that. |
12225 | 0 | return {}; |
12226 | 0 | } |
12227 | | }; |
12228 | | |
12229 | | // Returns -1 if conversions in L are considered better. |
12230 | | // 0 if they are considered indistinguishable. |
12231 | | // 1 if conversions in R are better. |
12232 | | int CompareConversions(const OverloadCandidate &L, |
12233 | 0 | const OverloadCandidate &R) { |
12234 | | // We cannot use `isBetterOverloadCandidate` because it is defined |
12235 | | // according to the C++ standard and provides a partial order, but we need |
12236 | | // a total order as this function is used in sort. |
12237 | 0 | assert(L.Conversions.size() == R.Conversions.size()); |
12238 | 0 | for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) { |
12239 | 0 | auto LS = L.IgnoreObjectArgument && I == 0 |
12240 | 0 | ? ConversionSignals::ForObjectArgument() |
12241 | 0 | : ConversionSignals::ForSequence(L.Conversions[I]); |
12242 | 0 | auto RS = R.IgnoreObjectArgument |
12243 | 0 | ? ConversionSignals::ForObjectArgument() |
12244 | 0 | : ConversionSignals::ForSequence(R.Conversions[I]); |
12245 | 0 | if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank)) |
12246 | 0 | return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank) |
12247 | 0 | ? -1 |
12248 | 0 | : 1; |
12249 | 0 | } |
12250 | | // FIXME: find a way to compare templates for being more or less |
12251 | | // specialized that provides a strict weak ordering. |
12252 | 0 | return 0; |
12253 | 0 | } |
12254 | | }; |
12255 | | } |
12256 | | |
12257 | | /// CompleteNonViableCandidate - Normally, overload resolution only |
12258 | | /// computes up to the first bad conversion. Produces the FixIt set if |
12259 | | /// possible. |
12260 | | static void |
12261 | | CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, |
12262 | | ArrayRef<Expr *> Args, |
12263 | 0 | OverloadCandidateSet::CandidateSetKind CSK) { |
12264 | 0 | assert(!Cand->Viable); |
12265 | | |
12266 | | // Don't do anything on failures other than bad conversion. |
12267 | 0 | if (Cand->FailureKind != ovl_fail_bad_conversion) |
12268 | 0 | return; |
12269 | | |
12270 | | // We only want the FixIts if all the arguments can be corrected. |
12271 | 0 | bool Unfixable = false; |
12272 | | // Use a implicit copy initialization to check conversion fixes. |
12273 | 0 | Cand->Fix.setConversionChecker(TryCopyInitialization); |
12274 | | |
12275 | | // Attempt to fix the bad conversion. |
12276 | 0 | unsigned ConvCount = Cand->Conversions.size(); |
12277 | 0 | for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; |
12278 | 0 | ++ConvIdx) { |
12279 | 0 | assert(ConvIdx != ConvCount && "no bad conversion in candidate"); |
12280 | 0 | if (Cand->Conversions[ConvIdx].isInitialized() && |
12281 | 0 | Cand->Conversions[ConvIdx].isBad()) { |
12282 | 0 | Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); |
12283 | 0 | break; |
12284 | 0 | } |
12285 | 0 | } |
12286 | | |
12287 | | // FIXME: this should probably be preserved from the overload |
12288 | | // operation somehow. |
12289 | 0 | bool SuppressUserConversions = false; |
12290 | |
|
12291 | 0 | unsigned ConvIdx = 0; |
12292 | 0 | unsigned ArgIdx = 0; |
12293 | 0 | ArrayRef<QualType> ParamTypes; |
12294 | 0 | bool Reversed = Cand->isReversed(); |
12295 | |
|
12296 | 0 | if (Cand->IsSurrogate) { |
12297 | 0 | QualType ConvType |
12298 | 0 | = Cand->Surrogate->getConversionType().getNonReferenceType(); |
12299 | 0 | if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) |
12300 | 0 | ConvType = ConvPtrType->getPointeeType(); |
12301 | 0 | ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); |
12302 | | // Conversion 0 is 'this', which doesn't have a corresponding parameter. |
12303 | 0 | ConvIdx = 1; |
12304 | 0 | } else if (Cand->Function) { |
12305 | 0 | ParamTypes = |
12306 | 0 | Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); |
12307 | 0 | if (isa<CXXMethodDecl>(Cand->Function) && |
12308 | 0 | !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { |
12309 | | // Conversion 0 is 'this', which doesn't have a corresponding parameter. |
12310 | 0 | ConvIdx = 1; |
12311 | 0 | if (CSK == OverloadCandidateSet::CSK_Operator && |
12312 | 0 | Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call && |
12313 | 0 | Cand->Function->getDeclName().getCXXOverloadedOperator() != |
12314 | 0 | OO_Subscript) |
12315 | | // Argument 0 is 'this', which doesn't have a corresponding parameter. |
12316 | 0 | ArgIdx = 1; |
12317 | 0 | } |
12318 | 0 | } else { |
12319 | | // Builtin operator. |
12320 | 0 | assert(ConvCount <= 3); |
12321 | 0 | ParamTypes = Cand->BuiltinParamTypes; |
12322 | 0 | } |
12323 | | |
12324 | | // Fill in the rest of the conversions. |
12325 | 0 | for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; |
12326 | 0 | ConvIdx != ConvCount; |
12327 | 0 | ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { |
12328 | 0 | assert(ArgIdx < Args.size() && "no argument for this arg conversion"); |
12329 | 0 | if (Cand->Conversions[ConvIdx].isInitialized()) { |
12330 | | // We've already checked this conversion. |
12331 | 0 | } else if (ParamIdx < ParamTypes.size()) { |
12332 | 0 | if (ParamTypes[ParamIdx]->isDependentType()) |
12333 | 0 | Cand->Conversions[ConvIdx].setAsIdentityConversion( |
12334 | 0 | Args[ArgIdx]->getType()); |
12335 | 0 | else { |
12336 | 0 | Cand->Conversions[ConvIdx] = |
12337 | 0 | TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], |
12338 | 0 | SuppressUserConversions, |
12339 | 0 | /*InOverloadResolution=*/true, |
12340 | | /*AllowObjCWritebackConversion=*/ |
12341 | 0 | S.getLangOpts().ObjCAutoRefCount); |
12342 | | // Store the FixIt in the candidate if it exists. |
12343 | 0 | if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) |
12344 | 0 | Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); |
12345 | 0 | } |
12346 | 0 | } else |
12347 | 0 | Cand->Conversions[ConvIdx].setEllipsis(); |
12348 | 0 | } |
12349 | 0 | } |
12350 | | |
12351 | | SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( |
12352 | | Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, |
12353 | | SourceLocation OpLoc, |
12354 | 0 | llvm::function_ref<bool(OverloadCandidate &)> Filter) { |
12355 | | // Sort the candidates by viability and position. Sorting directly would |
12356 | | // be prohibitive, so we make a set of pointers and sort those. |
12357 | 0 | SmallVector<OverloadCandidate*, 32> Cands; |
12358 | 0 | if (OCD == OCD_AllCandidates) Cands.reserve(size()); |
12359 | 0 | for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { |
12360 | 0 | if (!Filter(*Cand)) |
12361 | 0 | continue; |
12362 | 0 | switch (OCD) { |
12363 | 0 | case OCD_AllCandidates: |
12364 | 0 | if (!Cand->Viable) { |
12365 | 0 | if (!Cand->Function && !Cand->IsSurrogate) { |
12366 | | // This a non-viable builtin candidate. We do not, in general, |
12367 | | // want to list every possible builtin candidate. |
12368 | 0 | continue; |
12369 | 0 | } |
12370 | 0 | CompleteNonViableCandidate(S, Cand, Args, Kind); |
12371 | 0 | } |
12372 | 0 | break; |
12373 | | |
12374 | 0 | case OCD_ViableCandidates: |
12375 | 0 | if (!Cand->Viable) |
12376 | 0 | continue; |
12377 | 0 | break; |
12378 | | |
12379 | 0 | case OCD_AmbiguousCandidates: |
12380 | 0 | if (!Cand->Best) |
12381 | 0 | continue; |
12382 | 0 | break; |
12383 | 0 | } |
12384 | | |
12385 | 0 | Cands.push_back(Cand); |
12386 | 0 | } |
12387 | | |
12388 | 0 | llvm::stable_sort( |
12389 | 0 | Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); |
12390 | |
|
12391 | 0 | return Cands; |
12392 | 0 | } |
12393 | | |
12394 | | bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args, |
12395 | 0 | SourceLocation OpLoc) { |
12396 | 0 | bool DeferHint = false; |
12397 | 0 | if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) { |
12398 | | // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or |
12399 | | // host device candidates. |
12400 | 0 | auto WrongSidedCands = |
12401 | 0 | CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) { |
12402 | 0 | return (Cand.Viable == false && |
12403 | 0 | Cand.FailureKind == ovl_fail_bad_target) || |
12404 | 0 | (Cand.Function && |
12405 | 0 | Cand.Function->template hasAttr<CUDAHostAttr>() && |
12406 | 0 | Cand.Function->template hasAttr<CUDADeviceAttr>()); |
12407 | 0 | }); |
12408 | 0 | DeferHint = !WrongSidedCands.empty(); |
12409 | 0 | } |
12410 | 0 | return DeferHint; |
12411 | 0 | } |
12412 | | |
12413 | | /// When overload resolution fails, prints diagnostic messages containing the |
12414 | | /// candidates in the candidate set. |
12415 | | void OverloadCandidateSet::NoteCandidates( |
12416 | | PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD, |
12417 | | ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc, |
12418 | 0 | llvm::function_ref<bool(OverloadCandidate &)> Filter) { |
12419 | |
|
12420 | 0 | auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); |
12421 | |
|
12422 | 0 | S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc)); |
12423 | | |
12424 | | // In WebAssembly we don't want to emit further diagnostics if a table is |
12425 | | // passed as an argument to a function. |
12426 | 0 | bool NoteCands = true; |
12427 | 0 | for (const Expr *Arg : Args) { |
12428 | 0 | if (Arg->getType()->isWebAssemblyTableType()) |
12429 | 0 | NoteCands = false; |
12430 | 0 | } |
12431 | |
|
12432 | 0 | if (NoteCands) |
12433 | 0 | NoteCandidates(S, Args, Cands, Opc, OpLoc); |
12434 | |
|
12435 | 0 | if (OCD == OCD_AmbiguousCandidates) |
12436 | 0 | MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()}); |
12437 | 0 | } |
12438 | | |
12439 | | void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, |
12440 | | ArrayRef<OverloadCandidate *> Cands, |
12441 | 0 | StringRef Opc, SourceLocation OpLoc) { |
12442 | 0 | bool ReportedAmbiguousConversions = false; |
12443 | |
|
12444 | 0 | const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); |
12445 | 0 | unsigned CandsShown = 0; |
12446 | 0 | auto I = Cands.begin(), E = Cands.end(); |
12447 | 0 | for (; I != E; ++I) { |
12448 | 0 | OverloadCandidate *Cand = *I; |
12449 | |
|
12450 | 0 | if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() && |
12451 | 0 | ShowOverloads == Ovl_Best) { |
12452 | 0 | break; |
12453 | 0 | } |
12454 | 0 | ++CandsShown; |
12455 | |
|
12456 | 0 | if (Cand->Function) |
12457 | 0 | NoteFunctionCandidate(S, Cand, Args.size(), |
12458 | 0 | /*TakingCandidateAddress=*/false, DestAS); |
12459 | 0 | else if (Cand->IsSurrogate) |
12460 | 0 | NoteSurrogateCandidate(S, Cand); |
12461 | 0 | else { |
12462 | 0 | assert(Cand->Viable && |
12463 | 0 | "Non-viable built-in candidates are not added to Cands."); |
12464 | | // Generally we only see ambiguities including viable builtin |
12465 | | // operators if overload resolution got screwed up by an |
12466 | | // ambiguous user-defined conversion. |
12467 | | // |
12468 | | // FIXME: It's quite possible for different conversions to see |
12469 | | // different ambiguities, though. |
12470 | 0 | if (!ReportedAmbiguousConversions) { |
12471 | 0 | NoteAmbiguousUserConversions(S, OpLoc, Cand); |
12472 | 0 | ReportedAmbiguousConversions = true; |
12473 | 0 | } |
12474 | | |
12475 | | // If this is a viable builtin, print it. |
12476 | 0 | NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); |
12477 | 0 | } |
12478 | 0 | } |
12479 | | |
12480 | | // Inform S.Diags that we've shown an overload set with N elements. This may |
12481 | | // inform the future value of S.Diags.getNumOverloadCandidatesToShow(). |
12482 | 0 | S.Diags.overloadCandidatesShown(CandsShown); |
12483 | |
|
12484 | 0 | if (I != E) |
12485 | 0 | S.Diag(OpLoc, diag::note_ovl_too_many_candidates, |
12486 | 0 | shouldDeferDiags(S, Args, OpLoc)) |
12487 | 0 | << int(E - I); |
12488 | 0 | } |
12489 | | |
12490 | | static SourceLocation |
12491 | 0 | GetLocationForCandidate(const TemplateSpecCandidate *Cand) { |
12492 | 0 | return Cand->Specialization ? Cand->Specialization->getLocation() |
12493 | 0 | : SourceLocation(); |
12494 | 0 | } |
12495 | | |
12496 | | namespace { |
12497 | | struct CompareTemplateSpecCandidatesForDisplay { |
12498 | | Sema &S; |
12499 | 0 | CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} |
12500 | | |
12501 | | bool operator()(const TemplateSpecCandidate *L, |
12502 | 0 | const TemplateSpecCandidate *R) { |
12503 | | // Fast-path this check. |
12504 | 0 | if (L == R) |
12505 | 0 | return false; |
12506 | | |
12507 | | // Assuming that both candidates are not matches... |
12508 | | |
12509 | | // Sort by the ranking of deduction failures. |
12510 | 0 | if (L->DeductionFailure.Result != R->DeductionFailure.Result) |
12511 | 0 | return RankDeductionFailure(L->DeductionFailure) < |
12512 | 0 | RankDeductionFailure(R->DeductionFailure); |
12513 | | |
12514 | | // Sort everything else by location. |
12515 | 0 | SourceLocation LLoc = GetLocationForCandidate(L); |
12516 | 0 | SourceLocation RLoc = GetLocationForCandidate(R); |
12517 | | |
12518 | | // Put candidates without locations (e.g. builtins) at the end. |
12519 | 0 | if (LLoc.isInvalid()) |
12520 | 0 | return false; |
12521 | 0 | if (RLoc.isInvalid()) |
12522 | 0 | return true; |
12523 | | |
12524 | 0 | return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); |
12525 | 0 | } |
12526 | | }; |
12527 | | } |
12528 | | |
12529 | | /// Diagnose a template argument deduction failure. |
12530 | | /// We are treating these failures as overload failures due to bad |
12531 | | /// deductions. |
12532 | | void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, |
12533 | 0 | bool ForTakingAddress) { |
12534 | 0 | DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern |
12535 | 0 | DeductionFailure, /*NumArgs=*/0, ForTakingAddress); |
12536 | 0 | } |
12537 | | |
12538 | 0 | void TemplateSpecCandidateSet::destroyCandidates() { |
12539 | 0 | for (iterator i = begin(), e = end(); i != e; ++i) { |
12540 | 0 | i->DeductionFailure.Destroy(); |
12541 | 0 | } |
12542 | 0 | } |
12543 | | |
12544 | 0 | void TemplateSpecCandidateSet::clear() { |
12545 | 0 | destroyCandidates(); |
12546 | 0 | Candidates.clear(); |
12547 | 0 | } |
12548 | | |
12549 | | /// NoteCandidates - When no template specialization match is found, prints |
12550 | | /// diagnostic messages containing the non-matching specializations that form |
12551 | | /// the candidate set. |
12552 | | /// This is analoguous to OverloadCandidateSet::NoteCandidates() with |
12553 | | /// OCD == OCD_AllCandidates and Cand->Viable == false. |
12554 | 0 | void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { |
12555 | | // Sort the candidates by position (assuming no candidate is a match). |
12556 | | // Sorting directly would be prohibitive, so we make a set of pointers |
12557 | | // and sort those. |
12558 | 0 | SmallVector<TemplateSpecCandidate *, 32> Cands; |
12559 | 0 | Cands.reserve(size()); |
12560 | 0 | for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { |
12561 | 0 | if (Cand->Specialization) |
12562 | 0 | Cands.push_back(Cand); |
12563 | | // Otherwise, this is a non-matching builtin candidate. We do not, |
12564 | | // in general, want to list every possible builtin candidate. |
12565 | 0 | } |
12566 | |
|
12567 | 0 | llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); |
12568 | | |
12569 | | // FIXME: Perhaps rename OverloadsShown and getShowOverloads() |
12570 | | // for generalization purposes (?). |
12571 | 0 | const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); |
12572 | |
|
12573 | 0 | SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; |
12574 | 0 | unsigned CandsShown = 0; |
12575 | 0 | for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { |
12576 | 0 | TemplateSpecCandidate *Cand = *I; |
12577 | | |
12578 | | // Set an arbitrary limit on the number of candidates we'll spam |
12579 | | // the user with. FIXME: This limit should depend on details of the |
12580 | | // candidate list. |
12581 | 0 | if (CandsShown >= 4 && ShowOverloads == Ovl_Best) |
12582 | 0 | break; |
12583 | 0 | ++CandsShown; |
12584 | |
|
12585 | 0 | assert(Cand->Specialization && |
12586 | 0 | "Non-matching built-in candidates are not added to Cands."); |
12587 | 0 | Cand->NoteDeductionFailure(S, ForTakingAddress); |
12588 | 0 | } |
12589 | |
|
12590 | 0 | if (I != E) |
12591 | 0 | S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); |
12592 | 0 | } |
12593 | | |
12594 | | // [PossiblyAFunctionType] --> [Return] |
12595 | | // NonFunctionType --> NonFunctionType |
12596 | | // R (A) --> R(A) |
12597 | | // R (*)(A) --> R (A) |
12598 | | // R (&)(A) --> R (A) |
12599 | | // R (S::*)(A) --> R (A) |
12600 | 0 | QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { |
12601 | 0 | QualType Ret = PossiblyAFunctionType; |
12602 | 0 | if (const PointerType *ToTypePtr = |
12603 | 0 | PossiblyAFunctionType->getAs<PointerType>()) |
12604 | 0 | Ret = ToTypePtr->getPointeeType(); |
12605 | 0 | else if (const ReferenceType *ToTypeRef = |
12606 | 0 | PossiblyAFunctionType->getAs<ReferenceType>()) |
12607 | 0 | Ret = ToTypeRef->getPointeeType(); |
12608 | 0 | else if (const MemberPointerType *MemTypePtr = |
12609 | 0 | PossiblyAFunctionType->getAs<MemberPointerType>()) |
12610 | 0 | Ret = MemTypePtr->getPointeeType(); |
12611 | 0 | Ret = |
12612 | 0 | Context.getCanonicalType(Ret).getUnqualifiedType(); |
12613 | 0 | return Ret; |
12614 | 0 | } |
12615 | | |
12616 | | static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, |
12617 | 0 | bool Complain = true) { |
12618 | 0 | if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && |
12619 | 0 | S.DeduceReturnType(FD, Loc, Complain)) |
12620 | 0 | return true; |
12621 | | |
12622 | 0 | auto *FPT = FD->getType()->castAs<FunctionProtoType>(); |
12623 | 0 | if (S.getLangOpts().CPlusPlus17 && |
12624 | 0 | isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && |
12625 | 0 | !S.ResolveExceptionSpec(Loc, FPT)) |
12626 | 0 | return true; |
12627 | | |
12628 | 0 | return false; |
12629 | 0 | } |
12630 | | |
12631 | | namespace { |
12632 | | // A helper class to help with address of function resolution |
12633 | | // - allows us to avoid passing around all those ugly parameters |
12634 | | class AddressOfFunctionResolver { |
12635 | | Sema& S; |
12636 | | Expr* SourceExpr; |
12637 | | const QualType& TargetType; |
12638 | | QualType TargetFunctionType; // Extracted function type from target type |
12639 | | |
12640 | | bool Complain; |
12641 | | //DeclAccessPair& ResultFunctionAccessPair; |
12642 | | ASTContext& Context; |
12643 | | |
12644 | | bool TargetTypeIsNonStaticMemberFunction; |
12645 | | bool FoundNonTemplateFunction; |
12646 | | bool StaticMemberFunctionFromBoundPointer; |
12647 | | bool HasComplained; |
12648 | | |
12649 | | OverloadExpr::FindResult OvlExprInfo; |
12650 | | OverloadExpr *OvlExpr; |
12651 | | TemplateArgumentListInfo OvlExplicitTemplateArgs; |
12652 | | SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; |
12653 | | TemplateSpecCandidateSet FailedCandidates; |
12654 | | |
12655 | | public: |
12656 | | AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, |
12657 | | const QualType &TargetType, bool Complain) |
12658 | | : S(S), SourceExpr(SourceExpr), TargetType(TargetType), |
12659 | | Complain(Complain), Context(S.getASTContext()), |
12660 | | TargetTypeIsNonStaticMemberFunction( |
12661 | | !!TargetType->getAs<MemberPointerType>()), |
12662 | | FoundNonTemplateFunction(false), |
12663 | | StaticMemberFunctionFromBoundPointer(false), |
12664 | | HasComplained(false), |
12665 | | OvlExprInfo(OverloadExpr::find(SourceExpr)), |
12666 | | OvlExpr(OvlExprInfo.Expression), |
12667 | 0 | FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { |
12668 | 0 | ExtractUnqualifiedFunctionTypeFromTargetType(); |
12669 | |
|
12670 | 0 | if (TargetFunctionType->isFunctionType()) { |
12671 | 0 | if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) |
12672 | 0 | if (!UME->isImplicitAccess() && |
12673 | 0 | !S.ResolveSingleFunctionTemplateSpecialization(UME)) |
12674 | 0 | StaticMemberFunctionFromBoundPointer = true; |
12675 | 0 | } else if (OvlExpr->hasExplicitTemplateArgs()) { |
12676 | 0 | DeclAccessPair dap; |
12677 | 0 | if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( |
12678 | 0 | OvlExpr, false, &dap)) { |
12679 | 0 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) |
12680 | 0 | if (!Method->isStatic()) { |
12681 | | // If the target type is a non-function type and the function found |
12682 | | // is a non-static member function, pretend as if that was the |
12683 | | // target, it's the only possible type to end up with. |
12684 | 0 | TargetTypeIsNonStaticMemberFunction = true; |
12685 | | |
12686 | | // And skip adding the function if its not in the proper form. |
12687 | | // We'll diagnose this due to an empty set of functions. |
12688 | 0 | if (!OvlExprInfo.HasFormOfMemberPointer) |
12689 | 0 | return; |
12690 | 0 | } |
12691 | | |
12692 | 0 | Matches.push_back(std::make_pair(dap, Fn)); |
12693 | 0 | } |
12694 | 0 | return; |
12695 | 0 | } |
12696 | | |
12697 | 0 | if (OvlExpr->hasExplicitTemplateArgs()) |
12698 | 0 | OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); |
12699 | |
|
12700 | 0 | if (FindAllFunctionsThatMatchTargetTypeExactly()) { |
12701 | | // C++ [over.over]p4: |
12702 | | // If more than one function is selected, [...] |
12703 | 0 | if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { |
12704 | 0 | if (FoundNonTemplateFunction) |
12705 | 0 | EliminateAllTemplateMatches(); |
12706 | 0 | else |
12707 | 0 | EliminateAllExceptMostSpecializedTemplate(); |
12708 | 0 | } |
12709 | 0 | } |
12710 | |
|
12711 | 0 | if (S.getLangOpts().CUDA && Matches.size() > 1) |
12712 | 0 | EliminateSuboptimalCudaMatches(); |
12713 | 0 | } |
12714 | | |
12715 | 0 | bool hasComplained() const { return HasComplained; } |
12716 | | |
12717 | | private: |
12718 | 0 | bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { |
12719 | 0 | QualType Discard; |
12720 | 0 | return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || |
12721 | 0 | S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); |
12722 | 0 | } |
12723 | | |
12724 | | /// \return true if A is considered a better overload candidate for the |
12725 | | /// desired type than B. |
12726 | 0 | bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { |
12727 | | // If A doesn't have exactly the correct type, we don't want to classify it |
12728 | | // as "better" than anything else. This way, the user is required to |
12729 | | // disambiguate for us if there are multiple candidates and no exact match. |
12730 | 0 | return candidateHasExactlyCorrectType(A) && |
12731 | 0 | (!candidateHasExactlyCorrectType(B) || |
12732 | 0 | compareEnableIfAttrs(S, A, B) == Comparison::Better); |
12733 | 0 | } |
12734 | | |
12735 | | /// \return true if we were able to eliminate all but one overload candidate, |
12736 | | /// false otherwise. |
12737 | 0 | bool eliminiateSuboptimalOverloadCandidates() { |
12738 | | // Same algorithm as overload resolution -- one pass to pick the "best", |
12739 | | // another pass to be sure that nothing is better than the best. |
12740 | 0 | auto Best = Matches.begin(); |
12741 | 0 | for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) |
12742 | 0 | if (isBetterCandidate(I->second, Best->second)) |
12743 | 0 | Best = I; |
12744 | |
|
12745 | 0 | const FunctionDecl *BestFn = Best->second; |
12746 | 0 | auto IsBestOrInferiorToBest = [this, BestFn]( |
12747 | 0 | const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { |
12748 | 0 | return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); |
12749 | 0 | }; |
12750 | | |
12751 | | // Note: We explicitly leave Matches unmodified if there isn't a clear best |
12752 | | // option, so we can potentially give the user a better error |
12753 | 0 | if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) |
12754 | 0 | return false; |
12755 | 0 | Matches[0] = *Best; |
12756 | 0 | Matches.resize(1); |
12757 | 0 | return true; |
12758 | 0 | } |
12759 | | |
12760 | 0 | bool isTargetTypeAFunction() const { |
12761 | 0 | return TargetFunctionType->isFunctionType(); |
12762 | 0 | } |
12763 | | |
12764 | | // [ToType] [Return] |
12765 | | |
12766 | | // R (*)(A) --> R (A), IsNonStaticMemberFunction = false |
12767 | | // R (&)(A) --> R (A), IsNonStaticMemberFunction = false |
12768 | | // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true |
12769 | 0 | void inline ExtractUnqualifiedFunctionTypeFromTargetType() { |
12770 | 0 | TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); |
12771 | 0 | } |
12772 | | |
12773 | | // return true if any matching specializations were found |
12774 | | bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, |
12775 | 0 | const DeclAccessPair& CurAccessFunPair) { |
12776 | 0 | if (CXXMethodDecl *Method |
12777 | 0 | = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { |
12778 | | // Skip non-static function templates when converting to pointer, and |
12779 | | // static when converting to member pointer. |
12780 | 0 | bool CanConvertToFunctionPointer = |
12781 | 0 | Method->isStatic() || Method->isExplicitObjectMemberFunction(); |
12782 | 0 | if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction) |
12783 | 0 | return false; |
12784 | 0 | } |
12785 | 0 | else if (TargetTypeIsNonStaticMemberFunction) |
12786 | 0 | return false; |
12787 | | |
12788 | | // C++ [over.over]p2: |
12789 | | // If the name is a function template, template argument deduction is |
12790 | | // done (14.8.2.2), and if the argument deduction succeeds, the |
12791 | | // resulting template argument list is used to generate a single |
12792 | | // function template specialization, which is added to the set of |
12793 | | // overloaded functions considered. |
12794 | 0 | FunctionDecl *Specialization = nullptr; |
12795 | 0 | TemplateDeductionInfo Info(FailedCandidates.getLocation()); |
12796 | 0 | if (Sema::TemplateDeductionResult Result |
12797 | 0 | = S.DeduceTemplateArguments(FunctionTemplate, |
12798 | 0 | &OvlExplicitTemplateArgs, |
12799 | 0 | TargetFunctionType, Specialization, |
12800 | 0 | Info, /*IsAddressOfFunction*/true)) { |
12801 | | // Make a note of the failed deduction for diagnostics. |
12802 | 0 | FailedCandidates.addCandidate() |
12803 | 0 | .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), |
12804 | 0 | MakeDeductionFailureInfo(Context, Result, Info)); |
12805 | 0 | return false; |
12806 | 0 | } |
12807 | | |
12808 | | // Template argument deduction ensures that we have an exact match or |
12809 | | // compatible pointer-to-function arguments that would be adjusted by ICS. |
12810 | | // This function template specicalization works. |
12811 | 0 | assert(S.isSameOrCompatibleFunctionType( |
12812 | 0 | Context.getCanonicalType(Specialization->getType()), |
12813 | 0 | Context.getCanonicalType(TargetFunctionType))); |
12814 | | |
12815 | 0 | if (!S.checkAddressOfFunctionIsAvailable(Specialization)) |
12816 | 0 | return false; |
12817 | | |
12818 | 0 | Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); |
12819 | 0 | return true; |
12820 | 0 | } |
12821 | | |
12822 | | bool AddMatchingNonTemplateFunction(NamedDecl* Fn, |
12823 | 0 | const DeclAccessPair& CurAccessFunPair) { |
12824 | 0 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { |
12825 | | // Skip non-static functions when converting to pointer, and static |
12826 | | // when converting to member pointer. |
12827 | 0 | bool CanConvertToFunctionPointer = |
12828 | 0 | Method->isStatic() || Method->isExplicitObjectMemberFunction(); |
12829 | 0 | if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction) |
12830 | 0 | return false; |
12831 | 0 | } |
12832 | 0 | else if (TargetTypeIsNonStaticMemberFunction) |
12833 | 0 | return false; |
12834 | | |
12835 | 0 | if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { |
12836 | 0 | if (S.getLangOpts().CUDA) { |
12837 | 0 | FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); |
12838 | 0 | if (!(Caller && Caller->isImplicit()) && |
12839 | 0 | !S.IsAllowedCUDACall(Caller, FunDecl)) |
12840 | 0 | return false; |
12841 | 0 | } |
12842 | 0 | if (FunDecl->isMultiVersion()) { |
12843 | 0 | const auto *TA = FunDecl->getAttr<TargetAttr>(); |
12844 | 0 | if (TA && !TA->isDefaultVersion()) |
12845 | 0 | return false; |
12846 | 0 | const auto *TVA = FunDecl->getAttr<TargetVersionAttr>(); |
12847 | 0 | if (TVA && !TVA->isDefaultVersion()) |
12848 | 0 | return false; |
12849 | 0 | } |
12850 | | |
12851 | | // If any candidate has a placeholder return type, trigger its deduction |
12852 | | // now. |
12853 | 0 | if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), |
12854 | 0 | Complain)) { |
12855 | 0 | HasComplained |= Complain; |
12856 | 0 | return false; |
12857 | 0 | } |
12858 | | |
12859 | 0 | if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) |
12860 | 0 | return false; |
12861 | | |
12862 | | // If we're in C, we need to support types that aren't exactly identical. |
12863 | 0 | if (!S.getLangOpts().CPlusPlus || |
12864 | 0 | candidateHasExactlyCorrectType(FunDecl)) { |
12865 | 0 | Matches.push_back(std::make_pair( |
12866 | 0 | CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); |
12867 | 0 | FoundNonTemplateFunction = true; |
12868 | 0 | return true; |
12869 | 0 | } |
12870 | 0 | } |
12871 | | |
12872 | 0 | return false; |
12873 | 0 | } |
12874 | | |
12875 | 0 | bool FindAllFunctionsThatMatchTargetTypeExactly() { |
12876 | 0 | bool Ret = false; |
12877 | | |
12878 | | // If the overload expression doesn't have the form of a pointer to |
12879 | | // member, don't try to convert it to a pointer-to-member type. |
12880 | 0 | if (IsInvalidFormOfPointerToMemberFunction()) |
12881 | 0 | return false; |
12882 | | |
12883 | 0 | for (UnresolvedSetIterator I = OvlExpr->decls_begin(), |
12884 | 0 | E = OvlExpr->decls_end(); |
12885 | 0 | I != E; ++I) { |
12886 | | // Look through any using declarations to find the underlying function. |
12887 | 0 | NamedDecl *Fn = (*I)->getUnderlyingDecl(); |
12888 | | |
12889 | | // C++ [over.over]p3: |
12890 | | // Non-member functions and static member functions match |
12891 | | // targets of type "pointer-to-function" or "reference-to-function." |
12892 | | // Nonstatic member functions match targets of |
12893 | | // type "pointer-to-member-function." |
12894 | | // Note that according to DR 247, the containing class does not matter. |
12895 | 0 | if (FunctionTemplateDecl *FunctionTemplate |
12896 | 0 | = dyn_cast<FunctionTemplateDecl>(Fn)) { |
12897 | 0 | if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) |
12898 | 0 | Ret = true; |
12899 | 0 | } |
12900 | | // If we have explicit template arguments supplied, skip non-templates. |
12901 | 0 | else if (!OvlExpr->hasExplicitTemplateArgs() && |
12902 | 0 | AddMatchingNonTemplateFunction(Fn, I.getPair())) |
12903 | 0 | Ret = true; |
12904 | 0 | } |
12905 | 0 | assert(Ret || Matches.empty()); |
12906 | 0 | return Ret; |
12907 | 0 | } |
12908 | | |
12909 | 0 | void EliminateAllExceptMostSpecializedTemplate() { |
12910 | | // [...] and any given function template specialization F1 is |
12911 | | // eliminated if the set contains a second function template |
12912 | | // specialization whose function template is more specialized |
12913 | | // than the function template of F1 according to the partial |
12914 | | // ordering rules of 14.5.5.2. |
12915 | | |
12916 | | // The algorithm specified above is quadratic. We instead use a |
12917 | | // two-pass algorithm (similar to the one used to identify the |
12918 | | // best viable function in an overload set) that identifies the |
12919 | | // best function template (if it exists). |
12920 | |
|
12921 | 0 | UnresolvedSet<4> MatchesCopy; // TODO: avoid! |
12922 | 0 | for (unsigned I = 0, E = Matches.size(); I != E; ++I) |
12923 | 0 | MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); |
12924 | | |
12925 | | // TODO: It looks like FailedCandidates does not serve much purpose |
12926 | | // here, since the no_viable diagnostic has index 0. |
12927 | 0 | UnresolvedSetIterator Result = S.getMostSpecialized( |
12928 | 0 | MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, |
12929 | 0 | SourceExpr->getBeginLoc(), S.PDiag(), |
12930 | 0 | S.PDiag(diag::err_addr_ovl_ambiguous) |
12931 | 0 | << Matches[0].second->getDeclName(), |
12932 | 0 | S.PDiag(diag::note_ovl_candidate) |
12933 | 0 | << (unsigned)oc_function << (unsigned)ocs_described_template, |
12934 | 0 | Complain, TargetFunctionType); |
12935 | |
|
12936 | 0 | if (Result != MatchesCopy.end()) { |
12937 | | // Make it the first and only element |
12938 | 0 | Matches[0].first = Matches[Result - MatchesCopy.begin()].first; |
12939 | 0 | Matches[0].second = cast<FunctionDecl>(*Result); |
12940 | 0 | Matches.resize(1); |
12941 | 0 | } else |
12942 | 0 | HasComplained |= Complain; |
12943 | 0 | } |
12944 | | |
12945 | 0 | void EliminateAllTemplateMatches() { |
12946 | | // [...] any function template specializations in the set are |
12947 | | // eliminated if the set also contains a non-template function, [...] |
12948 | 0 | for (unsigned I = 0, N = Matches.size(); I != N; ) { |
12949 | 0 | if (Matches[I].second->getPrimaryTemplate() == nullptr) |
12950 | 0 | ++I; |
12951 | 0 | else { |
12952 | 0 | Matches[I] = Matches[--N]; |
12953 | 0 | Matches.resize(N); |
12954 | 0 | } |
12955 | 0 | } |
12956 | 0 | } |
12957 | | |
12958 | 0 | void EliminateSuboptimalCudaMatches() { |
12959 | 0 | S.EraseUnwantedCUDAMatches(S.getCurFunctionDecl(/*AllowLambda=*/true), |
12960 | 0 | Matches); |
12961 | 0 | } |
12962 | | |
12963 | | public: |
12964 | 0 | void ComplainNoMatchesFound() const { |
12965 | 0 | assert(Matches.empty()); |
12966 | 0 | S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) |
12967 | 0 | << OvlExpr->getName() << TargetFunctionType |
12968 | 0 | << OvlExpr->getSourceRange(); |
12969 | 0 | if (FailedCandidates.empty()) |
12970 | 0 | S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, |
12971 | 0 | /*TakingAddress=*/true); |
12972 | 0 | else { |
12973 | | // We have some deduction failure messages. Use them to diagnose |
12974 | | // the function templates, and diagnose the non-template candidates |
12975 | | // normally. |
12976 | 0 | for (UnresolvedSetIterator I = OvlExpr->decls_begin(), |
12977 | 0 | IEnd = OvlExpr->decls_end(); |
12978 | 0 | I != IEnd; ++I) |
12979 | 0 | if (FunctionDecl *Fun = |
12980 | 0 | dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) |
12981 | 0 | if (!functionHasPassObjectSizeParams(Fun)) |
12982 | 0 | S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, |
12983 | 0 | /*TakingAddress=*/true); |
12984 | 0 | FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); |
12985 | 0 | } |
12986 | 0 | } |
12987 | | |
12988 | 0 | bool IsInvalidFormOfPointerToMemberFunction() const { |
12989 | 0 | return TargetTypeIsNonStaticMemberFunction && |
12990 | 0 | !OvlExprInfo.HasFormOfMemberPointer; |
12991 | 0 | } |
12992 | | |
12993 | 0 | void ComplainIsInvalidFormOfPointerToMemberFunction() const { |
12994 | | // TODO: Should we condition this on whether any functions might |
12995 | | // have matched, or is it more appropriate to do that in callers? |
12996 | | // TODO: a fixit wouldn't hurt. |
12997 | 0 | S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) |
12998 | 0 | << TargetType << OvlExpr->getSourceRange(); |
12999 | 0 | } |
13000 | | |
13001 | 0 | bool IsStaticMemberFunctionFromBoundPointer() const { |
13002 | 0 | return StaticMemberFunctionFromBoundPointer; |
13003 | 0 | } |
13004 | | |
13005 | 0 | void ComplainIsStaticMemberFunctionFromBoundPointer() const { |
13006 | 0 | S.Diag(OvlExpr->getBeginLoc(), |
13007 | 0 | diag::err_invalid_form_pointer_member_function) |
13008 | 0 | << OvlExpr->getSourceRange(); |
13009 | 0 | } |
13010 | | |
13011 | 0 | void ComplainOfInvalidConversion() const { |
13012 | 0 | S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) |
13013 | 0 | << OvlExpr->getName() << TargetType; |
13014 | 0 | } |
13015 | | |
13016 | 0 | void ComplainMultipleMatchesFound() const { |
13017 | 0 | assert(Matches.size() > 1); |
13018 | 0 | S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) |
13019 | 0 | << OvlExpr->getName() << OvlExpr->getSourceRange(); |
13020 | 0 | S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, |
13021 | 0 | /*TakingAddress=*/true); |
13022 | 0 | } |
13023 | | |
13024 | 0 | bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } |
13025 | | |
13026 | 0 | int getNumMatches() const { return Matches.size(); } |
13027 | | |
13028 | 0 | FunctionDecl* getMatchingFunctionDecl() const { |
13029 | 0 | if (Matches.size() != 1) return nullptr; |
13030 | 0 | return Matches[0].second; |
13031 | 0 | } |
13032 | | |
13033 | 0 | const DeclAccessPair* getMatchingFunctionAccessPair() const { |
13034 | 0 | if (Matches.size() != 1) return nullptr; |
13035 | 0 | return &Matches[0].first; |
13036 | 0 | } |
13037 | | }; |
13038 | | } |
13039 | | |
13040 | | /// ResolveAddressOfOverloadedFunction - Try to resolve the address of |
13041 | | /// an overloaded function (C++ [over.over]), where @p From is an |
13042 | | /// expression with overloaded function type and @p ToType is the type |
13043 | | /// we're trying to resolve to. For example: |
13044 | | /// |
13045 | | /// @code |
13046 | | /// int f(double); |
13047 | | /// int f(int); |
13048 | | /// |
13049 | | /// int (*pfd)(double) = f; // selects f(double) |
13050 | | /// @endcode |
13051 | | /// |
13052 | | /// This routine returns the resulting FunctionDecl if it could be |
13053 | | /// resolved, and NULL otherwise. When @p Complain is true, this |
13054 | | /// routine will emit diagnostics if there is an error. |
13055 | | FunctionDecl * |
13056 | | Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, |
13057 | | QualType TargetType, |
13058 | | bool Complain, |
13059 | | DeclAccessPair &FoundResult, |
13060 | 0 | bool *pHadMultipleCandidates) { |
13061 | 0 | assert(AddressOfExpr->getType() == Context.OverloadTy); |
13062 | | |
13063 | 0 | AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, |
13064 | 0 | Complain); |
13065 | 0 | int NumMatches = Resolver.getNumMatches(); |
13066 | 0 | FunctionDecl *Fn = nullptr; |
13067 | 0 | bool ShouldComplain = Complain && !Resolver.hasComplained(); |
13068 | 0 | if (NumMatches == 0 && ShouldComplain) { |
13069 | 0 | if (Resolver.IsInvalidFormOfPointerToMemberFunction()) |
13070 | 0 | Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); |
13071 | 0 | else |
13072 | 0 | Resolver.ComplainNoMatchesFound(); |
13073 | 0 | } |
13074 | 0 | else if (NumMatches > 1 && ShouldComplain) |
13075 | 0 | Resolver.ComplainMultipleMatchesFound(); |
13076 | 0 | else if (NumMatches == 1) { |
13077 | 0 | Fn = Resolver.getMatchingFunctionDecl(); |
13078 | 0 | assert(Fn); |
13079 | 0 | if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) |
13080 | 0 | ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); |
13081 | 0 | FoundResult = *Resolver.getMatchingFunctionAccessPair(); |
13082 | 0 | if (Complain) { |
13083 | 0 | if (Resolver.IsStaticMemberFunctionFromBoundPointer()) |
13084 | 0 | Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); |
13085 | 0 | else |
13086 | 0 | CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); |
13087 | 0 | } |
13088 | 0 | } |
13089 | | |
13090 | 0 | if (pHadMultipleCandidates) |
13091 | 0 | *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); |
13092 | 0 | return Fn; |
13093 | 0 | } |
13094 | | |
13095 | | /// Given an expression that refers to an overloaded function, try to |
13096 | | /// resolve that function to a single function that can have its address taken. |
13097 | | /// This will modify `Pair` iff it returns non-null. |
13098 | | /// |
13099 | | /// This routine can only succeed if from all of the candidates in the overload |
13100 | | /// set for SrcExpr that can have their addresses taken, there is one candidate |
13101 | | /// that is more constrained than the rest. |
13102 | | FunctionDecl * |
13103 | 0 | Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { |
13104 | 0 | OverloadExpr::FindResult R = OverloadExpr::find(E); |
13105 | 0 | OverloadExpr *Ovl = R.Expression; |
13106 | 0 | bool IsResultAmbiguous = false; |
13107 | 0 | FunctionDecl *Result = nullptr; |
13108 | 0 | DeclAccessPair DAP; |
13109 | 0 | SmallVector<FunctionDecl *, 2> AmbiguousDecls; |
13110 | | |
13111 | | // Return positive for better, negative for worse, 0 for equal preference. |
13112 | 0 | auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) { |
13113 | 0 | FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true); |
13114 | 0 | return static_cast<int>(IdentifyCUDAPreference(Caller, FD1)) - |
13115 | 0 | static_cast<int>(IdentifyCUDAPreference(Caller, FD2)); |
13116 | 0 | }; |
13117 | |
|
13118 | 0 | auto CheckMoreConstrained = [&](FunctionDecl *FD1, |
13119 | 0 | FunctionDecl *FD2) -> std::optional<bool> { |
13120 | 0 | if (FunctionDecl *MF = FD1->getInstantiatedFromMemberFunction()) |
13121 | 0 | FD1 = MF; |
13122 | 0 | if (FunctionDecl *MF = FD2->getInstantiatedFromMemberFunction()) |
13123 | 0 | FD2 = MF; |
13124 | 0 | SmallVector<const Expr *, 1> AC1, AC2; |
13125 | 0 | FD1->getAssociatedConstraints(AC1); |
13126 | 0 | FD2->getAssociatedConstraints(AC2); |
13127 | 0 | bool AtLeastAsConstrained1, AtLeastAsConstrained2; |
13128 | 0 | if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1)) |
13129 | 0 | return std::nullopt; |
13130 | 0 | if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2)) |
13131 | 0 | return std::nullopt; |
13132 | 0 | if (AtLeastAsConstrained1 == AtLeastAsConstrained2) |
13133 | 0 | return std::nullopt; |
13134 | 0 | return AtLeastAsConstrained1; |
13135 | 0 | }; |
13136 | | |
13137 | | // Don't use the AddressOfResolver because we're specifically looking for |
13138 | | // cases where we have one overload candidate that lacks |
13139 | | // enable_if/pass_object_size/... |
13140 | 0 | for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { |
13141 | 0 | auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); |
13142 | 0 | if (!FD) |
13143 | 0 | return nullptr; |
13144 | | |
13145 | 0 | if (!checkAddressOfFunctionIsAvailable(FD)) |
13146 | 0 | continue; |
13147 | | |
13148 | | // If we found a better result, update Result. |
13149 | 0 | auto FoundBetter = [&]() { |
13150 | 0 | IsResultAmbiguous = false; |
13151 | 0 | DAP = I.getPair(); |
13152 | 0 | Result = FD; |
13153 | 0 | }; |
13154 | | |
13155 | | // We have more than one result - see if it is more constrained than the |
13156 | | // previous one. |
13157 | 0 | if (Result) { |
13158 | | // Check CUDA preference first. If the candidates have differennt CUDA |
13159 | | // preference, choose the one with higher CUDA preference. Otherwise, |
13160 | | // choose the one with more constraints. |
13161 | 0 | if (getLangOpts().CUDA) { |
13162 | 0 | int PreferenceByCUDA = CheckCUDAPreference(FD, Result); |
13163 | | // FD has different preference than Result. |
13164 | 0 | if (PreferenceByCUDA != 0) { |
13165 | | // FD is more preferable than Result. |
13166 | 0 | if (PreferenceByCUDA > 0) |
13167 | 0 | FoundBetter(); |
13168 | 0 | continue; |
13169 | 0 | } |
13170 | 0 | } |
13171 | | // FD has the same CUDA prefernece than Result. Continue check |
13172 | | // constraints. |
13173 | 0 | std::optional<bool> MoreConstrainedThanPrevious = |
13174 | 0 | CheckMoreConstrained(FD, Result); |
13175 | 0 | if (!MoreConstrainedThanPrevious) { |
13176 | 0 | IsResultAmbiguous = true; |
13177 | 0 | AmbiguousDecls.push_back(FD); |
13178 | 0 | continue; |
13179 | 0 | } |
13180 | 0 | if (!*MoreConstrainedThanPrevious) |
13181 | 0 | continue; |
13182 | | // FD is more constrained - replace Result with it. |
13183 | 0 | } |
13184 | 0 | FoundBetter(); |
13185 | 0 | } |
13186 | | |
13187 | 0 | if (IsResultAmbiguous) |
13188 | 0 | return nullptr; |
13189 | | |
13190 | 0 | if (Result) { |
13191 | 0 | SmallVector<const Expr *, 1> ResultAC; |
13192 | | // We skipped over some ambiguous declarations which might be ambiguous with |
13193 | | // the selected result. |
13194 | 0 | for (FunctionDecl *Skipped : AmbiguousDecls) { |
13195 | | // If skipped candidate has different CUDA preference than the result, |
13196 | | // there is no ambiguity. Otherwise check whether they have different |
13197 | | // constraints. |
13198 | 0 | if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0) |
13199 | 0 | continue; |
13200 | 0 | if (!CheckMoreConstrained(Skipped, Result)) |
13201 | 0 | return nullptr; |
13202 | 0 | } |
13203 | 0 | Pair = DAP; |
13204 | 0 | } |
13205 | 0 | return Result; |
13206 | 0 | } |
13207 | | |
13208 | | /// Given an overloaded function, tries to turn it into a non-overloaded |
13209 | | /// function reference using resolveAddressOfSingleOverloadCandidate. This |
13210 | | /// will perform access checks, diagnose the use of the resultant decl, and, if |
13211 | | /// requested, potentially perform a function-to-pointer decay. |
13212 | | /// |
13213 | | /// Returns false if resolveAddressOfSingleOverloadCandidate fails. |
13214 | | /// Otherwise, returns true. This may emit diagnostics and return true. |
13215 | | bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( |
13216 | 0 | ExprResult &SrcExpr, bool DoFunctionPointerConversion) { |
13217 | 0 | Expr *E = SrcExpr.get(); |
13218 | 0 | assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); |
13219 | | |
13220 | 0 | DeclAccessPair DAP; |
13221 | 0 | FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP); |
13222 | 0 | if (!Found || Found->isCPUDispatchMultiVersion() || |
13223 | 0 | Found->isCPUSpecificMultiVersion()) |
13224 | 0 | return false; |
13225 | | |
13226 | | // Emitting multiple diagnostics for a function that is both inaccessible and |
13227 | | // unavailable is consistent with our behavior elsewhere. So, always check |
13228 | | // for both. |
13229 | 0 | DiagnoseUseOfDecl(Found, E->getExprLoc()); |
13230 | 0 | CheckAddressOfMemberAccess(E, DAP); |
13231 | 0 | ExprResult Res = FixOverloadedFunctionReference(E, DAP, Found); |
13232 | 0 | if (Res.isInvalid()) |
13233 | 0 | return false; |
13234 | 0 | Expr *Fixed = Res.get(); |
13235 | 0 | if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType()) |
13236 | 0 | SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); |
13237 | 0 | else |
13238 | 0 | SrcExpr = Fixed; |
13239 | 0 | return true; |
13240 | 0 | } |
13241 | | |
13242 | | /// Given an expression that refers to an overloaded function, try to |
13243 | | /// resolve that overloaded function expression down to a single function. |
13244 | | /// |
13245 | | /// This routine can only resolve template-ids that refer to a single function |
13246 | | /// template, where that template-id refers to a single template whose template |
13247 | | /// arguments are either provided by the template-id or have defaults, |
13248 | | /// as described in C++0x [temp.arg.explicit]p3. |
13249 | | /// |
13250 | | /// If no template-ids are found, no diagnostics are emitted and NULL is |
13251 | | /// returned. |
13252 | | FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization( |
13253 | | OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult, |
13254 | 0 | TemplateSpecCandidateSet *FailedTSC) { |
13255 | | // C++ [over.over]p1: |
13256 | | // [...] [Note: any redundant set of parentheses surrounding the |
13257 | | // overloaded function name is ignored (5.1). ] |
13258 | | // C++ [over.over]p1: |
13259 | | // [...] The overloaded function name can be preceded by the & |
13260 | | // operator. |
13261 | | |
13262 | | // If we didn't actually find any template-ids, we're done. |
13263 | 0 | if (!ovl->hasExplicitTemplateArgs()) |
13264 | 0 | return nullptr; |
13265 | | |
13266 | 0 | TemplateArgumentListInfo ExplicitTemplateArgs; |
13267 | 0 | ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); |
13268 | | |
13269 | | // Look through all of the overloaded functions, searching for one |
13270 | | // whose type matches exactly. |
13271 | 0 | FunctionDecl *Matched = nullptr; |
13272 | 0 | for (UnresolvedSetIterator I = ovl->decls_begin(), |
13273 | 0 | E = ovl->decls_end(); I != E; ++I) { |
13274 | | // C++0x [temp.arg.explicit]p3: |
13275 | | // [...] In contexts where deduction is done and fails, or in contexts |
13276 | | // where deduction is not done, if a template argument list is |
13277 | | // specified and it, along with any default template arguments, |
13278 | | // identifies a single function template specialization, then the |
13279 | | // template-id is an lvalue for the function template specialization. |
13280 | 0 | FunctionTemplateDecl *FunctionTemplate |
13281 | 0 | = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); |
13282 | | |
13283 | | // C++ [over.over]p2: |
13284 | | // If the name is a function template, template argument deduction is |
13285 | | // done (14.8.2.2), and if the argument deduction succeeds, the |
13286 | | // resulting template argument list is used to generate a single |
13287 | | // function template specialization, which is added to the set of |
13288 | | // overloaded functions considered. |
13289 | 0 | FunctionDecl *Specialization = nullptr; |
13290 | 0 | TemplateDeductionInfo Info(ovl->getNameLoc()); |
13291 | 0 | if (TemplateDeductionResult Result |
13292 | 0 | = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, |
13293 | 0 | Specialization, Info, |
13294 | 0 | /*IsAddressOfFunction*/true)) { |
13295 | | // Make a note of the failed deduction for diagnostics. |
13296 | 0 | if (FailedTSC) |
13297 | 0 | FailedTSC->addCandidate().set( |
13298 | 0 | I.getPair(), FunctionTemplate->getTemplatedDecl(), |
13299 | 0 | MakeDeductionFailureInfo(Context, Result, Info)); |
13300 | 0 | continue; |
13301 | 0 | } |
13302 | | |
13303 | 0 | assert(Specialization && "no specialization and no error?"); |
13304 | | |
13305 | | // Multiple matches; we can't resolve to a single declaration. |
13306 | 0 | if (Matched) { |
13307 | 0 | if (Complain) { |
13308 | 0 | Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) |
13309 | 0 | << ovl->getName(); |
13310 | 0 | NoteAllOverloadCandidates(ovl); |
13311 | 0 | } |
13312 | 0 | return nullptr; |
13313 | 0 | } |
13314 | | |
13315 | 0 | Matched = Specialization; |
13316 | 0 | if (FoundResult) *FoundResult = I.getPair(); |
13317 | 0 | } |
13318 | | |
13319 | 0 | if (Matched && |
13320 | 0 | completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) |
13321 | 0 | return nullptr; |
13322 | | |
13323 | 0 | return Matched; |
13324 | 0 | } |
13325 | | |
13326 | | // Resolve and fix an overloaded expression that can be resolved |
13327 | | // because it identifies a single function template specialization. |
13328 | | // |
13329 | | // Last three arguments should only be supplied if Complain = true |
13330 | | // |
13331 | | // Return true if it was logically possible to so resolve the |
13332 | | // expression, regardless of whether or not it succeeded. Always |
13333 | | // returns true if 'complain' is set. |
13334 | | bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( |
13335 | | ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain, |
13336 | | SourceRange OpRangeForComplaining, QualType DestTypeForComplaining, |
13337 | 0 | unsigned DiagIDForComplaining) { |
13338 | 0 | assert(SrcExpr.get()->getType() == Context.OverloadTy); |
13339 | | |
13340 | 0 | OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); |
13341 | |
|
13342 | 0 | DeclAccessPair found; |
13343 | 0 | ExprResult SingleFunctionExpression; |
13344 | 0 | if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( |
13345 | 0 | ovl.Expression, /*complain*/ false, &found)) { |
13346 | 0 | if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { |
13347 | 0 | SrcExpr = ExprError(); |
13348 | 0 | return true; |
13349 | 0 | } |
13350 | | |
13351 | | // It is only correct to resolve to an instance method if we're |
13352 | | // resolving a form that's permitted to be a pointer to member. |
13353 | | // Otherwise we'll end up making a bound member expression, which |
13354 | | // is illegal in all the contexts we resolve like this. |
13355 | 0 | if (!ovl.HasFormOfMemberPointer && |
13356 | 0 | isa<CXXMethodDecl>(fn) && |
13357 | 0 | cast<CXXMethodDecl>(fn)->isInstance()) { |
13358 | 0 | if (!complain) return false; |
13359 | | |
13360 | 0 | Diag(ovl.Expression->getExprLoc(), |
13361 | 0 | diag::err_bound_member_function) |
13362 | 0 | << 0 << ovl.Expression->getSourceRange(); |
13363 | | |
13364 | | // TODO: I believe we only end up here if there's a mix of |
13365 | | // static and non-static candidates (otherwise the expression |
13366 | | // would have 'bound member' type, not 'overload' type). |
13367 | | // Ideally we would note which candidate was chosen and why |
13368 | | // the static candidates were rejected. |
13369 | 0 | SrcExpr = ExprError(); |
13370 | 0 | return true; |
13371 | 0 | } |
13372 | | |
13373 | | // Fix the expression to refer to 'fn'. |
13374 | 0 | SingleFunctionExpression = |
13375 | 0 | FixOverloadedFunctionReference(SrcExpr.get(), found, fn); |
13376 | | |
13377 | | // If desired, do function-to-pointer decay. |
13378 | 0 | if (doFunctionPointerConversion) { |
13379 | 0 | SingleFunctionExpression = |
13380 | 0 | DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); |
13381 | 0 | if (SingleFunctionExpression.isInvalid()) { |
13382 | 0 | SrcExpr = ExprError(); |
13383 | 0 | return true; |
13384 | 0 | } |
13385 | 0 | } |
13386 | 0 | } |
13387 | | |
13388 | 0 | if (!SingleFunctionExpression.isUsable()) { |
13389 | 0 | if (complain) { |
13390 | 0 | Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) |
13391 | 0 | << ovl.Expression->getName() |
13392 | 0 | << DestTypeForComplaining |
13393 | 0 | << OpRangeForComplaining |
13394 | 0 | << ovl.Expression->getQualifierLoc().getSourceRange(); |
13395 | 0 | NoteAllOverloadCandidates(SrcExpr.get()); |
13396 | |
|
13397 | 0 | SrcExpr = ExprError(); |
13398 | 0 | return true; |
13399 | 0 | } |
13400 | | |
13401 | 0 | return false; |
13402 | 0 | } |
13403 | | |
13404 | 0 | SrcExpr = SingleFunctionExpression; |
13405 | 0 | return true; |
13406 | 0 | } |
13407 | | |
13408 | | /// Add a single candidate to the overload set. |
13409 | | static void AddOverloadedCallCandidate(Sema &S, |
13410 | | DeclAccessPair FoundDecl, |
13411 | | TemplateArgumentListInfo *ExplicitTemplateArgs, |
13412 | | ArrayRef<Expr *> Args, |
13413 | | OverloadCandidateSet &CandidateSet, |
13414 | | bool PartialOverloading, |
13415 | 0 | bool KnownValid) { |
13416 | 0 | NamedDecl *Callee = FoundDecl.getDecl(); |
13417 | 0 | if (isa<UsingShadowDecl>(Callee)) |
13418 | 0 | Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); |
13419 | |
|
13420 | 0 | if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { |
13421 | 0 | if (ExplicitTemplateArgs) { |
13422 | 0 | assert(!KnownValid && "Explicit template arguments?"); |
13423 | 0 | return; |
13424 | 0 | } |
13425 | | // Prevent ill-formed function decls to be added as overload candidates. |
13426 | 0 | if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) |
13427 | 0 | return; |
13428 | | |
13429 | 0 | S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, |
13430 | 0 | /*SuppressUserConversions=*/false, |
13431 | 0 | PartialOverloading); |
13432 | 0 | return; |
13433 | 0 | } |
13434 | | |
13435 | 0 | if (FunctionTemplateDecl *FuncTemplate |
13436 | 0 | = dyn_cast<FunctionTemplateDecl>(Callee)) { |
13437 | 0 | S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, |
13438 | 0 | ExplicitTemplateArgs, Args, CandidateSet, |
13439 | 0 | /*SuppressUserConversions=*/false, |
13440 | 0 | PartialOverloading); |
13441 | 0 | return; |
13442 | 0 | } |
13443 | | |
13444 | 0 | assert(!KnownValid && "unhandled case in overloaded call candidate"); |
13445 | 0 | } |
13446 | | |
13447 | | /// Add the overload candidates named by callee and/or found by argument |
13448 | | /// dependent lookup to the given overload set. |
13449 | | void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, |
13450 | | ArrayRef<Expr *> Args, |
13451 | | OverloadCandidateSet &CandidateSet, |
13452 | 0 | bool PartialOverloading) { |
13453 | |
|
13454 | 0 | #ifndef NDEBUG |
13455 | | // Verify that ArgumentDependentLookup is consistent with the rules |
13456 | | // in C++0x [basic.lookup.argdep]p3: |
13457 | | // |
13458 | | // Let X be the lookup set produced by unqualified lookup (3.4.1) |
13459 | | // and let Y be the lookup set produced by argument dependent |
13460 | | // lookup (defined as follows). If X contains |
13461 | | // |
13462 | | // -- a declaration of a class member, or |
13463 | | // |
13464 | | // -- a block-scope function declaration that is not a |
13465 | | // using-declaration, or |
13466 | | // |
13467 | | // -- a declaration that is neither a function or a function |
13468 | | // template |
13469 | | // |
13470 | | // then Y is empty. |
13471 | |
|
13472 | 0 | if (ULE->requiresADL()) { |
13473 | 0 | for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), |
13474 | 0 | E = ULE->decls_end(); I != E; ++I) { |
13475 | 0 | assert(!(*I)->getDeclContext()->isRecord()); |
13476 | 0 | assert(isa<UsingShadowDecl>(*I) || |
13477 | 0 | !(*I)->getDeclContext()->isFunctionOrMethod()); |
13478 | 0 | assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); |
13479 | 0 | } |
13480 | 0 | } |
13481 | 0 | #endif |
13482 | | |
13483 | | // It would be nice to avoid this copy. |
13484 | 0 | TemplateArgumentListInfo TABuffer; |
13485 | 0 | TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; |
13486 | 0 | if (ULE->hasExplicitTemplateArgs()) { |
13487 | 0 | ULE->copyTemplateArgumentsInto(TABuffer); |
13488 | 0 | ExplicitTemplateArgs = &TABuffer; |
13489 | 0 | } |
13490 | |
|
13491 | 0 | for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), |
13492 | 0 | E = ULE->decls_end(); I != E; ++I) |
13493 | 0 | AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, |
13494 | 0 | CandidateSet, PartialOverloading, |
13495 | 0 | /*KnownValid*/ true); |
13496 | |
|
13497 | 0 | if (ULE->requiresADL()) |
13498 | 0 | AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), |
13499 | 0 | Args, ExplicitTemplateArgs, |
13500 | 0 | CandidateSet, PartialOverloading); |
13501 | 0 | } |
13502 | | |
13503 | | /// Add the call candidates from the given set of lookup results to the given |
13504 | | /// overload set. Non-function lookup results are ignored. |
13505 | | void Sema::AddOverloadedCallCandidates( |
13506 | | LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, |
13507 | 0 | ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) { |
13508 | 0 | for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) |
13509 | 0 | AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, |
13510 | 0 | CandidateSet, false, /*KnownValid*/ false); |
13511 | 0 | } |
13512 | | |
13513 | | /// Determine whether a declaration with the specified name could be moved into |
13514 | | /// a different namespace. |
13515 | 0 | static bool canBeDeclaredInNamespace(const DeclarationName &Name) { |
13516 | 0 | switch (Name.getCXXOverloadedOperator()) { |
13517 | 0 | case OO_New: case OO_Array_New: |
13518 | 0 | case OO_Delete: case OO_Array_Delete: |
13519 | 0 | return false; |
13520 | | |
13521 | 0 | default: |
13522 | 0 | return true; |
13523 | 0 | } |
13524 | 0 | } |
13525 | | |
13526 | | /// Attempt to recover from an ill-formed use of a non-dependent name in a |
13527 | | /// template, where the non-dependent name was declared after the template |
13528 | | /// was defined. This is common in code written for a compilers which do not |
13529 | | /// correctly implement two-stage name lookup. |
13530 | | /// |
13531 | | /// Returns true if a viable candidate was found and a diagnostic was issued. |
13532 | | static bool DiagnoseTwoPhaseLookup( |
13533 | | Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, |
13534 | | LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, |
13535 | | TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, |
13536 | 0 | CXXRecordDecl **FoundInClass = nullptr) { |
13537 | 0 | if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) |
13538 | 0 | return false; |
13539 | | |
13540 | 0 | for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { |
13541 | 0 | if (DC->isTransparentContext()) |
13542 | 0 | continue; |
13543 | | |
13544 | 0 | SemaRef.LookupQualifiedName(R, DC); |
13545 | |
|
13546 | 0 | if (!R.empty()) { |
13547 | 0 | R.suppressDiagnostics(); |
13548 | |
|
13549 | 0 | OverloadCandidateSet Candidates(FnLoc, CSK); |
13550 | 0 | SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, |
13551 | 0 | Candidates); |
13552 | |
|
13553 | 0 | OverloadCandidateSet::iterator Best; |
13554 | 0 | OverloadingResult OR = |
13555 | 0 | Candidates.BestViableFunction(SemaRef, FnLoc, Best); |
13556 | |
|
13557 | 0 | if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) { |
13558 | | // We either found non-function declarations or a best viable function |
13559 | | // at class scope. A class-scope lookup result disables ADL. Don't |
13560 | | // look past this, but let the caller know that we found something that |
13561 | | // either is, or might be, usable in this class. |
13562 | 0 | if (FoundInClass) { |
13563 | 0 | *FoundInClass = RD; |
13564 | 0 | if (OR == OR_Success) { |
13565 | 0 | R.clear(); |
13566 | 0 | R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); |
13567 | 0 | R.resolveKind(); |
13568 | 0 | } |
13569 | 0 | } |
13570 | 0 | return false; |
13571 | 0 | } |
13572 | | |
13573 | 0 | if (OR != OR_Success) { |
13574 | | // There wasn't a unique best function or function template. |
13575 | 0 | return false; |
13576 | 0 | } |
13577 | | |
13578 | | // Find the namespaces where ADL would have looked, and suggest |
13579 | | // declaring the function there instead. |
13580 | 0 | Sema::AssociatedNamespaceSet AssociatedNamespaces; |
13581 | 0 | Sema::AssociatedClassSet AssociatedClasses; |
13582 | 0 | SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, |
13583 | 0 | AssociatedNamespaces, |
13584 | 0 | AssociatedClasses); |
13585 | 0 | Sema::AssociatedNamespaceSet SuggestedNamespaces; |
13586 | 0 | if (canBeDeclaredInNamespace(R.getLookupName())) { |
13587 | 0 | DeclContext *Std = SemaRef.getStdNamespace(); |
13588 | 0 | for (Sema::AssociatedNamespaceSet::iterator |
13589 | 0 | it = AssociatedNamespaces.begin(), |
13590 | 0 | end = AssociatedNamespaces.end(); it != end; ++it) { |
13591 | | // Never suggest declaring a function within namespace 'std'. |
13592 | 0 | if (Std && Std->Encloses(*it)) |
13593 | 0 | continue; |
13594 | | |
13595 | | // Never suggest declaring a function within a namespace with a |
13596 | | // reserved name, like __gnu_cxx. |
13597 | 0 | NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); |
13598 | 0 | if (NS && |
13599 | 0 | NS->getQualifiedNameAsString().find("__") != std::string::npos) |
13600 | 0 | continue; |
13601 | | |
13602 | 0 | SuggestedNamespaces.insert(*it); |
13603 | 0 | } |
13604 | 0 | } |
13605 | |
|
13606 | 0 | SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) |
13607 | 0 | << R.getLookupName(); |
13608 | 0 | if (SuggestedNamespaces.empty()) { |
13609 | 0 | SemaRef.Diag(Best->Function->getLocation(), |
13610 | 0 | diag::note_not_found_by_two_phase_lookup) |
13611 | 0 | << R.getLookupName() << 0; |
13612 | 0 | } else if (SuggestedNamespaces.size() == 1) { |
13613 | 0 | SemaRef.Diag(Best->Function->getLocation(), |
13614 | 0 | diag::note_not_found_by_two_phase_lookup) |
13615 | 0 | << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); |
13616 | 0 | } else { |
13617 | | // FIXME: It would be useful to list the associated namespaces here, |
13618 | | // but the diagnostics infrastructure doesn't provide a way to produce |
13619 | | // a localized representation of a list of items. |
13620 | 0 | SemaRef.Diag(Best->Function->getLocation(), |
13621 | 0 | diag::note_not_found_by_two_phase_lookup) |
13622 | 0 | << R.getLookupName() << 2; |
13623 | 0 | } |
13624 | | |
13625 | | // Try to recover by calling this function. |
13626 | 0 | return true; |
13627 | 0 | } |
13628 | | |
13629 | 0 | R.clear(); |
13630 | 0 | } |
13631 | | |
13632 | 0 | return false; |
13633 | 0 | } |
13634 | | |
13635 | | /// Attempt to recover from ill-formed use of a non-dependent operator in a |
13636 | | /// template, where the non-dependent operator was declared after the template |
13637 | | /// was defined. |
13638 | | /// |
13639 | | /// Returns true if a viable candidate was found and a diagnostic was issued. |
13640 | | static bool |
13641 | | DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, |
13642 | | SourceLocation OpLoc, |
13643 | 0 | ArrayRef<Expr *> Args) { |
13644 | 0 | DeclarationName OpName = |
13645 | 0 | SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); |
13646 | 0 | LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); |
13647 | 0 | return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, |
13648 | 0 | OverloadCandidateSet::CSK_Operator, |
13649 | 0 | /*ExplicitTemplateArgs=*/nullptr, Args); |
13650 | 0 | } |
13651 | | |
13652 | | namespace { |
13653 | | class BuildRecoveryCallExprRAII { |
13654 | | Sema &SemaRef; |
13655 | | Sema::SatisfactionStackResetRAII SatStack; |
13656 | | |
13657 | | public: |
13658 | 0 | BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) { |
13659 | 0 | assert(SemaRef.IsBuildingRecoveryCallExpr == false); |
13660 | 0 | SemaRef.IsBuildingRecoveryCallExpr = true; |
13661 | 0 | } |
13662 | | |
13663 | 0 | ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; } |
13664 | | }; |
13665 | | } |
13666 | | |
13667 | | /// Attempts to recover from a call where no functions were found. |
13668 | | /// |
13669 | | /// This function will do one of three things: |
13670 | | /// * Diagnose, recover, and return a recovery expression. |
13671 | | /// * Diagnose, fail to recover, and return ExprError(). |
13672 | | /// * Do not diagnose, do not recover, and return ExprResult(). The caller is |
13673 | | /// expected to diagnose as appropriate. |
13674 | | static ExprResult |
13675 | | BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, |
13676 | | UnresolvedLookupExpr *ULE, |
13677 | | SourceLocation LParenLoc, |
13678 | | MutableArrayRef<Expr *> Args, |
13679 | | SourceLocation RParenLoc, |
13680 | 0 | bool EmptyLookup, bool AllowTypoCorrection) { |
13681 | | // Do not try to recover if it is already building a recovery call. |
13682 | | // This stops infinite loops for template instantiations like |
13683 | | // |
13684 | | // template <typename T> auto foo(T t) -> decltype(foo(t)) {} |
13685 | | // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} |
13686 | 0 | if (SemaRef.IsBuildingRecoveryCallExpr) |
13687 | 0 | return ExprResult(); |
13688 | 0 | BuildRecoveryCallExprRAII RCE(SemaRef); |
13689 | |
|
13690 | 0 | CXXScopeSpec SS; |
13691 | 0 | SS.Adopt(ULE->getQualifierLoc()); |
13692 | 0 | SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); |
13693 | |
|
13694 | 0 | TemplateArgumentListInfo TABuffer; |
13695 | 0 | TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; |
13696 | 0 | if (ULE->hasExplicitTemplateArgs()) { |
13697 | 0 | ULE->copyTemplateArgumentsInto(TABuffer); |
13698 | 0 | ExplicitTemplateArgs = &TABuffer; |
13699 | 0 | } |
13700 | |
|
13701 | 0 | LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), |
13702 | 0 | Sema::LookupOrdinaryName); |
13703 | 0 | CXXRecordDecl *FoundInClass = nullptr; |
13704 | 0 | if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, |
13705 | 0 | OverloadCandidateSet::CSK_Normal, |
13706 | 0 | ExplicitTemplateArgs, Args, &FoundInClass)) { |
13707 | | // OK, diagnosed a two-phase lookup issue. |
13708 | 0 | } else if (EmptyLookup) { |
13709 | | // Try to recover from an empty lookup with typo correction. |
13710 | 0 | R.clear(); |
13711 | 0 | NoTypoCorrectionCCC NoTypoValidator{}; |
13712 | 0 | FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), |
13713 | 0 | ExplicitTemplateArgs != nullptr, |
13714 | 0 | dyn_cast<MemberExpr>(Fn)); |
13715 | 0 | CorrectionCandidateCallback &Validator = |
13716 | 0 | AllowTypoCorrection |
13717 | 0 | ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) |
13718 | 0 | : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); |
13719 | 0 | if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, |
13720 | 0 | Args)) |
13721 | 0 | return ExprError(); |
13722 | 0 | } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) { |
13723 | | // We found a usable declaration of the name in a dependent base of some |
13724 | | // enclosing class. |
13725 | | // FIXME: We should also explain why the candidates found by name lookup |
13726 | | // were not viable. |
13727 | 0 | if (SemaRef.DiagnoseDependentMemberLookup(R)) |
13728 | 0 | return ExprError(); |
13729 | 0 | } else { |
13730 | | // We had viable candidates and couldn't recover; let the caller diagnose |
13731 | | // this. |
13732 | 0 | return ExprResult(); |
13733 | 0 | } |
13734 | | |
13735 | | // If we get here, we should have issued a diagnostic and formed a recovery |
13736 | | // lookup result. |
13737 | 0 | assert(!R.empty() && "lookup results empty despite recovery"); |
13738 | | |
13739 | | // If recovery created an ambiguity, just bail out. |
13740 | 0 | if (R.isAmbiguous()) { |
13741 | 0 | R.suppressDiagnostics(); |
13742 | 0 | return ExprError(); |
13743 | 0 | } |
13744 | | |
13745 | | // Build an implicit member call if appropriate. Just drop the |
13746 | | // casts and such from the call, we don't really care. |
13747 | 0 | ExprResult NewFn = ExprError(); |
13748 | 0 | if ((*R.begin())->isCXXClassMember()) |
13749 | 0 | NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, |
13750 | 0 | ExplicitTemplateArgs, S); |
13751 | 0 | else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) |
13752 | 0 | NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, |
13753 | 0 | ExplicitTemplateArgs); |
13754 | 0 | else |
13755 | 0 | NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); |
13756 | |
|
13757 | 0 | if (NewFn.isInvalid()) |
13758 | 0 | return ExprError(); |
13759 | | |
13760 | | // This shouldn't cause an infinite loop because we're giving it |
13761 | | // an expression with viable lookup results, which should never |
13762 | | // end up here. |
13763 | 0 | return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, |
13764 | 0 | MultiExprArg(Args.data(), Args.size()), |
13765 | 0 | RParenLoc); |
13766 | 0 | } |
13767 | | |
13768 | | /// Constructs and populates an OverloadedCandidateSet from |
13769 | | /// the given function. |
13770 | | /// \returns true when an the ExprResult output parameter has been set. |
13771 | | bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, |
13772 | | UnresolvedLookupExpr *ULE, |
13773 | | MultiExprArg Args, |
13774 | | SourceLocation RParenLoc, |
13775 | | OverloadCandidateSet *CandidateSet, |
13776 | 0 | ExprResult *Result) { |
13777 | 0 | #ifndef NDEBUG |
13778 | 0 | if (ULE->requiresADL()) { |
13779 | | // To do ADL, we must have found an unqualified name. |
13780 | 0 | assert(!ULE->getQualifier() && "qualified name with ADL"); |
13781 | | |
13782 | | // We don't perform ADL for implicit declarations of builtins. |
13783 | | // Verify that this was correctly set up. |
13784 | 0 | FunctionDecl *F; |
13785 | 0 | if (ULE->decls_begin() != ULE->decls_end() && |
13786 | 0 | ULE->decls_begin() + 1 == ULE->decls_end() && |
13787 | 0 | (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && |
13788 | 0 | F->getBuiltinID() && F->isImplicit()) |
13789 | 0 | llvm_unreachable("performing ADL for builtin"); |
13790 | | |
13791 | | // We don't perform ADL in C. |
13792 | 0 | assert(getLangOpts().CPlusPlus && "ADL enabled in C"); |
13793 | 0 | } |
13794 | 0 | #endif |
13795 | | |
13796 | 0 | UnbridgedCastsSet UnbridgedCasts; |
13797 | 0 | if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { |
13798 | 0 | *Result = ExprError(); |
13799 | 0 | return true; |
13800 | 0 | } |
13801 | | |
13802 | | // Add the functions denoted by the callee to the set of candidate |
13803 | | // functions, including those from argument-dependent lookup. |
13804 | 0 | AddOverloadedCallCandidates(ULE, Args, *CandidateSet); |
13805 | |
|
13806 | 0 | if (getLangOpts().MSVCCompat && |
13807 | 0 | CurContext->isDependentContext() && !isSFINAEContext() && |
13808 | 0 | (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { |
13809 | |
|
13810 | 0 | OverloadCandidateSet::iterator Best; |
13811 | 0 | if (CandidateSet->empty() || |
13812 | 0 | CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == |
13813 | 0 | OR_No_Viable_Function) { |
13814 | | // In Microsoft mode, if we are inside a template class member function |
13815 | | // then create a type dependent CallExpr. The goal is to postpone name |
13816 | | // lookup to instantiation time to be able to search into type dependent |
13817 | | // base classes. |
13818 | 0 | CallExpr *CE = |
13819 | 0 | CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue, |
13820 | 0 | RParenLoc, CurFPFeatureOverrides()); |
13821 | 0 | CE->markDependentForPostponedNameLookup(); |
13822 | 0 | *Result = CE; |
13823 | 0 | return true; |
13824 | 0 | } |
13825 | 0 | } |
13826 | | |
13827 | 0 | if (CandidateSet->empty()) |
13828 | 0 | return false; |
13829 | | |
13830 | 0 | UnbridgedCasts.restore(); |
13831 | 0 | return false; |
13832 | 0 | } |
13833 | | |
13834 | | // Guess at what the return type for an unresolvable overload should be. |
13835 | | static QualType chooseRecoveryType(OverloadCandidateSet &CS, |
13836 | 0 | OverloadCandidateSet::iterator *Best) { |
13837 | 0 | std::optional<QualType> Result; |
13838 | | // Adjust Type after seeing a candidate. |
13839 | 0 | auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) { |
13840 | 0 | if (!Candidate.Function) |
13841 | 0 | return; |
13842 | 0 | if (Candidate.Function->isInvalidDecl()) |
13843 | 0 | return; |
13844 | 0 | QualType T = Candidate.Function->getReturnType(); |
13845 | 0 | if (T.isNull()) |
13846 | 0 | return; |
13847 | 0 | if (!Result) |
13848 | 0 | Result = T; |
13849 | 0 | else if (Result != T) |
13850 | 0 | Result = QualType(); |
13851 | 0 | }; |
13852 | | |
13853 | | // Look for an unambiguous type from a progressively larger subset. |
13854 | | // e.g. if types disagree, but all *viable* overloads return int, choose int. |
13855 | | // |
13856 | | // First, consider only the best candidate. |
13857 | 0 | if (Best && *Best != CS.end()) |
13858 | 0 | ConsiderCandidate(**Best); |
13859 | | // Next, consider only viable candidates. |
13860 | 0 | if (!Result) |
13861 | 0 | for (const auto &C : CS) |
13862 | 0 | if (C.Viable) |
13863 | 0 | ConsiderCandidate(C); |
13864 | | // Finally, consider all candidates. |
13865 | 0 | if (!Result) |
13866 | 0 | for (const auto &C : CS) |
13867 | 0 | ConsiderCandidate(C); |
13868 | |
|
13869 | 0 | if (!Result) |
13870 | 0 | return QualType(); |
13871 | 0 | auto Value = *Result; |
13872 | 0 | if (Value.isNull() || Value->isUndeducedType()) |
13873 | 0 | return QualType(); |
13874 | 0 | return Value; |
13875 | 0 | } |
13876 | | |
13877 | | /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns |
13878 | | /// the completed call expression. If overload resolution fails, emits |
13879 | | /// diagnostics and returns ExprError() |
13880 | | static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, |
13881 | | UnresolvedLookupExpr *ULE, |
13882 | | SourceLocation LParenLoc, |
13883 | | MultiExprArg Args, |
13884 | | SourceLocation RParenLoc, |
13885 | | Expr *ExecConfig, |
13886 | | OverloadCandidateSet *CandidateSet, |
13887 | | OverloadCandidateSet::iterator *Best, |
13888 | | OverloadingResult OverloadResult, |
13889 | 0 | bool AllowTypoCorrection) { |
13890 | 0 | switch (OverloadResult) { |
13891 | 0 | case OR_Success: { |
13892 | 0 | FunctionDecl *FDecl = (*Best)->Function; |
13893 | 0 | SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); |
13894 | 0 | if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) |
13895 | 0 | return ExprError(); |
13896 | 0 | ExprResult Res = |
13897 | 0 | SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); |
13898 | 0 | if (Res.isInvalid()) |
13899 | 0 | return ExprError(); |
13900 | 0 | return SemaRef.BuildResolvedCallExpr( |
13901 | 0 | Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig, |
13902 | 0 | /*IsExecConfig=*/false, (*Best)->IsADLCandidate); |
13903 | 0 | } |
13904 | | |
13905 | 0 | case OR_No_Viable_Function: { |
13906 | | // Try to recover by looking for viable functions which the user might |
13907 | | // have meant to call. |
13908 | 0 | ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, |
13909 | 0 | Args, RParenLoc, |
13910 | 0 | CandidateSet->empty(), |
13911 | 0 | AllowTypoCorrection); |
13912 | 0 | if (Recovery.isInvalid() || Recovery.isUsable()) |
13913 | 0 | return Recovery; |
13914 | | |
13915 | | // If the user passes in a function that we can't take the address of, we |
13916 | | // generally end up emitting really bad error messages. Here, we attempt to |
13917 | | // emit better ones. |
13918 | 0 | for (const Expr *Arg : Args) { |
13919 | 0 | if (!Arg->getType()->isFunctionType()) |
13920 | 0 | continue; |
13921 | 0 | if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { |
13922 | 0 | auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); |
13923 | 0 | if (FD && |
13924 | 0 | !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, |
13925 | 0 | Arg->getExprLoc())) |
13926 | 0 | return ExprError(); |
13927 | 0 | } |
13928 | 0 | } |
13929 | | |
13930 | 0 | CandidateSet->NoteCandidates( |
13931 | 0 | PartialDiagnosticAt( |
13932 | 0 | Fn->getBeginLoc(), |
13933 | 0 | SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) |
13934 | 0 | << ULE->getName() << Fn->getSourceRange()), |
13935 | 0 | SemaRef, OCD_AllCandidates, Args); |
13936 | 0 | break; |
13937 | 0 | } |
13938 | | |
13939 | 0 | case OR_Ambiguous: |
13940 | 0 | CandidateSet->NoteCandidates( |
13941 | 0 | PartialDiagnosticAt(Fn->getBeginLoc(), |
13942 | 0 | SemaRef.PDiag(diag::err_ovl_ambiguous_call) |
13943 | 0 | << ULE->getName() << Fn->getSourceRange()), |
13944 | 0 | SemaRef, OCD_AmbiguousCandidates, Args); |
13945 | 0 | break; |
13946 | | |
13947 | 0 | case OR_Deleted: { |
13948 | 0 | CandidateSet->NoteCandidates( |
13949 | 0 | PartialDiagnosticAt(Fn->getBeginLoc(), |
13950 | 0 | SemaRef.PDiag(diag::err_ovl_deleted_call) |
13951 | 0 | << ULE->getName() << Fn->getSourceRange()), |
13952 | 0 | SemaRef, OCD_AllCandidates, Args); |
13953 | | |
13954 | | // We emitted an error for the unavailable/deleted function call but keep |
13955 | | // the call in the AST. |
13956 | 0 | FunctionDecl *FDecl = (*Best)->Function; |
13957 | 0 | ExprResult Res = |
13958 | 0 | SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); |
13959 | 0 | if (Res.isInvalid()) |
13960 | 0 | return ExprError(); |
13961 | 0 | return SemaRef.BuildResolvedCallExpr( |
13962 | 0 | Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig, |
13963 | 0 | /*IsExecConfig=*/false, (*Best)->IsADLCandidate); |
13964 | 0 | } |
13965 | 0 | } |
13966 | | |
13967 | | // Overload resolution failed, try to recover. |
13968 | 0 | SmallVector<Expr *, 8> SubExprs = {Fn}; |
13969 | 0 | SubExprs.append(Args.begin(), Args.end()); |
13970 | 0 | return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs, |
13971 | 0 | chooseRecoveryType(*CandidateSet, Best)); |
13972 | 0 | } |
13973 | | |
13974 | | static void markUnaddressableCandidatesUnviable(Sema &S, |
13975 | 0 | OverloadCandidateSet &CS) { |
13976 | 0 | for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { |
13977 | 0 | if (I->Viable && |
13978 | 0 | !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { |
13979 | 0 | I->Viable = false; |
13980 | 0 | I->FailureKind = ovl_fail_addr_not_available; |
13981 | 0 | } |
13982 | 0 | } |
13983 | 0 | } |
13984 | | |
13985 | | /// BuildOverloadedCallExpr - Given the call expression that calls Fn |
13986 | | /// (which eventually refers to the declaration Func) and the call |
13987 | | /// arguments Args/NumArgs, attempt to resolve the function call down |
13988 | | /// to a specific function. If overload resolution succeeds, returns |
13989 | | /// the call expression produced by overload resolution. |
13990 | | /// Otherwise, emits diagnostics and returns ExprError. |
13991 | | ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, |
13992 | | UnresolvedLookupExpr *ULE, |
13993 | | SourceLocation LParenLoc, |
13994 | | MultiExprArg Args, |
13995 | | SourceLocation RParenLoc, |
13996 | | Expr *ExecConfig, |
13997 | | bool AllowTypoCorrection, |
13998 | 0 | bool CalleesAddressIsTaken) { |
13999 | 0 | OverloadCandidateSet CandidateSet(Fn->getExprLoc(), |
14000 | 0 | OverloadCandidateSet::CSK_Normal); |
14001 | 0 | ExprResult result; |
14002 | |
|
14003 | 0 | if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, |
14004 | 0 | &result)) |
14005 | 0 | return result; |
14006 | | |
14007 | | // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that |
14008 | | // functions that aren't addressible are considered unviable. |
14009 | 0 | if (CalleesAddressIsTaken) |
14010 | 0 | markUnaddressableCandidatesUnviable(*this, CandidateSet); |
14011 | |
|
14012 | 0 | OverloadCandidateSet::iterator Best; |
14013 | 0 | OverloadingResult OverloadResult = |
14014 | 0 | CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); |
14015 | | |
14016 | | // Model the case with a call to a templated function whose definition |
14017 | | // encloses the call and whose return type contains a placeholder type as if |
14018 | | // the UnresolvedLookupExpr was type-dependent. |
14019 | 0 | if (OverloadResult == OR_Success) { |
14020 | 0 | const FunctionDecl *FDecl = Best->Function; |
14021 | 0 | if (FDecl && FDecl->isTemplateInstantiation() && |
14022 | 0 | FDecl->getReturnType()->isUndeducedType()) { |
14023 | 0 | if (const auto *TP = |
14024 | 0 | FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false); |
14025 | 0 | TP && TP->willHaveBody()) { |
14026 | 0 | return CallExpr::Create(Context, Fn, Args, Context.DependentTy, |
14027 | 0 | VK_PRValue, RParenLoc, CurFPFeatureOverrides()); |
14028 | 0 | } |
14029 | 0 | } |
14030 | 0 | } |
14031 | | |
14032 | 0 | return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, |
14033 | 0 | ExecConfig, &CandidateSet, &Best, |
14034 | 0 | OverloadResult, AllowTypoCorrection); |
14035 | 0 | } |
14036 | | |
14037 | 0 | static bool IsOverloaded(const UnresolvedSetImpl &Functions) { |
14038 | 0 | return Functions.size() > 1 || |
14039 | 0 | (Functions.size() == 1 && |
14040 | 0 | isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl())); |
14041 | 0 | } |
14042 | | |
14043 | | ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, |
14044 | | NestedNameSpecifierLoc NNSLoc, |
14045 | | DeclarationNameInfo DNI, |
14046 | | const UnresolvedSetImpl &Fns, |
14047 | 0 | bool PerformADL) { |
14048 | 0 | return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI, |
14049 | 0 | PerformADL, IsOverloaded(Fns), |
14050 | 0 | Fns.begin(), Fns.end()); |
14051 | 0 | } |
14052 | | |
14053 | | ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl, |
14054 | | CXXConversionDecl *Method, |
14055 | 0 | bool HadMultipleCandidates) { |
14056 | | // Convert the expression to match the conversion function's implicit object |
14057 | | // parameter. |
14058 | 0 | ExprResult Exp; |
14059 | 0 | if (Method->isExplicitObjectMemberFunction()) |
14060 | 0 | Exp = InitializeExplicitObjectArgument(*this, E, Method); |
14061 | 0 | else |
14062 | 0 | Exp = PerformImplicitObjectArgumentInitialization(E, /*Qualifier=*/nullptr, |
14063 | 0 | FoundDecl, Method); |
14064 | 0 | if (Exp.isInvalid()) |
14065 | 0 | return true; |
14066 | | |
14067 | 0 | if (Method->getParent()->isLambda() && |
14068 | 0 | Method->getConversionType()->isBlockPointerType()) { |
14069 | | // This is a lambda conversion to block pointer; check if the argument |
14070 | | // was a LambdaExpr. |
14071 | 0 | Expr *SubE = E; |
14072 | 0 | auto *CE = dyn_cast<CastExpr>(SubE); |
14073 | 0 | if (CE && CE->getCastKind() == CK_NoOp) |
14074 | 0 | SubE = CE->getSubExpr(); |
14075 | 0 | SubE = SubE->IgnoreParens(); |
14076 | 0 | if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE)) |
14077 | 0 | SubE = BE->getSubExpr(); |
14078 | 0 | if (isa<LambdaExpr>(SubE)) { |
14079 | | // For the conversion to block pointer on a lambda expression, we |
14080 | | // construct a special BlockLiteral instead; this doesn't really make |
14081 | | // a difference in ARC, but outside of ARC the resulting block literal |
14082 | | // follows the normal lifetime rules for block literals instead of being |
14083 | | // autoreleased. |
14084 | 0 | PushExpressionEvaluationContext( |
14085 | 0 | ExpressionEvaluationContext::PotentiallyEvaluated); |
14086 | 0 | ExprResult BlockExp = BuildBlockForLambdaConversion( |
14087 | 0 | Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get()); |
14088 | 0 | PopExpressionEvaluationContext(); |
14089 | | |
14090 | | // FIXME: This note should be produced by a CodeSynthesisContext. |
14091 | 0 | if (BlockExp.isInvalid()) |
14092 | 0 | Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv); |
14093 | 0 | return BlockExp; |
14094 | 0 | } |
14095 | 0 | } |
14096 | 0 | CallExpr *CE; |
14097 | 0 | QualType ResultType = Method->getReturnType(); |
14098 | 0 | ExprValueKind VK = Expr::getValueKindForType(ResultType); |
14099 | 0 | ResultType = ResultType.getNonLValueExprType(Context); |
14100 | 0 | if (Method->isExplicitObjectMemberFunction()) { |
14101 | 0 | ExprResult FnExpr = |
14102 | 0 | CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(), |
14103 | 0 | HadMultipleCandidates, E->getBeginLoc()); |
14104 | 0 | if (FnExpr.isInvalid()) |
14105 | 0 | return ExprError(); |
14106 | 0 | Expr *ObjectParam = Exp.get(); |
14107 | 0 | CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1), |
14108 | 0 | ResultType, VK, Exp.get()->getEndLoc(), |
14109 | 0 | CurFPFeatureOverrides()); |
14110 | 0 | } else { |
14111 | 0 | MemberExpr *ME = |
14112 | 0 | BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(), |
14113 | 0 | NestedNameSpecifierLoc(), SourceLocation(), Method, |
14114 | 0 | DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), |
14115 | 0 | HadMultipleCandidates, DeclarationNameInfo(), |
14116 | 0 | Context.BoundMemberTy, VK_PRValue, OK_Ordinary); |
14117 | |
|
14118 | 0 | CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK, |
14119 | 0 | Exp.get()->getEndLoc(), |
14120 | 0 | CurFPFeatureOverrides()); |
14121 | 0 | } |
14122 | | |
14123 | 0 | if (CheckFunctionCall(Method, CE, |
14124 | 0 | Method->getType()->castAs<FunctionProtoType>())) |
14125 | 0 | return ExprError(); |
14126 | | |
14127 | 0 | return CheckForImmediateInvocation(CE, CE->getDirectCallee()); |
14128 | 0 | } |
14129 | | |
14130 | | /// Create a unary operation that may resolve to an overloaded |
14131 | | /// operator. |
14132 | | /// |
14133 | | /// \param OpLoc The location of the operator itself (e.g., '*'). |
14134 | | /// |
14135 | | /// \param Opc The UnaryOperatorKind that describes this operator. |
14136 | | /// |
14137 | | /// \param Fns The set of non-member functions that will be |
14138 | | /// considered by overload resolution. The caller needs to build this |
14139 | | /// set based on the context using, e.g., |
14140 | | /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This |
14141 | | /// set should not contain any member functions; those will be added |
14142 | | /// by CreateOverloadedUnaryOp(). |
14143 | | /// |
14144 | | /// \param Input The input argument. |
14145 | | ExprResult |
14146 | | Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, |
14147 | | const UnresolvedSetImpl &Fns, |
14148 | 6 | Expr *Input, bool PerformADL) { |
14149 | 6 | OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); |
14150 | 6 | assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); |
14151 | 0 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); |
14152 | | // TODO: provide better source location info. |
14153 | 6 | DeclarationNameInfo OpNameInfo(OpName, OpLoc); |
14154 | | |
14155 | 6 | if (checkPlaceholderForOverload(*this, Input)) |
14156 | 0 | return ExprError(); |
14157 | | |
14158 | 6 | Expr *Args[2] = { Input, nullptr }; |
14159 | 6 | unsigned NumArgs = 1; |
14160 | | |
14161 | | // For post-increment and post-decrement, add the implicit '0' as |
14162 | | // the second argument, so that we know this is a post-increment or |
14163 | | // post-decrement. |
14164 | 6 | if (Opc == UO_PostInc || Opc == UO_PostDec) { |
14165 | 0 | llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); |
14166 | 0 | Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, |
14167 | 0 | SourceLocation()); |
14168 | 0 | NumArgs = 2; |
14169 | 0 | } |
14170 | | |
14171 | 6 | ArrayRef<Expr *> ArgsArray(Args, NumArgs); |
14172 | | |
14173 | 6 | if (Input->isTypeDependent()) { |
14174 | 6 | if (Fns.empty()) |
14175 | 6 | return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, |
14176 | 6 | VK_PRValue, OK_Ordinary, OpLoc, false, |
14177 | 6 | CurFPFeatureOverrides()); |
14178 | | |
14179 | 0 | CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators |
14180 | 0 | ExprResult Fn = CreateUnresolvedLookupExpr( |
14181 | 0 | NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns); |
14182 | 0 | if (Fn.isInvalid()) |
14183 | 0 | return ExprError(); |
14184 | 0 | return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray, |
14185 | 0 | Context.DependentTy, VK_PRValue, OpLoc, |
14186 | 0 | CurFPFeatureOverrides()); |
14187 | 0 | } |
14188 | | |
14189 | | // Build an empty overload set. |
14190 | 0 | OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); |
14191 | | |
14192 | | // Add the candidates from the given function set. |
14193 | 0 | AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); |
14194 | | |
14195 | | // Add operator candidates that are member functions. |
14196 | 0 | AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); |
14197 | | |
14198 | | // Add candidates from ADL. |
14199 | 0 | if (PerformADL) { |
14200 | 0 | AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, |
14201 | 0 | /*ExplicitTemplateArgs*/nullptr, |
14202 | 0 | CandidateSet); |
14203 | 0 | } |
14204 | | |
14205 | | // Add builtin operator candidates. |
14206 | 0 | AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); |
14207 | |
|
14208 | 0 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
14209 | | |
14210 | | // Perform overload resolution. |
14211 | 0 | OverloadCandidateSet::iterator Best; |
14212 | 0 | switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { |
14213 | 0 | case OR_Success: { |
14214 | | // We found a built-in operator or an overloaded operator. |
14215 | 0 | FunctionDecl *FnDecl = Best->Function; |
14216 | |
|
14217 | 0 | if (FnDecl) { |
14218 | 0 | Expr *Base = nullptr; |
14219 | | // We matched an overloaded operator. Build a call to that |
14220 | | // operator. |
14221 | | |
14222 | | // Convert the arguments. |
14223 | 0 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { |
14224 | 0 | CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl); |
14225 | |
|
14226 | 0 | ExprResult InputInit; |
14227 | 0 | if (Method->isExplicitObjectMemberFunction()) |
14228 | 0 | InputInit = InitializeExplicitObjectArgument(*this, Input, Method); |
14229 | 0 | else |
14230 | 0 | InputInit = PerformImplicitObjectArgumentInitialization( |
14231 | 0 | Input, /*Qualifier=*/nullptr, Best->FoundDecl, Method); |
14232 | 0 | if (InputInit.isInvalid()) |
14233 | 0 | return ExprError(); |
14234 | 0 | Base = Input = InputInit.get(); |
14235 | 0 | } else { |
14236 | | // Convert the arguments. |
14237 | 0 | ExprResult InputInit |
14238 | 0 | = PerformCopyInitialization(InitializedEntity::InitializeParameter( |
14239 | 0 | Context, |
14240 | 0 | FnDecl->getParamDecl(0)), |
14241 | 0 | SourceLocation(), |
14242 | 0 | Input); |
14243 | 0 | if (InputInit.isInvalid()) |
14244 | 0 | return ExprError(); |
14245 | 0 | Input = InputInit.get(); |
14246 | 0 | } |
14247 | | |
14248 | | // Build the actual expression node. |
14249 | 0 | ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, |
14250 | 0 | Base, HadMultipleCandidates, |
14251 | 0 | OpLoc); |
14252 | 0 | if (FnExpr.isInvalid()) |
14253 | 0 | return ExprError(); |
14254 | | |
14255 | | // Determine the result type. |
14256 | 0 | QualType ResultTy = FnDecl->getReturnType(); |
14257 | 0 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); |
14258 | 0 | ResultTy = ResultTy.getNonLValueExprType(Context); |
14259 | |
|
14260 | 0 | Args[0] = Input; |
14261 | 0 | CallExpr *TheCall = CXXOperatorCallExpr::Create( |
14262 | 0 | Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, |
14263 | 0 | CurFPFeatureOverrides(), Best->IsADLCandidate); |
14264 | |
|
14265 | 0 | if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) |
14266 | 0 | return ExprError(); |
14267 | | |
14268 | 0 | if (CheckFunctionCall(FnDecl, TheCall, |
14269 | 0 | FnDecl->getType()->castAs<FunctionProtoType>())) |
14270 | 0 | return ExprError(); |
14271 | 0 | return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl); |
14272 | 0 | } else { |
14273 | | // We matched a built-in operator. Convert the arguments, then |
14274 | | // break out so that we will build the appropriate built-in |
14275 | | // operator node. |
14276 | 0 | ExprResult InputRes = PerformImplicitConversion( |
14277 | 0 | Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, |
14278 | 0 | CCK_ForBuiltinOverloadedOp); |
14279 | 0 | if (InputRes.isInvalid()) |
14280 | 0 | return ExprError(); |
14281 | 0 | Input = InputRes.get(); |
14282 | 0 | break; |
14283 | 0 | } |
14284 | 0 | } |
14285 | | |
14286 | 0 | case OR_No_Viable_Function: |
14287 | | // This is an erroneous use of an operator which can be overloaded by |
14288 | | // a non-member function. Check for non-member operators which were |
14289 | | // defined too late to be candidates. |
14290 | 0 | if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) |
14291 | | // FIXME: Recover by calling the found function. |
14292 | 0 | return ExprError(); |
14293 | | |
14294 | | // No viable function; fall through to handling this as a |
14295 | | // built-in operator, which will produce an error message for us. |
14296 | 0 | break; |
14297 | | |
14298 | 0 | case OR_Ambiguous: |
14299 | 0 | CandidateSet.NoteCandidates( |
14300 | 0 | PartialDiagnosticAt(OpLoc, |
14301 | 0 | PDiag(diag::err_ovl_ambiguous_oper_unary) |
14302 | 0 | << UnaryOperator::getOpcodeStr(Opc) |
14303 | 0 | << Input->getType() << Input->getSourceRange()), |
14304 | 0 | *this, OCD_AmbiguousCandidates, ArgsArray, |
14305 | 0 | UnaryOperator::getOpcodeStr(Opc), OpLoc); |
14306 | 0 | return ExprError(); |
14307 | | |
14308 | 0 | case OR_Deleted: |
14309 | 0 | CandidateSet.NoteCandidates( |
14310 | 0 | PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) |
14311 | 0 | << UnaryOperator::getOpcodeStr(Opc) |
14312 | 0 | << Input->getSourceRange()), |
14313 | 0 | *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), |
14314 | 0 | OpLoc); |
14315 | 0 | return ExprError(); |
14316 | 0 | } |
14317 | | |
14318 | | // Either we found no viable overloaded operator or we matched a |
14319 | | // built-in operator. In either case, fall through to trying to |
14320 | | // build a built-in operation. |
14321 | 0 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); |
14322 | 0 | } |
14323 | | |
14324 | | /// Perform lookup for an overloaded binary operator. |
14325 | | void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, |
14326 | | OverloadedOperatorKind Op, |
14327 | | const UnresolvedSetImpl &Fns, |
14328 | 0 | ArrayRef<Expr *> Args, bool PerformADL) { |
14329 | 0 | SourceLocation OpLoc = CandidateSet.getLocation(); |
14330 | |
|
14331 | 0 | OverloadedOperatorKind ExtraOp = |
14332 | 0 | CandidateSet.getRewriteInfo().AllowRewrittenCandidates |
14333 | 0 | ? getRewrittenOverloadedOperator(Op) |
14334 | 0 | : OO_None; |
14335 | | |
14336 | | // Add the candidates from the given function set. This also adds the |
14337 | | // rewritten candidates using these functions if necessary. |
14338 | 0 | AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); |
14339 | | |
14340 | | // Add operator candidates that are member functions. |
14341 | 0 | AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); |
14342 | 0 | if (CandidateSet.getRewriteInfo().allowsReversed(Op)) |
14343 | 0 | AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, |
14344 | 0 | OverloadCandidateParamOrder::Reversed); |
14345 | | |
14346 | | // In C++20, also add any rewritten member candidates. |
14347 | 0 | if (ExtraOp) { |
14348 | 0 | AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); |
14349 | 0 | if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp)) |
14350 | 0 | AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, |
14351 | 0 | CandidateSet, |
14352 | 0 | OverloadCandidateParamOrder::Reversed); |
14353 | 0 | } |
14354 | | |
14355 | | // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not |
14356 | | // performed for an assignment operator (nor for operator[] nor operator->, |
14357 | | // which don't get here). |
14358 | 0 | if (Op != OO_Equal && PerformADL) { |
14359 | 0 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); |
14360 | 0 | AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, |
14361 | 0 | /*ExplicitTemplateArgs*/ nullptr, |
14362 | 0 | CandidateSet); |
14363 | 0 | if (ExtraOp) { |
14364 | 0 | DeclarationName ExtraOpName = |
14365 | 0 | Context.DeclarationNames.getCXXOperatorName(ExtraOp); |
14366 | 0 | AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, |
14367 | 0 | /*ExplicitTemplateArgs*/ nullptr, |
14368 | 0 | CandidateSet); |
14369 | 0 | } |
14370 | 0 | } |
14371 | | |
14372 | | // Add builtin operator candidates. |
14373 | | // |
14374 | | // FIXME: We don't add any rewritten candidates here. This is strictly |
14375 | | // incorrect; a builtin candidate could be hidden by a non-viable candidate, |
14376 | | // resulting in our selecting a rewritten builtin candidate. For example: |
14377 | | // |
14378 | | // enum class E { e }; |
14379 | | // bool operator!=(E, E) requires false; |
14380 | | // bool k = E::e != E::e; |
14381 | | // |
14382 | | // ... should select the rewritten builtin candidate 'operator==(E, E)'. But |
14383 | | // it seems unreasonable to consider rewritten builtin candidates. A core |
14384 | | // issue has been filed proposing to removed this requirement. |
14385 | 0 | AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); |
14386 | 0 | } |
14387 | | |
14388 | | /// Create a binary operation that may resolve to an overloaded |
14389 | | /// operator. |
14390 | | /// |
14391 | | /// \param OpLoc The location of the operator itself (e.g., '+'). |
14392 | | /// |
14393 | | /// \param Opc The BinaryOperatorKind that describes this operator. |
14394 | | /// |
14395 | | /// \param Fns The set of non-member functions that will be |
14396 | | /// considered by overload resolution. The caller needs to build this |
14397 | | /// set based on the context using, e.g., |
14398 | | /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This |
14399 | | /// set should not contain any member functions; those will be added |
14400 | | /// by CreateOverloadedBinOp(). |
14401 | | /// |
14402 | | /// \param LHS Left-hand argument. |
14403 | | /// \param RHS Right-hand argument. |
14404 | | /// \param PerformADL Whether to consider operator candidates found by ADL. |
14405 | | /// \param AllowRewrittenCandidates Whether to consider candidates found by |
14406 | | /// C++20 operator rewrites. |
14407 | | /// \param DefaultedFn If we are synthesizing a defaulted operator function, |
14408 | | /// the function in question. Such a function is never a candidate in |
14409 | | /// our overload resolution. This also enables synthesizing a three-way |
14410 | | /// comparison from < and == as described in C++20 [class.spaceship]p1. |
14411 | | ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, |
14412 | | BinaryOperatorKind Opc, |
14413 | | const UnresolvedSetImpl &Fns, Expr *LHS, |
14414 | | Expr *RHS, bool PerformADL, |
14415 | | bool AllowRewrittenCandidates, |
14416 | 23 | FunctionDecl *DefaultedFn) { |
14417 | 23 | Expr *Args[2] = { LHS, RHS }; |
14418 | 23 | LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple |
14419 | | |
14420 | 23 | if (!getLangOpts().CPlusPlus20) |
14421 | 23 | AllowRewrittenCandidates = false; |
14422 | | |
14423 | 23 | OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); |
14424 | | |
14425 | | // If either side is type-dependent, create an appropriate dependent |
14426 | | // expression. |
14427 | 23 | if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { |
14428 | 23 | if (Fns.empty()) { |
14429 | | // If there are no functions to store, just build a dependent |
14430 | | // BinaryOperator or CompoundAssignment. |
14431 | 23 | if (BinaryOperator::isCompoundAssignmentOp(Opc)) |
14432 | 0 | return CompoundAssignOperator::Create( |
14433 | 0 | Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, |
14434 | 0 | OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy, |
14435 | 0 | Context.DependentTy); |
14436 | 23 | return BinaryOperator::Create( |
14437 | 23 | Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue, |
14438 | 23 | OK_Ordinary, OpLoc, CurFPFeatureOverrides()); |
14439 | 23 | } |
14440 | | |
14441 | | // FIXME: save results of ADL from here? |
14442 | 0 | CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators |
14443 | | // TODO: provide better source location info in DNLoc component. |
14444 | 0 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); |
14445 | 0 | DeclarationNameInfo OpNameInfo(OpName, OpLoc); |
14446 | 0 | ExprResult Fn = CreateUnresolvedLookupExpr( |
14447 | 0 | NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL); |
14448 | 0 | if (Fn.isInvalid()) |
14449 | 0 | return ExprError(); |
14450 | 0 | return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args, |
14451 | 0 | Context.DependentTy, VK_PRValue, OpLoc, |
14452 | 0 | CurFPFeatureOverrides()); |
14453 | 0 | } |
14454 | | |
14455 | | // Always do placeholder-like conversions on the RHS. |
14456 | 0 | if (checkPlaceholderForOverload(*this, Args[1])) |
14457 | 0 | return ExprError(); |
14458 | | |
14459 | | // Do placeholder-like conversion on the LHS; note that we should |
14460 | | // not get here with a PseudoObject LHS. |
14461 | 0 | assert(Args[0]->getObjectKind() != OK_ObjCProperty); |
14462 | 0 | if (checkPlaceholderForOverload(*this, Args[0])) |
14463 | 0 | return ExprError(); |
14464 | | |
14465 | | // If this is the assignment operator, we only perform overload resolution |
14466 | | // if the left-hand side is a class or enumeration type. This is actually |
14467 | | // a hack. The standard requires that we do overload resolution between the |
14468 | | // various built-in candidates, but as DR507 points out, this can lead to |
14469 | | // problems. So we do it this way, which pretty much follows what GCC does. |
14470 | | // Note that we go the traditional code path for compound assignment forms. |
14471 | 0 | if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) |
14472 | 0 | return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); |
14473 | | |
14474 | | // If this is the .* operator, which is not overloadable, just |
14475 | | // create a built-in binary operator. |
14476 | 0 | if (Opc == BO_PtrMemD) |
14477 | 0 | return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); |
14478 | | |
14479 | | // Build the overload set. |
14480 | 0 | OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator, |
14481 | 0 | OverloadCandidateSet::OperatorRewriteInfo( |
14482 | 0 | Op, OpLoc, AllowRewrittenCandidates)); |
14483 | 0 | if (DefaultedFn) |
14484 | 0 | CandidateSet.exclude(DefaultedFn); |
14485 | 0 | LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); |
14486 | |
|
14487 | 0 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
14488 | | |
14489 | | // Perform overload resolution. |
14490 | 0 | OverloadCandidateSet::iterator Best; |
14491 | 0 | switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { |
14492 | 0 | case OR_Success: { |
14493 | | // We found a built-in operator or an overloaded operator. |
14494 | 0 | FunctionDecl *FnDecl = Best->Function; |
14495 | |
|
14496 | 0 | bool IsReversed = Best->isReversed(); |
14497 | 0 | if (IsReversed) |
14498 | 0 | std::swap(Args[0], Args[1]); |
14499 | |
|
14500 | 0 | if (FnDecl) { |
14501 | |
|
14502 | 0 | if (FnDecl->isInvalidDecl()) |
14503 | 0 | return ExprError(); |
14504 | | |
14505 | 0 | Expr *Base = nullptr; |
14506 | | // We matched an overloaded operator. Build a call to that |
14507 | | // operator. |
14508 | |
|
14509 | 0 | OverloadedOperatorKind ChosenOp = |
14510 | 0 | FnDecl->getDeclName().getCXXOverloadedOperator(); |
14511 | | |
14512 | | // C++2a [over.match.oper]p9: |
14513 | | // If a rewritten operator== candidate is selected by overload |
14514 | | // resolution for an operator@, its return type shall be cv bool |
14515 | 0 | if (Best->RewriteKind && ChosenOp == OO_EqualEqual && |
14516 | 0 | !FnDecl->getReturnType()->isBooleanType()) { |
14517 | 0 | bool IsExtension = |
14518 | 0 | FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType(); |
14519 | 0 | Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool |
14520 | 0 | : diag::err_ovl_rewrite_equalequal_not_bool) |
14521 | 0 | << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) |
14522 | 0 | << Args[0]->getSourceRange() << Args[1]->getSourceRange(); |
14523 | 0 | Diag(FnDecl->getLocation(), diag::note_declared_at); |
14524 | 0 | if (!IsExtension) |
14525 | 0 | return ExprError(); |
14526 | 0 | } |
14527 | | |
14528 | 0 | if (AllowRewrittenCandidates && !IsReversed && |
14529 | 0 | CandidateSet.getRewriteInfo().isReversible()) { |
14530 | | // We could have reversed this operator, but didn't. Check if some |
14531 | | // reversed form was a viable candidate, and if so, if it had a |
14532 | | // better conversion for either parameter. If so, this call is |
14533 | | // formally ambiguous, and allowing it is an extension. |
14534 | 0 | llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith; |
14535 | 0 | for (OverloadCandidate &Cand : CandidateSet) { |
14536 | 0 | if (Cand.Viable && Cand.Function && Cand.isReversed() && |
14537 | 0 | allowAmbiguity(Context, Cand.Function, FnDecl)) { |
14538 | 0 | for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { |
14539 | 0 | if (CompareImplicitConversionSequences( |
14540 | 0 | *this, OpLoc, Cand.Conversions[ArgIdx], |
14541 | 0 | Best->Conversions[ArgIdx]) == |
14542 | 0 | ImplicitConversionSequence::Better) { |
14543 | 0 | AmbiguousWith.push_back(Cand.Function); |
14544 | 0 | break; |
14545 | 0 | } |
14546 | 0 | } |
14547 | 0 | } |
14548 | 0 | } |
14549 | |
|
14550 | 0 | if (!AmbiguousWith.empty()) { |
14551 | 0 | bool AmbiguousWithSelf = |
14552 | 0 | AmbiguousWith.size() == 1 && |
14553 | 0 | declaresSameEntity(AmbiguousWith.front(), FnDecl); |
14554 | 0 | Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) |
14555 | 0 | << BinaryOperator::getOpcodeStr(Opc) |
14556 | 0 | << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf |
14557 | 0 | << Args[0]->getSourceRange() << Args[1]->getSourceRange(); |
14558 | 0 | if (AmbiguousWithSelf) { |
14559 | 0 | Diag(FnDecl->getLocation(), |
14560 | 0 | diag::note_ovl_ambiguous_oper_binary_reversed_self); |
14561 | | // Mark member== const or provide matching != to disallow reversed |
14562 | | // args. Eg. |
14563 | | // struct S { bool operator==(const S&); }; |
14564 | | // S()==S(); |
14565 | 0 | if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl)) |
14566 | 0 | if (Op == OverloadedOperatorKind::OO_EqualEqual && |
14567 | 0 | !MD->isConst() && |
14568 | 0 | !MD->hasCXXExplicitFunctionObjectParameter() && |
14569 | 0 | Context.hasSameUnqualifiedType( |
14570 | 0 | MD->getFunctionObjectParameterType(), |
14571 | 0 | MD->getParamDecl(0)->getType().getNonReferenceType()) && |
14572 | 0 | Context.hasSameUnqualifiedType( |
14573 | 0 | MD->getFunctionObjectParameterType(), |
14574 | 0 | Args[0]->getType()) && |
14575 | 0 | Context.hasSameUnqualifiedType( |
14576 | 0 | MD->getFunctionObjectParameterType(), |
14577 | 0 | Args[1]->getType())) |
14578 | 0 | Diag(FnDecl->getLocation(), |
14579 | 0 | diag::note_ovl_ambiguous_eqeq_reversed_self_non_const); |
14580 | 0 | } else { |
14581 | 0 | Diag(FnDecl->getLocation(), |
14582 | 0 | diag::note_ovl_ambiguous_oper_binary_selected_candidate); |
14583 | 0 | for (auto *F : AmbiguousWith) |
14584 | 0 | Diag(F->getLocation(), |
14585 | 0 | diag::note_ovl_ambiguous_oper_binary_reversed_candidate); |
14586 | 0 | } |
14587 | 0 | } |
14588 | 0 | } |
14589 | | |
14590 | | // Convert the arguments. |
14591 | 0 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { |
14592 | | // Best->Access is only meaningful for class members. |
14593 | 0 | CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); |
14594 | |
|
14595 | 0 | ExprResult Arg0, Arg1; |
14596 | 0 | unsigned ParamIdx = 0; |
14597 | 0 | if (Method->isExplicitObjectMemberFunction()) { |
14598 | 0 | Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl); |
14599 | 0 | ParamIdx = 1; |
14600 | 0 | } else { |
14601 | 0 | Arg0 = PerformImplicitObjectArgumentInitialization( |
14602 | 0 | Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method); |
14603 | 0 | } |
14604 | 0 | Arg1 = PerformCopyInitialization( |
14605 | 0 | InitializedEntity::InitializeParameter( |
14606 | 0 | Context, FnDecl->getParamDecl(ParamIdx)), |
14607 | 0 | SourceLocation(), Args[1]); |
14608 | 0 | if (Arg0.isInvalid() || Arg1.isInvalid()) |
14609 | 0 | return ExprError(); |
14610 | | |
14611 | 0 | Base = Args[0] = Arg0.getAs<Expr>(); |
14612 | 0 | Args[1] = RHS = Arg1.getAs<Expr>(); |
14613 | 0 | } else { |
14614 | | // Convert the arguments. |
14615 | 0 | ExprResult Arg0 = PerformCopyInitialization( |
14616 | 0 | InitializedEntity::InitializeParameter(Context, |
14617 | 0 | FnDecl->getParamDecl(0)), |
14618 | 0 | SourceLocation(), Args[0]); |
14619 | 0 | if (Arg0.isInvalid()) |
14620 | 0 | return ExprError(); |
14621 | | |
14622 | 0 | ExprResult Arg1 = |
14623 | 0 | PerformCopyInitialization( |
14624 | 0 | InitializedEntity::InitializeParameter(Context, |
14625 | 0 | FnDecl->getParamDecl(1)), |
14626 | 0 | SourceLocation(), Args[1]); |
14627 | 0 | if (Arg1.isInvalid()) |
14628 | 0 | return ExprError(); |
14629 | 0 | Args[0] = LHS = Arg0.getAs<Expr>(); |
14630 | 0 | Args[1] = RHS = Arg1.getAs<Expr>(); |
14631 | 0 | } |
14632 | | |
14633 | | // Build the actual expression node. |
14634 | 0 | ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, |
14635 | 0 | Best->FoundDecl, Base, |
14636 | 0 | HadMultipleCandidates, OpLoc); |
14637 | 0 | if (FnExpr.isInvalid()) |
14638 | 0 | return ExprError(); |
14639 | | |
14640 | | // Determine the result type. |
14641 | 0 | QualType ResultTy = FnDecl->getReturnType(); |
14642 | 0 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); |
14643 | 0 | ResultTy = ResultTy.getNonLValueExprType(Context); |
14644 | |
|
14645 | 0 | CallExpr *TheCall; |
14646 | 0 | ArrayRef<const Expr *> ArgsArray(Args, 2); |
14647 | 0 | const Expr *ImplicitThis = nullptr; |
14648 | | |
14649 | | // We always create a CXXOperatorCallExpr, even for explicit object |
14650 | | // members; CodeGen should take care not to emit the this pointer. |
14651 | 0 | TheCall = CXXOperatorCallExpr::Create( |
14652 | 0 | Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, |
14653 | 0 | CurFPFeatureOverrides(), Best->IsADLCandidate); |
14654 | |
|
14655 | 0 | if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl); |
14656 | 0 | Method && Method->isImplicitObjectMemberFunction()) { |
14657 | | // Cut off the implicit 'this'. |
14658 | 0 | ImplicitThis = ArgsArray[0]; |
14659 | 0 | ArgsArray = ArgsArray.slice(1); |
14660 | 0 | } |
14661 | |
|
14662 | 0 | if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, |
14663 | 0 | FnDecl)) |
14664 | 0 | return ExprError(); |
14665 | | |
14666 | | // Check for a self move. |
14667 | 0 | if (Op == OO_Equal) |
14668 | 0 | DiagnoseSelfMove(Args[0], Args[1], OpLoc); |
14669 | |
|
14670 | 0 | if (ImplicitThis) { |
14671 | 0 | QualType ThisType = Context.getPointerType(ImplicitThis->getType()); |
14672 | 0 | QualType ThisTypeFromDecl = Context.getPointerType( |
14673 | 0 | cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType()); |
14674 | |
|
14675 | 0 | CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType, |
14676 | 0 | ThisTypeFromDecl); |
14677 | 0 | } |
14678 | |
|
14679 | 0 | checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, |
14680 | 0 | isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), |
14681 | 0 | VariadicDoesNotApply); |
14682 | |
|
14683 | 0 | ExprResult R = MaybeBindToTemporary(TheCall); |
14684 | 0 | if (R.isInvalid()) |
14685 | 0 | return ExprError(); |
14686 | | |
14687 | 0 | R = CheckForImmediateInvocation(R, FnDecl); |
14688 | 0 | if (R.isInvalid()) |
14689 | 0 | return ExprError(); |
14690 | | |
14691 | | // For a rewritten candidate, we've already reversed the arguments |
14692 | | // if needed. Perform the rest of the rewrite now. |
14693 | 0 | if ((Best->RewriteKind & CRK_DifferentOperator) || |
14694 | 0 | (Op == OO_Spaceship && IsReversed)) { |
14695 | 0 | if (Op == OO_ExclaimEqual) { |
14696 | 0 | assert(ChosenOp == OO_EqualEqual && "unexpected operator name"); |
14697 | 0 | R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); |
14698 | 0 | } else { |
14699 | 0 | assert(ChosenOp == OO_Spaceship && "unexpected operator name"); |
14700 | 0 | llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); |
14701 | 0 | Expr *ZeroLiteral = |
14702 | 0 | IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); |
14703 | |
|
14704 | 0 | Sema::CodeSynthesisContext Ctx; |
14705 | 0 | Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; |
14706 | 0 | Ctx.Entity = FnDecl; |
14707 | 0 | pushCodeSynthesisContext(Ctx); |
14708 | |
|
14709 | 0 | R = CreateOverloadedBinOp( |
14710 | 0 | OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), |
14711 | 0 | IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true, |
14712 | 0 | /*AllowRewrittenCandidates=*/false); |
14713 | |
|
14714 | 0 | popCodeSynthesisContext(); |
14715 | 0 | } |
14716 | 0 | if (R.isInvalid()) |
14717 | 0 | return ExprError(); |
14718 | 0 | } else { |
14719 | 0 | assert(ChosenOp == Op && "unexpected operator name"); |
14720 | 0 | } |
14721 | | |
14722 | | // Make a note in the AST if we did any rewriting. |
14723 | 0 | if (Best->RewriteKind != CRK_None) |
14724 | 0 | R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); |
14725 | |
|
14726 | 0 | return R; |
14727 | 0 | } else { |
14728 | | // We matched a built-in operator. Convert the arguments, then |
14729 | | // break out so that we will build the appropriate built-in |
14730 | | // operator node. |
14731 | 0 | ExprResult ArgsRes0 = PerformImplicitConversion( |
14732 | 0 | Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], |
14733 | 0 | AA_Passing, CCK_ForBuiltinOverloadedOp); |
14734 | 0 | if (ArgsRes0.isInvalid()) |
14735 | 0 | return ExprError(); |
14736 | 0 | Args[0] = ArgsRes0.get(); |
14737 | |
|
14738 | 0 | ExprResult ArgsRes1 = PerformImplicitConversion( |
14739 | 0 | Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], |
14740 | 0 | AA_Passing, CCK_ForBuiltinOverloadedOp); |
14741 | 0 | if (ArgsRes1.isInvalid()) |
14742 | 0 | return ExprError(); |
14743 | 0 | Args[1] = ArgsRes1.get(); |
14744 | 0 | break; |
14745 | 0 | } |
14746 | 0 | } |
14747 | | |
14748 | 0 | case OR_No_Viable_Function: { |
14749 | | // C++ [over.match.oper]p9: |
14750 | | // If the operator is the operator , [...] and there are no |
14751 | | // viable functions, then the operator is assumed to be the |
14752 | | // built-in operator and interpreted according to clause 5. |
14753 | 0 | if (Opc == BO_Comma) |
14754 | 0 | break; |
14755 | | |
14756 | | // When defaulting an 'operator<=>', we can try to synthesize a three-way |
14757 | | // compare result using '==' and '<'. |
14758 | 0 | if (DefaultedFn && Opc == BO_Cmp) { |
14759 | 0 | ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], |
14760 | 0 | Args[1], DefaultedFn); |
14761 | 0 | if (E.isInvalid() || E.isUsable()) |
14762 | 0 | return E; |
14763 | 0 | } |
14764 | | |
14765 | | // For class as left operand for assignment or compound assignment |
14766 | | // operator do not fall through to handling in built-in, but report that |
14767 | | // no overloaded assignment operator found |
14768 | 0 | ExprResult Result = ExprError(); |
14769 | 0 | StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); |
14770 | 0 | auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, |
14771 | 0 | Args, OpLoc); |
14772 | 0 | DeferDiagsRAII DDR(*this, |
14773 | 0 | CandidateSet.shouldDeferDiags(*this, Args, OpLoc)); |
14774 | 0 | if (Args[0]->getType()->isRecordType() && |
14775 | 0 | Opc >= BO_Assign && Opc <= BO_OrAssign) { |
14776 | 0 | Diag(OpLoc, diag::err_ovl_no_viable_oper) |
14777 | 0 | << BinaryOperator::getOpcodeStr(Opc) |
14778 | 0 | << Args[0]->getSourceRange() << Args[1]->getSourceRange(); |
14779 | 0 | if (Args[0]->getType()->isIncompleteType()) { |
14780 | 0 | Diag(OpLoc, diag::note_assign_lhs_incomplete) |
14781 | 0 | << Args[0]->getType() |
14782 | 0 | << Args[0]->getSourceRange() << Args[1]->getSourceRange(); |
14783 | 0 | } |
14784 | 0 | } else { |
14785 | | // This is an erroneous use of an operator which can be overloaded by |
14786 | | // a non-member function. Check for non-member operators which were |
14787 | | // defined too late to be candidates. |
14788 | 0 | if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) |
14789 | | // FIXME: Recover by calling the found function. |
14790 | 0 | return ExprError(); |
14791 | | |
14792 | | // No viable function; try to create a built-in operation, which will |
14793 | | // produce an error. Then, show the non-viable candidates. |
14794 | 0 | Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); |
14795 | 0 | } |
14796 | 0 | assert(Result.isInvalid() && |
14797 | 0 | "C++ binary operator overloading is missing candidates!"); |
14798 | 0 | CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); |
14799 | 0 | return Result; |
14800 | 0 | } |
14801 | | |
14802 | 0 | case OR_Ambiguous: |
14803 | 0 | CandidateSet.NoteCandidates( |
14804 | 0 | PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) |
14805 | 0 | << BinaryOperator::getOpcodeStr(Opc) |
14806 | 0 | << Args[0]->getType() |
14807 | 0 | << Args[1]->getType() |
14808 | 0 | << Args[0]->getSourceRange() |
14809 | 0 | << Args[1]->getSourceRange()), |
14810 | 0 | *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), |
14811 | 0 | OpLoc); |
14812 | 0 | return ExprError(); |
14813 | | |
14814 | 0 | case OR_Deleted: |
14815 | 0 | if (isImplicitlyDeleted(Best->Function)) { |
14816 | 0 | FunctionDecl *DeletedFD = Best->Function; |
14817 | 0 | DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); |
14818 | 0 | if (DFK.isSpecialMember()) { |
14819 | 0 | Diag(OpLoc, diag::err_ovl_deleted_special_oper) |
14820 | 0 | << Args[0]->getType() << DFK.asSpecialMember(); |
14821 | 0 | } else { |
14822 | 0 | assert(DFK.isComparison()); |
14823 | 0 | Diag(OpLoc, diag::err_ovl_deleted_comparison) |
14824 | 0 | << Args[0]->getType() << DeletedFD; |
14825 | 0 | } |
14826 | | |
14827 | | // The user probably meant to call this special member. Just |
14828 | | // explain why it's deleted. |
14829 | 0 | NoteDeletedFunction(DeletedFD); |
14830 | 0 | return ExprError(); |
14831 | 0 | } |
14832 | 0 | CandidateSet.NoteCandidates( |
14833 | 0 | PartialDiagnosticAt( |
14834 | 0 | OpLoc, PDiag(diag::err_ovl_deleted_oper) |
14835 | 0 | << getOperatorSpelling(Best->Function->getDeclName() |
14836 | 0 | .getCXXOverloadedOperator()) |
14837 | 0 | << Args[0]->getSourceRange() |
14838 | 0 | << Args[1]->getSourceRange()), |
14839 | 0 | *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), |
14840 | 0 | OpLoc); |
14841 | 0 | return ExprError(); |
14842 | 0 | } |
14843 | | |
14844 | | // We matched a built-in operator; build it. |
14845 | 0 | return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); |
14846 | 0 | } |
14847 | | |
14848 | | ExprResult Sema::BuildSynthesizedThreeWayComparison( |
14849 | | SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, |
14850 | 0 | FunctionDecl *DefaultedFn) { |
14851 | 0 | const ComparisonCategoryInfo *Info = |
14852 | 0 | Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); |
14853 | | // If we're not producing a known comparison category type, we can't |
14854 | | // synthesize a three-way comparison. Let the caller diagnose this. |
14855 | 0 | if (!Info) |
14856 | 0 | return ExprResult((Expr*)nullptr); |
14857 | | |
14858 | | // If we ever want to perform this synthesis more generally, we will need to |
14859 | | // apply the temporary materialization conversion to the operands. |
14860 | 0 | assert(LHS->isGLValue() && RHS->isGLValue() && |
14861 | 0 | "cannot use prvalue expressions more than once"); |
14862 | 0 | Expr *OrigLHS = LHS; |
14863 | 0 | Expr *OrigRHS = RHS; |
14864 | | |
14865 | | // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to |
14866 | | // each of them multiple times below. |
14867 | 0 | LHS = new (Context) |
14868 | 0 | OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), |
14869 | 0 | LHS->getObjectKind(), LHS); |
14870 | 0 | RHS = new (Context) |
14871 | 0 | OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), |
14872 | 0 | RHS->getObjectKind(), RHS); |
14873 | |
|
14874 | 0 | ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, |
14875 | 0 | DefaultedFn); |
14876 | 0 | if (Eq.isInvalid()) |
14877 | 0 | return ExprError(); |
14878 | | |
14879 | 0 | ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, |
14880 | 0 | true, DefaultedFn); |
14881 | 0 | if (Less.isInvalid()) |
14882 | 0 | return ExprError(); |
14883 | | |
14884 | 0 | ExprResult Greater; |
14885 | 0 | if (Info->isPartial()) { |
14886 | 0 | Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, |
14887 | 0 | DefaultedFn); |
14888 | 0 | if (Greater.isInvalid()) |
14889 | 0 | return ExprError(); |
14890 | 0 | } |
14891 | | |
14892 | | // Form the list of comparisons we're going to perform. |
14893 | 0 | struct Comparison { |
14894 | 0 | ExprResult Cmp; |
14895 | 0 | ComparisonCategoryResult Result; |
14896 | 0 | } Comparisons[4] = |
14897 | 0 | { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal |
14898 | 0 | : ComparisonCategoryResult::Equivalent}, |
14899 | 0 | {Less, ComparisonCategoryResult::Less}, |
14900 | 0 | {Greater, ComparisonCategoryResult::Greater}, |
14901 | 0 | {ExprResult(), ComparisonCategoryResult::Unordered}, |
14902 | 0 | }; |
14903 | |
|
14904 | 0 | int I = Info->isPartial() ? 3 : 2; |
14905 | | |
14906 | | // Combine the comparisons with suitable conditional expressions. |
14907 | 0 | ExprResult Result; |
14908 | 0 | for (; I >= 0; --I) { |
14909 | | // Build a reference to the comparison category constant. |
14910 | 0 | auto *VI = Info->lookupValueInfo(Comparisons[I].Result); |
14911 | | // FIXME: Missing a constant for a comparison category. Diagnose this? |
14912 | 0 | if (!VI) |
14913 | 0 | return ExprResult((Expr*)nullptr); |
14914 | 0 | ExprResult ThisResult = |
14915 | 0 | BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); |
14916 | 0 | if (ThisResult.isInvalid()) |
14917 | 0 | return ExprError(); |
14918 | | |
14919 | | // Build a conditional unless this is the final case. |
14920 | 0 | if (Result.get()) { |
14921 | 0 | Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), |
14922 | 0 | ThisResult.get(), Result.get()); |
14923 | 0 | if (Result.isInvalid()) |
14924 | 0 | return ExprError(); |
14925 | 0 | } else { |
14926 | 0 | Result = ThisResult; |
14927 | 0 | } |
14928 | 0 | } |
14929 | | |
14930 | | // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to |
14931 | | // bind the OpaqueValueExprs before they're (repeatedly) used. |
14932 | 0 | Expr *SyntacticForm = BinaryOperator::Create( |
14933 | 0 | Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), |
14934 | 0 | Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc, |
14935 | 0 | CurFPFeatureOverrides()); |
14936 | 0 | Expr *SemanticForm[] = {LHS, RHS, Result.get()}; |
14937 | 0 | return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); |
14938 | 0 | } |
14939 | | |
14940 | | static bool PrepareArgumentsForCallToObjectOfClassType( |
14941 | | Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method, |
14942 | 0 | MultiExprArg Args, SourceLocation LParenLoc) { |
14943 | |
|
14944 | 0 | const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); |
14945 | 0 | unsigned NumParams = Proto->getNumParams(); |
14946 | 0 | unsigned NumArgsSlots = |
14947 | 0 | MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams); |
14948 | | // Build the full argument list for the method call (the implicit object |
14949 | | // parameter is placed at the beginning of the list). |
14950 | 0 | MethodArgs.reserve(MethodArgs.size() + NumArgsSlots); |
14951 | 0 | bool IsError = false; |
14952 | | // Initialize the implicit object parameter. |
14953 | | // Check the argument types. |
14954 | 0 | for (unsigned i = 0; i != NumParams; i++) { |
14955 | 0 | Expr *Arg; |
14956 | 0 | if (i < Args.size()) { |
14957 | 0 | Arg = Args[i]; |
14958 | 0 | ExprResult InputInit = |
14959 | 0 | S.PerformCopyInitialization(InitializedEntity::InitializeParameter( |
14960 | 0 | S.Context, Method->getParamDecl(i)), |
14961 | 0 | SourceLocation(), Arg); |
14962 | 0 | IsError |= InputInit.isInvalid(); |
14963 | 0 | Arg = InputInit.getAs<Expr>(); |
14964 | 0 | } else { |
14965 | 0 | ExprResult DefArg = |
14966 | 0 | S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); |
14967 | 0 | if (DefArg.isInvalid()) { |
14968 | 0 | IsError = true; |
14969 | 0 | break; |
14970 | 0 | } |
14971 | 0 | Arg = DefArg.getAs<Expr>(); |
14972 | 0 | } |
14973 | | |
14974 | 0 | MethodArgs.push_back(Arg); |
14975 | 0 | } |
14976 | 0 | return IsError; |
14977 | 0 | } |
14978 | | |
14979 | | ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, |
14980 | | SourceLocation RLoc, |
14981 | | Expr *Base, |
14982 | 0 | MultiExprArg ArgExpr) { |
14983 | 0 | SmallVector<Expr *, 2> Args; |
14984 | 0 | Args.push_back(Base); |
14985 | 0 | for (auto *e : ArgExpr) { |
14986 | 0 | Args.push_back(e); |
14987 | 0 | } |
14988 | 0 | DeclarationName OpName = |
14989 | 0 | Context.DeclarationNames.getCXXOperatorName(OO_Subscript); |
14990 | |
|
14991 | 0 | SourceRange Range = ArgExpr.empty() |
14992 | 0 | ? SourceRange{} |
14993 | 0 | : SourceRange(ArgExpr.front()->getBeginLoc(), |
14994 | 0 | ArgExpr.back()->getEndLoc()); |
14995 | | |
14996 | | // If either side is type-dependent, create an appropriate dependent |
14997 | | // expression. |
14998 | 0 | if (Expr::hasAnyTypeDependentArguments(Args)) { |
14999 | |
|
15000 | 0 | CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators |
15001 | | // CHECKME: no 'operator' keyword? |
15002 | 0 | DeclarationNameInfo OpNameInfo(OpName, LLoc); |
15003 | 0 | OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); |
15004 | 0 | ExprResult Fn = CreateUnresolvedLookupExpr( |
15005 | 0 | NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>()); |
15006 | 0 | if (Fn.isInvalid()) |
15007 | 0 | return ExprError(); |
15008 | | // Can't add any actual overloads yet |
15009 | | |
15010 | 0 | return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args, |
15011 | 0 | Context.DependentTy, VK_PRValue, RLoc, |
15012 | 0 | CurFPFeatureOverrides()); |
15013 | 0 | } |
15014 | | |
15015 | | // Handle placeholders |
15016 | 0 | UnbridgedCastsSet UnbridgedCasts; |
15017 | 0 | if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { |
15018 | 0 | return ExprError(); |
15019 | 0 | } |
15020 | | // Build an empty overload set. |
15021 | 0 | OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); |
15022 | | |
15023 | | // Subscript can only be overloaded as a member function. |
15024 | | |
15025 | | // Add operator candidates that are member functions. |
15026 | 0 | AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); |
15027 | | |
15028 | | // Add builtin operator candidates. |
15029 | 0 | if (Args.size() == 2) |
15030 | 0 | AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); |
15031 | |
|
15032 | 0 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
15033 | | |
15034 | | // Perform overload resolution. |
15035 | 0 | OverloadCandidateSet::iterator Best; |
15036 | 0 | switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { |
15037 | 0 | case OR_Success: { |
15038 | | // We found a built-in operator or an overloaded operator. |
15039 | 0 | FunctionDecl *FnDecl = Best->Function; |
15040 | |
|
15041 | 0 | if (FnDecl) { |
15042 | | // We matched an overloaded operator. Build a call to that |
15043 | | // operator. |
15044 | |
|
15045 | 0 | CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl); |
15046 | | |
15047 | | // Convert the arguments. |
15048 | 0 | CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); |
15049 | 0 | SmallVector<Expr *, 2> MethodArgs; |
15050 | | |
15051 | | // Handle 'this' parameter if the selected function is not static. |
15052 | 0 | if (Method->isExplicitObjectMemberFunction()) { |
15053 | 0 | ExprResult Res = |
15054 | 0 | InitializeExplicitObjectArgument(*this, Args[0], Method); |
15055 | 0 | if (Res.isInvalid()) |
15056 | 0 | return ExprError(); |
15057 | 0 | Args[0] = Res.get(); |
15058 | 0 | ArgExpr = Args; |
15059 | 0 | } else if (Method->isInstance()) { |
15060 | 0 | ExprResult Arg0 = PerformImplicitObjectArgumentInitialization( |
15061 | 0 | Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method); |
15062 | 0 | if (Arg0.isInvalid()) |
15063 | 0 | return ExprError(); |
15064 | | |
15065 | 0 | MethodArgs.push_back(Arg0.get()); |
15066 | 0 | } |
15067 | | |
15068 | 0 | bool IsError = PrepareArgumentsForCallToObjectOfClassType( |
15069 | 0 | *this, MethodArgs, Method, ArgExpr, LLoc); |
15070 | 0 | if (IsError) |
15071 | 0 | return ExprError(); |
15072 | | |
15073 | | // Build the actual expression node. |
15074 | 0 | DeclarationNameInfo OpLocInfo(OpName, LLoc); |
15075 | 0 | OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); |
15076 | 0 | ExprResult FnExpr = CreateFunctionRefExpr( |
15077 | 0 | *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates, |
15078 | 0 | OpLocInfo.getLoc(), OpLocInfo.getInfo()); |
15079 | 0 | if (FnExpr.isInvalid()) |
15080 | 0 | return ExprError(); |
15081 | | |
15082 | | // Determine the result type |
15083 | 0 | QualType ResultTy = FnDecl->getReturnType(); |
15084 | 0 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); |
15085 | 0 | ResultTy = ResultTy.getNonLValueExprType(Context); |
15086 | |
|
15087 | 0 | CallExpr *TheCall; |
15088 | 0 | if (Method->isInstance()) |
15089 | 0 | TheCall = CXXOperatorCallExpr::Create( |
15090 | 0 | Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, |
15091 | 0 | RLoc, CurFPFeatureOverrides()); |
15092 | 0 | else |
15093 | 0 | TheCall = |
15094 | 0 | CallExpr::Create(Context, FnExpr.get(), MethodArgs, ResultTy, VK, |
15095 | 0 | RLoc, CurFPFeatureOverrides()); |
15096 | |
|
15097 | 0 | if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) |
15098 | 0 | return ExprError(); |
15099 | | |
15100 | 0 | if (CheckFunctionCall(Method, TheCall, |
15101 | 0 | Method->getType()->castAs<FunctionProtoType>())) |
15102 | 0 | return ExprError(); |
15103 | | |
15104 | 0 | return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), |
15105 | 0 | FnDecl); |
15106 | 0 | } else { |
15107 | | // We matched a built-in operator. Convert the arguments, then |
15108 | | // break out so that we will build the appropriate built-in |
15109 | | // operator node. |
15110 | 0 | ExprResult ArgsRes0 = PerformImplicitConversion( |
15111 | 0 | Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], |
15112 | 0 | AA_Passing, CCK_ForBuiltinOverloadedOp); |
15113 | 0 | if (ArgsRes0.isInvalid()) |
15114 | 0 | return ExprError(); |
15115 | 0 | Args[0] = ArgsRes0.get(); |
15116 | |
|
15117 | 0 | ExprResult ArgsRes1 = PerformImplicitConversion( |
15118 | 0 | Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], |
15119 | 0 | AA_Passing, CCK_ForBuiltinOverloadedOp); |
15120 | 0 | if (ArgsRes1.isInvalid()) |
15121 | 0 | return ExprError(); |
15122 | 0 | Args[1] = ArgsRes1.get(); |
15123 | |
|
15124 | 0 | break; |
15125 | 0 | } |
15126 | 0 | } |
15127 | | |
15128 | 0 | case OR_No_Viable_Function: { |
15129 | 0 | PartialDiagnostic PD = |
15130 | 0 | CandidateSet.empty() |
15131 | 0 | ? (PDiag(diag::err_ovl_no_oper) |
15132 | 0 | << Args[0]->getType() << /*subscript*/ 0 |
15133 | 0 | << Args[0]->getSourceRange() << Range) |
15134 | 0 | : (PDiag(diag::err_ovl_no_viable_subscript) |
15135 | 0 | << Args[0]->getType() << Args[0]->getSourceRange() << Range); |
15136 | 0 | CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, |
15137 | 0 | OCD_AllCandidates, ArgExpr, "[]", LLoc); |
15138 | 0 | return ExprError(); |
15139 | 0 | } |
15140 | | |
15141 | 0 | case OR_Ambiguous: |
15142 | 0 | if (Args.size() == 2) { |
15143 | 0 | CandidateSet.NoteCandidates( |
15144 | 0 | PartialDiagnosticAt( |
15145 | 0 | LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) |
15146 | 0 | << "[]" << Args[0]->getType() << Args[1]->getType() |
15147 | 0 | << Args[0]->getSourceRange() << Range), |
15148 | 0 | *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); |
15149 | 0 | } else { |
15150 | 0 | CandidateSet.NoteCandidates( |
15151 | 0 | PartialDiagnosticAt(LLoc, |
15152 | 0 | PDiag(diag::err_ovl_ambiguous_subscript_call) |
15153 | 0 | << Args[0]->getType() |
15154 | 0 | << Args[0]->getSourceRange() << Range), |
15155 | 0 | *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); |
15156 | 0 | } |
15157 | 0 | return ExprError(); |
15158 | | |
15159 | 0 | case OR_Deleted: |
15160 | 0 | CandidateSet.NoteCandidates( |
15161 | 0 | PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) |
15162 | 0 | << "[]" << Args[0]->getSourceRange() |
15163 | 0 | << Range), |
15164 | 0 | *this, OCD_AllCandidates, Args, "[]", LLoc); |
15165 | 0 | return ExprError(); |
15166 | 0 | } |
15167 | | |
15168 | | // We matched a built-in operator; build it. |
15169 | 0 | return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); |
15170 | 0 | } |
15171 | | |
15172 | | /// BuildCallToMemberFunction - Build a call to a member |
15173 | | /// function. MemExpr is the expression that refers to the member |
15174 | | /// function (and includes the object parameter), Args/NumArgs are the |
15175 | | /// arguments to the function call (not including the object |
15176 | | /// parameter). The caller needs to validate that the member |
15177 | | /// expression refers to a non-static member function or an overloaded |
15178 | | /// member function. |
15179 | | ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, |
15180 | | SourceLocation LParenLoc, |
15181 | | MultiExprArg Args, |
15182 | | SourceLocation RParenLoc, |
15183 | | Expr *ExecConfig, bool IsExecConfig, |
15184 | 0 | bool AllowRecovery) { |
15185 | 0 | assert(MemExprE->getType() == Context.BoundMemberTy || |
15186 | 0 | MemExprE->getType() == Context.OverloadTy); |
15187 | | |
15188 | | // Dig out the member expression. This holds both the object |
15189 | | // argument and the member function we're referring to. |
15190 | 0 | Expr *NakedMemExpr = MemExprE->IgnoreParens(); |
15191 | | |
15192 | | // Determine whether this is a call to a pointer-to-member function. |
15193 | 0 | if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { |
15194 | 0 | assert(op->getType() == Context.BoundMemberTy); |
15195 | 0 | assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); |
15196 | | |
15197 | 0 | QualType fnType = |
15198 | 0 | op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); |
15199 | |
|
15200 | 0 | const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); |
15201 | 0 | QualType resultType = proto->getCallResultType(Context); |
15202 | 0 | ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); |
15203 | | |
15204 | | // Check that the object type isn't more qualified than the |
15205 | | // member function we're calling. |
15206 | 0 | Qualifiers funcQuals = proto->getMethodQuals(); |
15207 | |
|
15208 | 0 | QualType objectType = op->getLHS()->getType(); |
15209 | 0 | if (op->getOpcode() == BO_PtrMemI) |
15210 | 0 | objectType = objectType->castAs<PointerType>()->getPointeeType(); |
15211 | 0 | Qualifiers objectQuals = objectType.getQualifiers(); |
15212 | |
|
15213 | 0 | Qualifiers difference = objectQuals - funcQuals; |
15214 | 0 | difference.removeObjCGCAttr(); |
15215 | 0 | difference.removeAddressSpace(); |
15216 | 0 | if (difference) { |
15217 | 0 | std::string qualsString = difference.getAsString(); |
15218 | 0 | Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) |
15219 | 0 | << fnType.getUnqualifiedType() |
15220 | 0 | << qualsString |
15221 | 0 | << (qualsString.find(' ') == std::string::npos ? 1 : 2); |
15222 | 0 | } |
15223 | |
|
15224 | 0 | CXXMemberCallExpr *call = CXXMemberCallExpr::Create( |
15225 | 0 | Context, MemExprE, Args, resultType, valueKind, RParenLoc, |
15226 | 0 | CurFPFeatureOverrides(), proto->getNumParams()); |
15227 | |
|
15228 | 0 | if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), |
15229 | 0 | call, nullptr)) |
15230 | 0 | return ExprError(); |
15231 | | |
15232 | 0 | if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) |
15233 | 0 | return ExprError(); |
15234 | | |
15235 | 0 | if (CheckOtherCall(call, proto)) |
15236 | 0 | return ExprError(); |
15237 | | |
15238 | 0 | return MaybeBindToTemporary(call); |
15239 | 0 | } |
15240 | | |
15241 | | // We only try to build a recovery expr at this level if we can preserve |
15242 | | // the return type, otherwise we return ExprError() and let the caller |
15243 | | // recover. |
15244 | 0 | auto BuildRecoveryExpr = [&](QualType Type) { |
15245 | 0 | if (!AllowRecovery) |
15246 | 0 | return ExprError(); |
15247 | 0 | std::vector<Expr *> SubExprs = {MemExprE}; |
15248 | 0 | llvm::append_range(SubExprs, Args); |
15249 | 0 | return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs, |
15250 | 0 | Type); |
15251 | 0 | }; |
15252 | 0 | if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) |
15253 | 0 | return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue, |
15254 | 0 | RParenLoc, CurFPFeatureOverrides()); |
15255 | | |
15256 | 0 | UnbridgedCastsSet UnbridgedCasts; |
15257 | 0 | if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) |
15258 | 0 | return ExprError(); |
15259 | | |
15260 | 0 | MemberExpr *MemExpr; |
15261 | 0 | CXXMethodDecl *Method = nullptr; |
15262 | 0 | bool HadMultipleCandidates = false; |
15263 | 0 | DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); |
15264 | 0 | NestedNameSpecifier *Qualifier = nullptr; |
15265 | 0 | if (isa<MemberExpr>(NakedMemExpr)) { |
15266 | 0 | MemExpr = cast<MemberExpr>(NakedMemExpr); |
15267 | 0 | Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); |
15268 | 0 | FoundDecl = MemExpr->getFoundDecl(); |
15269 | 0 | Qualifier = MemExpr->getQualifier(); |
15270 | 0 | UnbridgedCasts.restore(); |
15271 | 0 | } else { |
15272 | 0 | UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); |
15273 | 0 | Qualifier = UnresExpr->getQualifier(); |
15274 | |
|
15275 | 0 | QualType ObjectType = UnresExpr->getBaseType(); |
15276 | 0 | Expr::Classification ObjectClassification |
15277 | 0 | = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() |
15278 | 0 | : UnresExpr->getBase()->Classify(Context); |
15279 | | |
15280 | | // Add overload candidates |
15281 | 0 | OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), |
15282 | 0 | OverloadCandidateSet::CSK_Normal); |
15283 | | |
15284 | | // FIXME: avoid copy. |
15285 | 0 | TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; |
15286 | 0 | if (UnresExpr->hasExplicitTemplateArgs()) { |
15287 | 0 | UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); |
15288 | 0 | TemplateArgs = &TemplateArgsBuffer; |
15289 | 0 | } |
15290 | |
|
15291 | 0 | for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), |
15292 | 0 | E = UnresExpr->decls_end(); I != E; ++I) { |
15293 | |
|
15294 | 0 | QualType ExplicitObjectType = ObjectType; |
15295 | |
|
15296 | 0 | NamedDecl *Func = *I; |
15297 | 0 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); |
15298 | 0 | if (isa<UsingShadowDecl>(Func)) |
15299 | 0 | Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); |
15300 | |
|
15301 | 0 | bool HasExplicitParameter = false; |
15302 | 0 | if (const auto *M = dyn_cast<FunctionDecl>(Func); |
15303 | 0 | M && M->hasCXXExplicitFunctionObjectParameter()) |
15304 | 0 | HasExplicitParameter = true; |
15305 | 0 | else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func); |
15306 | 0 | M && |
15307 | 0 | M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter()) |
15308 | 0 | HasExplicitParameter = true; |
15309 | |
|
15310 | 0 | if (HasExplicitParameter) |
15311 | 0 | ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr); |
15312 | | |
15313 | | // Microsoft supports direct constructor calls. |
15314 | 0 | if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { |
15315 | 0 | AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, |
15316 | 0 | CandidateSet, |
15317 | 0 | /*SuppressUserConversions*/ false); |
15318 | 0 | } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { |
15319 | | // If explicit template arguments were provided, we can't call a |
15320 | | // non-template member function. |
15321 | 0 | if (TemplateArgs) |
15322 | 0 | continue; |
15323 | | |
15324 | 0 | AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType, |
15325 | 0 | ObjectClassification, Args, CandidateSet, |
15326 | 0 | /*SuppressUserConversions=*/false); |
15327 | 0 | } else { |
15328 | 0 | AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), |
15329 | 0 | I.getPair(), ActingDC, TemplateArgs, |
15330 | 0 | ExplicitObjectType, ObjectClassification, |
15331 | 0 | Args, CandidateSet, |
15332 | 0 | /*SuppressUserConversions=*/false); |
15333 | 0 | } |
15334 | 0 | } |
15335 | |
|
15336 | 0 | HadMultipleCandidates = (CandidateSet.size() > 1); |
15337 | |
|
15338 | 0 | DeclarationName DeclName = UnresExpr->getMemberName(); |
15339 | |
|
15340 | 0 | UnbridgedCasts.restore(); |
15341 | |
|
15342 | 0 | OverloadCandidateSet::iterator Best; |
15343 | 0 | bool Succeeded = false; |
15344 | 0 | switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), |
15345 | 0 | Best)) { |
15346 | 0 | case OR_Success: |
15347 | 0 | Method = cast<CXXMethodDecl>(Best->Function); |
15348 | 0 | FoundDecl = Best->FoundDecl; |
15349 | 0 | CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); |
15350 | 0 | if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc())) |
15351 | 0 | break; |
15352 | | // If FoundDecl is different from Method (such as if one is a template |
15353 | | // and the other a specialization), make sure DiagnoseUseOfDecl is |
15354 | | // called on both. |
15355 | | // FIXME: This would be more comprehensively addressed by modifying |
15356 | | // DiagnoseUseOfDecl to accept both the FoundDecl and the decl |
15357 | | // being used. |
15358 | 0 | if (Method != FoundDecl.getDecl() && |
15359 | 0 | DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc())) |
15360 | 0 | break; |
15361 | 0 | Succeeded = true; |
15362 | 0 | break; |
15363 | | |
15364 | 0 | case OR_No_Viable_Function: |
15365 | 0 | CandidateSet.NoteCandidates( |
15366 | 0 | PartialDiagnosticAt( |
15367 | 0 | UnresExpr->getMemberLoc(), |
15368 | 0 | PDiag(diag::err_ovl_no_viable_member_function_in_call) |
15369 | 0 | << DeclName << MemExprE->getSourceRange()), |
15370 | 0 | *this, OCD_AllCandidates, Args); |
15371 | 0 | break; |
15372 | 0 | case OR_Ambiguous: |
15373 | 0 | CandidateSet.NoteCandidates( |
15374 | 0 | PartialDiagnosticAt(UnresExpr->getMemberLoc(), |
15375 | 0 | PDiag(diag::err_ovl_ambiguous_member_call) |
15376 | 0 | << DeclName << MemExprE->getSourceRange()), |
15377 | 0 | *this, OCD_AmbiguousCandidates, Args); |
15378 | 0 | break; |
15379 | 0 | case OR_Deleted: |
15380 | 0 | CandidateSet.NoteCandidates( |
15381 | 0 | PartialDiagnosticAt(UnresExpr->getMemberLoc(), |
15382 | 0 | PDiag(diag::err_ovl_deleted_member_call) |
15383 | 0 | << DeclName << MemExprE->getSourceRange()), |
15384 | 0 | *this, OCD_AllCandidates, Args); |
15385 | 0 | break; |
15386 | 0 | } |
15387 | | // Overload resolution fails, try to recover. |
15388 | 0 | if (!Succeeded) |
15389 | 0 | return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best)); |
15390 | | |
15391 | 0 | ExprResult Res = |
15392 | 0 | FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); |
15393 | 0 | if (Res.isInvalid()) |
15394 | 0 | return ExprError(); |
15395 | 0 | MemExprE = Res.get(); |
15396 | | |
15397 | | // If overload resolution picked a static member |
15398 | | // build a non-member call based on that function. |
15399 | 0 | if (Method->isStatic()) { |
15400 | 0 | return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc, |
15401 | 0 | ExecConfig, IsExecConfig); |
15402 | 0 | } |
15403 | | |
15404 | 0 | MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); |
15405 | 0 | } |
15406 | | |
15407 | 0 | QualType ResultType = Method->getReturnType(); |
15408 | 0 | ExprValueKind VK = Expr::getValueKindForType(ResultType); |
15409 | 0 | ResultType = ResultType.getNonLValueExprType(Context); |
15410 | |
|
15411 | 0 | assert(Method && "Member call to something that isn't a method?"); |
15412 | 0 | const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); |
15413 | |
|
15414 | 0 | CallExpr *TheCall = nullptr; |
15415 | 0 | llvm::SmallVector<Expr *, 8> NewArgs; |
15416 | 0 | if (Method->isExplicitObjectMemberFunction()) { |
15417 | 0 | PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args, |
15418 | 0 | NewArgs); |
15419 | | // Build the actual expression node. |
15420 | 0 | ExprResult FnExpr = |
15421 | 0 | CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr, |
15422 | 0 | HadMultipleCandidates, MemExpr->getExprLoc()); |
15423 | 0 | if (FnExpr.isInvalid()) |
15424 | 0 | return ExprError(); |
15425 | | |
15426 | 0 | TheCall = |
15427 | 0 | CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc, |
15428 | 0 | CurFPFeatureOverrides(), Proto->getNumParams()); |
15429 | 0 | } else { |
15430 | | // Convert the object argument (for a non-static member function call). |
15431 | | // We only need to do this if there was actually an overload; otherwise |
15432 | | // it was done at lookup. |
15433 | 0 | ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization( |
15434 | 0 | MemExpr->getBase(), Qualifier, FoundDecl, Method); |
15435 | 0 | if (ObjectArg.isInvalid()) |
15436 | 0 | return ExprError(); |
15437 | 0 | MemExpr->setBase(ObjectArg.get()); |
15438 | 0 | TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK, |
15439 | 0 | RParenLoc, CurFPFeatureOverrides(), |
15440 | 0 | Proto->getNumParams()); |
15441 | 0 | } |
15442 | | |
15443 | | // Check for a valid return type. |
15444 | 0 | if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), |
15445 | 0 | TheCall, Method)) |
15446 | 0 | return BuildRecoveryExpr(ResultType); |
15447 | | |
15448 | | // Convert the rest of the arguments |
15449 | 0 | if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, |
15450 | 0 | RParenLoc)) |
15451 | 0 | return BuildRecoveryExpr(ResultType); |
15452 | | |
15453 | 0 | DiagnoseSentinelCalls(Method, LParenLoc, Args); |
15454 | |
|
15455 | 0 | if (CheckFunctionCall(Method, TheCall, Proto)) |
15456 | 0 | return ExprError(); |
15457 | | |
15458 | | // In the case the method to call was not selected by the overloading |
15459 | | // resolution process, we still need to handle the enable_if attribute. Do |
15460 | | // that here, so it will not hide previous -- and more relevant -- errors. |
15461 | 0 | if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { |
15462 | 0 | if (const EnableIfAttr *Attr = |
15463 | 0 | CheckEnableIf(Method, LParenLoc, Args, true)) { |
15464 | 0 | Diag(MemE->getMemberLoc(), |
15465 | 0 | diag::err_ovl_no_viable_member_function_in_call) |
15466 | 0 | << Method << Method->getSourceRange(); |
15467 | 0 | Diag(Method->getLocation(), |
15468 | 0 | diag::note_ovl_candidate_disabled_by_function_cond_attr) |
15469 | 0 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); |
15470 | 0 | return ExprError(); |
15471 | 0 | } |
15472 | 0 | } |
15473 | | |
15474 | 0 | if (isa<CXXConstructorDecl, CXXDestructorDecl>(CurContext) && |
15475 | 0 | TheCall->getDirectCallee()->isPure()) { |
15476 | 0 | const FunctionDecl *MD = TheCall->getDirectCallee(); |
15477 | |
|
15478 | 0 | if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && |
15479 | 0 | MemExpr->performsVirtualDispatch(getLangOpts())) { |
15480 | 0 | Diag(MemExpr->getBeginLoc(), |
15481 | 0 | diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) |
15482 | 0 | << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) |
15483 | 0 | << MD->getParent(); |
15484 | |
|
15485 | 0 | Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); |
15486 | 0 | if (getLangOpts().AppleKext) |
15487 | 0 | Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) |
15488 | 0 | << MD->getParent() << MD->getDeclName(); |
15489 | 0 | } |
15490 | 0 | } |
15491 | |
|
15492 | 0 | if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) { |
15493 | | // a->A::f() doesn't go through the vtable, except in AppleKext mode. |
15494 | 0 | bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; |
15495 | 0 | CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, |
15496 | 0 | CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, |
15497 | 0 | MemExpr->getMemberLoc()); |
15498 | 0 | } |
15499 | |
|
15500 | 0 | return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), |
15501 | 0 | TheCall->getDirectCallee()); |
15502 | 0 | } |
15503 | | |
15504 | | /// BuildCallToObjectOfClassType - Build a call to an object of class |
15505 | | /// type (C++ [over.call.object]), which can end up invoking an |
15506 | | /// overloaded function call operator (@c operator()) or performing a |
15507 | | /// user-defined conversion on the object argument. |
15508 | | ExprResult |
15509 | | Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, |
15510 | | SourceLocation LParenLoc, |
15511 | | MultiExprArg Args, |
15512 | 0 | SourceLocation RParenLoc) { |
15513 | 0 | if (checkPlaceholderForOverload(*this, Obj)) |
15514 | 0 | return ExprError(); |
15515 | 0 | ExprResult Object = Obj; |
15516 | |
|
15517 | 0 | UnbridgedCastsSet UnbridgedCasts; |
15518 | 0 | if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) |
15519 | 0 | return ExprError(); |
15520 | | |
15521 | 0 | assert(Object.get()->getType()->isRecordType() && |
15522 | 0 | "Requires object type argument"); |
15523 | | |
15524 | | // C++ [over.call.object]p1: |
15525 | | // If the primary-expression E in the function call syntax |
15526 | | // evaluates to a class object of type "cv T", then the set of |
15527 | | // candidate functions includes at least the function call |
15528 | | // operators of T. The function call operators of T are obtained by |
15529 | | // ordinary lookup of the name operator() in the context of |
15530 | | // (E).operator(). |
15531 | 0 | OverloadCandidateSet CandidateSet(LParenLoc, |
15532 | 0 | OverloadCandidateSet::CSK_Operator); |
15533 | 0 | DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); |
15534 | |
|
15535 | 0 | if (RequireCompleteType(LParenLoc, Object.get()->getType(), |
15536 | 0 | diag::err_incomplete_object_call, Object.get())) |
15537 | 0 | return true; |
15538 | | |
15539 | 0 | const auto *Record = Object.get()->getType()->castAs<RecordType>(); |
15540 | 0 | LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); |
15541 | 0 | LookupQualifiedName(R, Record->getDecl()); |
15542 | 0 | R.suppressAccessDiagnostics(); |
15543 | |
|
15544 | 0 | for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); |
15545 | 0 | Oper != OperEnd; ++Oper) { |
15546 | 0 | AddMethodCandidate(Oper.getPair(), Object.get()->getType(), |
15547 | 0 | Object.get()->Classify(Context), Args, CandidateSet, |
15548 | 0 | /*SuppressUserConversion=*/false); |
15549 | 0 | } |
15550 | | |
15551 | | // When calling a lambda, both the call operator, and |
15552 | | // the conversion operator to function pointer |
15553 | | // are considered. But when constraint checking |
15554 | | // on the call operator fails, it will also fail on the |
15555 | | // conversion operator as the constraints are always the same. |
15556 | | // As the user probably does not intend to perform a surrogate call, |
15557 | | // we filter them out to produce better error diagnostics, ie to avoid |
15558 | | // showing 2 failed overloads instead of one. |
15559 | 0 | bool IgnoreSurrogateFunctions = false; |
15560 | 0 | if (CandidateSet.size() == 1 && Record->getAsCXXRecordDecl()->isLambda()) { |
15561 | 0 | const OverloadCandidate &Candidate = *CandidateSet.begin(); |
15562 | 0 | if (!Candidate.Viable && |
15563 | 0 | Candidate.FailureKind == ovl_fail_constraints_not_satisfied) |
15564 | 0 | IgnoreSurrogateFunctions = true; |
15565 | 0 | } |
15566 | | |
15567 | | // C++ [over.call.object]p2: |
15568 | | // In addition, for each (non-explicit in C++0x) conversion function |
15569 | | // declared in T of the form |
15570 | | // |
15571 | | // operator conversion-type-id () cv-qualifier; |
15572 | | // |
15573 | | // where cv-qualifier is the same cv-qualification as, or a |
15574 | | // greater cv-qualification than, cv, and where conversion-type-id |
15575 | | // denotes the type "pointer to function of (P1,...,Pn) returning |
15576 | | // R", or the type "reference to pointer to function of |
15577 | | // (P1,...,Pn) returning R", or the type "reference to function |
15578 | | // of (P1,...,Pn) returning R", a surrogate call function [...] |
15579 | | // is also considered as a candidate function. Similarly, |
15580 | | // surrogate call functions are added to the set of candidate |
15581 | | // functions for each conversion function declared in an |
15582 | | // accessible base class provided the function is not hidden |
15583 | | // within T by another intervening declaration. |
15584 | 0 | const auto &Conversions = |
15585 | 0 | cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); |
15586 | 0 | for (auto I = Conversions.begin(), E = Conversions.end(); |
15587 | 0 | !IgnoreSurrogateFunctions && I != E; ++I) { |
15588 | 0 | NamedDecl *D = *I; |
15589 | 0 | CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); |
15590 | 0 | if (isa<UsingShadowDecl>(D)) |
15591 | 0 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); |
15592 | | |
15593 | | // Skip over templated conversion functions; they aren't |
15594 | | // surrogates. |
15595 | 0 | if (isa<FunctionTemplateDecl>(D)) |
15596 | 0 | continue; |
15597 | | |
15598 | 0 | CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); |
15599 | 0 | if (!Conv->isExplicit()) { |
15600 | | // Strip the reference type (if any) and then the pointer type (if |
15601 | | // any) to get down to what might be a function type. |
15602 | 0 | QualType ConvType = Conv->getConversionType().getNonReferenceType(); |
15603 | 0 | if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) |
15604 | 0 | ConvType = ConvPtrType->getPointeeType(); |
15605 | |
|
15606 | 0 | if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) |
15607 | 0 | { |
15608 | 0 | AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, |
15609 | 0 | Object.get(), Args, CandidateSet); |
15610 | 0 | } |
15611 | 0 | } |
15612 | 0 | } |
15613 | |
|
15614 | 0 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
15615 | | |
15616 | | // Perform overload resolution. |
15617 | 0 | OverloadCandidateSet::iterator Best; |
15618 | 0 | switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), |
15619 | 0 | Best)) { |
15620 | 0 | case OR_Success: |
15621 | | // Overload resolution succeeded; we'll build the appropriate call |
15622 | | // below. |
15623 | 0 | break; |
15624 | | |
15625 | 0 | case OR_No_Viable_Function: { |
15626 | 0 | PartialDiagnostic PD = |
15627 | 0 | CandidateSet.empty() |
15628 | 0 | ? (PDiag(diag::err_ovl_no_oper) |
15629 | 0 | << Object.get()->getType() << /*call*/ 1 |
15630 | 0 | << Object.get()->getSourceRange()) |
15631 | 0 | : (PDiag(diag::err_ovl_no_viable_object_call) |
15632 | 0 | << Object.get()->getType() << Object.get()->getSourceRange()); |
15633 | 0 | CandidateSet.NoteCandidates( |
15634 | 0 | PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, |
15635 | 0 | OCD_AllCandidates, Args); |
15636 | 0 | break; |
15637 | 0 | } |
15638 | 0 | case OR_Ambiguous: |
15639 | 0 | if (!R.isAmbiguous()) |
15640 | 0 | CandidateSet.NoteCandidates( |
15641 | 0 | PartialDiagnosticAt(Object.get()->getBeginLoc(), |
15642 | 0 | PDiag(diag::err_ovl_ambiguous_object_call) |
15643 | 0 | << Object.get()->getType() |
15644 | 0 | << Object.get()->getSourceRange()), |
15645 | 0 | *this, OCD_AmbiguousCandidates, Args); |
15646 | 0 | break; |
15647 | | |
15648 | 0 | case OR_Deleted: |
15649 | 0 | CandidateSet.NoteCandidates( |
15650 | 0 | PartialDiagnosticAt(Object.get()->getBeginLoc(), |
15651 | 0 | PDiag(diag::err_ovl_deleted_object_call) |
15652 | 0 | << Object.get()->getType() |
15653 | 0 | << Object.get()->getSourceRange()), |
15654 | 0 | *this, OCD_AllCandidates, Args); |
15655 | 0 | break; |
15656 | 0 | } |
15657 | | |
15658 | 0 | if (Best == CandidateSet.end()) |
15659 | 0 | return true; |
15660 | | |
15661 | 0 | UnbridgedCasts.restore(); |
15662 | |
|
15663 | 0 | if (Best->Function == nullptr) { |
15664 | | // Since there is no function declaration, this is one of the |
15665 | | // surrogate candidates. Dig out the conversion function. |
15666 | 0 | CXXConversionDecl *Conv |
15667 | 0 | = cast<CXXConversionDecl>( |
15668 | 0 | Best->Conversions[0].UserDefined.ConversionFunction); |
15669 | |
|
15670 | 0 | CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, |
15671 | 0 | Best->FoundDecl); |
15672 | 0 | if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) |
15673 | 0 | return ExprError(); |
15674 | 0 | assert(Conv == Best->FoundDecl.getDecl() && |
15675 | 0 | "Found Decl & conversion-to-functionptr should be same, right?!"); |
15676 | | // We selected one of the surrogate functions that converts the |
15677 | | // object parameter to a function pointer. Perform the conversion |
15678 | | // on the object argument, then let BuildCallExpr finish the job. |
15679 | | |
15680 | | // Create an implicit member expr to refer to the conversion operator. |
15681 | | // and then call it. |
15682 | 0 | ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, |
15683 | 0 | Conv, HadMultipleCandidates); |
15684 | 0 | if (Call.isInvalid()) |
15685 | 0 | return ExprError(); |
15686 | | // Record usage of conversion in an implicit cast. |
15687 | 0 | Call = ImplicitCastExpr::Create( |
15688 | 0 | Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(), |
15689 | 0 | nullptr, VK_PRValue, CurFPFeatureOverrides()); |
15690 | |
|
15691 | 0 | return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); |
15692 | 0 | } |
15693 | | |
15694 | 0 | CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); |
15695 | | |
15696 | | // We found an overloaded operator(). Build a CXXOperatorCallExpr |
15697 | | // that calls this method, using Object for the implicit object |
15698 | | // parameter and passing along the remaining arguments. |
15699 | 0 | CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); |
15700 | | |
15701 | | // An error diagnostic has already been printed when parsing the declaration. |
15702 | 0 | if (Method->isInvalidDecl()) |
15703 | 0 | return ExprError(); |
15704 | | |
15705 | 0 | const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); |
15706 | 0 | unsigned NumParams = Proto->getNumParams(); |
15707 | |
|
15708 | 0 | DeclarationNameInfo OpLocInfo( |
15709 | 0 | Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); |
15710 | 0 | OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); |
15711 | 0 | ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, |
15712 | 0 | Obj, HadMultipleCandidates, |
15713 | 0 | OpLocInfo.getLoc(), |
15714 | 0 | OpLocInfo.getInfo()); |
15715 | 0 | if (NewFn.isInvalid()) |
15716 | 0 | return true; |
15717 | | |
15718 | 0 | SmallVector<Expr *, 8> MethodArgs; |
15719 | 0 | MethodArgs.reserve(NumParams + 1); |
15720 | |
|
15721 | 0 | bool IsError = false; |
15722 | | |
15723 | | // Initialize the implicit object parameter if needed. |
15724 | | // Since C++23, this could also be a call to a static call operator |
15725 | | // which we emit as a regular CallExpr. |
15726 | 0 | llvm::SmallVector<Expr *, 8> NewArgs; |
15727 | 0 | if (Method->isExplicitObjectMemberFunction()) { |
15728 | | // FIXME: we should do that during the definition of the lambda when we can. |
15729 | 0 | DiagnoseInvalidExplicitObjectParameterInLambda(Method); |
15730 | 0 | PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs); |
15731 | 0 | } else if (Method->isInstance()) { |
15732 | 0 | ExprResult ObjRes = PerformImplicitObjectArgumentInitialization( |
15733 | 0 | Object.get(), /*Qualifier=*/nullptr, Best->FoundDecl, Method); |
15734 | 0 | if (ObjRes.isInvalid()) |
15735 | 0 | IsError = true; |
15736 | 0 | else |
15737 | 0 | Object = ObjRes; |
15738 | 0 | MethodArgs.push_back(Object.get()); |
15739 | 0 | } |
15740 | |
|
15741 | 0 | IsError |= PrepareArgumentsForCallToObjectOfClassType( |
15742 | 0 | *this, MethodArgs, Method, Args, LParenLoc); |
15743 | | |
15744 | | // If this is a variadic call, handle args passed through "...". |
15745 | 0 | if (Proto->isVariadic()) { |
15746 | | // Promote the arguments (C99 6.5.2.2p7). |
15747 | 0 | for (unsigned i = NumParams, e = Args.size(); i < e; i++) { |
15748 | 0 | ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, |
15749 | 0 | nullptr); |
15750 | 0 | IsError |= Arg.isInvalid(); |
15751 | 0 | MethodArgs.push_back(Arg.get()); |
15752 | 0 | } |
15753 | 0 | } |
15754 | |
|
15755 | 0 | if (IsError) |
15756 | 0 | return true; |
15757 | | |
15758 | 0 | DiagnoseSentinelCalls(Method, LParenLoc, Args); |
15759 | | |
15760 | | // Once we've built TheCall, all of the expressions are properly owned. |
15761 | 0 | QualType ResultTy = Method->getReturnType(); |
15762 | 0 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); |
15763 | 0 | ResultTy = ResultTy.getNonLValueExprType(Context); |
15764 | |
|
15765 | 0 | CallExpr *TheCall; |
15766 | 0 | if (Method->isInstance()) |
15767 | 0 | TheCall = CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), |
15768 | 0 | MethodArgs, ResultTy, VK, RParenLoc, |
15769 | 0 | CurFPFeatureOverrides()); |
15770 | 0 | else |
15771 | 0 | TheCall = CallExpr::Create(Context, NewFn.get(), MethodArgs, ResultTy, VK, |
15772 | 0 | RParenLoc, CurFPFeatureOverrides()); |
15773 | |
|
15774 | 0 | if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) |
15775 | 0 | return true; |
15776 | | |
15777 | 0 | if (CheckFunctionCall(Method, TheCall, Proto)) |
15778 | 0 | return true; |
15779 | | |
15780 | 0 | return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); |
15781 | 0 | } |
15782 | | |
15783 | | /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> |
15784 | | /// (if one exists), where @c Base is an expression of class type and |
15785 | | /// @c Member is the name of the member we're trying to find. |
15786 | | ExprResult |
15787 | | Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, |
15788 | 0 | bool *NoArrowOperatorFound) { |
15789 | 0 | assert(Base->getType()->isRecordType() && |
15790 | 0 | "left-hand side must have class type"); |
15791 | | |
15792 | 0 | if (checkPlaceholderForOverload(*this, Base)) |
15793 | 0 | return ExprError(); |
15794 | | |
15795 | 0 | SourceLocation Loc = Base->getExprLoc(); |
15796 | | |
15797 | | // C++ [over.ref]p1: |
15798 | | // |
15799 | | // [...] An expression x->m is interpreted as (x.operator->())->m |
15800 | | // for a class object x of type T if T::operator->() exists and if |
15801 | | // the operator is selected as the best match function by the |
15802 | | // overload resolution mechanism (13.3). |
15803 | 0 | DeclarationName OpName = |
15804 | 0 | Context.DeclarationNames.getCXXOperatorName(OO_Arrow); |
15805 | 0 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); |
15806 | |
|
15807 | 0 | if (RequireCompleteType(Loc, Base->getType(), |
15808 | 0 | diag::err_typecheck_incomplete_tag, Base)) |
15809 | 0 | return ExprError(); |
15810 | | |
15811 | 0 | LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); |
15812 | 0 | LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl()); |
15813 | 0 | R.suppressAccessDiagnostics(); |
15814 | |
|
15815 | 0 | for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); |
15816 | 0 | Oper != OperEnd; ++Oper) { |
15817 | 0 | AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), |
15818 | 0 | std::nullopt, CandidateSet, |
15819 | 0 | /*SuppressUserConversion=*/false); |
15820 | 0 | } |
15821 | |
|
15822 | 0 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
15823 | | |
15824 | | // Perform overload resolution. |
15825 | 0 | OverloadCandidateSet::iterator Best; |
15826 | 0 | switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { |
15827 | 0 | case OR_Success: |
15828 | | // Overload resolution succeeded; we'll build the call below. |
15829 | 0 | break; |
15830 | | |
15831 | 0 | case OR_No_Viable_Function: { |
15832 | 0 | auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); |
15833 | 0 | if (CandidateSet.empty()) { |
15834 | 0 | QualType BaseType = Base->getType(); |
15835 | 0 | if (NoArrowOperatorFound) { |
15836 | | // Report this specific error to the caller instead of emitting a |
15837 | | // diagnostic, as requested. |
15838 | 0 | *NoArrowOperatorFound = true; |
15839 | 0 | return ExprError(); |
15840 | 0 | } |
15841 | 0 | Diag(OpLoc, diag::err_typecheck_member_reference_arrow) |
15842 | 0 | << BaseType << Base->getSourceRange(); |
15843 | 0 | if (BaseType->isRecordType() && !BaseType->isPointerType()) { |
15844 | 0 | Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) |
15845 | 0 | << FixItHint::CreateReplacement(OpLoc, "."); |
15846 | 0 | } |
15847 | 0 | } else |
15848 | 0 | Diag(OpLoc, diag::err_ovl_no_viable_oper) |
15849 | 0 | << "operator->" << Base->getSourceRange(); |
15850 | 0 | CandidateSet.NoteCandidates(*this, Base, Cands); |
15851 | 0 | return ExprError(); |
15852 | 0 | } |
15853 | 0 | case OR_Ambiguous: |
15854 | 0 | if (!R.isAmbiguous()) |
15855 | 0 | CandidateSet.NoteCandidates( |
15856 | 0 | PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) |
15857 | 0 | << "->" << Base->getType() |
15858 | 0 | << Base->getSourceRange()), |
15859 | 0 | *this, OCD_AmbiguousCandidates, Base); |
15860 | 0 | return ExprError(); |
15861 | | |
15862 | 0 | case OR_Deleted: |
15863 | 0 | CandidateSet.NoteCandidates( |
15864 | 0 | PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) |
15865 | 0 | << "->" << Base->getSourceRange()), |
15866 | 0 | *this, OCD_AllCandidates, Base); |
15867 | 0 | return ExprError(); |
15868 | 0 | } |
15869 | | |
15870 | 0 | CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); |
15871 | | |
15872 | | // Convert the object parameter. |
15873 | 0 | CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); |
15874 | |
|
15875 | 0 | if (Method->isExplicitObjectMemberFunction()) { |
15876 | 0 | ExprResult R = InitializeExplicitObjectArgument(*this, Base, Method); |
15877 | 0 | if (R.isInvalid()) |
15878 | 0 | return ExprError(); |
15879 | 0 | Base = R.get(); |
15880 | 0 | } else { |
15881 | 0 | ExprResult BaseResult = PerformImplicitObjectArgumentInitialization( |
15882 | 0 | Base, /*Qualifier=*/nullptr, Best->FoundDecl, Method); |
15883 | 0 | if (BaseResult.isInvalid()) |
15884 | 0 | return ExprError(); |
15885 | 0 | Base = BaseResult.get(); |
15886 | 0 | } |
15887 | | |
15888 | | // Build the operator call. |
15889 | 0 | ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, |
15890 | 0 | Base, HadMultipleCandidates, OpLoc); |
15891 | 0 | if (FnExpr.isInvalid()) |
15892 | 0 | return ExprError(); |
15893 | | |
15894 | 0 | QualType ResultTy = Method->getReturnType(); |
15895 | 0 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); |
15896 | 0 | ResultTy = ResultTy.getNonLValueExprType(Context); |
15897 | |
|
15898 | 0 | CallExpr *TheCall = |
15899 | 0 | CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base, |
15900 | 0 | ResultTy, VK, OpLoc, CurFPFeatureOverrides()); |
15901 | |
|
15902 | 0 | if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) |
15903 | 0 | return ExprError(); |
15904 | | |
15905 | 0 | if (CheckFunctionCall(Method, TheCall, |
15906 | 0 | Method->getType()->castAs<FunctionProtoType>())) |
15907 | 0 | return ExprError(); |
15908 | | |
15909 | 0 | return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); |
15910 | 0 | } |
15911 | | |
15912 | | /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to |
15913 | | /// a literal operator described by the provided lookup results. |
15914 | | ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, |
15915 | | DeclarationNameInfo &SuffixInfo, |
15916 | | ArrayRef<Expr*> Args, |
15917 | | SourceLocation LitEndLoc, |
15918 | 0 | TemplateArgumentListInfo *TemplateArgs) { |
15919 | 0 | SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); |
15920 | |
|
15921 | 0 | OverloadCandidateSet CandidateSet(UDSuffixLoc, |
15922 | 0 | OverloadCandidateSet::CSK_Normal); |
15923 | 0 | AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, |
15924 | 0 | TemplateArgs); |
15925 | |
|
15926 | 0 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
15927 | | |
15928 | | // Perform overload resolution. This will usually be trivial, but might need |
15929 | | // to perform substitutions for a literal operator template. |
15930 | 0 | OverloadCandidateSet::iterator Best; |
15931 | 0 | switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { |
15932 | 0 | case OR_Success: |
15933 | 0 | case OR_Deleted: |
15934 | 0 | break; |
15935 | | |
15936 | 0 | case OR_No_Viable_Function: |
15937 | 0 | CandidateSet.NoteCandidates( |
15938 | 0 | PartialDiagnosticAt(UDSuffixLoc, |
15939 | 0 | PDiag(diag::err_ovl_no_viable_function_in_call) |
15940 | 0 | << R.getLookupName()), |
15941 | 0 | *this, OCD_AllCandidates, Args); |
15942 | 0 | return ExprError(); |
15943 | | |
15944 | 0 | case OR_Ambiguous: |
15945 | 0 | CandidateSet.NoteCandidates( |
15946 | 0 | PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) |
15947 | 0 | << R.getLookupName()), |
15948 | 0 | *this, OCD_AmbiguousCandidates, Args); |
15949 | 0 | return ExprError(); |
15950 | 0 | } |
15951 | | |
15952 | 0 | FunctionDecl *FD = Best->Function; |
15953 | 0 | ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, |
15954 | 0 | nullptr, HadMultipleCandidates, |
15955 | 0 | SuffixInfo.getLoc(), |
15956 | 0 | SuffixInfo.getInfo()); |
15957 | 0 | if (Fn.isInvalid()) |
15958 | 0 | return true; |
15959 | | |
15960 | | // Check the argument types. This should almost always be a no-op, except |
15961 | | // that array-to-pointer decay is applied to string literals. |
15962 | 0 | Expr *ConvArgs[2]; |
15963 | 0 | for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { |
15964 | 0 | ExprResult InputInit = PerformCopyInitialization( |
15965 | 0 | InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), |
15966 | 0 | SourceLocation(), Args[ArgIdx]); |
15967 | 0 | if (InputInit.isInvalid()) |
15968 | 0 | return true; |
15969 | 0 | ConvArgs[ArgIdx] = InputInit.get(); |
15970 | 0 | } |
15971 | | |
15972 | 0 | QualType ResultTy = FD->getReturnType(); |
15973 | 0 | ExprValueKind VK = Expr::getValueKindForType(ResultTy); |
15974 | 0 | ResultTy = ResultTy.getNonLValueExprType(Context); |
15975 | |
|
15976 | 0 | UserDefinedLiteral *UDL = UserDefinedLiteral::Create( |
15977 | 0 | Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK, |
15978 | 0 | LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides()); |
15979 | |
|
15980 | 0 | if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) |
15981 | 0 | return ExprError(); |
15982 | | |
15983 | 0 | if (CheckFunctionCall(FD, UDL, nullptr)) |
15984 | 0 | return ExprError(); |
15985 | | |
15986 | 0 | return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD); |
15987 | 0 | } |
15988 | | |
15989 | | /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the |
15990 | | /// given LookupResult is non-empty, it is assumed to describe a member which |
15991 | | /// will be invoked. Otherwise, the function will be found via argument |
15992 | | /// dependent lookup. |
15993 | | /// CallExpr is set to a valid expression and FRS_Success returned on success, |
15994 | | /// otherwise CallExpr is set to ExprError() and some non-success value |
15995 | | /// is returned. |
15996 | | Sema::ForRangeStatus |
15997 | | Sema::BuildForRangeBeginEndCall(SourceLocation Loc, |
15998 | | SourceLocation RangeLoc, |
15999 | | const DeclarationNameInfo &NameInfo, |
16000 | | LookupResult &MemberLookup, |
16001 | | OverloadCandidateSet *CandidateSet, |
16002 | 0 | Expr *Range, ExprResult *CallExpr) { |
16003 | 0 | Scope *S = nullptr; |
16004 | |
|
16005 | 0 | CandidateSet->clear(OverloadCandidateSet::CSK_Normal); |
16006 | 0 | if (!MemberLookup.empty()) { |
16007 | 0 | ExprResult MemberRef = |
16008 | 0 | BuildMemberReferenceExpr(Range, Range->getType(), Loc, |
16009 | 0 | /*IsPtr=*/false, CXXScopeSpec(), |
16010 | 0 | /*TemplateKWLoc=*/SourceLocation(), |
16011 | 0 | /*FirstQualifierInScope=*/nullptr, |
16012 | 0 | MemberLookup, |
16013 | 0 | /*TemplateArgs=*/nullptr, S); |
16014 | 0 | if (MemberRef.isInvalid()) { |
16015 | 0 | *CallExpr = ExprError(); |
16016 | 0 | return FRS_DiagnosticIssued; |
16017 | 0 | } |
16018 | 0 | *CallExpr = |
16019 | 0 | BuildCallExpr(S, MemberRef.get(), Loc, std::nullopt, Loc, nullptr); |
16020 | 0 | if (CallExpr->isInvalid()) { |
16021 | 0 | *CallExpr = ExprError(); |
16022 | 0 | return FRS_DiagnosticIssued; |
16023 | 0 | } |
16024 | 0 | } else { |
16025 | 0 | ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr, |
16026 | 0 | NestedNameSpecifierLoc(), |
16027 | 0 | NameInfo, UnresolvedSet<0>()); |
16028 | 0 | if (FnR.isInvalid()) |
16029 | 0 | return FRS_DiagnosticIssued; |
16030 | 0 | UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get()); |
16031 | |
|
16032 | 0 | bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, |
16033 | 0 | CandidateSet, CallExpr); |
16034 | 0 | if (CandidateSet->empty() || CandidateSetError) { |
16035 | 0 | *CallExpr = ExprError(); |
16036 | 0 | return FRS_NoViableFunction; |
16037 | 0 | } |
16038 | 0 | OverloadCandidateSet::iterator Best; |
16039 | 0 | OverloadingResult OverloadResult = |
16040 | 0 | CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); |
16041 | |
|
16042 | 0 | if (OverloadResult == OR_No_Viable_Function) { |
16043 | 0 | *CallExpr = ExprError(); |
16044 | 0 | return FRS_NoViableFunction; |
16045 | 0 | } |
16046 | 0 | *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, |
16047 | 0 | Loc, nullptr, CandidateSet, &Best, |
16048 | 0 | OverloadResult, |
16049 | 0 | /*AllowTypoCorrection=*/false); |
16050 | 0 | if (CallExpr->isInvalid() || OverloadResult != OR_Success) { |
16051 | 0 | *CallExpr = ExprError(); |
16052 | 0 | return FRS_DiagnosticIssued; |
16053 | 0 | } |
16054 | 0 | } |
16055 | 0 | return FRS_Success; |
16056 | 0 | } |
16057 | | |
16058 | | |
16059 | | /// FixOverloadedFunctionReference - E is an expression that refers to |
16060 | | /// a C++ overloaded function (possibly with some parentheses and |
16061 | | /// perhaps a '&' around it). We have resolved the overloaded function |
16062 | | /// to the function declaration Fn, so patch up the expression E to |
16063 | | /// refer (possibly indirectly) to Fn. Returns the new expr. |
16064 | | ExprResult Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, |
16065 | 0 | FunctionDecl *Fn) { |
16066 | 0 | if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { |
16067 | 0 | ExprResult SubExpr = |
16068 | 0 | FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn); |
16069 | 0 | if (SubExpr.isInvalid()) |
16070 | 0 | return ExprError(); |
16071 | 0 | if (SubExpr.get() == PE->getSubExpr()) |
16072 | 0 | return PE; |
16073 | | |
16074 | 0 | return new (Context) |
16075 | 0 | ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get()); |
16076 | 0 | } |
16077 | | |
16078 | 0 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { |
16079 | 0 | ExprResult SubExpr = |
16080 | 0 | FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn); |
16081 | 0 | if (SubExpr.isInvalid()) |
16082 | 0 | return ExprError(); |
16083 | 0 | assert(Context.hasSameType(ICE->getSubExpr()->getType(), |
16084 | 0 | SubExpr.get()->getType()) && |
16085 | 0 | "Implicit cast type cannot be determined from overload"); |
16086 | 0 | assert(ICE->path_empty() && "fixing up hierarchy conversion?"); |
16087 | 0 | if (SubExpr.get() == ICE->getSubExpr()) |
16088 | 0 | return ICE; |
16089 | | |
16090 | 0 | return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(), |
16091 | 0 | SubExpr.get(), nullptr, ICE->getValueKind(), |
16092 | 0 | CurFPFeatureOverrides()); |
16093 | 0 | } |
16094 | | |
16095 | 0 | if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { |
16096 | 0 | if (!GSE->isResultDependent()) { |
16097 | 0 | ExprResult SubExpr = |
16098 | 0 | FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); |
16099 | 0 | if (SubExpr.isInvalid()) |
16100 | 0 | return ExprError(); |
16101 | 0 | if (SubExpr.get() == GSE->getResultExpr()) |
16102 | 0 | return GSE; |
16103 | | |
16104 | | // Replace the resulting type information before rebuilding the generic |
16105 | | // selection expression. |
16106 | 0 | ArrayRef<Expr *> A = GSE->getAssocExprs(); |
16107 | 0 | SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); |
16108 | 0 | unsigned ResultIdx = GSE->getResultIndex(); |
16109 | 0 | AssocExprs[ResultIdx] = SubExpr.get(); |
16110 | |
|
16111 | 0 | if (GSE->isExprPredicate()) |
16112 | 0 | return GenericSelectionExpr::Create( |
16113 | 0 | Context, GSE->getGenericLoc(), GSE->getControllingExpr(), |
16114 | 0 | GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), |
16115 | 0 | GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), |
16116 | 0 | ResultIdx); |
16117 | 0 | return GenericSelectionExpr::Create( |
16118 | 0 | Context, GSE->getGenericLoc(), GSE->getControllingType(), |
16119 | 0 | GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), |
16120 | 0 | GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), |
16121 | 0 | ResultIdx); |
16122 | 0 | } |
16123 | | // Rather than fall through to the unreachable, return the original generic |
16124 | | // selection expression. |
16125 | 0 | return GSE; |
16126 | 0 | } |
16127 | | |
16128 | 0 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { |
16129 | 0 | assert(UnOp->getOpcode() == UO_AddrOf && |
16130 | 0 | "Can only take the address of an overloaded function"); |
16131 | 0 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { |
16132 | 0 | if (Method->isStatic()) { |
16133 | | // Do nothing: static member functions aren't any different |
16134 | | // from non-member functions. |
16135 | 0 | } else { |
16136 | | // Fix the subexpression, which really has to be an |
16137 | | // UnresolvedLookupExpr holding an overloaded member function |
16138 | | // or template. |
16139 | 0 | ExprResult SubExpr = |
16140 | 0 | FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn); |
16141 | 0 | if (SubExpr.isInvalid()) |
16142 | 0 | return ExprError(); |
16143 | 0 | if (SubExpr.get() == UnOp->getSubExpr()) |
16144 | 0 | return UnOp; |
16145 | | |
16146 | 0 | if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(), |
16147 | 0 | SubExpr.get(), Method)) |
16148 | 0 | return ExprError(); |
16149 | | |
16150 | 0 | assert(isa<DeclRefExpr>(SubExpr.get()) && |
16151 | 0 | "fixed to something other than a decl ref"); |
16152 | 0 | assert(cast<DeclRefExpr>(SubExpr.get())->getQualifier() && |
16153 | 0 | "fixed to a member ref with no nested name qualifier"); |
16154 | | |
16155 | | // We have taken the address of a pointer to member |
16156 | | // function. Perform the computation here so that we get the |
16157 | | // appropriate pointer to member type. |
16158 | 0 | QualType ClassType |
16159 | 0 | = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); |
16160 | 0 | QualType MemPtrType |
16161 | 0 | = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); |
16162 | | // Under the MS ABI, lock down the inheritance model now. |
16163 | 0 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) |
16164 | 0 | (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); |
16165 | |
|
16166 | 0 | return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf, |
16167 | 0 | MemPtrType, VK_PRValue, OK_Ordinary, |
16168 | 0 | UnOp->getOperatorLoc(), false, |
16169 | 0 | CurFPFeatureOverrides()); |
16170 | 0 | } |
16171 | 0 | } |
16172 | 0 | ExprResult SubExpr = |
16173 | 0 | FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn); |
16174 | 0 | if (SubExpr.isInvalid()) |
16175 | 0 | return ExprError(); |
16176 | 0 | if (SubExpr.get() == UnOp->getSubExpr()) |
16177 | 0 | return UnOp; |
16178 | | |
16179 | 0 | return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf, |
16180 | 0 | SubExpr.get()); |
16181 | 0 | } |
16182 | | |
16183 | 0 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { |
16184 | | // FIXME: avoid copy. |
16185 | 0 | TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; |
16186 | 0 | if (ULE->hasExplicitTemplateArgs()) { |
16187 | 0 | ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); |
16188 | 0 | TemplateArgs = &TemplateArgsBuffer; |
16189 | 0 | } |
16190 | |
|
16191 | 0 | QualType Type = Fn->getType(); |
16192 | 0 | ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue; |
16193 | | |
16194 | | // FIXME: Duplicated from BuildDeclarationNameExpr. |
16195 | 0 | if (unsigned BID = Fn->getBuiltinID()) { |
16196 | 0 | if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) { |
16197 | 0 | Type = Context.BuiltinFnTy; |
16198 | 0 | ValueKind = VK_PRValue; |
16199 | 0 | } |
16200 | 0 | } |
16201 | |
|
16202 | 0 | DeclRefExpr *DRE = BuildDeclRefExpr( |
16203 | 0 | Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(), |
16204 | 0 | Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs); |
16205 | 0 | DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); |
16206 | 0 | return DRE; |
16207 | 0 | } |
16208 | | |
16209 | 0 | if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { |
16210 | | // FIXME: avoid copy. |
16211 | 0 | TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; |
16212 | 0 | if (MemExpr->hasExplicitTemplateArgs()) { |
16213 | 0 | MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); |
16214 | 0 | TemplateArgs = &TemplateArgsBuffer; |
16215 | 0 | } |
16216 | |
|
16217 | 0 | Expr *Base; |
16218 | | |
16219 | | // If we're filling in a static method where we used to have an |
16220 | | // implicit member access, rewrite to a simple decl ref. |
16221 | 0 | if (MemExpr->isImplicitAccess()) { |
16222 | 0 | if (cast<CXXMethodDecl>(Fn)->isStatic()) { |
16223 | 0 | DeclRefExpr *DRE = BuildDeclRefExpr( |
16224 | 0 | Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), |
16225 | 0 | MemExpr->getQualifierLoc(), Found.getDecl(), |
16226 | 0 | MemExpr->getTemplateKeywordLoc(), TemplateArgs); |
16227 | 0 | DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); |
16228 | 0 | return DRE; |
16229 | 0 | } else { |
16230 | 0 | SourceLocation Loc = MemExpr->getMemberLoc(); |
16231 | 0 | if (MemExpr->getQualifier()) |
16232 | 0 | Loc = MemExpr->getQualifierLoc().getBeginLoc(); |
16233 | 0 | Base = |
16234 | 0 | BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); |
16235 | 0 | } |
16236 | 0 | } else |
16237 | 0 | Base = MemExpr->getBase(); |
16238 | | |
16239 | 0 | ExprValueKind valueKind; |
16240 | 0 | QualType type; |
16241 | 0 | if (cast<CXXMethodDecl>(Fn)->isStatic()) { |
16242 | 0 | valueKind = VK_LValue; |
16243 | 0 | type = Fn->getType(); |
16244 | 0 | } else { |
16245 | 0 | valueKind = VK_PRValue; |
16246 | 0 | type = Context.BoundMemberTy; |
16247 | 0 | } |
16248 | |
|
16249 | 0 | return BuildMemberExpr( |
16250 | 0 | Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), |
16251 | 0 | MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, |
16252 | 0 | /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), |
16253 | 0 | type, valueKind, OK_Ordinary, TemplateArgs); |
16254 | 0 | } |
16255 | | |
16256 | 0 | llvm_unreachable("Invalid reference to overloaded function"); |
16257 | 0 | } |
16258 | | |
16259 | | ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, |
16260 | | DeclAccessPair Found, |
16261 | 0 | FunctionDecl *Fn) { |
16262 | 0 | return FixOverloadedFunctionReference(E.get(), Found, Fn); |
16263 | 0 | } |
16264 | | |
16265 | | bool clang::shouldEnforceArgLimit(bool PartialOverloading, |
16266 | 0 | FunctionDecl *Function) { |
16267 | 0 | if (!PartialOverloading || !Function) |
16268 | 0 | return true; |
16269 | 0 | if (Function->isVariadic()) |
16270 | 0 | return false; |
16271 | 0 | if (const auto *Proto = |
16272 | 0 | dyn_cast<FunctionProtoType>(Function->getFunctionType())) |
16273 | 0 | if (Proto->isTemplateVariadic()) |
16274 | 0 | return false; |
16275 | 0 | if (auto *Pattern = Function->getTemplateInstantiationPattern()) |
16276 | 0 | if (const auto *Proto = |
16277 | 0 | dyn_cast<FunctionProtoType>(Pattern->getFunctionType())) |
16278 | 0 | if (Proto->isTemplateVariadic()) |
16279 | 0 | return false; |
16280 | 0 | return true; |
16281 | 0 | } |