Welcome to mirror list, hosted at ThFree Co, Russian Federation.

FN_multi_function_builder.hh « functions « blender « source - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: e6dc01eb539448a22a3dacdb6e786bf3385cef0b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
/* SPDX-License-Identifier: GPL-2.0-or-later */

#pragma once

/** \file
 * \ingroup fn
 *
 * This file contains several utilities to create multi-functions with less redundant code.
 */

#include <functional>

#include "BLI_devirtualize_parameters.hh"

#include "FN_multi_function.hh"

namespace blender::fn {

namespace devi = devirtualize_parameters;

/**
 * These presets determine what code is generated for a #CustomMF. Different presets make different
 * trade-offs between run-time performance and compile-time/binary size.
 */
namespace CustomMF_presets {

/** Method to execute a function in case devirtualization was not possible. */
enum class FallbackMode {
  /** Access all elements in virtual arrays through virtual function calls. */
  Simple,
  /** Process elements in chunks to reduce virtual function call overhead. */
  Materialized,
};

/**
 * The "naive" method for executing a #CustomMF. Every element is processed separately and input
 * values are retrieved from the virtual arrays one by one. This generates the least amount of
 * code, but is also the slowest method.
 */
struct Simple {
  static constexpr bool use_devirtualization = false;
  static constexpr FallbackMode fallback_mode = FallbackMode::Simple;
};

/**
 * This is an improvement over the #Simple method. It still generates a relatively small amount of
 * code, because the function is only instantiated once. It's generally faster than #Simple,
 * because inputs are retrieved from the virtual arrays in chunks, reducing virtual method call
 * overhead.
 */
struct Materialized {
  static constexpr bool use_devirtualization = false;
  static constexpr FallbackMode fallback_mode = FallbackMode::Materialized;
};

/**
 * The most efficient preset, but also potentially generates a lot of code (exponential in the
 * number of inputs of the function). It generates separate optimized loops for all combinations of
 * inputs. This should be used for small functions of which all inputs are likely to be single
 * values or spans, and the number of inputs is relatively small.
 */
struct AllSpanOrSingle {
  static constexpr bool use_devirtualization = true;
  static constexpr FallbackMode fallback_mode = FallbackMode::Materialized;

