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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
|
//===- DialectConversion.h - MLIR dialect conversion pass -------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file declares a generic pass for converting between MLIR dialects.
//
//===----------------------------------------------------------------------===//
#ifndef MLIR_TRANSFORMS_DIALECTCONVERSION_H_
#define MLIR_TRANSFORMS_DIALECTCONVERSION_H_
#include "mlir/Config/mlir-config.h"
#include "mlir/Rewrite/FrozenRewritePatternSet.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/StringMap.h"
#include <type_traits>
namespace mlir {
// Forward declarations.
class Attribute;
class Block;
struct ConversionConfig;
class ConversionPatternRewriter;
class MLIRContext;
class Operation;
struct OperationConverter;
class Type;
class Value;
//===----------------------------------------------------------------------===//
// Type Conversion
//===----------------------------------------------------------------------===//
/// Type conversion class. Specific conversions and materializations can be
/// registered using addConversion and addMaterialization, respectively.
class TypeConverter {
public:
virtual ~TypeConverter() = default;
TypeConverter() = default;
// Copy the registered conversions, but not the caches
TypeConverter(const TypeConverter &other)
: conversions(other.conversions),
sourceMaterializations(other.sourceMaterializations),
targetMaterializations(other.targetMaterializations),
typeAttributeConversions(other.typeAttributeConversions) {}
TypeConverter &operator=(const TypeConverter &other) {
conversions = other.conversions;
sourceMaterializations = other.sourceMaterializations;
targetMaterializations = other.targetMaterializations;
typeAttributeConversions = other.typeAttributeConversions;
return *this;
}
/// This class provides all of the information necessary to convert a type
/// signature.
class SignatureConversion {
public:
SignatureConversion(unsigned numOrigInputs)
: remappedInputs(numOrigInputs) {}
/// This struct represents a range of new types or a range of values that
/// remaps an existing signature input.
struct InputMapping {
size_t inputNo, size;
SmallVector<Value, 1> replacementValues;
/// Return "true" if this input was replaces with one or multiple values.
bool replacedWithValues() const { return !replacementValues.empty(); }
};
/// Return the argument types for the new signature.
ArrayRef<Type> getConvertedTypes() const { return argTypes; }
/// Get the input mapping for the given argument.
std::optional<InputMapping> getInputMapping(unsigned input) const {
return remappedInputs[input];
}
//===------------------------------------------------------------------===//
// Conversion Hooks
//===------------------------------------------------------------------===//
/// Remap an input of the original signature with a new set of types. The
/// new types are appended to the new signature conversion.
void addInputs(unsigned origInputNo, ArrayRef<Type> types);
/// Append new input types to the signature conversion, this should only be
/// used if the new types are not intended to remap an existing input.
void addInputs(ArrayRef<Type> types);
/// Remap an input of the original signature to `replacements`
/// values. This drops the original argument.
void remapInput(unsigned origInputNo, ArrayRef<Value> replacements);
private:
/// Remap an input of the original signature with a range of types in the
/// new signature.
void remapInput(unsigned origInputNo, unsigned newInputNo,
unsigned newInputCount = 1);
/// The remapping information for each of the original arguments.
SmallVector<std::optional<InputMapping>, 4> remappedInputs;
/// The set of new argument types.
SmallVector<Type, 4> argTypes;
};
/// The general result of a type attribute conversion callback, allowing
/// for early termination. The default constructor creates the na case.
class AttributeConversionResult {
public:
constexpr AttributeConversionResult() : impl() {}
AttributeConversionResult(Attribute attr) : impl(attr, resultTag) {}
static AttributeConversionResult result(Attribute attr);
static AttributeConversionResult na();
static AttributeConversionResult abort();
bool hasResult() const;
bool isNa() const;
bool isAbort() const;
Attribute getResult() const;
private:
AttributeConversionResult(Attribute attr, unsigned tag) : impl(attr, tag) {}
llvm::PointerIntPair<Attribute, 2> impl;
// Note that na is 0 so that we can use PointerIntPair's default
// constructor.
static constexpr unsigned naTag = 0;
static constexpr unsigned resultTag = 1;
static constexpr unsigned abortTag = 2;
};
/// Register a conversion function. A conversion function must be convertible
/// to any of the following forms (where `T` is `Value` or a class derived
/// from `Type`, including `Type` itself):
///
/// * std::optional<Type>(T)
/// - This form represents a 1-1 type conversion. It should return nullptr
/// or `std::nullopt` to signify failure. If `std::nullopt` is returned,
/// the converter is allowed to try another conversion function to
/// perform the conversion.
/// * std::optional<LogicalResult>(T, SmallVectorImpl<Type> &)
/// - This form represents a 1-N type conversion. It should return
/// `failure` or `std::nullopt` to signify a failed conversion. If the
/// new set of types is empty, the type is removed and any usages of the
/// existing value are expected to be removed during conversion. If
/// `std::nullopt` is returned, the converter is allowed to try another
/// conversion function to perform the conversion.
///
/// Conversion functions that accept `Value` as the first argument are
/// context-aware. I.e., they can take into account IR when converting the
/// type of the given value. Context-unaware conversion functions accept
/// `Type` or a derived class as the first argument.
///
/// Note: Context-unaware conversions are cached, but context-aware
/// conversions are not.
///
/// Note: When attempting to convert a type, e.g. via 'convertType', the
/// mostly recently added conversions will be invoked first.
template <typename FnT, typename T = typename llvm::function_traits<
std::decay_t<FnT>>::template arg_t<0>>
void addConversion(FnT &&callback) {
registerConversion(wrapCallback<T>(std::forward<FnT>(callback)));
}
/// All of the following materializations require function objects that are
/// convertible to the following form:
/// `Value(OpBuilder &, T, ValueRange, Location)`,
/// where `T` is any subclass of `Type`. This function is responsible for
/// creating an operation, using the OpBuilder and Location provided, that
/// "casts" a range of values into a single value of the given type `T`. It
/// must return a Value of the type `T` on success and `nullptr` if
/// it failed but other materialization should be attempted. Materialization
/// functions must be provided when a type conversion may persist after the
/// conversion has finished.
///
/// Note: Target materializations may optionally accept an additional Type
/// parameter, which is the original type of the SSA value. Furthermore, `T`
/// can be a TypeRange; in that case, the function must return a
/// SmallVector<Value>.
/// This method registers a materialization that will be called when
/// converting a replacement value back to its original source type.
/// This is used when some uses of the original value persist beyond the main
/// conversion.
template <typename FnT, typename T = typename llvm::function_traits<
std::decay_t<FnT>>::template arg_t<1>>
void addSourceMaterialization(FnT &&callback) {
sourceMaterializations.emplace_back(
wrapSourceMaterialization<T>(std::forward<FnT>(callback)));
}
/// This method registers a materialization that will be called when
/// converting a value to a target type according to a pattern's type
/// converter.
///
/// Note: Target materializations can optionally inspect the "original"
/// type. This type may be different from the type of the input value.
/// For example, let's assume that a conversion pattern "P1" replaced an SSA
/// value "v1" (type "t1") with "v2" (type "t2"). Then a different conversion
/// pattern "P2" matches an op that has "v1" as an operand. Let's furthermore
/// assume that "P2" determines that the converted target type of "t1" is
/// "t3", which may be different from "t2". In this example, the target
/// materialization will be invoked with: outputType = "t3", inputs = "v2",
/// originalType = "t1". Note that the original type "t1" cannot be recovered
/// from just "t3" and "v2"; that's why the originalType parameter exists.
///
/// Note: During a 1:N conversion, the result types can be a TypeRange. In
/// that case the materialization produces a SmallVector<Value>.
template <typename FnT, typename T = typename llvm::function_traits<
std::decay_t<FnT>>::template arg_t<1>>
void addTargetMaterialization(FnT &&callback) {
targetMaterializations.emplace_back(
wrapTargetMaterialization<T>(std::forward<FnT>(callback)));
}
/// Register a conversion function for attributes within types. Type
/// converters may call this function in order to allow hoking into the
/// translation of attributes that exist within types. For example, a type
/// converter for the `memref` type could use these conversions to convert
/// memory spaces or layouts in an extensible way.
///
/// The conversion functions take a non-null Type or subclass of Type and a
/// non-null Attribute (or subclass of Attribute), and returns a
/// `AttributeConversionResult`. This result can either contain an
/// `Attribute`, which may be `nullptr`, representing the conversion's
/// success, `AttributeConversionResult::na()` (the default empty value),
/// indicating that the conversion function did not apply and that further
/// conversion functions should be checked, or
/// `AttributeConversionResult::abort()` indicating that the conversion
/// process should be aborted.
///
/// Registered conversion functions are callled in the reverse of the order in
/// which they were registered.
template <
typename FnT,
typename T =
typename llvm::function_traits<std::decay_t<FnT>>::template arg_t<0>,
typename A =
typename llvm::function_traits<std::decay_t<FnT>>::template arg_t<1>>
void addTypeAttributeConversion(FnT &&callback) {
registerTypeAttributeConversion(
wrapTypeAttributeConversion<T, A>(std::forward<FnT>(callback)));
}
/// Convert the given type. This function returns failure if no valid
/// conversion exists, success otherwise. If the new set of types is empty,
/// the type is removed and any usages of the existing value are expected to
/// be removed during conversion.
///
/// Note: This overload invokes only context-unaware type conversion
/// functions. Users should call the other overload if possible.
LogicalResult convertType(Type t, SmallVectorImpl<Type> &results) const;
/// Convert the type of the given value. This function returns failure if no
/// valid conversion exists, success otherwise. If the new set of types is
/// empty, the type is removed and any usages of the existing value are
/// expected to be removed during conversion.
///
/// Note: This overload invokes both context-aware and context-unaware type
/// conversion functions.
LogicalResult convertType(Value v, SmallVectorImpl<Type> &results) const;
/// This hook simplifies defining 1-1 type conversions. This function returns
/// the type to convert to on success, and a null type on failure.
Type convertType(Type t) const;
Type convertType(Value v) const;
/// Attempts a 1-1 type conversion, expecting the result type to be
/// `TargetType`. Returns the converted type cast to `TargetType` on success,
/// and a null type on conversion or cast failure.
template <typename TargetType>
TargetType convertType(Type t) const {
return dyn_cast_or_null<TargetType>(convertType(t));
}
template <typename TargetType>
TargetType convertType(Value v) const {
return dyn_cast_or_null<TargetType>(convertType(v));
}
/// Convert the given types, filling 'results' as necessary. This returns
/// "failure" if the conversion of any of the types fails, "success"
/// otherwise.
LogicalResult convertTypes(TypeRange types,
SmallVectorImpl<Type> &results) const;
/// Convert the types of the given values, filling 'results' as necessary.
/// This returns "failure" if the conversion of any of the types fails,
/// "success" otherwise.
LogicalResult convertTypes(ValueRange values,
SmallVectorImpl<Type> &results) const;
/// Return true if the given type is legal for this type converter, i.e. the
/// type converts to itself.
bool isLegal(Type type) const;
bool isLegal(Value value) const;
/// Return true if all of the given types are legal for this type converter.
bool isLegal(TypeRange range) const {
return llvm::all_of(range, [this](Type type) { return isLegal(type); });
}
bool isLegal(ValueRange range) const {
return llvm::all_of(range, [this](Value value) { return isLegal(value); });
}
/// Return true if the given operation has legal operand and result types.
bool isLegal(Operation *op) const;
/// Return true if the types of block arguments within the region are legal.
bool isLegal(Region *region) const;
/// Return true if the inputs and outputs of the given function type are
/// legal.
bool isSignatureLegal(FunctionType ty) const;
/// This method allows for converting a specific argument of a signature. It
/// takes as inputs the original argument input number, type.
/// On success, it populates 'result' with any new mappings.
LogicalResult convertSignatureArg(unsigned inputNo, Type type,
SignatureConversion &result) const;
LogicalResult convertSignatureArgs(TypeRange types,
SignatureConversion &result,
unsigned origInputOffset = 0) const;
LogicalResult convertSignatureArg(unsigned inputNo, Value value,
SignatureConversion &result) const;
LogicalResult convertSignatureArgs(ValueRange values,
SignatureConversion &result,
unsigned origInputOffset = 0) const;
/// This function converts the type signature of the given block, by invoking
/// 'convertSignatureArg' for each argument. This function should return a
/// valid conversion for the signature on success, std::nullopt otherwise.
std::optional<SignatureConversion> convertBlockSignature(Block *block) const;
/// Materialize a conversion from a set of types into one result type by
/// generating a cast sequence of some kind. See the respective
/// `add*Materialization` for more information on the context for these
/// methods.
Value materializeSourceConversion(OpBuilder &builder, Location loc,
Type resultType, ValueRange inputs) const;
Value materializeTargetConversion(OpBuilder &builder, Location loc,
Type resultType, ValueRange inputs,
Type originalType = {}) const;
SmallVector<Value> materializeTargetConversion(OpBuilder &builder,
Location loc,
TypeRange resultType,
ValueRange inputs,
Type originalType = {}) const;
/// Convert an attribute present `attr` from within the type `type` using
/// the registered conversion functions. If no applicable conversion has been
/// registered, return std::nullopt. Note that the empty attribute/`nullptr`
/// is a valid return value for this function.
std::optional<Attribute> convertTypeAttribute(Type type,
Attribute attr) const;
private:
/// The signature of the callback used to convert a type. If the new set of
/// types is empty, the type is removed and any usages of the existing value
/// are expected to be removed during conversion.
using ConversionCallbackFn = std::function<std::optional<LogicalResult>(
PointerUnion<Type, Value>, SmallVectorImpl<Type> &)>;
/// The signature of the callback used to materialize a source conversion.
///
/// Arguments: builder, result type, inputs, location
using SourceMaterializationCallbackFn =
std::function<Value(OpBuilder &, Type, ValueRange, Location)>;
/// The signature of the callback used to materialize a target conversion.
///
/// Arguments: builder, result types, inputs, location, original type
using TargetMaterializationCallbackFn = std::function<SmallVector<Value>(
OpBuilder &, TypeRange, ValueRange, Location, Type)>;
/// The signature of the callback used to convert a type attribute.
using TypeAttributeConversionCallbackFn =
std::function<AttributeConversionResult(Type, Attribute)>;
/// Generate a wrapper for the given callback. This allows for accepting
/// different callback forms, that all compose into a single version.
/// With callback of form: `std::optional<Type>(T)`, where `T` can be a
/// `Value` or a `Type` (or a class derived from `Type`).
template <typename T, typename FnT>
std::enable_if_t<std::is_invocable_v<FnT, T>, ConversionCallbackFn>
wrapCallback(FnT &&callback) {
return wrapCallback<T>([callback = std::forward<FnT>(callback)](
T typeOrValue, SmallVectorImpl<Type> &results) {
if (std::optional<Type> resultOpt = callback(typeOrValue)) {
bool wasSuccess = static_cast<bool>(*resultOpt);
if (wasSuccess)
results.push_back(*resultOpt);
return std::optional<LogicalResult>(success(wasSuccess));
}
return std::optional<LogicalResult>();
});
}
/// With callback of form: `std::optional<LogicalResult>(
/// T, SmallVectorImpl<Type> &)`, where `T` is a type.
template <typename T, typename FnT>
std::enable_if_t<std::is_invocable_v<FnT, T, SmallVectorImpl<Type> &> &&
std::is_base_of_v<Type, T>,
ConversionCallbackFn>
wrapCallback(FnT &&callback) const {
return [callback = std::forward<FnT>(callback)](
PointerUnion<Type, Value> typeOrValue,
SmallVectorImpl<Type> &results) -> std::optional<LogicalResult> {
T derivedType;
if (Type t = dyn_cast<Type>(typeOrValue)) {
derivedType = dyn_cast<T>(t);
} else if (Value v = dyn_cast<Value>(typeOrValue)) {
derivedType = dyn_cast<T>(v.getType());
} else {
llvm_unreachable("unexpected variant");
}
if (!derivedType)
return std::nullopt;
return callback(derivedType, results);
};
}
/// With callback of form: `std::optional<LogicalResult>(
/// T, SmallVectorImpl<Type>)`, where `T` is a `Value`.
template <typename T, typename FnT>
std::enable_if_t<std::is_invocable_v<FnT, T, SmallVectorImpl<Type> &> &&
std::is_same_v<T, Value>,
ConversionCallbackFn>
wrapCallback(FnT &&callback) {
contextAwareTypeConversionsIndex = conversions.size();
return [callback = std::forward<FnT>(callback)](
PointerUnion<Type, Value> typeOrValue,
SmallVectorImpl<Type> &results) -> std::optional<LogicalResult> {
if (Type t = dyn_cast<Type>(typeOrValue)) {
// Context-aware type conversion was called with a type.
return std::nullopt;
} else if (Value v = dyn_cast<Value>(typeOrValue)) {
return callback(v, results);
}
llvm_unreachable("unexpected variant");
return std::nullopt;
};
}
/// Register a type conversion.
void registerConversion(ConversionCallbackFn callback) {
conversions.emplace_back(std::move(callback));
cachedDirectConversions.clear();
cachedMultiConversions.clear();
}
/// Generate a wrapper for the given source materialization callback. The
/// callback may take any subclass of `Type` and the wrapper will check for
/// the target type to be of the expected class before calling the callback.
template <typename T, typename FnT>
SourceMaterializationCallbackFn
wrapSourceMaterialization(FnT &&callback) const {
return [callback = std::forward<FnT>(callback)](
OpBuilder &builder, Type resultType, ValueRange inputs,
Location loc) -> Value {
if (T derivedType = dyn_cast<T>(resultType))
return callback(builder, derivedType, inputs, loc);
return Value();
};
}
/// Generate a wrapper for the given target materialization callback.
/// The callback may take any subclass of `Type` and the wrapper will check
/// for the target type to be of the expected class before calling the
/// callback.
///
/// With callback of form:
/// - Value(OpBuilder &, T, ValueRange, Location, Type)
/// - SmallVector<Value>(OpBuilder &, TypeRange, ValueRange, Location, Type)
template <typename T, typename FnT>
std::enable_if_t<
std::is_invocable_v<FnT, OpBuilder &, T, ValueRange, Location, Type>,
TargetMaterializationCallbackFn>
wrapTargetMaterialization(FnT &&callback) const {
return [callback = std::forward<FnT>(callback)](
OpBuilder &builder, TypeRange resultTypes, ValueRange inputs,
Location loc, Type originalType) -> SmallVector<Value> {
SmallVector<Value> result;
if constexpr (std::is_same<T, TypeRange>::value) {
// This is a 1:N target materialization. Return the produces values
// directly.
result = callback(builder, resultTypes, inputs, loc, originalType);
} else if constexpr (std::is_assignable<Type, T>::value) {
// This is a 1:1 target materialization. Invoke the callback only if a
// single SSA value is requested.
if (resultTypes.size() == 1) {
// Invoke the callback only if the type class of the callback matches
// the requested result type.
if (T derivedType = dyn_cast<T>(resultTypes.front())) {
// 1:1 materializations produce single values, but we store 1:N
// target materialization functions in the type converter. Wrap the
// result value in a SmallVector<Value>.
Value val =
callback(builder, derivedType, inputs, loc, originalType);
if (val)
result.push_back(val);
}
}
} else {
static_assert(sizeof(T) == 0, "T must be a Type or a TypeRange");
}
return result;
};
}
/// With callback of form:
/// - Value(OpBuilder &, T, ValueRange, Location)
/// - SmallVector<Value>(OpBuilder &, TypeRange, ValueRange, Location)
template <typename T, typename FnT>
std::enable_if_t<
std::is_invocable_v<FnT, OpBuilder &, T, ValueRange, Location>,
TargetMaterializationCallbackFn>
wrapTargetMaterialization(FnT &&callback) const {
return wrapTargetMaterialization<T>(
[callback = std::forward<FnT>(callback)](
OpBuilder &builder, T resultTypes, ValueRange inputs, Location loc,
Type originalType) {
return callback(builder, resultTypes, inputs, loc);
});
}
/// Generate a wrapper for the given memory space conversion callback. The
/// callback may take any subclass of `Attribute` and the wrapper will check
/// for the target attribute to be of the expected class before calling the
/// callback.
template <typename T, typename A, typename FnT>
TypeAttributeConversionCallbackFn
wrapTypeAttributeConversion(FnT &&callback) const {
return [callback = std::forward<FnT>(callback)](
Type type, Attribute attr) -> AttributeConversionResult {
if (T derivedType = dyn_cast<T>(type)) {
if (A derivedAttr = dyn_cast_or_null<A>(attr))
return callback(derivedType, derivedAttr);
}
return AttributeConversionResult::na();
};
}
/// Register a memory space conversion, clearing caches.
void
registerTypeAttributeConversion(TypeAttributeConversionCallbackFn callback) {
typeAttributeConversions.emplace_back(std::move(callback));
// Clear type conversions in case a memory space is lingering inside.
cachedDirectConversions.clear();
cachedMultiConversions.clear();
}
/// Internal implementation of the type conversion.
LogicalResult convertTypeImpl(PointerUnion<Type, Value> t,
SmallVectorImpl<Type> &results) const;
/// The set of registered conversion functions.
SmallVector<ConversionCallbackFn, 4> conversions;
/// The list of registered materialization functions.
SmallVector<SourceMaterializationCallbackFn, 2> sourceMaterializations;
SmallVector<TargetMaterializationCallbackFn, 2> targetMaterializations;
/// The list of registered type attribute conversion functions.
SmallVector<TypeAttributeConversionCallbackFn, 2> typeAttributeConversions;
/// A set of cached conversions to avoid recomputing in the common case.
/// Direct 1-1 conversions are the most common, so this cache stores the
/// successful 1-1 conversions as well as all failed conversions.
mutable DenseMap<Type, Type> cachedDirectConversions;
/// This cache stores the successful 1->N conversions, where N != 1.
mutable DenseMap<Type, SmallVector<Type, 2>> cachedMultiConversions;
/// A mutex used for cache access
mutable llvm::sys::SmartRWMutex<true> cacheMutex;
/// Whether the type converter has context-aware type conversions. I.e.,
/// conversion rules that depend on the SSA value instead of just the type.
/// We store here the index in the `conversions` vector of the last added
/// context-aware conversion, if any. This is useful because we can't cache
/// the result of type conversion happening after context-aware conversions,
/// because the type converter may return different results for the same input
/// type. This is why it is recommened to add context-aware conversions first,
/// any context-free conversions after will benefit from caching.
int contextAwareTypeConversionsIndex = -1;
};
//===----------------------------------------------------------------------===//
// Conversion Patterns
//===----------------------------------------------------------------------===//
/// Base class for the conversion patterns. This pattern class enables type
/// conversions, and other uses specific to the conversion framework. As such,
/// patterns of this type can only be used with the 'apply*' methods below.
class ConversionPattern : public RewritePattern {
public:
using OpAdaptor = ArrayRef<Value>;
using OneToNOpAdaptor = ArrayRef<ValueRange>;
/// Hook for derived classes to implement combined matching and rewriting.
/// This overload supports only 1:1 replacements. The 1:N overload is called
/// by the driver. By default, it calls this 1:1 overload or fails to match
/// if 1:N replacements were found.
virtual LogicalResult
matchAndRewrite(Operation *op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const {
llvm_unreachable("matchAndRewrite is not implemented");
}
/// Hook for derived classes to implement combined matching and rewriting.
/// This overload supports 1:N replacements.
virtual LogicalResult
matchAndRewrite(Operation *op, ArrayRef<ValueRange> operands,
ConversionPatternRewriter &rewriter) const {
return dispatchTo1To1(*this, op, operands, rewriter);
}
/// Attempt to match and rewrite the IR root at the specified operation.
LogicalResult matchAndRewrite(Operation *op,
PatternRewriter &rewriter) const final;
/// Return the type converter held by this pattern, or nullptr if the pattern
/// does not require type conversion.
const TypeConverter *getTypeConverter() const { return typeConverter; }
template <typename ConverterTy>
std::enable_if_t<std::is_base_of<TypeConverter, ConverterTy>::value,
const ConverterTy *>
getTypeConverter() const {
return static_cast<const ConverterTy *>(typeConverter);
}
protected:
/// See `RewritePattern::RewritePattern` for information on the other
/// available constructors.
using RewritePattern::RewritePattern;
/// Construct a conversion pattern with the given converter, and forward the
/// remaining arguments to RewritePattern.
template <typename... Args>
ConversionPattern(const TypeConverter &typeConverter, Args &&...args)
: RewritePattern(std::forward<Args>(args)...),
typeConverter(&typeConverter) {}
/// Given an array of value ranges, which are the inputs to a 1:N adaptor,
/// try to extract the single value of each range to construct a the inputs
/// for a 1:1 adaptor.
///
/// Returns failure if at least one range has 0 or more than 1 value.
FailureOr<SmallVector<Value>>
getOneToOneAdaptorOperands(ArrayRef<ValueRange> operands) const;
/// Overloaded method used to dispatch to the 1:1 'matchAndRewrite' method
/// if possible and emit diagnostic with a failure return value otherwise.
/// 'self' should be '*this' of the derived-pattern and is used to dispatch
/// to the correct 'matchAndRewrite' method in the derived pattern.
template <typename SelfPattern, typename SourceOp>
static LogicalResult dispatchTo1To1(const SelfPattern &self, SourceOp op,
ArrayRef<ValueRange> operands,
ConversionPatternRewriter &rewriter);
/// Same as above, but accepts an adaptor as operand.
template <typename SelfPattern, typename SourceOp>
static LogicalResult dispatchTo1To1(
const SelfPattern &self, SourceOp op,
typename SourceOp::template GenericAdaptor<ArrayRef<ValueRange>> adaptor,
ConversionPatternRewriter &rewriter);
protected:
/// An optional type converter for use by this pattern.
const TypeConverter *typeConverter = nullptr;
};
/// OpConversionPattern is a wrapper around ConversionPattern that allows for
/// matching and rewriting against an instance of a derived operation class as
/// opposed to a raw Operation.
template <typename SourceOp>
class OpConversionPattern : public ConversionPattern {
public:
using OpAdaptor = typename SourceOp::Adaptor;
using OneToNOpAdaptor =
typename SourceOp::template GenericAdaptor<ArrayRef<ValueRange>>;
OpConversionPattern(MLIRContext *context, PatternBenefit benefit = 1)
: ConversionPattern(SourceOp::getOperationName(), benefit, context) {}
OpConversionPattern(const TypeConverter &typeConverter, MLIRContext *context,
PatternBenefit benefit = 1)
: ConversionPattern(typeConverter, SourceOp::getOperationName(), benefit,
context) {}
/// Wrappers around the ConversionPattern methods that pass the derived op
/// type.
LogicalResult
matchAndRewrite(Operation *op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const final {
auto sourceOp = cast<SourceOp>(op);
return matchAndRewrite(sourceOp, OpAdaptor(operands, sourceOp), rewriter);
}
LogicalResult
matchAndRewrite(Operation *op, ArrayRef<ValueRange> operands,
ConversionPatternRewriter &rewriter) const final {
auto sourceOp = cast<SourceOp>(op);
return matchAndRewrite(sourceOp, OneToNOpAdaptor(operands, sourceOp),
rewriter);
}
/// Methods that operate on the SourceOp type. One of these must be
/// overridden by the derived pattern class.
virtual LogicalResult
matchAndRewrite(SourceOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const {
llvm_unreachable("matchAndRewrite is not implemented");
}
virtual LogicalResult
matchAndRewrite(SourceOp op, OneToNOpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const {
return dispatchTo1To1(*this, op, adaptor, rewriter);
}
private:
using ConversionPattern::matchAndRewrite;
};
/// OpInterfaceConversionPattern is a wrapper around ConversionPattern that
/// allows for matching and rewriting against an instance of an OpInterface
/// class as opposed to a raw Operation.
template <typename SourceOp>
class OpInterfaceConversionPattern : public ConversionPattern {
public:
OpInterfaceConversionPattern(MLIRContext *context, PatternBenefit benefit = 1)
: ConversionPattern(Pattern::MatchInterfaceOpTypeTag(),
SourceOp::getInterfaceID(), benefit, context) {}
OpInterfaceConversionPattern(const TypeConverter &typeConverter,
MLIRContext *context, PatternBenefit benefit = 1)
: ConversionPattern(typeConverter, Pattern::MatchInterfaceOpTypeTag(),
SourceOp::getInterfaceID(), benefit, context) {}
/// Wrappers around the ConversionPattern methods that pass the derived op
/// type.
LogicalResult
matchAndRewrite(Operation *op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const final {
return matchAndRewrite(cast<SourceOp>(op), operands, rewriter);
}
LogicalResult
matchAndRewrite(Operation *op, ArrayRef<ValueRange> operands,
ConversionPatternRewriter &rewriter) const final {
return matchAndRewrite(cast<SourceOp>(op), operands, rewriter);
}
/// Methods that operate on the SourceOp type. One of these must be
/// overridden by the derived pattern class.
virtual LogicalResult
matchAndRewrite(SourceOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const {
llvm_unreachable("matchAndRewrite is not implemented");
}
virtual LogicalResult
matchAndRewrite(SourceOp op, ArrayRef<ValueRange> operands,
ConversionPatternRewriter &rewriter) const {
return dispatchTo1To1(*this, op, operands, rewriter);
}
private:
using ConversionPattern::matchAndRewrite;
};
/// OpTraitConversionPattern is a wrapper around ConversionPattern that allows
/// for matching and rewriting against instances of an operation that possess a
/// given trait.
template <template <typename> class TraitType>
class OpTraitConversionPattern : public ConversionPattern {
public:
OpTraitConversionPattern(MLIRContext *context, PatternBenefit benefit = 1)
: ConversionPattern(Pattern::MatchTraitOpTypeTag(),
TypeID::get<TraitType>(), benefit, context) {}
OpTraitConversionPattern(const TypeConverter &typeConverter,
MLIRContext *context, PatternBenefit benefit = 1)
: ConversionPattern(typeConverter, Pattern::MatchTraitOpTypeTag(),
TypeID::get<TraitType>(), benefit, context) {}
};
/// Generic utility to convert op result types according to type converter
/// without knowing exact op type.
/// Clones existing op with new result types and returns it.
FailureOr<Operation *>
convertOpResultTypes(Operation *op, ValueRange operands,
const TypeConverter &converter,
ConversionPatternRewriter &rewriter);
/// Add a pattern to the given pattern list to convert the signature of a
/// FunctionOpInterface op with the given type converter. This only supports
/// ops which use FunctionType to represent their type.
void populateFunctionOpInterfaceTypeConversionPattern(
StringRef functionLikeOpName, RewritePatternSet &patterns,
const TypeConverter &converter);
template <typename FuncOpT>
void populateFunctionOpInterfaceTypeConversionPattern(
RewritePatternSet &patterns, const TypeConverter &converter) {
populateFunctionOpInterfaceTypeConversionPattern(FuncOpT::getOperationName(),
patterns, converter);
}
void populateAnyFunctionOpInterfaceTypeConversionPattern(
RewritePatternSet &patterns, const TypeConverter &converter);
//===----------------------------------------------------------------------===//
// Conversion PatternRewriter
//===----------------------------------------------------------------------===//
namespace detail {
struct ConversionPatternRewriterImpl;
} // namespace detail
/// This class implements a pattern rewriter for use with ConversionPatterns. It
/// extends the base PatternRewriter and provides special conversion specific
/// hooks.
class ConversionPatternRewriter final : public PatternRewriter {
public:
~ConversionPatternRewriter() override;
/// Return the configuration of the current dialect conversion.
const ConversionConfig &getConfig() const;
/// Apply a signature conversion to given block. This replaces the block with
/// a new block containing the updated signature. The operations of the given
/// block are inlined into the newly-created block, which is returned.
///
/// If no block argument types are changing, the original block will be
/// left in place and returned.
///
/// A signature converison must be provided. (Type converters can construct
/// a signature conversion with `convertBlockSignature`.)
///
/// Optionally, a type converter can be provided to build materializations.
/// Note: If no type converter was provided or the type converter does not
/// specify any suitable source/target materialization rules, the dialect
/// conversion may fail to legalize unresolved materializations.
Block *
applySignatureConversion(Block *block,
TypeConverter::SignatureConversion &conversion,
const TypeConverter *converter = nullptr);
/// Apply a signature conversion to each block in the given region. This
/// replaces each block with a new block containing the updated signature. If
/// an updated signature would match the current signature, the respective
/// block is left in place as is. (See `applySignatureConversion` for
/// details.) The new entry block of the region is returned.
///
/// SignatureConversions are computed with the specified type converter.
/// This function returns "failure" if the type converter failed to compute
/// a SignatureConversion for at least one block.
///
/// Optionally, a special SignatureConversion can be specified for the entry
/// block. This is because the types of the entry block arguments are often
/// tied semantically to the operation.
FailureOr<Block *> convertRegionTypes(
Region *region, const TypeConverter &converter,
TypeConverter::SignatureConversion *entryConversion = nullptr);
/// Replace all the uses of `from` with `to`. The type of `from` and `to` is
/// allowed to differ. The conversion driver will try to reconcile all type
/// mismatches that still exist at the end of the conversion with
/// materializations. This function supports both 1:1 and 1:N replacements.
///
/// Note: If `allowPatternRollback` is set to "true", this function behaves
/// slightly different:
///
/// 1. All current and future uses of `from` are replaced. The same value must
/// not be replaced multiple times. That's an API violation.
/// 2. Uses are not replaced immediately but in a delayed fashion. Patterns
/// may still see the original uses when inspecting IR.
/// 3. Uses within the same block that appear before the defining operation
/// of the replacement value are not replaced. This allows users to
/// perform certain replaceAllUsesExcept-style replacements, even though
/// such API is not directly supported.
///
/// Note: In an attempt to align the ConversionPatternRewriter and
/// RewriterBase APIs, (3) may be removed in the future.
void replaceAllUsesWith(Value from, ValueRange to);
void replaceAllUsesWith(Value from, Value to) override {
replaceAllUsesWith(from, ValueRange{to});
}
/// Return the converted value of 'key' with a type defined by the type
/// converter of the currently executing pattern. Return nullptr in the case
/// of failure, the remapped value otherwise.
Value getRemappedValue(Value key);
/// Return the converted values that replace 'keys' with types defined by the
/// type converter of the currently executing pattern. Returns failure if the
/// remap failed, success otherwise.
LogicalResult getRemappedValues(ValueRange keys,
SmallVectorImpl<Value> &results);
//===--------------------------------------------------------------------===//
// PatternRewriter Hooks
//===--------------------------------------------------------------------===//
/// Indicate that the conversion rewriter can recover from rewrite failure.
/// Recovery is supported via rollback, allowing for continued processing of
/// patterns even if a failure is encountered during the rewrite step.
bool canRecoverFromRewriteFailure() const override { return true; }
/// Replace the given operation with the new values. The number of op results
/// and replacement values must match. The types may differ: the dialect
/// conversion driver will reconcile any surviving type mismatches at the end
/// of the conversion process with source materializations. The given
/// operation is erased.
void replaceOp(Operation *op, ValueRange newValues) override;
/// Replace the given operation with the results of the new op. The number of
/// op results must match. The types may differ: the dialect conversion
/// driver will reconcile any surviving type mismatches at the end of the
/// conversion process with source materializations. The original operation
/// is erased.
void replaceOp(Operation *op, Operation *newOp) override;
/// Replace the given operation with the new value ranges. The number of op
/// results and value ranges must match. The given operation is erased.
void replaceOpWithMultiple(Operation *op,
SmallVector<SmallVector<Value>> &&newValues);
template <typename RangeT = ValueRange>
void replaceOpWithMultiple(Operation *op, ArrayRef<RangeT> newValues) {
replaceOpWithMultiple(op,
llvm::to_vector_of<SmallVector<Value>>(newValues));
}
template <typename RangeT>
void replaceOpWithMultiple(Operation *op, RangeT &&newValues) {
replaceOpWithMultiple(op,
ArrayRef(llvm::to_vector_of<ValueRange>(newValues)));
}
/// PatternRewriter hook for erasing a dead operation. The uses of this
/// operation *must* be made dead by the end of the conversion process,
/// otherwise an assert will be issued.
void eraseOp(Operation *op) override;
/// PatternRewriter hook for erase all operations in a block. This is not yet
/// implemented for dialect conversion.
void eraseBlock(Block *block) override;
/// PatternRewriter hook for inlining the ops of a block into another block.
void inlineBlockBefore(Block *source, Block *dest, Block::iterator before,
ValueRange argValues = {}) override;
using PatternRewriter::inlineBlockBefore;
/// PatternRewriter hook for updating the given operation in-place.
/// Note: These methods only track updates to the given operation itself,
/// and not nested regions. Updates to regions will still require notification
/// through other more specific hooks above.
void startOpModification(Operation *op) override;
/// PatternRewriter hook for updating the given operation in-place.
void finalizeOpModification(Operation *op) override;
/// PatternRewriter hook for updating the given operation in-place.
void cancelOpModification(Operation *op) override;
/// Return a reference to the internal implementation.
detail::ConversionPatternRewriterImpl &getImpl();
private:
// Allow OperationConverter to construct new rewriters.
friend struct OperationConverter;
/// Conversion pattern rewriters must not be used outside of dialect
/// conversions. They apply some IR rewrites in a delayed fashion and could
/// bring the IR into an inconsistent state when used standalone.
explicit ConversionPatternRewriter(MLIRContext *ctx,
const ConversionConfig &config);
// Hide unsupported pattern rewriter API.
using OpBuilder::setListener;
std::unique_ptr<detail::ConversionPatternRewriterImpl> impl;
};
template <typename SelfPattern, typename SourceOp>
LogicalResult
ConversionPattern::dispatchTo1To1(const SelfPattern &self, SourceOp op,
ArrayRef<ValueRange> operands,
ConversionPatternRewriter &rewriter) {
FailureOr<SmallVector<Value>> oneToOneOperands =
self.getOneToOneAdaptorOperands(operands);
if (failed(oneToOneOperands))
return rewriter.notifyMatchFailure(op,
"pattern '" + self.getDebugName() +
"' does not support 1:N conversion");
return self.matchAndRewrite(op, *oneToOneOperands, rewriter);
}
template <typename SelfPattern, typename SourceOp>
LogicalResult ConversionPattern::dispatchTo1To1(
const SelfPattern &self, SourceOp op,
typename SourceOp::template GenericAdaptor<ArrayRef<ValueRange>> adaptor,
ConversionPatternRewriter &rewriter) {
FailureOr<SmallVector<Value>> oneToOneOperands =
self.getOneToOneAdaptorOperands(adaptor.getOperands());
if (failed(oneToOneOperands))
return rewriter.notifyMatchFailure(op,
"pattern '" + self.getDebugName() +
"' does not support 1:N conversion");
return self.matchAndRewrite(
op, typename SourceOp::Adaptor(*oneToOneOperands, adaptor), rewriter);
}
//===----------------------------------------------------------------------===//
// ConversionTarget
//===----------------------------------------------------------------------===//
/// This class describes a specific conversion target.
class ConversionTarget {
public:
/// This enumeration corresponds to the specific action to take when
/// considering an operation legal for this conversion target.
enum class LegalizationAction {
/// The target supports this operation.
Legal,
/// This operation has dynamic legalization constraints that must be checked
/// by the target.
Dynamic,
/// The target explicitly does not support this operation.
Illegal,
};
|