1//===- Overload.h - C++ Overloading -----------------------------*- C++ -*-===//
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 defines the data structures and types used in C++
10// overload resolution.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_OVERLOAD_H
15#define LLVM_CLANG_SEMA_OVERLOAD_H
16
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclAccessPair.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/Type.h"
24#include "clang/Basic/LLVM.h"
25#include "clang/Basic/SourceLocation.h"
26#include "clang/Sema/SemaFixItUtils.h"
27#include "clang/Sema/TemplateDeduction.h"
28#include "llvm/ADT/ArrayRef.h"
29#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/ADT/SmallVector.h"
32#include "llvm/ADT/StringRef.h"
33#include "llvm/Support/AlignOf.h"
34#include "llvm/Support/Allocator.h"
35#include "llvm/Support/Casting.h"
36#include "llvm/Support/ErrorHandling.h"
37#include <cassert>
38#include <cstddef>
39#include <cstdint>
40#include <utility>
41
42namespace clang {
43
44class APValue;
45class ASTContext;
46class Sema;
47
48 /// OverloadingResult - Capture the result of performing overload
49 /// resolution.
50 enum OverloadingResult {
51 /// Overload resolution succeeded.
52 OR_Success,
53
54 /// No viable function found.
55 OR_No_Viable_Function,
56
57 /// Ambiguous candidates found.
58 OR_Ambiguous,
59
60 /// Succeeded, but refers to a deleted function.
61 OR_Deleted
62 };
63
64 enum OverloadCandidateDisplayKind {
65 /// Requests that all candidates be shown. Viable candidates will
66 /// be printed first.
67 OCD_AllCandidates,
68
69 /// Requests that only viable candidates be shown.
70 OCD_ViableCandidates,
71
72 /// Requests that only tied-for-best candidates be shown.
73 OCD_AmbiguousCandidates
74 };
75
76 /// The parameter ordering that will be used for the candidate. This is
77 /// used to represent C++20 binary operator rewrites that reverse the order
78 /// of the arguments. If the parameter ordering is Reversed, the Args list is
79 /// reversed (but obviously the ParamDecls for the function are not).
80 ///
81 /// After forming an OverloadCandidate with reversed parameters, the list
82 /// of conversions will (as always) be indexed by argument, so will be
83 /// in reverse parameter order.
84 enum class OverloadCandidateParamOrder : char { Normal, Reversed };
85
86 /// The kinds of rewrite we perform on overload candidates. Note that the
87 /// values here are chosen to serve as both bitflags and as a rank (lower
88 /// values are preferred by overload resolution).
89 enum OverloadCandidateRewriteKind : unsigned {
90 /// Candidate is not a rewritten candidate.
91 CRK_None = 0x0,
92
93 /// Candidate is a rewritten candidate with a different operator name.
94 CRK_DifferentOperator = 0x1,
95
96 /// Candidate is a rewritten candidate with a reversed order of parameters.
97 CRK_Reversed = 0x2,
98 };
99
100 /// ImplicitConversionKind - The kind of implicit conversion used to
101 /// convert an argument to a parameter's type. The enumerator values
102 /// match with the table titled 'Conversions' in [over.ics.scs] and are listed
103 /// such that better conversion kinds have smaller values.
104 enum ImplicitConversionKind {
105 /// Identity conversion (no conversion)
106 ICK_Identity = 0,
107
108 /// Lvalue-to-rvalue conversion (C++ [conv.lval])
109 ICK_Lvalue_To_Rvalue,
110
111 /// Array-to-pointer conversion (C++ [conv.array])
112 ICK_Array_To_Pointer,
113
114 /// Function-to-pointer (C++ [conv.array])
115 ICK_Function_To_Pointer,
116
117 /// Function pointer conversion (C++17 [conv.fctptr])
118 ICK_Function_Conversion,
119
120 /// Qualification conversions (C++ [conv.qual])
121 ICK_Qualification,
122
123 /// Integral promotions (C++ [conv.prom])
124 ICK_Integral_Promotion,
125
126 /// Floating point promotions (C++ [conv.fpprom])
127 ICK_Floating_Promotion,
128
129 /// Complex promotions (Clang extension)
130 ICK_Complex_Promotion,
131
132 /// Integral conversions (C++ [conv.integral])
133 ICK_Integral_Conversion,
134
135 /// Floating point conversions (C++ [conv.double]
136 ICK_Floating_Conversion,
137
138 /// Complex conversions (C99 6.3.1.6)
139 ICK_Complex_Conversion,
140
141 /// Floating-integral conversions (C++ [conv.fpint])
142 ICK_Floating_Integral,
143
144 /// Pointer conversions (C++ [conv.ptr])
145 ICK_Pointer_Conversion,
146
147 /// Pointer-to-member conversions (C++ [conv.mem])
148 ICK_Pointer_Member,
149
150 /// Boolean conversions (C++ [conv.bool])
151 ICK_Boolean_Conversion,
152
153 /// Conversions between compatible types in C99
154 ICK_Compatible_Conversion,
155
156 /// Derived-to-base (C++ [over.best.ics])
157 ICK_Derived_To_Base,
158
159 /// Vector conversions
160 ICK_Vector_Conversion,
161
162 /// Arm SVE Vector conversions
163 ICK_SVE_Vector_Conversion,
164
165 /// RISC-V RVV Vector conversions
166 ICK_RVV_Vector_Conversion,
167
168 /// A vector splat from an arithmetic type
169 ICK_Vector_Splat,
170
171 /// Complex-real conversions (C99 6.3.1.7)
172 ICK_Complex_Real,
173
174 /// Block Pointer conversions
175 ICK_Block_Pointer_Conversion,
176
177 /// Transparent Union Conversions
178 ICK_TransparentUnionConversion,
179
180 /// Objective-C ARC writeback conversion
181 ICK_Writeback_Conversion,
182
183 /// Zero constant to event (OpenCL1.2 6.12.10)
184 ICK_Zero_Event_Conversion,
185
186 /// Zero constant to queue
187 ICK_Zero_Queue_Conversion,
188
189 /// Conversions allowed in C, but not C++
190 ICK_C_Only_Conversion,
191
192 /// C-only conversion between pointers with incompatible types
193 ICK_Incompatible_Pointer_Conversion,
194
195 /// Fixed point type conversions according to N1169.
196 ICK_Fixed_Point_Conversion,
197
198 /// The number of conversion kinds
199 ICK_Num_Conversion_Kinds,
200 };
201
202 /// ImplicitConversionRank - The rank of an implicit conversion
203 /// kind. The enumerator values match with Table 9 of (C++
204 /// 13.3.3.1.1) and are listed such that better conversion ranks
205 /// have smaller values.
206 enum ImplicitConversionRank {
207 /// Exact Match
208 ICR_Exact_Match = 0,
209
210 /// Promotion
211 ICR_Promotion,
212
213 /// Conversion
214 ICR_Conversion,
215
216 /// OpenCL Scalar Widening
217 ICR_OCL_Scalar_Widening,
218
219 /// Complex <-> Real conversion
220 ICR_Complex_Real_Conversion,
221
222 /// ObjC ARC writeback conversion
223 ICR_Writeback_Conversion,
224
225 /// Conversion only allowed in the C standard (e.g. void* to char*).
226 ICR_C_Conversion,
227
228 /// Conversion not allowed by the C standard, but that we accept as an
229 /// extension anyway.
230 ICR_C_Conversion_Extension
231 };
232
233 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind);
234
235 /// NarrowingKind - The kind of narrowing conversion being performed by a
236 /// standard conversion sequence according to C++11 [dcl.init.list]p7.
237 enum NarrowingKind {
238 /// Not a narrowing conversion.
239 NK_Not_Narrowing,
240
241 /// A narrowing conversion by virtue of the source and destination types.
242 NK_Type_Narrowing,
243
244 /// A narrowing conversion, because a constant expression got narrowed.
245 NK_Constant_Narrowing,
246
247 /// A narrowing conversion, because a non-constant-expression variable might
248 /// have got narrowed.
249 NK_Variable_Narrowing,
250
251 /// Cannot tell whether this is a narrowing conversion because the
252 /// expression is value-dependent.
253 NK_Dependent_Narrowing,
254 };
255
256 /// StandardConversionSequence - represents a standard conversion
257 /// sequence (C++ 13.3.3.1.1). A standard conversion sequence
258 /// contains between zero and three conversions. If a particular
259 /// conversion is not needed, it will be set to the identity conversion
260 /// (ICK_Identity).
261 class StandardConversionSequence {
262 public:
263 /// First -- The first conversion can be an lvalue-to-rvalue
264 /// conversion, array-to-pointer conversion, or
265 /// function-to-pointer conversion.
266 ImplicitConversionKind First : 8;
267
268 /// Second - The second conversion can be an integral promotion,
269 /// floating point promotion, integral conversion, floating point
270 /// conversion, floating-integral conversion, pointer conversion,
271 /// pointer-to-member conversion, or boolean conversion.
272 ImplicitConversionKind Second : 8;
273
274 /// Third - The third conversion can be a qualification conversion
275 /// or a function conversion.
276 ImplicitConversionKind Third : 8;
277
278 /// Whether this is the deprecated conversion of a
279 /// string literal to a pointer to non-const character data
280 /// (C++ 4.2p2).
281 LLVM_PREFERRED_TYPE(bool)
282 unsigned DeprecatedStringLiteralToCharPtr : 1;
283
284 /// Whether the qualification conversion involves a change in the
285 /// Objective-C lifetime (for automatic reference counting).
286 LLVM_PREFERRED_TYPE(bool)
287 unsigned QualificationIncludesObjCLifetime : 1;
288
289 /// IncompatibleObjC - Whether this is an Objective-C conversion
290 /// that we should warn about (if we actually use it).
291 LLVM_PREFERRED_TYPE(bool)
292 unsigned IncompatibleObjC : 1;
293
294 /// ReferenceBinding - True when this is a reference binding
295 /// (C++ [over.ics.ref]).
296 LLVM_PREFERRED_TYPE(bool)
297 unsigned ReferenceBinding : 1;
298
299 /// DirectBinding - True when this is a reference binding that is a
300 /// direct binding (C++ [dcl.init.ref]).
301 LLVM_PREFERRED_TYPE(bool)
302 unsigned DirectBinding : 1;
303
304 /// Whether this is an lvalue reference binding (otherwise, it's
305 /// an rvalue reference binding).
306 LLVM_PREFERRED_TYPE(bool)
307 unsigned IsLvalueReference : 1;
308
309 /// Whether we're binding to a function lvalue.
310 LLVM_PREFERRED_TYPE(bool)
311 unsigned BindsToFunctionLvalue : 1;
312
313 /// Whether we're binding to an rvalue.
314 LLVM_PREFERRED_TYPE(bool)
315 unsigned BindsToRvalue : 1;
316
317 /// Whether this binds an implicit object argument to a
318 /// non-static member function without a ref-qualifier.
319 LLVM_PREFERRED_TYPE(bool)
320 unsigned BindsImplicitObjectArgumentWithoutRefQualifier : 1;
321
322 /// Whether this binds a reference to an object with a different
323 /// Objective-C lifetime qualifier.
324 LLVM_PREFERRED_TYPE(bool)
325 unsigned ObjCLifetimeConversionBinding : 1;
326
327 /// FromType - The type that this conversion is converting
328 /// from. This is an opaque pointer that can be translated into a
329 /// QualType.
330 void *FromTypePtr;
331
332 /// ToType - The types that this conversion is converting to in
333 /// each step. This is an opaque pointer that can be translated
334 /// into a QualType.
335 void *ToTypePtrs[3];
336
337 /// CopyConstructor - The copy constructor that is used to perform
338 /// this conversion, when the conversion is actually just the
339 /// initialization of an object via copy constructor. Such
340 /// conversions are either identity conversions or derived-to-base
341 /// conversions.
342 CXXConstructorDecl *CopyConstructor;
343 DeclAccessPair FoundCopyConstructor;
344
345 void setFromType(QualType T) { FromTypePtr = T.getAsOpaquePtr(); }
346
347 void setToType(unsigned Idx, QualType T) {
348 assert(Idx < 3 && "To type index is out of range");
349 ToTypePtrs[Idx] = T.getAsOpaquePtr();
350 }
351
352 void setAllToTypes(QualType T) {
353 ToTypePtrs[0] = T.getAsOpaquePtr();
354 ToTypePtrs[1] = ToTypePtrs[0];
355 ToTypePtrs[2] = ToTypePtrs[0];
356 }
357
358 QualType getFromType() const {
359 return QualType::getFromOpaquePtr(Ptr: FromTypePtr);
360 }
361
362 QualType getToType(unsigned Idx) const {
363 assert(Idx < 3 && "To type index is out of range");
364 return QualType::getFromOpaquePtr(Ptr: ToTypePtrs[Idx]);
365 }
366
367 void setAsIdentityConversion();
368
369 bool isIdentityConversion() const {
370 return Second == ICK_Identity && Third == ICK_Identity;
371 }
372
373 ImplicitConversionRank getRank() const;
374 NarrowingKind
375 getNarrowingKind(ASTContext &Context, const Expr *Converted,
376 APValue &ConstantValue, QualType &ConstantType,
377 bool IgnoreFloatToIntegralConversion = false) const;
378 bool isPointerConversionToBool() const;
379 bool isPointerConversionToVoidPointer(ASTContext& Context) const;
380 void dump() const;
381 };
382
383 /// UserDefinedConversionSequence - Represents a user-defined
384 /// conversion sequence (C++ 13.3.3.1.2).
385 struct UserDefinedConversionSequence {
386 /// Represents the standard conversion that occurs before
387 /// the actual user-defined conversion.
388 ///
389 /// C++11 13.3.3.1.2p1:
390 /// If the user-defined conversion is specified by a constructor
391 /// (12.3.1), the initial standard conversion sequence converts
392 /// the source type to the type required by the argument of the
393 /// constructor. If the user-defined conversion is specified by
394 /// a conversion function (12.3.2), the initial standard
395 /// conversion sequence converts the source type to the implicit
396 /// object parameter of the conversion function.
397 StandardConversionSequence Before;
398
399 /// EllipsisConversion - When this is true, it means user-defined
400 /// conversion sequence starts with a ... (ellipsis) conversion, instead of
401 /// a standard conversion. In this case, 'Before' field must be ignored.
402 // FIXME. I much rather put this as the first field. But there seems to be
403 // a gcc code gen. bug which causes a crash in a test. Putting it here seems
404 // to work around the crash.
405 bool EllipsisConversion : 1;
406
407 /// HadMultipleCandidates - When this is true, it means that the
408 /// conversion function was resolved from an overloaded set having
409 /// size greater than 1.
410 bool HadMultipleCandidates : 1;
411
412 /// After - Represents the standard conversion that occurs after
413 /// the actual user-defined conversion.
414 StandardConversionSequence After;
415
416 /// ConversionFunction - The function that will perform the
417 /// user-defined conversion. Null if the conversion is an
418 /// aggregate initialization from an initializer list.
419 FunctionDecl* ConversionFunction;
420
421 /// The declaration that we found via name lookup, which might be
422 /// the same as \c ConversionFunction or it might be a using declaration
423 /// that refers to \c ConversionFunction.
424 DeclAccessPair FoundConversionFunction;
425
426 void dump() const;
427 };
428
429 /// Represents an ambiguous user-defined conversion sequence.
430 struct AmbiguousConversionSequence {
431 using ConversionSet =
432 SmallVector<std::pair<NamedDecl *, FunctionDecl *>, 4>;
433
434 void *FromTypePtr;
435 void *ToTypePtr;
436 char Buffer[sizeof(ConversionSet)];
437
438 QualType getFromType() const {
439 return QualType::getFromOpaquePtr(Ptr: FromTypePtr);
440 }
441
442 QualType getToType() const {
443 return QualType::getFromOpaquePtr(Ptr: ToTypePtr);
444 }
445
446 void setFromType(QualType T) { FromTypePtr = T.getAsOpaquePtr(); }
447 void setToType(QualType T) { ToTypePtr = T.getAsOpaquePtr(); }
448
449 ConversionSet &conversions() {
450 return *reinterpret_cast<ConversionSet*>(Buffer);
451 }
452
453 const ConversionSet &conversions() const {
454 return *reinterpret_cast<const ConversionSet*>(Buffer);
455 }
456
457 void addConversion(NamedDecl *Found, FunctionDecl *D) {
458 conversions().push_back(Elt: std::make_pair(x&: Found, y&: D));
459 }
460
461 using iterator = ConversionSet::iterator;
462
463 iterator begin() { return conversions().begin(); }
464 iterator end() { return conversions().end(); }
465
466 using const_iterator = ConversionSet::const_iterator;
467
468 const_iterator begin() const { return conversions().begin(); }
469 const_iterator end() const { return conversions().end(); }
470
471 void construct();
472 void destruct();
473 void copyFrom(const AmbiguousConversionSequence &);
474 };
475
476 /// BadConversionSequence - Records information about an invalid
477 /// conversion sequence.
478 struct BadConversionSequence {
479 enum FailureKind {
480 no_conversion,
481 unrelated_class,
482 bad_qualifiers,
483 lvalue_ref_to_rvalue,
484 rvalue_ref_to_lvalue,
485 too_few_initializers,
486 too_many_initializers,
487 };
488
489 // This can be null, e.g. for implicit object arguments.
490 Expr *FromExpr;
491
492 FailureKind Kind;
493
494 private:
495 // The type we're converting from (an opaque QualType).
496 void *FromTy;
497
498 // The type we're converting to (an opaque QualType).
499 void *ToTy;
500
501 public:
502 void init(FailureKind K, Expr *From, QualType To) {
503 init(K, From: From->getType(), To);
504 FromExpr = From;
505 }
506
507 void init(FailureKind K, QualType From, QualType To) {
508 Kind = K;
509 FromExpr = nullptr;
510 setFromType(From);
511 setToType(To);
512 }
513
514 QualType getFromType() const { return QualType::getFromOpaquePtr(Ptr: FromTy); }
515 QualType getToType() const { return QualType::getFromOpaquePtr(Ptr: ToTy); }
516
517 void setFromExpr(Expr *E) {
518 FromExpr = E;
519 setFromType(E->getType());
520 }
521
522 void setFromType(QualType T) { FromTy = T.getAsOpaquePtr(); }
523 void setToType(QualType T) { ToTy = T.getAsOpaquePtr(); }
524 };
525
526 /// ImplicitConversionSequence - Represents an implicit conversion
527 /// sequence, which may be a standard conversion sequence
528 /// (C++ 13.3.3.1.1), user-defined conversion sequence (C++ 13.3.3.1.2),
529 /// or an ellipsis conversion sequence (C++ 13.3.3.1.3).
530 class ImplicitConversionSequence {
531 public:
532 /// Kind - The kind of implicit conversion sequence. BadConversion
533 /// specifies that there is no conversion from the source type to
534 /// the target type. AmbiguousConversion represents the unique
535 /// ambiguous conversion (C++0x [over.best.ics]p10).
536 /// StaticObjectArgumentConversion represents the conversion rules for
537 /// the synthesized first argument of calls to static member functions
538 /// ([over.best.ics.general]p8).
539 enum Kind {
540 StandardConversion = 0,
541 StaticObjectArgumentConversion,
542 UserDefinedConversion,
543 AmbiguousConversion,
544 EllipsisConversion,
545 BadConversion
546 };
547
548 private:
549 enum {
550 Uninitialized = BadConversion + 1
551 };
552
553 /// ConversionKind - The kind of implicit conversion sequence.
554 LLVM_PREFERRED_TYPE(Kind)
555 unsigned ConversionKind : 31;
556
557 // Whether the initializer list was of an incomplete array.
558 LLVM_PREFERRED_TYPE(bool)
559 unsigned InitializerListOfIncompleteArray : 1;
560
561 /// When initializing an array or std::initializer_list from an
562 /// initializer-list, this is the array or std::initializer_list type being
563 /// initialized. The remainder of the conversion sequence, including ToType,
564 /// describe the worst conversion of an initializer to an element of the
565 /// array or std::initializer_list. (Note, 'worst' is not well defined.)
566 QualType InitializerListContainerType;
567
568 void setKind(Kind K) {
569 destruct();
570 ConversionKind = K;
571 }
572
573 void destruct() {
574 if (ConversionKind == AmbiguousConversion) Ambiguous.destruct();
575 }
576
577 public:
578 union {
579 /// When ConversionKind == StandardConversion, provides the
580 /// details of the standard conversion sequence.
581 StandardConversionSequence Standard;
582
583 /// When ConversionKind == UserDefinedConversion, provides the
584 /// details of the user-defined conversion sequence.
585 UserDefinedConversionSequence UserDefined;
586
587 /// When ConversionKind == AmbiguousConversion, provides the
588 /// details of the ambiguous conversion.
589 AmbiguousConversionSequence Ambiguous;
590
591 /// When ConversionKind == BadConversion, provides the details
592 /// of the bad conversion.
593 BadConversionSequence Bad;
594 };
595
596 ImplicitConversionSequence()
597 : ConversionKind(Uninitialized),
598 InitializerListOfIncompleteArray(false) {
599 Standard.setAsIdentityConversion();
600 }
601
602 ImplicitConversionSequence(const ImplicitConversionSequence &Other)
603 : ConversionKind(Other.ConversionKind),
604 InitializerListOfIncompleteArray(
605 Other.InitializerListOfIncompleteArray),
606 InitializerListContainerType(Other.InitializerListContainerType) {
607 switch (ConversionKind) {
608 case Uninitialized: break;
609 case StandardConversion: Standard = Other.Standard; break;
610 case StaticObjectArgumentConversion:
611 break;
612 case UserDefinedConversion: UserDefined = Other.UserDefined; break;
613 case AmbiguousConversion: Ambiguous.copyFrom(Other.Ambiguous); break;
614 case EllipsisConversion: break;
615 case BadConversion: Bad = Other.Bad; break;
616 }
617 }
618
619 ImplicitConversionSequence &
620 operator=(const ImplicitConversionSequence &Other) {
621 destruct();
622 new (this) ImplicitConversionSequence(Other);
623 return *this;
624 }
625
626 ~ImplicitConversionSequence() {
627 destruct();
628 }
629
630 Kind getKind() const {
631 assert(isInitialized() && "querying uninitialized conversion");
632 return Kind(ConversionKind);
633 }
634
635 /// Return a ranking of the implicit conversion sequence
636 /// kind, where smaller ranks represent better conversion
637 /// sequences.
638 ///
639 /// In particular, this routine gives user-defined conversion
640 /// sequences and ambiguous conversion sequences the same rank,
641 /// per C++ [over.best.ics]p10.
642 unsigned getKindRank() const {
643 switch (getKind()) {
644 case StandardConversion:
645 case StaticObjectArgumentConversion:
646 return 0;
647
648 case UserDefinedConversion:
649 case AmbiguousConversion:
650 return 1;
651
652 case EllipsisConversion:
653 return 2;
654
655 case BadConversion:
656 return 3;
657 }
658
659 llvm_unreachable("Invalid ImplicitConversionSequence::Kind!");
660 }
661
662 bool isBad() const { return getKind() == BadConversion; }
663 bool isStandard() const { return getKind() == StandardConversion; }
664 bool isStaticObjectArgument() const {
665 return getKind() == StaticObjectArgumentConversion;
666 }
667 bool isEllipsis() const { return getKind() == EllipsisConversion; }
668 bool isAmbiguous() const { return getKind() == AmbiguousConversion; }
669 bool isUserDefined() const { return getKind() == UserDefinedConversion; }
670 bool isFailure() const { return isBad() || isAmbiguous(); }
671
672 /// Determines whether this conversion sequence has been
673 /// initialized. Most operations should never need to query
674 /// uninitialized conversions and should assert as above.
675 bool isInitialized() const { return ConversionKind != Uninitialized; }
676
677 /// Sets this sequence as a bad conversion for an explicit argument.
678 void setBad(BadConversionSequence::FailureKind Failure,
679 Expr *FromExpr, QualType ToType) {
680 setKind(BadConversion);
681 Bad.init(K: Failure, From: FromExpr, To: ToType);
682 }
683
684 /// Sets this sequence as a bad conversion for an implicit argument.
685 void setBad(BadConversionSequence::FailureKind Failure,
686 QualType FromType, QualType ToType) {
687 setKind(BadConversion);
688 Bad.init(K: Failure, From: FromType, To: ToType);
689 }
690
691 void setStandard() { setKind(StandardConversion); }
692 void setStaticObjectArgument() { setKind(StaticObjectArgumentConversion); }
693 void setEllipsis() { setKind(EllipsisConversion); }
694 void setUserDefined() { setKind(UserDefinedConversion); }
695
696 void setAmbiguous() {
697 if (ConversionKind == AmbiguousConversion) return;
698 ConversionKind = AmbiguousConversion;
699 Ambiguous.construct();
700 }
701
702 void setAsIdentityConversion(QualType T) {
703 setStandard();
704 Standard.setAsIdentityConversion();
705 Standard.setFromType(T);
706 Standard.setAllToTypes(T);
707 }
708
709 // True iff this is a conversion sequence from an initializer list to an
710 // array or std::initializer.
711 bool hasInitializerListContainerType() const {
712 return !InitializerListContainerType.isNull();
713 }
714 void setInitializerListContainerType(QualType T, bool IA) {
715 InitializerListContainerType = T;
716 InitializerListOfIncompleteArray = IA;
717 }
718 bool isInitializerListOfIncompleteArray() const {
719 return InitializerListOfIncompleteArray;
720 }
721 QualType getInitializerListContainerType() const {
722 assert(hasInitializerListContainerType() &&
723 "not initializer list container");
724 return InitializerListContainerType;
725 }
726
727 /// Form an "implicit" conversion sequence from nullptr_t to bool, for a
728 /// direct-initialization of a bool object from nullptr_t.
729 static ImplicitConversionSequence getNullptrToBool(QualType SourceType,
730 QualType DestType,
731 bool NeedLValToRVal) {
732 ImplicitConversionSequence ICS;
733 ICS.setStandard();
734 ICS.Standard.setAsIdentityConversion();
735 ICS.Standard.setFromType(SourceType);
736 if (NeedLValToRVal)
737 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
738 ICS.Standard.setToType(Idx: 0, T: SourceType);
739 ICS.Standard.Second = ICK_Boolean_Conversion;
740 ICS.Standard.setToType(Idx: 1, T: DestType);
741 ICS.Standard.setToType(Idx: 2, T: DestType);
742 return ICS;
743 }
744
745 // The result of a comparison between implicit conversion
746 // sequences. Use Sema::CompareImplicitConversionSequences to
747 // actually perform the comparison.
748 enum CompareKind {
749 Better = -1,
750 Indistinguishable = 0,
751 Worse = 1
752 };
753
754 void DiagnoseAmbiguousConversion(Sema &S,
755 SourceLocation CaretLoc,
756 const PartialDiagnostic &PDiag) const;
757
758 void dump() const;
759 };
760
761 enum OverloadFailureKind {
762 ovl_fail_too_many_arguments,
763 ovl_fail_too_few_arguments,
764 ovl_fail_bad_conversion,
765 ovl_fail_bad_deduction,
766
767 /// This conversion candidate was not considered because it
768 /// duplicates the work of a trivial or derived-to-base
769 /// conversion.
770 ovl_fail_trivial_conversion,
771
772 /// This conversion candidate was not considered because it is
773 /// an illegal instantiation of a constructor temploid: it is
774 /// callable with one argument, we only have one argument, and
775 /// its first parameter type is exactly the type of the class.
776 ///
777 /// Defining such a constructor directly is illegal, and
778 /// template-argument deduction is supposed to ignore such
779 /// instantiations, but we can still get one with the right
780 /// kind of implicit instantiation.
781 ovl_fail_illegal_constructor,
782
783 /// This conversion candidate is not viable because its result
784 /// type is not implicitly convertible to the desired type.
785 ovl_fail_bad_final_conversion,
786
787 /// This conversion function template specialization candidate is not
788 /// viable because the final conversion was not an exact match.
789 ovl_fail_final_conversion_not_exact,
790
791 /// (CUDA) This candidate was not viable because the callee
792 /// was not accessible from the caller's target (i.e. host->device,
793 /// global->host, device->host).
794 ovl_fail_bad_target,
795
796 /// This candidate function was not viable because an enable_if
797 /// attribute disabled it.
798 ovl_fail_enable_if,
799
800 /// This candidate constructor or conversion function is explicit but
801 /// the context doesn't permit explicit functions.
802 ovl_fail_explicit,
803
804 /// This candidate was not viable because its address could not be taken.
805 ovl_fail_addr_not_available,
806
807 /// This inherited constructor is not viable because it would slice the
808 /// argument.
809 ovl_fail_inhctor_slice,
810
811 /// This candidate was not viable because it is a non-default multiversioned
812 /// function.
813 ovl_non_default_multiversion_function,
814
815 /// This constructor/conversion candidate fail due to an address space
816 /// mismatch between the object being constructed and the overload
817 /// candidate.
818 ovl_fail_object_addrspace_mismatch,
819
820 /// This candidate was not viable because its associated constraints were
821 /// not satisfied.
822 ovl_fail_constraints_not_satisfied,
823
824 /// This candidate was not viable because it has internal linkage and is
825 /// from a different module unit than the use.
826 ovl_fail_module_mismatched,
827 };
828
829 /// A list of implicit conversion sequences for the arguments of an
830 /// OverloadCandidate.
831 using ConversionSequenceList =
832 llvm::MutableArrayRef<ImplicitConversionSequence>;
833
834 /// OverloadCandidate - A single candidate in an overload set (C++ 13.3).
835 struct OverloadCandidate {
836 /// Function - The actual function that this candidate
837 /// represents. When NULL, this is a built-in candidate
838 /// (C++ [over.oper]) or a surrogate for a conversion to a
839 /// function pointer or reference (C++ [over.call.object]).
840 FunctionDecl *Function;
841
842 /// FoundDecl - The original declaration that was looked up /
843 /// invented / otherwise found, together with its access.
844 /// Might be a UsingShadowDecl or a FunctionTemplateDecl.
845 DeclAccessPair FoundDecl;
846
847 /// BuiltinParamTypes - Provides the parameter types of a built-in overload
848 /// candidate. Only valid when Function is NULL.
849 QualType BuiltinParamTypes[3];
850
851 /// Surrogate - The conversion function for which this candidate
852 /// is a surrogate, but only if IsSurrogate is true.
853 CXXConversionDecl *Surrogate;
854
855 /// The conversion sequences used to convert the function arguments
856 /// to the function parameters. Note that these are indexed by argument,
857 /// so may not match the parameter order of Function.
858 ConversionSequenceList Conversions;
859
860 /// The FixIt hints which can be used to fix the Bad candidate.
861 ConversionFixItGenerator Fix;
862
863 /// Viable - True to indicate that this overload candidate is viable.
864 bool Viable : 1;
865
866 /// Whether this candidate is the best viable function, or tied for being
867 /// the best viable function.
868 ///
869 /// For an ambiguous overload resolution, indicates whether this candidate
870 /// was part of the ambiguity kernel: the minimal non-empty set of viable
871 /// candidates such that all elements of the ambiguity kernel are better
872 /// than all viable candidates not in the ambiguity kernel.
873 bool Best : 1;
874
875 /// IsSurrogate - True to indicate that this candidate is a
876 /// surrogate for a conversion to a function pointer or reference
877 /// (C++ [over.call.object]).
878 bool IsSurrogate : 1;
879
880 /// IgnoreObjectArgument - True to indicate that the first
881 /// argument's conversion, which for this function represents the
882 /// implicit object argument, should be ignored. This will be true
883 /// when the candidate is a static member function (where the
884 /// implicit object argument is just a placeholder) or a
885 /// non-static member function when the call doesn't have an
886 /// object argument.
887 bool IgnoreObjectArgument : 1;
888
889 /// True if the candidate was found using ADL.
890 CallExpr::ADLCallKind IsADLCandidate : 1;
891
892 /// Whether this is a rewritten candidate, and if so, of what kind?
893 LLVM_PREFERRED_TYPE(OverloadCandidateRewriteKind)
894 unsigned RewriteKind : 2;
895
896 /// FailureKind - The reason why this candidate is not viable.
897 /// Actually an OverloadFailureKind.
898 unsigned char FailureKind;
899
900 /// The number of call arguments that were explicitly provided,
901 /// to be used while performing partial ordering of function templates.
902 unsigned ExplicitCallArguments;
903
904 union {
905 DeductionFailureInfo DeductionFailure;
906
907 /// FinalConversion - For a conversion function (where Function is
908 /// a CXXConversionDecl), the standard conversion that occurs
909 /// after the call to the overload candidate to convert the result
910 /// of calling the conversion function to the required type.
911 StandardConversionSequence FinalConversion;
912 };
913
914 /// Get RewriteKind value in OverloadCandidateRewriteKind type (This
915 /// function is to workaround the spurious GCC bitfield enum warning)
916 OverloadCandidateRewriteKind getRewriteKind() const {
917 return static_cast<OverloadCandidateRewriteKind>(RewriteKind);
918 }
919
920 bool isReversed() const { return getRewriteKind() & CRK_Reversed; }
921
922 /// hasAmbiguousConversion - Returns whether this overload
923 /// candidate requires an ambiguous conversion or not.
924 bool hasAmbiguousConversion() const {
925 for (auto &C : Conversions) {
926 if (!C.isInitialized()) return false;
927 if (C.isAmbiguous()) return true;
928 }
929 return false;
930 }
931
932 bool TryToFixBadConversion(unsigned Idx, Sema &S) {
933 bool CanFix = Fix.tryToFixConversion(
934 FromExpr: Conversions[Idx].Bad.FromExpr,
935 FromQTy: Conversions[Idx].Bad.getFromType(),
936 ToQTy: Conversions[Idx].Bad.getToType(), S);
937
938 // If at least one conversion fails, the candidate cannot be fixed.
939 if (!CanFix)
940 Fix.clear();
941
942 return CanFix;
943 }
944
945 unsigned getNumParams() const {
946 if (IsSurrogate) {
947 QualType STy = Surrogate->getConversionType();
948 while (STy->isPointerType() || STy->isReferenceType())
949 STy = STy->getPointeeType();
950 return STy->castAs<FunctionProtoType>()->getNumParams();
951 }
952 if (Function)
953 return Function->getNumParams();
954 return ExplicitCallArguments;
955 }
956
957 bool NotValidBecauseConstraintExprHasError() const;
958
959 private:
960 friend class OverloadCandidateSet;
961 OverloadCandidate()
962 : IsSurrogate(false), IsADLCandidate(CallExpr::NotADL), RewriteKind(CRK_None) {}
963 };
964
965 /// OverloadCandidateSet - A set of overload candidates, used in C++
966 /// overload resolution (C++ 13.3).
967 class OverloadCandidateSet {
968 public:
969 enum CandidateSetKind {
970 /// Normal lookup.
971 CSK_Normal,
972
973 /// C++ [over.match.oper]:
974 /// Lookup of operator function candidates in a call using operator
975 /// syntax. Candidates that have no parameters of class type will be
976 /// skipped unless there is a parameter of (reference to) enum type and
977 /// the corresponding argument is of the same enum type.
978 CSK_Operator,
979
980 /// C++ [over.match.copy]:
981 /// Copy-initialization of an object of class type by user-defined
982 /// conversion.
983 CSK_InitByUserDefinedConversion,
984
985 /// C++ [over.match.ctor], [over.match.list]
986 /// Initialization of an object of class type by constructor,
987 /// using either a parenthesized or braced list of arguments.
988 CSK_InitByConstructor,
989 };
990
991 /// Information about operator rewrites to consider when adding operator
992 /// functions to a candidate set.
993 struct OperatorRewriteInfo {
994 OperatorRewriteInfo()
995 : OriginalOperator(OO_None), OpLoc(), AllowRewrittenCandidates(false) {}
996 OperatorRewriteInfo(OverloadedOperatorKind Op, SourceLocation OpLoc,
997 bool AllowRewritten)
998 : OriginalOperator(Op), OpLoc(OpLoc),
999 AllowRewrittenCandidates(AllowRewritten) {}
1000
1001 /// The original operator as written in the source.
1002 OverloadedOperatorKind OriginalOperator;
1003 /// The source location of the operator.
1004 SourceLocation OpLoc;
1005 /// Whether we should include rewritten candidates in the overload set.
1006 bool AllowRewrittenCandidates;
1007
1008 /// Would use of this function result in a rewrite using a different
1009 /// operator?
1010 bool isRewrittenOperator(const FunctionDecl *FD) {
1011 return OriginalOperator &&
1012 FD->getDeclName().getCXXOverloadedOperator() != OriginalOperator;
1013 }
1014
1015 bool isAcceptableCandidate(const FunctionDecl *FD) {
1016 if (!OriginalOperator)
1017 return true;
1018
1019 // For an overloaded operator, we can have candidates with a different
1020 // name in our unqualified lookup set. Make sure we only consider the
1021 // ones we're supposed to.
1022 OverloadedOperatorKind OO =
1023 FD->getDeclName().getCXXOverloadedOperator();
1024 return OO && (OO == OriginalOperator ||
1025 (AllowRewrittenCandidates &&
1026 OO == getRewrittenOverloadedOperator(Kind: OriginalOperator)));
1027 }
1028
1029 /// Determine the kind of rewrite that should be performed for this
1030 /// candidate.
1031 OverloadCandidateRewriteKind
1032 getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO) {
1033 OverloadCandidateRewriteKind CRK = CRK_None;
1034 if (isRewrittenOperator(FD))
1035 CRK = OverloadCandidateRewriteKind(CRK | CRK_DifferentOperator);
1036 if (PO == OverloadCandidateParamOrder::Reversed)
1037 CRK = OverloadCandidateRewriteKind(CRK | CRK_Reversed);
1038 return CRK;
1039 }
1040 /// Determines whether this operator could be implemented by a function
1041 /// with reversed parameter order.
1042 bool isReversible() {
1043 return AllowRewrittenCandidates && OriginalOperator &&
1044 (getRewrittenOverloadedOperator(Kind: OriginalOperator) != OO_None ||
1045 allowsReversed(Op: OriginalOperator));
1046 }
1047
1048 /// Determine whether reversing parameter order is allowed for operator
1049 /// Op.
1050 bool allowsReversed(OverloadedOperatorKind Op);
1051
1052 /// Determine whether we should add a rewritten candidate for \p FD with
1053 /// reversed parameter order.
1054 /// \param OriginalArgs are the original non reversed arguments.
1055 bool shouldAddReversed(Sema &S, ArrayRef<Expr *> OriginalArgs,
1056 FunctionDecl *FD);
1057 };
1058
1059 private:
1060 SmallVector<OverloadCandidate, 16> Candidates;
1061 llvm::SmallPtrSet<uintptr_t, 16> Functions;
1062
1063 // Allocator for ConversionSequenceLists. We store the first few of these
1064 // inline to avoid allocation for small sets.
1065 llvm::BumpPtrAllocator SlabAllocator;
1066
1067 SourceLocation Loc;
1068 CandidateSetKind Kind;
1069 OperatorRewriteInfo RewriteInfo;
1070
1071 constexpr static unsigned NumInlineBytes =
1072 24 * sizeof(ImplicitConversionSequence);
1073 unsigned NumInlineBytesUsed = 0;
1074 alignas(void *) char InlineSpace[NumInlineBytes];
1075
1076 // Address space of the object being constructed.
1077 LangAS DestAS = LangAS::Default;
1078
1079 /// If we have space, allocates from inline storage. Otherwise, allocates
1080 /// from the slab allocator.
1081 /// FIXME: It would probably be nice to have a SmallBumpPtrAllocator
1082 /// instead.
1083 /// FIXME: Now that this only allocates ImplicitConversionSequences, do we
1084 /// want to un-generalize this?
1085 template <typename T>
1086 T *slabAllocate(unsigned N) {
1087 // It's simpler if this doesn't need to consider alignment.
1088 static_assert(alignof(T) == alignof(void *),
1089 "Only works for pointer-aligned types.");
1090 static_assert(std::is_trivial<T>::value ||
1091 std::is_same<ImplicitConversionSequence, T>::value,
1092 "Add destruction logic to OverloadCandidateSet::clear().");
1093
1094 unsigned NBytes = sizeof(T) * N;
1095 if (NBytes > NumInlineBytes - NumInlineBytesUsed)
1096 return SlabAllocator.Allocate<T>(N);
1097 char *FreeSpaceStart = InlineSpace + NumInlineBytesUsed;
1098 assert(uintptr_t(FreeSpaceStart) % alignof(void *) == 0 &&
1099 "Misaligned storage!");
1100
1101 NumInlineBytesUsed += NBytes;
1102 return reinterpret_cast<T *>(FreeSpaceStart);
1103 }
1104
1105 void destroyCandidates();
1106
1107 public:
1108 OverloadCandidateSet(SourceLocation Loc, CandidateSetKind CSK,
1109 OperatorRewriteInfo RewriteInfo = {})
1110 : Loc(Loc), Kind(CSK), RewriteInfo(RewriteInfo) {}
1111 OverloadCandidateSet(const OverloadCandidateSet &) = delete;
1112 OverloadCandidateSet &operator=(const OverloadCandidateSet &) = delete;
1113 ~OverloadCandidateSet() { destroyCandidates(); }
1114
1115 SourceLocation getLocation() const { return Loc; }
1116 CandidateSetKind getKind() const { return Kind; }
1117 OperatorRewriteInfo getRewriteInfo() const { return RewriteInfo; }
1118
1119 /// Whether diagnostics should be deferred.
1120 bool shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args, SourceLocation OpLoc);
1121
1122 /// Determine when this overload candidate will be new to the
1123 /// overload set.
1124 bool isNewCandidate(Decl *F, OverloadCandidateParamOrder PO =
1125 OverloadCandidateParamOrder::Normal) {
1126 uintptr_t Key = reinterpret_cast<uintptr_t>(F->getCanonicalDecl());
1127 Key |= static_cast<uintptr_t>(PO);
1128 return Functions.insert(Ptr: Key).second;
1129 }
1130
1131 /// Exclude a function from being considered by overload resolution.
1132 void exclude(Decl *F) {
1133 isNewCandidate(F, PO: OverloadCandidateParamOrder::Normal);
1134 isNewCandidate(F, PO: OverloadCandidateParamOrder::Reversed);
1135 }
1136
1137 /// Clear out all of the candidates.
1138 void clear(CandidateSetKind CSK);
1139
1140 using iterator = SmallVectorImpl<OverloadCandidate>::iterator;
1141
1142 iterator begin() { return Candidates.begin(); }
1143 iterator end() { return Candidates.end(); }
1144
1145 size_t size() const { return Candidates.size(); }
1146 bool empty() const { return Candidates.empty(); }
1147
1148 /// Allocate storage for conversion sequences for NumConversions
1149 /// conversions.
1150 ConversionSequenceList
1151 allocateConversionSequences(unsigned NumConversions) {
1152 ImplicitConversionSequence *Conversions =
1153 slabAllocate<ImplicitConversionSequence>(N: NumConversions);
1154
1155 // Construct the new objects.
1156 for (unsigned I = 0; I != NumConversions; ++I)
1157 new (&Conversions[I]) ImplicitConversionSequence();
1158
1159 return ConversionSequenceList(Conversions, NumConversions);
1160 }
1161
1162 /// Add a new candidate with NumConversions conversion sequence slots
1163 /// to the overload set.
1164 OverloadCandidate &
1165 addCandidate(unsigned NumConversions = 0,
1166 ConversionSequenceList Conversions = std::nullopt) {
1167 assert((Conversions.empty() || Conversions.size() == NumConversions) &&
1168 "preallocated conversion sequence has wrong length");
1169
1170 Candidates.push_back(Elt: OverloadCandidate());
1171 OverloadCandidate &C = Candidates.back();
1172 C.Conversions = Conversions.empty()
1173 ? allocateConversionSequences(NumConversions)
1174 : Conversions;
1175 return C;
1176 }
1177
1178 /// Find the best viable function on this overload set, if it exists.
1179 OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc,
1180 OverloadCandidateSet::iterator& Best);
1181
1182 SmallVector<OverloadCandidate *, 32> CompleteCandidates(
1183 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
1184 SourceLocation OpLoc = SourceLocation(),
1185 llvm::function_ref<bool(OverloadCandidate &)> Filter =
1186 [](OverloadCandidate &) { return true; });
1187
1188 void NoteCandidates(
1189 PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD,
1190 ArrayRef<Expr *> Args, StringRef Opc = "",
1191 SourceLocation Loc = SourceLocation(),
1192 llvm::function_ref<bool(OverloadCandidate &)> Filter =
1193 [](OverloadCandidate &) { return true; });
1194
1195 void NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
1196 ArrayRef<OverloadCandidate *> Cands,
1197 StringRef Opc = "",
1198 SourceLocation OpLoc = SourceLocation());
1199
1200 LangAS getDestAS() { return DestAS; }
1201
1202 void setDestAS(LangAS AS) {
1203 assert((Kind == CSK_InitByConstructor ||
1204 Kind == CSK_InitByUserDefinedConversion) &&
1205 "can't set the destination address space when not constructing an "
1206 "object");
1207 DestAS = AS;
1208 }
1209
1210 };
1211
1212 bool isBetterOverloadCandidate(Sema &S,
1213 const OverloadCandidate &Cand1,
1214 const OverloadCandidate &Cand2,
1215 SourceLocation Loc,
1216 OverloadCandidateSet::CandidateSetKind Kind);
1217
1218 struct ConstructorInfo {
1219 DeclAccessPair FoundDecl;
1220 CXXConstructorDecl *Constructor;
1221 FunctionTemplateDecl *ConstructorTmpl;
1222
1223 explicit operator bool() const { return Constructor; }
1224 };
1225
1226 // FIXME: Add an AddOverloadCandidate / AddTemplateOverloadCandidate overload
1227 // that takes one of these.
1228 inline ConstructorInfo getConstructorInfo(NamedDecl *ND) {
1229 if (isa<UsingDecl>(Val: ND))
1230 return ConstructorInfo{};
1231
1232 // For constructors, the access check is performed against the underlying
1233 // declaration, not the found declaration.
1234 auto *D = ND->getUnderlyingDecl();
1235 ConstructorInfo Info = {DeclAccessPair::make(D: ND, AS: D->getAccess()), nullptr,
1236 nullptr};
1237 Info.ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
1238 if (Info.ConstructorTmpl)
1239 D = Info.ConstructorTmpl->getTemplatedDecl();
1240 Info.Constructor = dyn_cast<CXXConstructorDecl>(Val: D);
1241 return Info;
1242 }
1243
1244 // Returns false if signature help is relevant despite number of arguments
1245 // exceeding parameters. Specifically, it returns false when
1246 // PartialOverloading is true and one of the following:
1247 // * Function is variadic
1248 // * Function is template variadic
1249 // * Function is an instantiation of template variadic function
1250 // The last case may seem strange. The idea is that if we added one more
1251 // argument, we'd end up with a function similar to Function. Since, in the
1252 // context of signature help and/or code completion, we do not know what the
1253 // type of the next argument (that the user is typing) will be, this is as
1254 // good candidate as we can get, despite the fact that it takes one less
1255 // parameter.
1256 bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function);
1257
1258} // namespace clang
1259
1260#endif // LLVM_CLANG_SEMA_OVERLOAD_H
1261

source code of clang/include/clang/Sema/Overload.h