  template<typename Fn, typename... ParamTypes>
  void try_devirtualize(devi::Devirtualizer<Fn, ParamTypes...> &devirtualizer)
  {
    using devi::DeviMode;
    devirtualizer.try_execute_devirtualized(
        make_value_sequence<DeviMode,
                            DeviMode::Span | DeviMode::Single | DeviMode::Range,
                            sizeof...(ParamTypes)>());
  }
};

/**
 * A slightly weaker variant of #AllSpanOrSingle. It generates less code, because it assumes that
 * some of the inputs are most likely single values. It should be used for small functions which
 * have too many inputs to make #AllSingleOrSpan a reasonable choice.
 */
template<size_t... Indices> struct SomeSpanOrSingle {
  static constexpr bool use_devirtualization = true;
  static constexpr FallbackMode fallback_mode = FallbackMode::Materialized;

  template<typename Fn, typename... ParamTypes>
  void try_devirtualize(devi::Devirtualizer<Fn, ParamTypes...> &devirtualizer)
  {
    using devi::DeviMode;
    devirtualizer.try_execute_devirtualized(
        make_two_value_sequence<DeviMode,
                                DeviMode::Span | DeviMode::Single | DeviMode::Range,
                                DeviMode::Single,
                                sizeof...(ParamTypes),
                                0,
                                (Indices + 1)...>());
  }
};

}  // namespace CustomMF_presets

namespace detail {

/**
 * Executes #element_fn for all indices in the mask. The passed in #args contain the input as well
 * as output parameters. Usually types in #args are devirtualized (e.g. a `Span<int>` is passed in
 * instead of a `VArray<int>`).
 */
template<typename MaskT, typename... Args, typename... ParamTags, size_t... I, typename ElementFn>
void execute_array(TypeSequence<ParamTags...> /* param_tags */,
                   std::index_sequence<I...> /* indices */,
                   ElementFn element_fn,
                   MaskT mask,
                   /* Use restrict to tell the compiler that pointer inputs do not alias each
                    * other. This is important for some compiler optimizations. */
                   Args &&__restrict... args)
{
  for (const int64_t i : mask) {
    element_fn([&]() -> decltype(auto) {
      using ParamTag = typename TypeSequence<ParamTags...>::template at_index<I>;
      if constexpr (ParamTag::category == MFParamCategory::SingleInput) {
        /* For inputs, pass the value (or a reference to it) to the function. */
        return args[i];
      }
      else if constexpr (ParamTag::category == MFParamCategory::SingleOutput) {
        /* For outputs, pass a pointer to the function. This is done instead of passing a
         * reference, because the pointer points to uninitialized memory. */
        return &args[i];
      }
    }()...);
  }
}

}  // namespace detail

namespace materialize_detail {

enum class ArgMode {
  Unknown,
  Single,
  Span,
  Materialized,
};

template<typename ParamTag> struct ArgInfo {
  ArgMode mode = ArgMode::Unknown;
  Span<typename ParamTag::base_type> internal_span;
};

/**
 * Similar to #execute_array but accepts two mask inputs, one for inputs and one for outputs.
 */
template<typename... ParamTags, typename ElementFn, typename... Chunks>
void execute_materialized_impl(TypeSequence<ParamTags...> /* param_tags */,
                               const ElementFn element_fn,
                               const IndexRange in_mask,
                               const IndexMask out_mask,
                               Chunks &&__restrict... chunks)
{
  BLI_assert(in_mask.size() == out_mask.size());
  for (const int64_t i : IndexRange(in_mask.size())) {
    const int64_t in_i = in_mask[i];
    const int64_t out_i = out_mask[i];
    element_fn([&]() -> decltype(auto) {
      using ParamTag = ParamTags;
      if constexpr (ParamTag::category == MFParamCategory::SingleInput) {
        return chunks[in_i];
      }
      else if constexpr (ParamTag::category == MFParamCategory::SingleOutput) {
        /* For outputs, a pointer is passed, because the memory is uninitialized. */
        return &chunks[out_i];
      }
    }()...);
  }
}

/**
 * Executes #element_fn for all indices in #mask. However, instead of processing every element
 * separately, processing happens in chunks. This allows retrieving from input virtual arrays in
 * chunks, which reduces virtual function call overhead.
 */
template<typename... ParamTags, size_t... I, typename ElementFn, typename... Args>
void execute_materialized(TypeSequence<ParamTags...> /* param_tags */,
                          std::index_sequence<I...> /* indices */,
                          const ElementFn element_fn,
                          const IndexMask mask,
                          Args &&...args)
{

  /* In theory, all elements could be processed in one chunk. However, that has the disadvantage
   * that large temporary arrays are needed. Using small chunks allows using small arrays, which
   * are reused multiple times, which improves cache efficiency. The chunk size also shouldn't be
   * too small, because then overhead of the outer loop over chunks becomes significant again. */
  static constexpr int64_t MaxChunkSize = 32;
  const int64_t mask_size = mask.size();
  const int64_t buffer_size = std::min(mask_size, MaxChunkSize);

  /* Local buffers that are used to temporarily store values retrieved from virtual arrays. */
  std::tuple<TypedBuffer<typename ParamTags::base_type, MaxChunkSize>...> buffers_owner;

  /* A span for each parameter which is either empty or points to memory in #buffers_owner. */
  std::tuple<MutableSpan<typename ParamTags::base_type>...> buffers;

  /* Information about every parameter. */
  std::tuple<ArgInfo<ParamTags>...> args_info;

  (
      /* Setup information for all parameters. */
      [&] {
        typedef ParamTags ParamTag;
        typedef typename ParamTag::base_type T;
        [[maybe_unused]] ArgInfo<ParamTags> &arg_info = std::get<I>(args_info);
        if constexpr (ParamTag::category == MFParamCategory::SingleInput) {
          VArray<T> &varray = *args;
          if (varray.is_single()) {
            /* If an input #VArray is a single value, we have to fill the buffer with that value
             * only once. The same unchanged buffer can then be reused in every chunk. */
            MutableSpan<T> in_chunk{std::get<I>(buffers_owner).ptr(), buffer_size};
            const T in_single = varray.get_internal_single();
            uninitialized_fill_n(in_chunk.data(), in_chunk.size(), in_single);
            std::get<I>(buffers) = in_chunk;
            arg_info.mode = ArgMode::Single;
          }
          else if (varray.is_span()) {
            /* Remember the span so that it doesn't have to be retrieved in every iteration. */
            arg_info.internal_span = varray.get_internal_span();
          }
        }
      }(),
      ...);

  /* Outer loop over all chunks. */
  for (int64_t chunk_start = 0; chunk_start < mask_size; chunk_start += MaxChunkSize) {
    const IndexMask sliced_mask = mask.slice(chunk_start, MaxChunkSize);
    const int64_t chunk_size = sliced_mask.size();
    const bool sliced_mask_is_range = sliced_mask.is_range();

    execute_materialized_impl(
        TypeSequence<ParamTags...>(),
        element_fn,
        /* Inputs are "compressed" into contiguous arrays without gaps. */
        IndexRange(chunk_size),
        /* Outputs are written directly into the correct place in the output arrays. */
        sliced_mask,
        /* Prepare every parameter for this chunk. */
        [&] {
          using ParamTag = ParamTags;
          using T = typename ParamTag::base_type;
          [[maybe_unused]] ArgInfo<ParamTags> &arg_info = std::get<I>(args_info);
          if constexpr (ParamTag::category == MFParamCategory::SingleInput) {
            if (arg_info.mode == ArgMode::Single) {
              /* The single value has been filled into a buffer already reused for every chunk. */
              return Span<T>(std::get<I>(buffers));
            }
            else {
              const VArray<T> &varray = *args;
              if (sliced_mask_is_range) {
                if (!arg_info.internal_span.is_empty()) {
                  /* In this case we can just use an existing span instead of "compressing" it into
                   * a new temporary buffer. */
                  const IndexRange sliced_mask_range = sliced_mask.as_range();
                  arg_info.mode = ArgMode::Span;
                  return arg_info.internal_span.slice(sliced_mask_range);
                }
              }
              /* As a fallback, do a virtual function call to retrieve all elements in the current
               * chunk. The elements are stored in a temporary buffer reused for every chunk. */
              MutableSpan<T> in_chunk{std::get<I>(buffers_owner).ptr(), chunk_size};
              varray.materialize_compressed_to_uninitialized(sliced_mask, in_chunk);
              /* Remember that this parameter has been materialized, so that the values are
               * destructed properly when the chunk is done. */
              arg_info.mode = ArgMode::Materialized;
              return Span<T>(in_chunk);
            }
          }
          else if constexpr (ParamTag::category == MFParamCategory::SingleOutput) {
            /* For outputs, just pass a pointer. This is important so that `__restrict` works. */
            return args->data();
          }
        }()...);

    (
        /* Destruct values that have been materialized before. */
        [&] {
          typedef ParamTags ParamTag;
          typedef typename ParamTag::base_type T;
          [[maybe_unused]] ArgInfo<ParamTags> &arg_info = std::get<I>(args_info);
          if constexpr (ParamTag::category == MFParamCategory::SingleInput) {
            if (arg_info.mode == ArgMode::Materialized) {
              T *in_chunk = std::get<I>(buffers_owner).ptr();
              destruct_n(in_chunk, chunk_size);
            }
          }
        }(),
        ...);
  }

  (
      /* Destruct buffers for single value inputs. */
      [&] {
        typedef ParamTags ParamTag;
        typedef typename ParamTag::base_type T;
        [[maybe_unused]] ArgInfo<ParamTags> &arg_info = std::get<I>(args_info);
        if constexpr (ParamTag::category == MFParamCategory::SingleInput) {
          if (arg_info.mode == ArgMode::Single) {
            MutableSpan<T> in_chunk = std::get<I>(buffers);
            destruct_n(in_chunk.data(), in_chunk.size());
          }
        }
      }(),
      ...);
}
}  // namespace materialize_detail

template<typename... ParamTags> class CustomMF : public MultiFunction {
 private:
  std::function<void(IndexMask mask, MFParams params)> fn_;
  MFSignature signature_;

  using TagsSequence = TypeSequence<ParamTags...>;

 public:
  template<typename ElementFn, typename ExecPreset = CustomMF_presets::Materialized>
  CustomMF(const char *name,
           ElementFn element_fn,
           ExecPreset exec_preset = CustomMF_presets::Materialized())
  {
    MFSignatureBuilder signature{name};
    add_signature_parameters(signature, std::make_index_sequence<TagsSequence::size()>());
    signature_ = signature.build();
    this->set_signature(&signature_);

    fn_ = [element_fn, exec_preset](IndexMask mask, MFParams params) {
      execute(
          element_fn, exec_preset, mask, params, std::make_index_sequence<TagsSequence::size()>());
    };
  }

  template<typename ElementFn, typename ExecPreset, size_t... I>
  static void execute(ElementFn element_fn,
                      ExecPreset exec_preset,
                      IndexMask mask,
                      MFParams params,
                      std::index_sequence<I...> /* indices */)
  {
    std::tuple<typename ParamTags::array_type...> retrieved_params;
    (
        /* Get all parameters from #params and store them in #retrieved_params. */
        [&]() {
          typedef typename TagsSequence::template at_index<I> ParamTag;
          typedef typename ParamTag::base_type T;

          if constexpr (ParamTag::category == MFParamCategory::SingleInput) {
            std::get<I>(retrieved_params) = params.readonly_single_input<T>(I);
          }
          if constexpr (ParamTag::category == MFParamCategory::SingleOutput) {
            std::get<I>(retrieved_params) = params.uninitialized_single_output<T>(I);
          }
        }(),
        ...);

    auto array_executor = [&](auto &&...args) {
      detail::execute_array(TagsSequence(),
                            std::make_index_sequence<TagsSequence::size()>(),
                            element_fn,
                            std::forward<decltype(args)>(args)...);
    };

    /* First try devirtualized execution, since this is the most efficient. */
    bool executed_devirtualized = false;
    if constexpr (ExecPreset::use_devirtualization) {
      devi::Devirtualizer<decltype(array_executor), IndexMask, typename ParamTags::array_type...>
          devirtualizer{
              array_executor, &mask, [&] { return &std::get<I>(retrieved_params); }()...};
      exec_preset.try_devirtualize(devirtualizer);
      executed_devirtualized = devirtualizer.executed();
    }

    /* If devirtualized execution was disabled or not possible, use a fallback method which is
     * slower but always works. */
    if (!executed_devirtualized) {
      if constexpr (ExecPreset::fallback_mode == CustomMF_presets::FallbackMode::Materialized) {
        materialize_detail::execute_materialized(
            TypeSequence<ParamTags...>(), std::index_sequence<I...>(), element_fn, mask, [&] {
              return &std::get<I>(retrieved_params);
            }()...);
      }
      else {
        detail::execute_array(TagsSequence(),
                              std::make_index_sequence<TagsSequence::size()>(),
                              element_fn,
                              mask,
                              std::get<I>(retrieved_params)...);
      }
    }
  }

  template<size_t... I>
  static void add_signature_parameters(MFSignatureBuilder &signature,
                                       std::index_sequence<I...> /* indices */)
  {
    (
        /* Loop over all parameter types and add an entry for each in the signature. */
        [&] {
          typedef typename TagsSequence::template at_index<I> ParamTag;
          signature.add(ParamTag(), "");
        }(),
        ...);
  }

  void call(IndexMask mask, MFParams params, MFContext UNUSED(context)) const override
  {
    fn_(mask, params);
  }
};

/**
 * Generates a multi-function with the following parameters:
 * 1. single input (SI) of type In1
 * 2. single output (SO) of type Out1
 *
 * This example creates a function that adds 10 to the incoming values:
 * `CustomMF_SI_SO<int, int> fn("add 10", [](int value) { return value + 10; });`
 */
template<typename In1, typename Out1>
class CustomMF_SI_SO : public CustomMF<MFParamTag<MFParamCategory::SingleInput, In1>,
                                       MFParamTag<MFParamCategory::SingleOutput, Out1>> {
 public:
  template<typename ElementFn, typename ExecPreset = CustomMF_presets::Materialized>
  CustomMF_SI_SO(const char *name,
                 ElementFn element_fn,
                 ExecPreset exec_preset = CustomMF_presets::Materialized())
      : CustomMF<MFParamTag<MFParamCategory::SingleInput, In1>,
                 MFParamTag<MFParamCategory::SingleOutput, Out1>>(
            name,
            [element_fn](const In1 &in1, Out1 *out1) { new (out1) Out1(element_fn(in1)); },
            exec_preset)
  {
  }
};

/**
 * Generates a multi-function with the following parameters:
 * 1. single input (SI) of type In1
 * 2. single input (SI) of type In2
 * 3. single output (SO) of type Out1
 */
template<typename In1, typename In2, typename Out1>
class CustomMF_SI_SI_SO : public CustomMF<MFParamTag<MFParamCategory::SingleInput, In1>,
                                          MFParamTag<MFParamCategory::SingleInput, In2>,
                                          MFParamTag<MFParamCategory::SingleOutput, Out1>> {
 public:
  template<typename ElementFn, typename ExecPreset = CustomMF_presets::Materialized>
  CustomMF_SI_SI_SO(const char *name,
                    ElementFn element_fn,
                    ExecPreset exec_preset = CustomMF_presets::Materialized())
      : CustomMF<MFParamTag<MFParamCategory::SingleInput, In1>,
                 MFParamTag<MFParamCategory::SingleInput, In2>,
                 MFParamTag<MFParamCategory::SingleOutput, Out1>>(
            name,
            [element_fn](const In1 &in1, const In2 &in2, Out1 *out1) {
              new (out1) Out1(element_fn(in1, in2));
            },
            exec_preset)
  {
  }
};

/**
 * Generates a multi-function with the following parameters:
 * 1. single input (SI) of type In1
 * 2. single input (SI) of type In2
 * 3. single input (SI) of type In3
 * 4. single output (SO) of type Out1
 */
template<typename In1, typename In2, typename In3, typename Out1>
class CustomMF_SI_SI_SI_SO : public CustomMF<MFParamTag<MFParamCategory::SingleInput, In1>,
                                             MFParamTag<MFParamCategory::SingleInput, In2>,
                                             MFParamTag<MFParamCategory::SingleInput, In3>,
                                             MFParamTag<MFParamCategory::SingleOutput, Out1>> {
 public:
  template<typename ElementFn, typename ExecPreset = CustomMF_presets::Materialized>
  CustomMF_SI_SI_SI_SO(const char *name,
                       ElementFn element_fn,
                       ExecPreset exec_preset = CustomMF_presets::Materialized())
      : CustomMF<MFParamTag<MFParamCategory::SingleInput, In1>,
                 MFParamTag<MFParamCategory::SingleInput, In2>,
                 MFParamTag<MFParamCategory::SingleInput, In3>,
                 MFParamTag<MFParamCategory::SingleOutput, Out1>>(
            name,
            [element_fn](const In1 &in1, const In2 &in2, const In3 &in3, Out1 *out1) {
              new (out1) Out1(element_fn(in1, in2, in3));
            },
            exec_preset)
  {
  }
};

/**
 * Generates a multi-function with the following parameters:
 * 1. single input (SI) of type In1
 * 2. single input (SI) of type In2
 * 3. single input (SI) of type In3
 * 4. single input (SI) of type In4
 * 5. single output (SO) of type Out1
 */
template<typename In1, typename In2, typename In3, typename In4, typename Out1>
class CustomMF_SI_SI_SI_SI_SO : public CustomMF<MFParamTag<MFParamCategory::SingleInput, In1>,
                                                MFParamTag<MFParamCategory::SingleInput, In2>,
                                                MFParamTag<MFParamCategory::SingleInput, In3>,
                                                MFParamTag<MFParamCategory::SingleInput, In4>,
                                                MFParamTag<MFParamCategory::SingleOutput, Out1>> {
 public:
  template<typename ElementFn, typename ExecPreset = CustomMF_presets::Materialized>
  CustomMF_SI_SI_SI_SI_SO(const char *name,
                          ElementFn element_fn,
                          ExecPreset exec_preset = CustomMF_presets::Materialized())
      : CustomMF<MFParamTag<MFParamCategory::SingleInput, In1>,
                 MFParamTag<MFParamCategory::SingleInput, In2>,
                 MFParamTag<MFParamCategory::SingleInput, In3>,
                 MFParamTag<MFParamCategory::SingleInput, In4>,
                 MFParamTag<MFParamCategory::SingleOutput, Out1>>(
            name,
            [element_fn](
                const In1 &in1, const In2 &in2, const In3 &in3, const In4 &in4, Out1 *out1) {
              new (out1) Out1(element_fn(in1, in2, in3, in4));
            },
            exec_preset)
  {
  }
};

/**
 * Generates a multi-function with the following parameters:
 * 1. single mutable (SM) of type Mut1
 */
template<typename Mut1> class CustomMF_SM : public MultiFunction {
 private:
  using FunctionT = std::function<void(IndexMask, MutableSpan<Mut1>)>;
  FunctionT function_;
  MFSignature signature_;

 public:
  CustomMF_SM(const char *name, FunctionT function) : function_(std::move(function))
  {
    MFSignatureBuilder signature{name};
    signature.single_mutable<Mut1>("Mut1");
    signature_ = signature.build();
    this->set_signature(&signature_);
  }

  template<typename ElementFuncT>
  CustomMF_SM(const char *name, ElementFuncT element_fn)
      : CustomMF_SM(name, CustomMF_SM::create_function(element_fn))
  {
  }

  template<typename ElementFuncT> static FunctionT create_function(ElementFuncT element_fn)
  {
    return [=](IndexMask mask, MutableSpan<Mut1> mut1) {
      mask.to_best_mask_type([&](const auto &mask) {
        for (const int64_t i : mask) {
          element_fn(mut1[i]);
        }
      });
    };
  }

  void call(IndexMask mask, MFParams params, MFContext UNUSED(context)) const override
  {
    MutableSpan<Mut1> mut1 = params.single_mutable<Mut1>(0);
    function_(mask, mut1);
  }
};

/**
 * A multi-function that outputs the same value every time. The value is not owned by an instance
 * of this function. If #make_value_copy is false, the caller is responsible for destructing and
 * freeing the value.
 */
class CustomMF_GenericConstant : public MultiFunction {
 private:
  const CPPType &type_;
  const void *value_;
  MFSignature signature_;
  bool owns_value_;

