forked from apache/tvm
-
Notifications
You must be signed in to change notification settings - Fork 4
/
packed_func.h
1519 lines (1440 loc) · 51.1 KB
/
packed_func.h
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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file tvm/runtime/packed_func.h
* \brief Type-erased function used across TVM API.
*/
#ifndef TVM_RUNTIME_PACKED_FUNC_H_
#define TVM_RUNTIME_PACKED_FUNC_H_
#include <dmlc/logging.h>
#include <tvm/runtime/c_runtime_api.h>
#include <tvm/runtime/container.h>
#include <tvm/runtime/data_type.h>
#include <tvm/runtime/module.h>
#include <tvm/runtime/ndarray.h>
#include <tvm/runtime/object.h>
#include <functional>
#include <limits>
#include <memory>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
// Whether use TVM runtime in header only mode.
#ifndef TVM_RUNTIME_HEADER_ONLY
#define TVM_RUNTIME_HEADER_ONLY 0
#endif
// Always inline macro only use in template
// expansion cases where we know inline is important.
#ifdef _MSC_VER
#define TVM_ALWAYS_INLINE __forceinline
#else
#define TVM_ALWAYS_INLINE inline __attribute__((always_inline))
#endif
namespace tvm {
namespace runtime {
// forward declarations
class TVMArgs;
class TVMArgValue;
class TVMMovableArgValue_;
class TVMRetValue;
class TVMArgsSetter;
/*!
* \brief Packed function is a type-erased function.
* The arguments are passed by packed format.
*
* This is an useful unified interface to call generated functions,
* It is the unified function function type of TVM.
* It corresponds to TVMFunctionHandle in C runtime API.
*/
class PackedFunc {
public:
/*!
* \brief The internal std::function
* \param args The arguments to the function.
* \param rv The return value.
*
* \code
* // Example code on how to implemented FType
* void MyPackedFunc(TVMArgs args, TVMRetValue* rv) {
* // automatically convert arguments to desired type.
* int a0 = args[0];
* float a1 = args[1];
* ...
* // automatically assign values to rv
* std::string my_return_value = "x";
* *rv = my_return_value;
* }
* \endcode
*/
using FType = std::function<void(TVMArgs args, TVMRetValue* rv)>;
/*! \brief default constructor */
PackedFunc() {}
/*! \brief constructor from null */
PackedFunc(std::nullptr_t null) {} // NOLINT(*)
/*!
* \brief constructing a packed function from a std::function.
* \param body the internal container of packed function.
*/
explicit PackedFunc(FType body) : body_(body) {}
/*!
* \brief Call packed function by directly passing in unpacked format.
* \param args Arguments to be passed.
* \tparam Args arguments to be passed.
*
* \code
* // Example code on how to call packed function
* void CallPacked(PackedFunc f) {
* // call like normal functions by pass in arguments
* // return value is automatically converted back
* int rvalue = f(1, 2.0);
* }
* \endcode
*/
template <typename... Args>
inline TVMRetValue operator()(Args&&... args) const;
/*!
* \brief Call the function in packed format.
* \param args The arguments
* \param rv The return value.
*/
inline void CallPacked(TVMArgs args, TVMRetValue* rv) const;
/*! \return the internal body function */
inline FType body() const;
/*! \return Whether the packed function is nullptr */
bool operator==(std::nullptr_t null) const { return body_ == nullptr; }
/*! \return Whether the packed function is not nullptr */
bool operator!=(std::nullptr_t null) const { return body_ != nullptr; }
private:
/*! \brief internal container of packed function */
FType body_;
};
/*!
* \brief Please refer to \ref TypedPackedFuncAnchor "TypedPackedFunc<R(Args..)>"
*/
template <typename FType>
class TypedPackedFunc;
/*!
* \anchor TypedPackedFuncAnchor
* \brief A PackedFunc wrapper to provide typed function signature.
* It is backed by a PackedFunc internally.
*
* TypedPackedFunc enables compile time type checking.
* TypedPackedFunc works with the runtime system:
* - It can be passed as an argument of PackedFunc.
* - It can be assigned to TVMRetValue.
* - It can be directly converted to a type-erased PackedFunc.
*
* Developers should prefer TypedPackedFunc over PackedFunc in C++ code
* as it enables compile time checking.
* We can construct a TypedPackedFunc from a lambda function
* with the same signature.
*
* \code
* // user defined lambda function.
* auto addone = [](int x)->int {
* return x + 1;
* };
* // We can directly convert
* // lambda function to TypedPackedFunc
* TypedPackedFunc<int(int)> ftyped(addone);
* // invoke the function.
* int y = ftyped(1);
* // Can be directly converted to PackedFunc
* PackedFunc packed = ftype;
* \endcode
* \tparam R The return value of the function.
* \tparam Args The argument signature of the function.
*/
template <typename R, typename... Args>
class TypedPackedFunc<R(Args...)> {
public:
/*! \brief short hand for this function type */
using TSelf = TypedPackedFunc<R(Args...)>;
/*! \brief default constructor */
TypedPackedFunc() {}
/*! \brief constructor from null */
TypedPackedFunc(std::nullptr_t null) {} // NOLINT(*)
/*!
* \brief construct by wrap a PackedFunc
*
* Example usage:
* \code
* PackedFunc packed([](TVMArgs args, TVMRetValue *rv) {
* int x = args[0];
* *rv = x + 1;
* });
* // construct from packed function
* TypedPackedFunc<int(int)> ftyped(packed);
* // call the typed version.
* CHECK_EQ(ftyped(1), 2);
* \endcode
*
* \param packed The packed function
*/
inline TypedPackedFunc(PackedFunc packed); // NOLINT(*)
/*!
* \brief constructor from TVMRetValue
* \param value The TVMRetValue
*/
inline TypedPackedFunc(const TVMRetValue& value); // NOLINT(*)
/*!
* \brief constructor from TVMArgValue
* \param value The TVMArgValue
*/
inline TypedPackedFunc(const TVMArgValue& value); // NOLINT(*)
/*!
* \brief constructor from TVMMovableArgValue_
* \param value The TVMMovableArgValue_
*/
inline TypedPackedFunc(TVMMovableArgValue_&& value); // NOLINT(*)
/*!
* \brief construct from a lambda function with the same signature.
*
* Example usage:
* \code
* auto typed_lambda = [](int x)->int { return x + 1; }
* // construct from packed function
* TypedPackedFunc<int(int)> ftyped(typed_lambda);
* // call the typed version.
* CHECK_EQ(ftyped(1), 2);
* \endcode
*
* \param typed_lambda typed lambda function.
* \tparam FLambda the type of the lambda function.
*/
template <typename FLambda, typename = typename std::enable_if<
std::is_convertible<FLambda,
std::function<R(Args...)>>::value>::type>
TypedPackedFunc(const FLambda& typed_lambda) { // NOLINT(*)
this->AssignTypedLambda(typed_lambda);
}
/*!
* \brief copy assignment operator from typed lambda
*
* Example usage:
* \code
* // construct from packed function
* TypedPackedFunc<int(int)> ftyped;
* ftyped = [](int x) { return x + 1; }
* // call the typed version.
* CHECK_EQ(ftyped(1), 2);
* \endcode
*
* \param typed_lambda typed lambda function.
* \tparam FLambda the type of the lambda function.
* \returns reference to self.
*/
template <typename FLambda, typename = typename std::enable_if<
std::is_convertible<FLambda,
std::function<R(Args...)>>::value>::type>
TSelf& operator=(FLambda typed_lambda) { // NOLINT(*)
this->AssignTypedLambda(typed_lambda);
return *this;
}
/*!
* \brief copy assignment operator from PackedFunc.
* \param packed The packed function.
* \returns reference to self.
*/
TSelf& operator=(PackedFunc packed) {
packed_ = packed;
return *this;
}
/*!
* \brief Invoke the operator.
* \param args The arguments
* \returns The return value.
*/
TVM_ALWAYS_INLINE R operator()(Args... args) const;
/*!
* \brief convert to PackedFunc
* \return the internal PackedFunc
*/
operator PackedFunc() const { return packed(); }
/*!
* \return reference the internal PackedFunc
*/
const PackedFunc& packed() const { return packed_; }
/*! \return Whether the packed function is nullptr */
bool operator==(std::nullptr_t null) const { return packed_ == nullptr; }
/*! \return Whether the packed function is not nullptr */
bool operator!=(std::nullptr_t null) const { return packed_ != nullptr; }
private:
friend class TVMRetValue;
/*! \brief The internal packed function */
PackedFunc packed_;
/*!
* \brief Assign the packed field using a typed lambda function.
*
* \param flambda The lambda function.
* \tparam FLambda The lambda function type.
* \note We capture the lambda when possible for maximum efficiency.
*/
template <typename FLambda>
inline void AssignTypedLambda(FLambda flambda);
};
/*! \brief Arguments into TVM functions. */
class TVMArgs {
public:
const TVMValue* values;
const int* type_codes;
int num_args;
/*!
* \brief constructor
* \param values The argument values
* \param type_codes The argument type codes
* \param num_args number of arguments.
*/
TVMArgs(const TVMValue* values, const int* type_codes, int num_args)
: values(values), type_codes(type_codes), num_args(num_args) {}
/*! \return size of the arguments */
inline int size() const;
/*!
* \brief Get i-th argument
* \param i the index.
* \return the ith argument.
*/
inline TVMArgValue operator[](int i) const;
};
/*!
* \brief Convert argument type code to string.
* \param type_code The input type code.
* \return The corresponding string repr.
*/
inline const char* ArgTypeCode2Str(int type_code);
// macro to check type code.
#define TVM_CHECK_TYPE_CODE(CODE, T) \
CHECK_EQ(CODE, T) << " expected " << ArgTypeCode2Str(T) << " but get " << ArgTypeCode2Str(CODE)
/*!
* \brief Type traits for runtime type check during FFI conversion.
* \tparam T the type to be checked.
*/
template <typename T>
struct ObjectTypeChecker {
static bool Check(const Object* ptr) {
using ContainerType = typename T::ContainerType;
if (ptr == nullptr) return T::_type_is_nullable;
return ptr->IsInstance<ContainerType>();
}
static std::string TypeName() {
using ContainerType = typename T::ContainerType;
return ContainerType::_type_key;
}
};
/*!
* \brief Internal base class to
* handle conversion to POD values.
*/
class TVMPODValue_ {
public:
operator double() const {
// Allow automatic conversion from int to float
// This avoids errors when user pass in int from
// the frontend while the API expects a float.
if (type_code_ == kDLInt) {
return static_cast<double>(value_.v_int64);
}
TVM_CHECK_TYPE_CODE(type_code_, kDLFloat);
return value_.v_float64;
}
operator int64_t() const {
TVM_CHECK_TYPE_CODE(type_code_, kDLInt);
return value_.v_int64;
}
operator uint64_t() const {
TVM_CHECK_TYPE_CODE(type_code_, kDLInt);
return value_.v_int64;
}
operator int() const {
TVM_CHECK_TYPE_CODE(type_code_, kDLInt);
CHECK_LE(value_.v_int64, std::numeric_limits<int>::max());
CHECK_GE(value_.v_int64, std::numeric_limits<int>::min());
return static_cast<int>(value_.v_int64);
}
operator bool() const {
TVM_CHECK_TYPE_CODE(type_code_, kDLInt);
return value_.v_int64 != 0;
}
operator void*() const {
if (type_code_ == kTVMNullptr) return nullptr;
if (type_code_ == kTVMDLTensorHandle) return value_.v_handle;
TVM_CHECK_TYPE_CODE(type_code_, kTVMOpaqueHandle);
return value_.v_handle;
}
operator DLTensor*() const {
if (type_code_ == kTVMDLTensorHandle || type_code_ == kTVMNDArrayHandle) {
return static_cast<DLTensor*>(value_.v_handle);
} else {
if (type_code_ == kTVMNullptr) return nullptr;
LOG(FATAL) << "Expect "
<< "DLTensor* or NDArray but get " << ArgTypeCode2Str(type_code_);
return nullptr;
}
}
operator NDArray() const {
if (type_code_ == kTVMNullptr) return NDArray(ObjectPtr<Object>(nullptr));
TVM_CHECK_TYPE_CODE(type_code_, kTVMNDArrayHandle);
return NDArray(NDArray::FFIDataFromHandle(static_cast<TVMArrayHandle>(value_.v_handle)));
}
operator Module() const {
if (type_code_ == kTVMNullptr) {
return Module(ObjectPtr<Object>(nullptr));
}
TVM_CHECK_TYPE_CODE(type_code_, kTVMModuleHandle);
return Module(ObjectPtr<Object>(static_cast<Object*>(value_.v_handle)));
}
operator TVMContext() const {
TVM_CHECK_TYPE_CODE(type_code_, kTVMContext);
return value_.v_ctx;
}
int type_code() const { return type_code_; }
/*!
* \brief return handle as specific pointer type.
* \tparam T the data type.
* \return The pointer type.
*/
template <typename T>
T* ptr() const {
return static_cast<T*>(value_.v_handle);
}
// ObjectRef handling
template <typename TObjectRef,
typename = typename std::enable_if<std::is_base_of<ObjectRef, TObjectRef>::value>::type>
inline bool IsObjectRef() const;
template <typename TObjectRef>
inline TObjectRef AsObjectRef() const;
protected:
friend class TVMArgsSetter;
friend class TVMRetValue;
TVMPODValue_() : type_code_(kTVMNullptr) {}
TVMPODValue_(TVMValue value, int type_code) : value_(value), type_code_(type_code) {}
/*! \brief The value */
TVMValue value_;
/*! \brief the type code */
int type_code_;
};
/*!
* \brief A single argument value to PackedFunc.
* Containing both type_code and TVMValue
*
* Provides utilities to do type cast into other types.
*/
class TVMArgValue : public TVMPODValue_ {
public:
/*! \brief default constructor */
TVMArgValue() {}
/*!
* \brief constructor
* \param value of the function
* \param type_code The type code.
*/
TVMArgValue(TVMValue value, int type_code) : TVMPODValue_(value, type_code) {}
// reuse converter from parent
using TVMPODValue_::operator double;
using TVMPODValue_::operator int64_t;
using TVMPODValue_::operator uint64_t;
using TVMPODValue_::operator int;
using TVMPODValue_::operator bool;
using TVMPODValue_::operator void*;
using TVMPODValue_::operator DLTensor*;
using TVMPODValue_::operator NDArray;
using TVMPODValue_::operator TVMContext;
using TVMPODValue_::operator Module;
using TVMPODValue_::AsObjectRef;
using TVMPODValue_::IsObjectRef;
// conversion operator.
operator std::string() const {
if (type_code_ == kTVMDataType) {
return DLDataType2String(operator DLDataType());
} else if (type_code_ == kTVMBytes) {
TVMByteArray* arr = static_cast<TVMByteArray*>(value_.v_handle);
return std::string(arr->data, arr->size);
} else {
TVM_CHECK_TYPE_CODE(type_code_, kTVMStr);
return std::string(value_.v_str);
}
}
operator PackedFunc() const {
if (type_code_ == kTVMNullptr) return PackedFunc();
TVM_CHECK_TYPE_CODE(type_code_, kTVMPackedFuncHandle);
return *ptr<PackedFunc>();
}
template <typename FType>
operator TypedPackedFunc<FType>() const {
return TypedPackedFunc<FType>(operator PackedFunc());
}
const TVMValue& value() const { return value_; }
template <typename T, typename = typename std::enable_if<std::is_class<T>::value>::type>
inline operator T() const;
inline operator DLDataType() const;
inline operator DataType() const;
};
/*!
* \brief Internal auxiliary struct for TypedPackedFunc to indicate a movable argument.
*
* We can only construct a movable argument once from a single argument position.
* If the argument is passed as RValue reference, the result will be moved.
* We should only construct a MovableArg from an argument once,
* as the result will can moved.
*
* \note For internal development purpose only.
*/
class TVMMovableArgValue_ : public TVMArgValue {
public:
TVMMovableArgValue_(TVMValue value, int type_code) : TVMArgValue(value, type_code) {}
// reuse converter from parent
using TVMArgValue::operator double;
using TVMArgValue::operator int64_t;
using TVMArgValue::operator uint64_t;
using TVMArgValue::operator int;
using TVMArgValue::operator bool;
using TVMArgValue::operator void*;
using TVMArgValue::operator DLTensor*;
using TVMArgValue::operator TVMContext;
using TVMArgValue::operator std::string;
using TVMArgValue::operator DLDataType;
using TVMArgValue::operator DataType;
using TVMArgValue::operator PackedFunc;
/*!
* \brief Helper converter function.
* Try to move out an argument if possible,
* fall back to normal argument conversion rule otherwise.
*/
template <typename T,
typename = typename std::enable_if<std::is_base_of<ObjectRef, T>::value>::type>
inline operator T() const;
};
/*!
* \brief Return Value container,
* Unlike TVMArgValue, which only holds reference and do not delete
* the underlying container during destruction.
*
* TVMRetValue holds value and will manage the underlying containers
* when it stores a complicated data type.
*/
class TVMRetValue : public TVMPODValue_ {
public:
/*! \brief default constructor */
TVMRetValue() {}
/*!
* \brief move constructor from anoter return value.
* \param other The other return value.
*/
TVMRetValue(TVMRetValue&& other) : TVMPODValue_(other.value_, other.type_code_) {
other.value_.v_handle = nullptr;
other.type_code_ = kTVMNullptr;
}
/*! \brief destructor */
~TVMRetValue() { this->Clear(); }
// reuse converter from parent
using TVMPODValue_::operator double;
using TVMPODValue_::operator int64_t;
using TVMPODValue_::operator uint64_t;
using TVMPODValue_::operator int;
using TVMPODValue_::operator bool;
using TVMPODValue_::operator void*;
using TVMPODValue_::operator DLTensor*;
using TVMPODValue_::operator TVMContext;
using TVMPODValue_::operator NDArray;
using TVMPODValue_::operator Module;
using TVMPODValue_::AsObjectRef;
using TVMPODValue_::IsObjectRef;
TVMRetValue(const TVMRetValue& other) : TVMPODValue_() { this->Assign(other); }
// conversion operators
operator std::string() const {
if (type_code_ == kTVMDataType) {
return DLDataType2String(operator DLDataType());
} else if (type_code_ == kTVMBytes) {
return *ptr<std::string>();
}
TVM_CHECK_TYPE_CODE(type_code_, kTVMStr);
return *ptr<std::string>();
}
operator DLDataType() const {
if (type_code_ == kTVMStr) {
return String2DLDataType(operator std::string());
}
TVM_CHECK_TYPE_CODE(type_code_, kTVMDataType);
return value_.v_type;
}
operator DataType() const { return DataType(operator DLDataType()); }
operator PackedFunc() const {
if (type_code_ == kTVMNullptr) return PackedFunc();
TVM_CHECK_TYPE_CODE(type_code_, kTVMPackedFuncHandle);
return *ptr<PackedFunc>();
}
template <typename FType>
operator TypedPackedFunc<FType>() const {
return TypedPackedFunc<FType>(operator PackedFunc());
}
// Assign operators
TVMRetValue& operator=(TVMRetValue&& other) {
this->Clear();
value_ = other.value_;
type_code_ = other.type_code_;
other.type_code_ = kTVMNullptr;
return *this;
}
TVMRetValue& operator=(double value) {
this->SwitchToPOD(kDLFloat);
value_.v_float64 = value;
return *this;
}
TVMRetValue& operator=(std::nullptr_t value) {
this->SwitchToPOD(kTVMNullptr);
value_.v_handle = value;
return *this;
}
TVMRetValue& operator=(void* value) {
this->SwitchToPOD(kTVMOpaqueHandle);
value_.v_handle = value;
return *this;
}
TVMRetValue& operator=(int64_t value) {
this->SwitchToPOD(kDLInt);
value_.v_int64 = value;
return *this;
}
TVMRetValue& operator=(int value) {
this->SwitchToPOD(kDLInt);
value_.v_int64 = value;
return *this;
}
TVMRetValue& operator=(TVMContext value) {
this->SwitchToPOD(kTVMContext);
value_.v_ctx = value;
return *this;
}
TVMRetValue& operator=(DLDataType t) {
this->SwitchToPOD(kTVMDataType);
value_.v_type = t;
return *this;
}
TVMRetValue& operator=(const DataType& other) { return operator=(other.operator DLDataType()); }
TVMRetValue& operator=(bool value) {
this->SwitchToPOD(kDLInt);
value_.v_int64 = value;
return *this;
}
TVMRetValue& operator=(std::string value) {
this->SwitchToClass(kTVMStr, value);
return *this;
}
TVMRetValue& operator=(TVMByteArray value) {
this->SwitchToClass(kTVMBytes, std::string(value.data, value.size));
return *this;
}
TVMRetValue& operator=(NDArray other) {
if (other.data_ != nullptr) {
this->Clear();
type_code_ = kTVMNDArrayHandle;
value_.v_handle = NDArray::FFIGetHandle(other);
ObjectRef::FFIClearAfterMove(&other);
} else {
SwitchToPOD(kTVMNullptr);
}
return *this;
}
TVMRetValue& operator=(Module m) {
SwitchToObject(kTVMModuleHandle, std::move(m.data_));
return *this;
}
TVMRetValue& operator=(PackedFunc f) {
if (f == nullptr) {
this->SwitchToPOD(kTVMNullptr);
} else {
this->SwitchToClass(kTVMPackedFuncHandle, f);
}
return *this;
}
template <typename FType>
TVMRetValue& operator=(const TypedPackedFunc<FType>& f) {
return operator=(f.packed());
}
TVMRetValue& operator=(const TVMRetValue& other) { // NOLINT(*0
this->Assign(other);
return *this;
}
TVMRetValue& operator=(const TVMArgValue& other) {
this->Assign(other);
return *this;
}
TVMRetValue& operator=(TVMMovableArgValue_&& other) {
this->Assign(other);
return *this;
}
/*!
* \brief Move the value back to front-end via C API.
* This marks the current container as null.
* The managed resources are moved to the front-end.
* The front end should take charge in managing them.
*
* \param ret_value The return value.
* \param ret_type_code The return type code.
*/
void MoveToCHost(TVMValue* ret_value, int* ret_type_code) {
// cannot move str; need specially handle.
CHECK(type_code_ != kTVMStr && type_code_ != kTVMBytes);
*ret_value = value_;
*ret_type_code = type_code_;
type_code_ = kTVMNullptr;
}
/*!
* \brief Construct a new TVMRetValue by
* moving from return value stored via C API.
* \param value the value.
* \param type_code The type code.
* \return The created TVMRetValue.
*/
static TVMRetValue MoveFromCHost(TVMValue value, int type_code) {
// Can move POD and everything under the object system.
CHECK(type_code <= kTVMPackedFuncHandle || type_code == kTVMNDArrayHandle);
TVMRetValue ret;
ret.value_ = value;
ret.type_code_ = type_code;
return ret;
}
/*! \return The value field, if the data is POD */
const TVMValue& value() const {
CHECK(type_code_ != kTVMObjectHandle && type_code_ != kTVMPackedFuncHandle &&
type_code_ != kTVMModuleHandle && type_code_ != kTVMStr)
<< "TVMRetValue.value can only be used for POD data";
return value_;
}
// ObjectRef handling
template <typename TObjectRef,
typename = typename std::enable_if<std::is_base_of<ObjectRef, TObjectRef>::value>::type>
inline TVMRetValue& operator=(TObjectRef other);
template <typename T, typename = typename std::enable_if<std::is_class<T>::value>::type>
inline operator T() const;
private:
template <typename T>
void Assign(const T& other) {
switch (other.type_code()) {
case kTVMStr: {
SwitchToClass<std::string>(kTVMStr, other);
break;
}
case kTVMBytes: {
SwitchToClass<std::string>(kTVMBytes, other);
break;
}
case kTVMPackedFuncHandle: {
SwitchToClass<PackedFunc>(kTVMPackedFuncHandle, other);
break;
}
case kTVMModuleHandle: {
*this = other.operator Module();
break;
}
case kTVMNDArrayHandle: {
*this = other.operator NDArray();
break;
}
case kTVMObjectHandle: {
// Avoid operator ObjectRef as we already know it is not NDArray/Module
SwitchToObject(kTVMObjectHandle,
GetObjectPtr<Object>(static_cast<Object*>(other.value_.v_handle)));
break;
}
case kTVMObjectRValueRefArg: {
operator=(other.operator ObjectRef());
break;
}
default: {
SwitchToPOD(other.type_code());
value_ = other.value_;
break;
}
}
}
// get the internal container.
void SwitchToPOD(int type_code) {
if (type_code_ != type_code) {
this->Clear();
type_code_ = type_code;
}
}
template <typename T>
void SwitchToClass(int type_code, T v) {
if (type_code_ != type_code) {
this->Clear();
type_code_ = type_code;
value_.v_handle = new T(v);
} else {
*static_cast<T*>(value_.v_handle) = v;
}
}
void SwitchToObject(int type_code, ObjectPtr<Object> other) {
if (other.data_ != nullptr) {
this->Clear();
type_code_ = type_code;
// move the handle out
value_.v_handle = other.data_;
other.data_ = nullptr;
} else {
SwitchToPOD(kTVMNullptr);
}
}
void Clear() {
if (type_code_ == kTVMNullptr) return;
switch (type_code_) {
case kTVMStr:
case kTVMBytes:
delete ptr<std::string>();
break;
case kTVMPackedFuncHandle:
delete ptr<PackedFunc>();
break;
case kTVMNDArrayHandle: {
NDArray::FFIDecRef(static_cast<TVMArrayHandle>(value_.v_handle));
break;
}
case kTVMModuleHandle: {
static_cast<Object*>(value_.v_handle)->DecRef();
break;
}
case kTVMObjectHandle: {
static_cast<Object*>(value_.v_handle)->DecRef();
break;
}
}
type_code_ = kTVMNullptr;
}
};
/*!
* \brief Type trait to specify special value conversion rules from
* TVMArgValue and TVMRetValue.
*
* The trait can be specialized to add type specific conversion logic
* from the TVMArgvalue and TVMRetValue.
*
* \tparam TObjectRef the specific ObjectRefType.
*/
template <typename TObjectRef>
struct PackedFuncValueConverter {
/*!
* \brief Convert a TObjectRef from an argument value.
* \param val The argument value.
* \return the converted result.
*/
static TObjectRef From(const TVMArgValue& val) { return val.AsObjectRef<TObjectRef>(); }
/*!
* \brief Convert a TObjectRef from a return value.
* \param val The argument value.
* \return the converted result.
*/
static TObjectRef From(const TVMRetValue& val) { return val.AsObjectRef<TObjectRef>(); }
};
/*!
* \brief Export a function with the PackedFunc signature
* as a PackedFunc that can be loaded by LibraryModule.
*
* \param ExportName The symbol name to be exported.
* \param Function The function with PackedFunc signature.
* \sa PackedFunc
*
* \code
*
* void AddOne_(TVMArgs args, TVMRetValue* rv) {
* int value = args[0];
* *rv = value + 1;
* }
* // Expose the function as "AddOne"
* TVM_DLL_EXPORT_PACKED_FUNC(AddOne, AddOne_);
*
* \endcode
*/
#define TVM_DLL_EXPORT_PACKED_FUNC(ExportName, Function) \
extern "C" { \
TVM_DLL int ExportName(TVMValue* args, int* type_code, int num_args, TVMValue* out_value, \
int* out_type_code); \
int ExportName(TVMValue* args, int* type_code, int num_args, TVMValue* out_value, \
int* out_type_code) { \
try { \
::tvm::runtime::TVMRetValue rv; \
Function(::tvm::runtime::TVMArgs(args, type_code, num_args), &rv); \
rv.MoveToCHost(out_value, out_type_code); \
return 0; \
} catch (const ::std::runtime_error& _except_) { \
TVMAPISetLastError(_except_.what()); \
return -1; \
} \
} \
}
/*!
* \brief Export typed function as a PackedFunc
* that can be loaded by LibraryModule.
*
* \param ExportName The symbol name to be exported.
* \param Function The typed function.
* \note ExportName and Function must be different,
* see code examples below.
*
* \sa TypedPackedFunc
*
* \code
*
* int AddOne_(int x) {
* return x + 1;
* }
*
* // Expose the function as "AddOne"
* TVM_DLL_EXPORT_TYPED_FUNC(AddOne, AddOne_);
*
* // Expose the function as "SubOne"
* TVM_DLL_EXPORT_TYPED_FUNC(SubOne, [](int x) {
* return x - 1;
* });
*
* // The following code will cause compilation error.
* // Because the same Function and ExortName
* // TVM_DLL_EXPORT_TYPED_FUNC(AddOne_, AddOne_);
*
* // The following code is OK, assuming the macro
* // is in a different namespace from xyz
* // TVM_DLL_EXPORT_TYPED_FUNC(AddOne_, xyz::AddOne_);
*
* \endcode
*/
#define TVM_DLL_EXPORT_TYPED_FUNC(ExportName, Function) \
extern "C" { \
TVM_DLL int ExportName(TVMValue* args, int* type_code, int num_args, TVMValue* out_value, \
int* out_type_code) { \
try { \
auto f = Function; \
using FType = ::tvm::runtime::detail::function_signature<decltype(f)>::FType; \
::tvm::runtime::TVMRetValue rv; \
::tvm::runtime::detail::unpack_call_by_signature<FType>::run( \
f, ::tvm::runtime::TVMArgs(args, type_code, num_args), &rv); \
rv.MoveToCHost(out_value, out_type_code); \
return 0; \
} catch (const ::std::runtime_error& _except_) { \
TVMAPISetLastError(_except_.what()); \
return -1; \
} \
} \
}
inline TVMArgValue TVMArgs::operator[](int i) const {
CHECK_LT(i, num_args) << "not enough argument passed, " << num_args << " passed"
<< " but request arg[" << i << "].";
return TVMArgValue(values[i], type_codes[i]);
}
inline int TVMArgs::size() const { return num_args; }
inline void PackedFunc::CallPacked(TVMArgs args, TVMRetValue* rv) const { body_(args, rv); }
inline PackedFunc::FType PackedFunc::body() const { return body_; }
// internal namespace
inline const char* ArgTypeCode2Str(int type_code) {
switch (type_code) {
case kDLInt:
return "int";
case kDLUInt:
return "uint";
case kDLFloat:
return "float";
case kTVMStr:
return "str";
case kTVMBytes:
return "bytes";
case kTVMOpaqueHandle:
return "handle";
case kTVMNullptr:
return "NULL";
case kTVMDLTensorHandle:
return "ArrayHandle";
case kTVMDataType:
return "DLDataType";
case kTVMContext:
return "TVMContext";