  template<typename T> friend class CustomMF_Constant;

 public:
  CustomMF_GenericConstant(const CPPType &type, const void *value, bool make_value_copy);
  ~CustomMF_GenericConstant();
  void call(IndexMask mask, MFParams params, MFContext context) const override;
  uint64_t hash() const override;
  bool equals(const MultiFunction &other) const override;
};

/**
 * A multi-function that outputs the same array every time. The array is not owned by in instance
 * of this function. The caller is responsible for destructing and freeing the values.
 */
class CustomMF_GenericConstantArray : public MultiFunction {
 private:
  GSpan array_;
  MFSignature signature_;

 public:
  CustomMF_GenericConstantArray(GSpan array);
  void call(IndexMask mask, MFParams params, MFContext context) const override;
};

/**
 * Generates a multi-function that outputs a constant value.
 */
template<typename T> class CustomMF_Constant : public MultiFunction {
 private:
  T value_;
  MFSignature signature_;

 public:
  template<typename U> CustomMF_Constant(U &&value) : value_(std::forward<U>(value))
  {
    MFSignatureBuilder signature{"Constant"};
    signature.single_output<T>("Value");
    signature_ = signature.build();
    this->set_signature(&signature_);
  }

  void call(IndexMask mask, MFParams params, MFContext UNUSED(context)) const override
  {
    MutableSpan<T> output = params.uninitialized_single_output<T>(0);
    mask.to_best_mask_type([&](const auto &mask) {
      for (const int64_t i : mask) {
        new (&output[i]) T(value_);
      }
    });
  }

  uint64_t hash() const override
  {
    return get_default_hash(value_);
  }

  bool equals(const MultiFunction &other) const override
  {
    const CustomMF_Constant *other1 = dynamic_cast<const CustomMF_Constant *>(&other);
    if (other1 != nullptr) {
      return value_ == other1->value_;
    }
    const CustomMF_GenericConstant *other2 = dynamic_cast<const CustomMF_GenericConstant *>(
        &other);
    if (other2 != nullptr) {
      const CPPType &type = CPPType::get<T>();
      if (type == other2->type_) {
        return type.is_equal_or_false(static_cast<const void *>(&value_), other2->value_);
      }
    }
    return false;
  }
};

class CustomMF_DefaultOutput : public MultiFunction {
 private:
  int output_amount_;
  MFSignature signature_;

 public:
  CustomMF_DefaultOutput(Span<MFDataType> input_types, Span<MFDataType> output_types);
  void call(IndexMask mask, MFParams params, MFContext context) const override;
};

class CustomMF_GenericCopy : public MultiFunction {
 private:
  MFSignature signature_;

 public:
  CustomMF_GenericCopy(MFDataType data_type);
  void call(IndexMask mask, MFParams params, MFContext context) const override;
};

}  // namespace blender::fn