File: SPIRVCanonicalization.cpp

package info (click to toggle)
swiftlang 6.1.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,791,604 kB
  • sloc: cpp: 9,901,740; ansic: 2,201,431; asm: 1,091,827; python: 308,252; objc: 82,166; f90: 80,126; lisp: 38,358; pascal: 25,559; sh: 20,429; ml: 5,058; perl: 4,745; makefile: 4,484; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (1396 lines) | stat: -rw-r--r-- 49,770 bytes parent folder | download | duplicates (6)
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
//===- SPIRVCanonicalization.cpp - MLIR SPIR-V canonicalization patterns --===//
//
// 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 defines the folders and canonicalization patterns for SPIR-V ops.
//
//===----------------------------------------------------------------------===//

#include <optional>
#include <utility>

#include "mlir/Dialect/SPIRV/IR/SPIRVOps.h"

#include "mlir/Dialect/CommonFolders.h"
#include "mlir/Dialect/SPIRV/IR/SPIRVDialect.h"
#include "mlir/Dialect/SPIRV/IR/SPIRVTypes.h"
#include "mlir/Dialect/UB/IR/UBOps.h"
#include "mlir/IR/Matchers.h"
#include "mlir/IR/PatternMatch.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVectorExtras.h"

using namespace mlir;

//===----------------------------------------------------------------------===//
// Common utility functions
//===----------------------------------------------------------------------===//

/// Returns the boolean value under the hood if the given `boolAttr` is a scalar
/// or splat vector bool constant.
static std::optional<bool> getScalarOrSplatBoolAttr(Attribute attr) {
  if (!attr)
    return std::nullopt;

  if (auto boolAttr = llvm::dyn_cast<BoolAttr>(attr))
    return boolAttr.getValue();
  if (auto splatAttr = llvm::dyn_cast<SplatElementsAttr>(attr))
    if (splatAttr.getElementType().isInteger(1))
      return splatAttr.getSplatValue<bool>();
  return std::nullopt;
}

// Extracts an element from the given `composite` by following the given
// `indices`. Returns a null Attribute if error happens.
static Attribute extractCompositeElement(Attribute composite,
                                         ArrayRef<unsigned> indices) {
  // Check that given composite is a constant.
  if (!composite)
    return {};
  // Return composite itself if we reach the end of the index chain.
  if (indices.empty())
    return composite;

  if (auto vector = llvm::dyn_cast<ElementsAttr>(composite)) {
    assert(indices.size() == 1 && "must have exactly one index for a vector");
    return vector.getValues<Attribute>()[indices[0]];
  }

  if (auto array = llvm::dyn_cast<ArrayAttr>(composite)) {
    assert(!indices.empty() && "must have at least one index for an array");
    return extractCompositeElement(array.getValue()[indices[0]],
                                   indices.drop_front());
  }

  return {};
}

static bool isDivZeroOrOverflow(const APInt &a, const APInt &b) {
  bool div0 = b.isZero();
  bool overflow = a.isMinSignedValue() && b.isAllOnes();

  return div0 || overflow;
}

//===----------------------------------------------------------------------===//
// TableGen'erated canonicalizers
//===----------------------------------------------------------------------===//

namespace {
#include "SPIRVCanonicalization.inc"
} // namespace

//===----------------------------------------------------------------------===//
// spirv.AccessChainOp
//===----------------------------------------------------------------------===//

namespace {

/// Combines chained `spirv::AccessChainOp` operations into one
/// `spirv::AccessChainOp` operation.
struct CombineChainedAccessChain final
    : OpRewritePattern<spirv::AccessChainOp> {
  using OpRewritePattern::OpRewritePattern;

  LogicalResult matchAndRewrite(spirv::AccessChainOp accessChainOp,
                                PatternRewriter &rewriter) const override {
    auto parentAccessChainOp =
        accessChainOp.getBasePtr().getDefiningOp<spirv::AccessChainOp>();

    if (!parentAccessChainOp) {
      return failure();
    }

    // Combine indices.
    SmallVector<Value, 4> indices(parentAccessChainOp.getIndices());
    llvm::append_range(indices, accessChainOp.getIndices());

    rewriter.replaceOpWithNewOp<spirv::AccessChainOp>(
        accessChainOp, parentAccessChainOp.getBasePtr(), indices);

    return success();
  }
};
} // namespace

void spirv::AccessChainOp::getCanonicalizationPatterns(
    RewritePatternSet &results, MLIRContext *context) {
  results.add<CombineChainedAccessChain>(context);
}

//===----------------------------------------------------------------------===//
// spirv.IAddCarry
//===----------------------------------------------------------------------===//

// We are required to use CompositeConstructOp to create a constant struct as
// they are not yet implemented as constant, hence we can not do so in a fold.
struct IAddCarryFold final : OpRewritePattern<spirv::IAddCarryOp> {
  using OpRewritePattern::OpRewritePattern;

  LogicalResult matchAndRewrite(spirv::IAddCarryOp op,
                                PatternRewriter &rewriter) const override {
    Location loc = op.getLoc();
    Value lhs = op.getOperand1();
    Value rhs = op.getOperand2();
    Type constituentType = lhs.getType();

    // iaddcarry (x, 0) = <0, x>
    if (matchPattern(rhs, m_Zero())) {
      Value constituents[2] = {rhs, lhs};
      rewriter.replaceOpWithNewOp<spirv::CompositeConstructOp>(op, op.getType(),
                                                               constituents);
      return success();
    }

    // According to the SPIR-V spec:
    //
    //  Result Type must be from OpTypeStruct.  The struct must have two
    //  members...
    //
    //  Member 0 of the result gets the low-order bits (full component width) of
    //  the addition.
    //
    //  Member 1 of the result gets the high-order (carry) bit of the result of
    //  the addition. That is, it gets the value 1 if the addition overflowed
    //  the component width, and 0 otherwise.
    Attribute lhsAttr;
    Attribute rhsAttr;
    if (!matchPattern(lhs, m_Constant(&lhsAttr)) ||
        !matchPattern(rhs, m_Constant(&rhsAttr)))
      return failure();

    auto adds = constFoldBinaryOp<IntegerAttr>(
        {lhsAttr, rhsAttr},
        [](const APInt &a, const APInt &b) { return a + b; });
    if (!adds)
      return failure();

    auto carrys = constFoldBinaryOp<IntegerAttr>(
        ArrayRef{adds, lhsAttr}, [](const APInt &a, const APInt &b) {
          APInt zero = APInt::getZero(a.getBitWidth());
          return a.ult(b) ? (zero + 1) : zero;
        });

    if (!carrys)
      return failure();

    Value addsVal =
        rewriter.create<spirv::ConstantOp>(loc, constituentType, adds);

    Value carrysVal =
        rewriter.create<spirv::ConstantOp>(loc, constituentType, carrys);

    // Create empty struct
    Value undef = rewriter.create<spirv::UndefOp>(loc, op.getType());
    // Fill in adds at id 0
    Value intermediate =
        rewriter.create<spirv::CompositeInsertOp>(loc, addsVal, undef, 0);
    // Fill in carrys at id 1
    rewriter.replaceOpWithNewOp<spirv::CompositeInsertOp>(op, carrysVal,
                                                          intermediate, 1);
    return success();
  }
};

void spirv::IAddCarryOp::getCanonicalizationPatterns(
    RewritePatternSet &patterns, MLIRContext *context) {
  patterns.add<IAddCarryFold>(context);
}

//===----------------------------------------------------------------------===//
// spirv.[S|U]MulExtended
//===----------------------------------------------------------------------===//

// We are required to use CompositeConstructOp to create a constant struct as
// they are not yet implemented as constant, hence we can not do so in a fold.
template <typename MulOp, bool IsSigned>
struct MulExtendedFold final : OpRewritePattern<MulOp> {
  using OpRewritePattern<MulOp>::OpRewritePattern;

  LogicalResult matchAndRewrite(MulOp op,
                                PatternRewriter &rewriter) const override {
    Location loc = op.getLoc();
    Value lhs = op.getOperand1();
    Value rhs = op.getOperand2();
    Type constituentType = lhs.getType();

    // [su]mulextended (x, 0) = <0, 0>
    if (matchPattern(rhs, m_Zero())) {
      Value zero = spirv::ConstantOp::getZero(constituentType, loc, rewriter);
      Value constituents[2] = {zero, zero};
      rewriter.replaceOpWithNewOp<spirv::CompositeConstructOp>(op, op.getType(),
                                                               constituents);
      return success();
    }

    // According to the SPIR-V spec:
    //
    // Result Type must be from OpTypeStruct.  The struct must have two
    // members...
    //
    // Member 0 of the result gets the low-order bits of the multiplication.
    //
    // Member 1 of the result gets the high-order bits of the multiplication.
    Attribute lhsAttr;
    Attribute rhsAttr;
    if (!matchPattern(lhs, m_Constant(&lhsAttr)) ||
        !matchPattern(rhs, m_Constant(&rhsAttr)))
      return failure();

    auto lowBits = constFoldBinaryOp<IntegerAttr>(
        {lhsAttr, rhsAttr},
        [](const APInt &a, const APInt &b) { return a * b; });

    if (!lowBits)
      return failure();

    auto highBits = constFoldBinaryOp<IntegerAttr>(
        {lhsAttr, rhsAttr}, [](const APInt &a, const APInt &b) {
          if (IsSigned) {
            return llvm::APIntOps::mulhs(a, b);
          } else {
            return llvm::APIntOps::mulhu(a, b);
          }
        });

    if (!highBits)
      return failure();

    Value lowBitsVal =
        rewriter.create<spirv::ConstantOp>(loc, constituentType, lowBits);

    Value highBitsVal =
        rewriter.create<spirv::ConstantOp>(loc, constituentType, highBits);

    // Create empty struct
    Value undef = rewriter.create<spirv::UndefOp>(loc, op.getType());
    // Fill in lowBits at id 0
    Value intermediate =
        rewriter.create<spirv::CompositeInsertOp>(loc, lowBitsVal, undef, 0);
    // Fill in highBits at id 1
    rewriter.replaceOpWithNewOp<spirv::CompositeInsertOp>(op, highBitsVal,
                                                          intermediate, 1);
    return success();
  }
};

using SMulExtendedOpFold = MulExtendedFold<spirv::SMulExtendedOp, true>;
void spirv::SMulExtendedOp::getCanonicalizationPatterns(
    RewritePatternSet &patterns, MLIRContext *context) {
  patterns.add<SMulExtendedOpFold>(context);
}

struct UMulExtendedOpXOne final : OpRewritePattern<spirv::UMulExtendedOp> {
  using OpRewritePattern::OpRewritePattern;

  LogicalResult matchAndRewrite(spirv::UMulExtendedOp op,
                                PatternRewriter &rewriter) const override {
    Location loc = op.getLoc();
    Value lhs = op.getOperand1();
    Value rhs = op.getOperand2();
    Type constituentType = lhs.getType();

    // umulextended (x, 1) = <x, 0>
    if (matchPattern(rhs, m_One())) {
      Value zero = spirv::ConstantOp::getZero(constituentType, loc, rewriter);
      Value constituents[2] = {lhs, zero};
      rewriter.replaceOpWithNewOp<spirv::CompositeConstructOp>(op, op.getType(),
                                                               constituents);
      return success();
    }

    return failure();
  }
};

using UMulExtendedOpFold = MulExtendedFold<spirv::UMulExtendedOp, false>;
void spirv::UMulExtendedOp::getCanonicalizationPatterns(
    RewritePatternSet &patterns, MLIRContext *context) {
  patterns.add<UMulExtendedOpFold, UMulExtendedOpXOne>(context);
}

//===----------------------------------------------------------------------===//
// spirv.UMod
//===----------------------------------------------------------------------===//

// Input:
//    %0 = spirv.UMod %arg0, %const32 : i32
//    %1 = spirv.UMod %0, %const4 : i32
// Output:
//    %0 = spirv.UMod %arg0, %const32 : i32
//    %1 = spirv.UMod %arg0, %const4 : i32

// The transformation is only applied if one divisor is a multiple of the other.

// TODO(https://github.com/llvm/llvm-project/issues/63174): Add support for vector constants
struct UModSimplification final : OpRewritePattern<spirv::UModOp> {
  using OpRewritePattern::OpRewritePattern;

  LogicalResult matchAndRewrite(spirv::UModOp umodOp,
                                PatternRewriter &rewriter) const override {
    auto prevUMod = umodOp.getOperand(0).getDefiningOp<spirv::UModOp>();
    if (!prevUMod)
      return failure();

    IntegerAttr prevValue;
    IntegerAttr currValue;
    if (!matchPattern(prevUMod.getOperand(1), m_Constant(&prevValue)) ||
        !matchPattern(umodOp.getOperand(1), m_Constant(&currValue)))
      return failure();

    APInt prevConstValue = prevValue.getValue();
    APInt currConstValue = currValue.getValue();

    // Ensure that one divisor is a multiple of the other. If not, fail the
    // transformation.
    if (prevConstValue.urem(currConstValue) != 0 &&
        currConstValue.urem(prevConstValue) != 0)
      return failure();

    // The transformation is safe. Replace the existing UMod operation with a
    // new UMod operation, using the original dividend and the current divisor.
    rewriter.replaceOpWithNewOp<spirv::UModOp>(
        umodOp, umodOp.getType(), prevUMod.getOperand(0), umodOp.getOperand(1));

    return success();
  }
};

void spirv::UModOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
                                                MLIRContext *context) {
  patterns.insert<UModSimplification>(context);
}

//===----------------------------------------------------------------------===//
// spirv.BitcastOp
//===----------------------------------------------------------------------===//

OpFoldResult spirv::BitcastOp::fold(FoldAdaptor /*adaptor*/) {
  Value curInput = getOperand();
  if (getType() == curInput.getType())
    return curInput;

  // Look through nested bitcasts.
  if (auto prevCast = curInput.getDefiningOp<spirv::BitcastOp>()) {
    Value prevInput = prevCast.getOperand();
    if (prevInput.getType() == getType())
      return prevInput;

    getOperandMutable().assign(prevInput);
    return getResult();
  }

  // TODO(kuhar): Consider constant-folding the operand attribute.
  return {};
}

//===----------------------------------------------------------------------===//
// spirv.CompositeExtractOp
//===----------------------------------------------------------------------===//

OpFoldResult spirv::CompositeExtractOp::fold(FoldAdaptor adaptor) {
  Value compositeOp = getComposite();

  while (auto insertOp =
             compositeOp.getDefiningOp<spirv::CompositeInsertOp>()) {
    if (getIndices() == insertOp.getIndices())
      return insertOp.getObject();
    compositeOp = insertOp.getComposite();
  }

  if (auto constructOp =
          compositeOp.getDefiningOp<spirv::CompositeConstructOp>()) {
    auto type = llvm::cast<spirv::CompositeType>(constructOp.getType());
    if (getIndices().size() == 1 &&
        constructOp.getConstituents().size() == type.getNumElements()) {
      auto i = llvm::cast<IntegerAttr>(*getIndices().begin());
      if (i.getValue().getSExtValue() <
          static_cast<int64_t>(constructOp.getConstituents().size()))
        return constructOp.getConstituents()[i.getValue().getSExtValue()];
    }
  }

  auto indexVector = llvm::map_to_vector(getIndices(), [](Attribute attr) {
    return static_cast<unsigned>(llvm::cast<IntegerAttr>(attr).getInt());
  });
  return extractCompositeElement(adaptor.getComposite(), indexVector);
}

//===----------------------------------------------------------------------===//
// spirv.Constant
//===----------------------------------------------------------------------===//

OpFoldResult spirv::ConstantOp::fold(FoldAdaptor /*adaptor*/) {
  return getValue();
}

//===----------------------------------------------------------------------===//
// spirv.IAdd
//===----------------------------------------------------------------------===//

OpFoldResult spirv::IAddOp::fold(FoldAdaptor adaptor) {
  // x + 0 = x
  if (matchPattern(getOperand2(), m_Zero()))
    return getOperand1();

  // According to the SPIR-V spec:
  //
  // The resulting value will equal the low-order N bits of the correct result
  // R, where N is the component width and R is computed with enough precision
  // to avoid overflow and underflow.
  return constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(),
      [](APInt a, const APInt &b) { return std::move(a) + b; });
}

//===----------------------------------------------------------------------===//
// spirv.IMul
//===----------------------------------------------------------------------===//

OpFoldResult spirv::IMulOp::fold(FoldAdaptor adaptor) {
  // x * 0 == 0
  if (matchPattern(getOperand2(), m_Zero()))
    return getOperand2();
  // x * 1 = x
  if (matchPattern(getOperand2(), m_One()))
    return getOperand1();

  // According to the SPIR-V spec:
  //
  // The resulting value will equal the low-order N bits of the correct result
  // R, where N is the component width and R is computed with enough precision
  // to avoid overflow and underflow.
  return constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(),
      [](const APInt &a, const APInt &b) { return a * b; });
}

//===----------------------------------------------------------------------===//
// spirv.ISub
//===----------------------------------------------------------------------===//

OpFoldResult spirv::ISubOp::fold(FoldAdaptor adaptor) {
  // x - x = 0
  if (getOperand1() == getOperand2())
    return Builder(getContext()).getIntegerAttr(getType(), 0);

  // According to the SPIR-V spec:
  //
  // The resulting value will equal the low-order N bits of the correct result
  // R, where N is the component width and R is computed with enough precision
  // to avoid overflow and underflow.
  return constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(),
      [](APInt a, const APInt &b) { return std::move(a) - b; });
}

//===----------------------------------------------------------------------===//
// spirv.SDiv
//===----------------------------------------------------------------------===//

OpFoldResult spirv::SDivOp::fold(FoldAdaptor adaptor) {
  // sdiv (x, 1) = x
  if (matchPattern(getOperand2(), m_One()))
    return getOperand1();

  // According to the SPIR-V spec:
  //
  // Signed-integer division of Operand 1 divided by Operand 2.
  // Results are computed per component. Behavior is undefined if Operand 2 is
  // 0. Behavior is undefined if Operand 2 is -1 and Operand 1 is the minimum
  // representable value for the operands' type, causing signed overflow.
  //
  // So don't fold during undefined behavior.
  bool div0OrOverflow = false;
  auto res = constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(), [&](const APInt &a, const APInt &b) {
        if (div0OrOverflow || isDivZeroOrOverflow(a, b)) {
          div0OrOverflow = true;
          return a;
        }
        return a.sdiv(b);
      });
  return div0OrOverflow ? Attribute() : res;
}

//===----------------------------------------------------------------------===//
// spirv.SMod
//===----------------------------------------------------------------------===//

OpFoldResult spirv::SModOp::fold(FoldAdaptor adaptor) {
  // smod (x, 1) = 0
  if (matchPattern(getOperand2(), m_One()))
    return Builder(getContext()).getZeroAttr(getType());

  // According to SPIR-V spec:
  //
  // Signed remainder operation for the remainder whose sign matches the sign
  // of Operand 2. Behavior is undefined if Operand 2 is 0. Behavior is
  // undefined if Operand 2 is -1 and Operand 1 is the minimum representable
  // value for the operands' type, causing signed overflow. Otherwise, the
  // result is the remainder r of Operand 1 divided by Operand 2 where if
  // r ≠ 0, the sign of r is the same as the sign of Operand 2.
  //
  // So don't fold during undefined behavior
  bool div0OrOverflow = false;
  auto res = constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(), [&](const APInt &a, const APInt &b) {
        if (div0OrOverflow || isDivZeroOrOverflow(a, b)) {
          div0OrOverflow = true;
          return a;
        }
        APInt c = a.abs().urem(b.abs());
        if (c.isZero())
          return c;
        if (b.isNegative()) {
          APInt zero = APInt::getZero(c.getBitWidth());
          return a.isNegative() ? (zero - c) : (b + c);
        }
        return a.isNegative() ? (b - c) : c;
      });
  return div0OrOverflow ? Attribute() : res;
}

//===----------------------------------------------------------------------===//
// spirv.SRem
//===----------------------------------------------------------------------===//

OpFoldResult spirv::SRemOp::fold(FoldAdaptor adaptor) {
  // x % 1 = 0
  if (matchPattern(getOperand2(), m_One()))
    return Builder(getContext()).getZeroAttr(getType());

  // According to SPIR-V spec:
  //
  // Signed remainder operation for the remainder whose sign matches the sign
  // of Operand 1. Behavior is undefined if Operand 2 is 0. Behavior is
  // undefined if Operand 2 is -1 and Operand 1 is the minimum representable
  // value for the operands' type, causing signed overflow. Otherwise, the
  // result is the remainder r of Operand 1 divided by Operand 2 where if
  // r ≠ 0, the sign of r is the same as the sign of Operand 1.

  // Don't fold if it would do undefined behavior.
  bool div0OrOverflow = false;
  auto res = constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(), [&](APInt a, const APInt &b) {
        if (div0OrOverflow || isDivZeroOrOverflow(a, b)) {
          div0OrOverflow = true;
          return a;
        }
        return a.srem(b);
      });
  return div0OrOverflow ? Attribute() : res;
}

//===----------------------------------------------------------------------===//
// spirv.UDiv
//===----------------------------------------------------------------------===//

OpFoldResult spirv::UDivOp::fold(FoldAdaptor adaptor) {
  // udiv (x, 1) = x
  if (matchPattern(getOperand2(), m_One()))
    return getOperand1();

  // According to the SPIR-V spec:
  //
  // Unsigned-integer division of Operand 1 divided by Operand 2. Behavior is
  // undefined if Operand 2 is 0.
  //
  // So don't fold during undefined behavior.
  bool div0 = false;
  auto res = constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(), [&](const APInt &a, const APInt &b) {
        if (div0 || b.isZero()) {
          div0 = true;
          return a;
        }
        return a.udiv(b);
      });
  return div0 ? Attribute() : res;
}

//===----------------------------------------------------------------------===//
// spirv.UMod
//===----------------------------------------------------------------------===//

OpFoldResult spirv::UModOp::fold(FoldAdaptor adaptor) {
  // umod (x, 1) = 0
  if (matchPattern(getOperand2(), m_One()))
    return Builder(getContext()).getZeroAttr(getType());

  // According to the SPIR-V spec:
  //
  // Unsigned modulo operation of Operand 1 modulo Operand 2. Behavior is
  // undefined if Operand 2 is 0.
  //
  // So don't fold during undefined behavior.
  bool div0 = false;
  auto res = constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(), [&](const APInt &a, const APInt &b) {
        if (div0 || b.isZero()) {
          div0 = true;
          return a;
        }
        return a.urem(b);
      });
  return div0 ? Attribute() : res;
}

//===----------------------------------------------------------------------===//
// spirv.SNegate
//===----------------------------------------------------------------------===//

OpFoldResult spirv::SNegateOp::fold(FoldAdaptor adaptor) {
  // -(-x) = 0 - (0 - x) = x
  auto op = getOperand();
  if (auto negateOp = op.getDefiningOp<spirv::SNegateOp>())
    return negateOp->getOperand(0);

  // According to the SPIR-V spec:
  //
  // Signed-integer subtract of Operand from zero.
  return constFoldUnaryOp<IntegerAttr>(
      adaptor.getOperands(), [](const APInt &a) {
        APInt zero = APInt::getZero(a.getBitWidth());
        return zero - a;
      });
}

//===----------------------------------------------------------------------===//
// spirv.NotOp
//===----------------------------------------------------------------------===//

OpFoldResult spirv::NotOp::fold(spirv::NotOp::FoldAdaptor adaptor) {
  // !(!x) = x
  auto op = getOperand();
  if (auto notOp = op.getDefiningOp<spirv::NotOp>())
    return notOp->getOperand(0);

  // According to the SPIR-V spec:
  //
  // Complement the bits of Operand.
  return constFoldUnaryOp<IntegerAttr>(adaptor.getOperands(), [&](APInt a) {
    a.flipAllBits();
    return a;
  });
}

//===----------------------------------------------------------------------===//
// spirv.LogicalAnd
//===----------------------------------------------------------------------===//

OpFoldResult spirv::LogicalAndOp::fold(FoldAdaptor adaptor) {
  if (std::optional<bool> rhs =
          getScalarOrSplatBoolAttr(adaptor.getOperand2())) {
    // x && true = x
    if (*rhs)
      return getOperand1();

    // x && false = false
    if (!*rhs)
      return adaptor.getOperand2();
  }

  return Attribute();
}

//===----------------------------------------------------------------------===//
// spirv.LogicalEqualOp
//===----------------------------------------------------------------------===//

OpFoldResult
spirv::LogicalEqualOp::fold(spirv::LogicalEqualOp::FoldAdaptor adaptor) {
  // x == x -> true
  if (getOperand1() == getOperand2()) {
    auto trueAttr = BoolAttr::get(getContext(), true);
    if (isa<IntegerType>(getType()))
      return trueAttr;
    if (auto vecTy = dyn_cast<VectorType>(getType()))
      return SplatElementsAttr::get(vecTy, trueAttr);
  }

  return constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(), [](const APInt &a, const APInt &b) {
        return a == b ? APInt::getAllOnes(1) : APInt::getZero(1);
      });
}

//===----------------------------------------------------------------------===//
// spirv.LogicalNotEqualOp
//===----------------------------------------------------------------------===//

OpFoldResult spirv::LogicalNotEqualOp::fold(FoldAdaptor adaptor) {
  if (std::optional<bool> rhs =
          getScalarOrSplatBoolAttr(adaptor.getOperand2())) {
    // x != false -> x
    if (!rhs.value())
      return getOperand1();
  }

  // x == x -> false
  if (getOperand1() == getOperand2()) {
    auto falseAttr = BoolAttr::get(getContext(), false);
    if (isa<IntegerType>(getType()))
      return falseAttr;
    if (auto vecTy = dyn_cast<VectorType>(getType()))
      return SplatElementsAttr::get(vecTy, falseAttr);
  }

  return constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(), [](const APInt &a, const APInt &b) {
        return a == b ? APInt::getZero(1) : APInt::getAllOnes(1);
      });
}

//===----------------------------------------------------------------------===//
// spirv.LogicalNot
//===----------------------------------------------------------------------===//

OpFoldResult spirv::LogicalNotOp::fold(FoldAdaptor adaptor) {
  // !(!x) = x
  auto op = getOperand();
  if (auto notOp = op.getDefiningOp<spirv::LogicalNotOp>())
    return notOp->getOperand(0);

  // According to the SPIR-V spec:
  //
  // Complement the bits of Operand.
  return constFoldUnaryOp<IntegerAttr>(adaptor.getOperands(),
                                       [](const APInt &a) {
                                         APInt zero = APInt::getZero(1);
                                         return a == 1 ? zero : (zero + 1);
                                       });
}

void spirv::LogicalNotOp::getCanonicalizationPatterns(
    RewritePatternSet &results, MLIRContext *context) {
  results
      .add<ConvertLogicalNotOfIEqual, ConvertLogicalNotOfINotEqual,
           ConvertLogicalNotOfLogicalEqual, ConvertLogicalNotOfLogicalNotEqual>(
          context);
}

//===----------------------------------------------------------------------===//
// spirv.LogicalOr
//===----------------------------------------------------------------------===//

OpFoldResult spirv::LogicalOrOp::fold(FoldAdaptor adaptor) {
  if (auto rhs = getScalarOrSplatBoolAttr(adaptor.getOperand2())) {
    if (*rhs) {
      // x || true = true
      return adaptor.getOperand2();
    }

    if (!*rhs) {
      // x || false = x
      return getOperand1();
    }
  }

  return Attribute();
}

//===----------------------------------------------------------------------===//
// spirv.SelectOp
//===----------------------------------------------------------------------===//

OpFoldResult spirv::SelectOp::fold(FoldAdaptor adaptor) {
  // spirv.Select _ x x -> x
  Value trueVals = getTrueValue();
  Value falseVals = getFalseValue();
  if (trueVals == falseVals)
    return trueVals;

  ArrayRef<Attribute> operands = adaptor.getOperands();

  // spirv.Select true  x y -> x
  // spirv.Select false x y -> y
  if (auto boolAttr = getScalarOrSplatBoolAttr(operands[0]))
    return *boolAttr ? trueVals : falseVals;

  // Check that all the operands are constant
  if (!operands[0] || !operands[1] || !operands[2])
    return Attribute();

  // Note: getScalarOrSplatBoolAttr will always return a boolAttr if we are in
  // the scalar case. Hence, we are only required to consider the case of
  // DenseElementsAttr in foldSelectOp.
  auto condAttrs = dyn_cast<DenseElementsAttr>(operands[0]);
  auto trueAttrs = dyn_cast<DenseElementsAttr>(operands[1]);
  auto falseAttrs = dyn_cast<DenseElementsAttr>(operands[2]);
  if (!condAttrs || !trueAttrs || !falseAttrs)
    return Attribute();

  auto elementResults = llvm::to_vector<4>(trueAttrs.getValues<Attribute>());
  auto iters = llvm::zip_equal(elementResults, condAttrs.getValues<BoolAttr>(),
                               falseAttrs.getValues<Attribute>());
  for (auto [result, cond, falseRes] : iters) {
    if (!cond.getValue())
      result = falseRes;
  }

  auto resultType = trueAttrs.getType();
  return DenseElementsAttr::get(cast<ShapedType>(resultType), elementResults);
}

//===----------------------------------------------------------------------===//
// spirv.IEqualOp
//===----------------------------------------------------------------------===//

OpFoldResult spirv::IEqualOp::fold(spirv::IEqualOp::FoldAdaptor adaptor) {
  // x == x -> true
  if (getOperand1() == getOperand2()) {
    auto trueAttr = BoolAttr::get(getContext(), true);
    if (isa<IntegerType>(getType()))
      return trueAttr;
    if (auto vecTy = dyn_cast<VectorType>(getType()))
      return SplatElementsAttr::get(vecTy, trueAttr);
  }

  return constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(), getType(), [](const APInt &a, const APInt &b) {
        return a == b ? APInt::getAllOnes(1) : APInt::getZero(1);
      });
}

//===----------------------------------------------------------------------===//
// spirv.INotEqualOp
//===----------------------------------------------------------------------===//

OpFoldResult spirv::INotEqualOp::fold(spirv::INotEqualOp::FoldAdaptor adaptor) {
  // x == x -> false
  if (getOperand1() == getOperand2()) {
    auto falseAttr = BoolAttr::get(getContext(), false);
    if (isa<IntegerType>(getType()))
      return falseAttr;
    if (auto vecTy = dyn_cast<VectorType>(getType()))
      return SplatElementsAttr::get(vecTy, falseAttr);
  }

  return constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(), getType(), [](const APInt &a, const APInt &b) {
        return a == b ? APInt::getZero(1) : APInt::getAllOnes(1);
      });
}

//===----------------------------------------------------------------------===//
// spirv.SGreaterThan
//===----------------------------------------------------------------------===//

OpFoldResult
spirv::SGreaterThanOp::fold(spirv::SGreaterThanOp::FoldAdaptor adaptor) {
  // x == x -> false
  if (getOperand1() == getOperand2()) {
    auto falseAttr = BoolAttr::get(getContext(), false);
    if (isa<IntegerType>(getType()))
      return falseAttr;
    if (auto vecTy = dyn_cast<VectorType>(getType()))
      return SplatElementsAttr::get(vecTy, falseAttr);
  }

  return constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(), getType(), [](const APInt &a, const APInt &b) {
        return a.sgt(b) ? APInt::getAllOnes(1) : APInt::getZero(1);
      });
}

//===----------------------------------------------------------------------===//
// spirv.SGreaterThanEqual
//===----------------------------------------------------------------------===//

OpFoldResult spirv::SGreaterThanEqualOp::fold(
    spirv::SGreaterThanEqualOp::FoldAdaptor adaptor) {
  // x == x -> true
  if (getOperand1() == getOperand2()) {
    auto trueAttr = BoolAttr::get(getContext(), true);
    if (isa<IntegerType>(getType()))
      return trueAttr;
    if (auto vecTy = dyn_cast<VectorType>(getType()))
      return SplatElementsAttr::get(vecTy, trueAttr);
  }

  return constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(), getType(), [](const APInt &a, const APInt &b) {
        return a.sge(b) ? APInt::getAllOnes(1) : APInt::getZero(1);
      });
}

//===----------------------------------------------------------------------===//
// spirv.UGreaterThan
//===----------------------------------------------------------------------===//

OpFoldResult
spirv::UGreaterThanOp::fold(spirv::UGreaterThanOp::FoldAdaptor adaptor) {
  // x == x -> false
  if (getOperand1() == getOperand2()) {
    auto falseAttr = BoolAttr::get(getContext(), false);
    if (isa<IntegerType>(getType()))
      return falseAttr;
    if (auto vecTy = dyn_cast<VectorType>(getType()))
      return SplatElementsAttr::get(vecTy, falseAttr);
  }

  return constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(), getType(), [](const APInt &a, const APInt &b) {
        return a.ugt(b) ? APInt::getAllOnes(1) : APInt::getZero(1);
      });
}

//===----------------------------------------------------------------------===//
// spirv.UGreaterThanEqual
//===----------------------------------------------------------------------===//

OpFoldResult spirv::UGreaterThanEqualOp::fold(
    spirv::UGreaterThanEqualOp::FoldAdaptor adaptor) {
  // x == x -> true
  if (getOperand1() == getOperand2()) {
    auto trueAttr = BoolAttr::get(getContext(), true);
    if (isa<IntegerType>(getType()))
      return trueAttr;
    if (auto vecTy = dyn_cast<VectorType>(getType()))
      return SplatElementsAttr::get(vecTy, trueAttr);
  }

  return constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(), getType(), [](const APInt &a, const APInt &b) {
        return a.uge(b) ? APInt::getAllOnes(1) : APInt::getZero(1);
      });
}

//===----------------------------------------------------------------------===//
// spirv.SLessThan
//===----------------------------------------------------------------------===//

OpFoldResult spirv::SLessThanOp::fold(spirv::SLessThanOp::FoldAdaptor adaptor) {
  // x == x -> false
  if (getOperand1() == getOperand2()) {
    auto falseAttr = BoolAttr::get(getContext(), false);
    if (isa<IntegerType>(getType()))
      return falseAttr;
    if (auto vecTy = dyn_cast<VectorType>(getType()))
      return SplatElementsAttr::get(vecTy, falseAttr);
  }

  return constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(), getType(), [](const APInt &a, const APInt &b) {
        return a.slt(b) ? APInt::getAllOnes(1) : APInt::getZero(1);
      });
}

//===----------------------------------------------------------------------===//
// spirv.SLessThanEqual
//===----------------------------------------------------------------------===//

OpFoldResult
spirv::SLessThanEqualOp::fold(spirv::SLessThanEqualOp::FoldAdaptor adaptor) {
  // x == x -> true
  if (getOperand1() == getOperand2()) {
    auto trueAttr = BoolAttr::get(getContext(), true);
    if (isa<IntegerType>(getType()))
      return trueAttr;
    if (auto vecTy = dyn_cast<VectorType>(getType()))
      return SplatElementsAttr::get(vecTy, trueAttr);
  }

  return constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(), getType(), [](const APInt &a, const APInt &b) {
        return a.sle(b) ? APInt::getAllOnes(1) : APInt::getZero(1);
      });
}

//===----------------------------------------------------------------------===//
// spirv.ULessThan
//===----------------------------------------------------------------------===//

OpFoldResult spirv::ULessThanOp::fold(spirv::ULessThanOp::FoldAdaptor adaptor) {
  // x == x -> false
  if (getOperand1() == getOperand2()) {
    auto falseAttr = BoolAttr::get(getContext(), false);
    if (isa<IntegerType>(getType()))
      return falseAttr;
    if (auto vecTy = dyn_cast<VectorType>(getType()))
      return SplatElementsAttr::get(vecTy, falseAttr);
  }

  return constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(), getType(), [](const APInt &a, const APInt &b) {
        return a.ult(b) ? APInt::getAllOnes(1) : APInt::getZero(1);
      });
}

//===----------------------------------------------------------------------===//
// spirv.ULessThanEqual
//===----------------------------------------------------------------------===//

OpFoldResult
spirv::ULessThanEqualOp::fold(spirv::ULessThanEqualOp::FoldAdaptor adaptor) {
  // x == x -> true
  if (getOperand1() == getOperand2()) {
    auto trueAttr = BoolAttr::get(getContext(), true);
    if (isa<IntegerType>(getType()))
      return trueAttr;
    if (auto vecTy = dyn_cast<VectorType>(getType()))
      return SplatElementsAttr::get(vecTy, trueAttr);
  }

  return constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(), getType(), [](const APInt &a, const APInt &b) {
        return a.ule(b) ? APInt::getAllOnes(1) : APInt::getZero(1);
      });
}

//===----------------------------------------------------------------------===//
// spirv.ShiftLeftLogical
//===----------------------------------------------------------------------===//

OpFoldResult spirv::ShiftLeftLogicalOp::fold(
    spirv::ShiftLeftLogicalOp::FoldAdaptor adaptor) {
  // x << 0 -> x
  if (matchPattern(adaptor.getOperand2(), m_Zero())) {
    return getOperand1();
  }

  // Unfortunately due to below undefined behaviour can't fold 0 for Base.

  // Results are computed per component, and within each component, per bit...
  //
  // The result is undefined if Shift is greater than or equal to the bit width
  // of the components of Base.
  //
  // So we can use the APInt << method, but don't fold if undefined behaviour.
  bool shiftToLarge = false;
  auto res = constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(), [&](const APInt &a, const APInt &b) {
        if (shiftToLarge || b.uge(a.getBitWidth())) {
          shiftToLarge = true;
          return a;
        }
        return a << b;
      });
  return shiftToLarge ? Attribute() : res;
}

//===----------------------------------------------------------------------===//
// spirv.ShiftRightArithmetic
//===----------------------------------------------------------------------===//

OpFoldResult spirv::ShiftRightArithmeticOp::fold(
    spirv::ShiftRightArithmeticOp::FoldAdaptor adaptor) {
  // x >> 0 -> x
  if (matchPattern(adaptor.getOperand2(), m_Zero())) {
    return getOperand1();
  }

  // Unfortunately due to below undefined behaviour can't fold 0, -1 for Base.

  // Results are computed per component, and within each component, per bit...
  //
  // The result is undefined if Shift is greater than or equal to the bit width
  // of the components of Base.
  //
  // So we can use the APInt ashr method, but don't fold if undefined behaviour.
  bool shiftToLarge = false;
  auto res = constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(), [&](const APInt &a, const APInt &b) {
        if (shiftToLarge || b.uge(a.getBitWidth())) {
          shiftToLarge = true;
          return a;
        }
        return a.ashr(b);
      });
  return shiftToLarge ? Attribute() : res;
}

//===----------------------------------------------------------------------===//
// spirv.ShiftRightLogical
//===----------------------------------------------------------------------===//

OpFoldResult spirv::ShiftRightLogicalOp::fold(
    spirv::ShiftRightLogicalOp::FoldAdaptor adaptor) {
  // x >> 0 -> x
  if (matchPattern(adaptor.getOperand2(), m_Zero())) {
    return getOperand1();
  }

  // Unfortunately due to below undefined behaviour can't fold 0 for Base.

  // Results are computed per component, and within each component, per bit...
  //
  // The result is undefined if Shift is greater than or equal to the bit width
  // of the components of Base.
  //
  // So we can use the APInt lshr method, but don't fold if undefined behaviour.
  bool shiftToLarge = false;
  auto res = constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(), [&](const APInt &a, const APInt &b) {
        if (shiftToLarge || b.uge(a.getBitWidth())) {
          shiftToLarge = true;
          return a;
        }
        return a.lshr(b);
      });
  return shiftToLarge ? Attribute() : res;
}

//===----------------------------------------------------------------------===//
// spirv.BitwiseAndOp
//===----------------------------------------------------------------------===//

OpFoldResult
spirv::BitwiseAndOp::fold(spirv::BitwiseAndOp::FoldAdaptor adaptor) {
  // x & x -> x
  if (getOperand1() == getOperand2()) {
    return getOperand1();
  }

  APInt rhsMask;
  if (matchPattern(adaptor.getOperand2(), m_ConstantInt(&rhsMask))) {
    // x & 0 -> 0
    if (rhsMask.isZero())
      return getOperand2();

    // x & <all ones> -> x
    if (rhsMask.isAllOnes())
      return getOperand1();

    // (UConvert x : iN to iK) & <mask with N low bits set> -> UConvert x
    if (auto zext = getOperand1().getDefiningOp<spirv::UConvertOp>()) {
      int valueBits =
          getElementTypeOrSelf(zext.getOperand()).getIntOrFloatBitWidth();
      if (rhsMask.zextOrTrunc(valueBits).isAllOnes())
        return getOperand1();
    }
  }

  // According to the SPIR-V spec:
  //
  // Type is a scalar or vector of integer type.
  // Results are computed per component, and within each component, per bit.
  // So we can use the APInt & method.
  return constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(),
      [](const APInt &a, const APInt &b) { return a & b; });
}

//===----------------------------------------------------------------------===//
// spirv.BitwiseOrOp
//===----------------------------------------------------------------------===//

OpFoldResult spirv::BitwiseOrOp::fold(spirv::BitwiseOrOp::FoldAdaptor adaptor) {
  // x | x -> x
  if (getOperand1() == getOperand2()) {
    return getOperand1();
  }

  APInt rhsMask;
  if (matchPattern(adaptor.getOperand2(), m_ConstantInt(&rhsMask))) {
    // x | 0 -> x
    if (rhsMask.isZero())
      return getOperand1();

    // x | <all ones> -> <all ones>
    if (rhsMask.isAllOnes())
      return getOperand2();
  }

  // According to the SPIR-V spec:
  //
  // Type is a scalar or vector of integer type.
  // Results are computed per component, and within each component, per bit.
  // So we can use the APInt | method.
  return constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(),
      [](const APInt &a, const APInt &b) { return a | b; });
}

//===----------------------------------------------------------------------===//
// spirv.BitwiseXorOp
//===----------------------------------------------------------------------===//

OpFoldResult
spirv::BitwiseXorOp::fold(spirv::BitwiseXorOp::FoldAdaptor adaptor) {
  // x ^ 0 -> x
  if (matchPattern(adaptor.getOperand2(), m_Zero())) {
    return getOperand1();
  }

  // x ^ x -> 0
  if (getOperand1() == getOperand2())
    return Builder(getContext()).getZeroAttr(getType());

  // According to the SPIR-V spec:
  //
  // Type is a scalar or vector of integer type.
  // Results are computed per component, and within each component, per bit.
  // So we can use the APInt ^ method.
  return constFoldBinaryOp<IntegerAttr>(
      adaptor.getOperands(),
      [](const APInt &a, const APInt &b) { return a ^ b; });
}

//===----------------------------------------------------------------------===//
// spirv.mlir.selection
//===----------------------------------------------------------------------===//

namespace {
// Blocks from the given `spirv.mlir.selection` operation must satisfy the
// following layout:
//
//       +-----------------------------------------------+
//       | header block                                  |
//       | spirv.BranchConditionalOp %cond, ^case0, ^case1 |
//       +-----------------------------------------------+
//                            /   \
//                             ...
//
//
//   +------------------------+    +------------------------+
//   | case #0                |    | case #1                |
//   | spirv.Store %ptr %value0 |    | spirv.Store %ptr %value1 |
//   | spirv.Branch ^merge      |    | spirv.Branch ^merge      |
//   +------------------------+    +------------------------+
//
//
//                             ...
//                            \   /
//                              v
//                       +-------------+
//                       | merge block |
//                       +-------------+
//
struct ConvertSelectionOpToSelect final : OpRewritePattern<spirv::SelectionOp> {
  using OpRewritePattern::OpRewritePattern;

  LogicalResult matchAndRewrite(spirv::SelectionOp selectionOp,
                                PatternRewriter &rewriter) const override {
    Operation *op = selectionOp.getOperation();
    Region &body = op->getRegion(0);
    // Verifier allows an empty region for `spirv.mlir.selection`.
    if (body.empty()) {
      return failure();
    }

    // Check that region consists of 4 blocks:
    // header block, `true` block, `false` block and merge block.
    if (llvm::range_size(body) != 4) {
      return failure();
    }

    Block *headerBlock = selectionOp.getHeaderBlock();
    if (!onlyContainsBranchConditionalOp(headerBlock)) {
      return failure();
    }

    auto brConditionalOp =
        cast<spirv::BranchConditionalOp>(headerBlock->front());

    Block *trueBlock = brConditionalOp.getSuccessor(0);
    Block *falseBlock = brConditionalOp.getSuccessor(1);
    Block *mergeBlock = selectionOp.getMergeBlock();

    if (failed(canCanonicalizeSelection(trueBlock, falseBlock, mergeBlock)))
      return failure();

    Value trueValue = getSrcValue(trueBlock);
    Value falseValue = getSrcValue(falseBlock);
    Value ptrValue = getDstPtr(trueBlock);
    auto storeOpAttributes =
        cast<spirv::StoreOp>(trueBlock->front())->getAttrs();

    auto selectOp = rewriter.create<spirv::SelectOp>(
        selectionOp.getLoc(), trueValue.getType(),
        brConditionalOp.getCondition(), trueValue, falseValue);
    rewriter.create<spirv::StoreOp>(selectOp.getLoc(), ptrValue,
                                    selectOp.getResult(), storeOpAttributes);

    // `spirv.mlir.selection` is not needed anymore.
    rewriter.eraseOp(op);
    return success();
  }

private:
  // Checks that given blocks follow the following rules:
  // 1. Each conditional block consists of two operations, the first operation
  //    is a `spirv.Store` and the last operation is a `spirv.Branch`.
  // 2. Each `spirv.Store` uses the same pointer and the same memory attributes.
  // 3. A control flow goes into the given merge block from the given
  //    conditional blocks.
  LogicalResult canCanonicalizeSelection(Block *trueBlock, Block *falseBlock,
                                         Block *mergeBlock) const;

  bool onlyContainsBranchConditionalOp(Block *block) const {
    return llvm::hasSingleElement(*block) &&
           isa<spirv::BranchConditionalOp>(block->front());
  }

  bool isSameAttrList(spirv::StoreOp lhs, spirv::StoreOp rhs) const {
    return lhs->getDiscardableAttrDictionary() ==
               rhs->getDiscardableAttrDictionary() &&
           lhs.getProperties() == rhs.getProperties();
  }

  // Returns a source value for the given block.
  Value getSrcValue(Block *block) const {
    auto storeOp = cast<spirv::StoreOp>(block->front());
    return storeOp.getValue();
  }

  // Returns a destination value for the given block.
  Value getDstPtr(Block *block) const {
    auto storeOp = cast<spirv::StoreOp>(block->front());
    return storeOp.getPtr();
  }
};

LogicalResult ConvertSelectionOpToSelect::canCanonicalizeSelection(
    Block *trueBlock, Block *falseBlock, Block *mergeBlock) const {
  // Each block must consists of 2 operations.
  if (llvm::range_size(*trueBlock) != 2 || llvm::range_size(*falseBlock) != 2) {
    return failure();
  }

  auto trueBrStoreOp = dyn_cast<spirv::StoreOp>(trueBlock->front());
  auto trueBrBranchOp =
      dyn_cast<spirv::BranchOp>(*std::next(trueBlock->begin()));
  auto falseBrStoreOp = dyn_cast<spirv::StoreOp>(falseBlock->front());
  auto falseBrBranchOp =
      dyn_cast<spirv::BranchOp>(*std::next(falseBlock->begin()));

  if (!trueBrStoreOp || !trueBrBranchOp || !falseBrStoreOp ||
      !falseBrBranchOp) {
    return failure();
  }

  // Checks that given type is valid for `spirv.SelectOp`.
  // According to SPIR-V spec:
  // "Before version 1.4, Result Type must be a pointer, scalar, or vector.
  // Starting with version 1.4, Result Type can additionally be a composite type
  // other than a vector."
  bool isScalarOrVector =
      llvm::cast<spirv::SPIRVType>(trueBrStoreOp.getValue().getType())
          .isScalarOrVector();

  // Check that each `spirv.Store` uses the same pointer, memory access
  // attributes and a valid type of the value.
  if ((trueBrStoreOp.getPtr() != falseBrStoreOp.getPtr()) ||
      !isSameAttrList(trueBrStoreOp, falseBrStoreOp) || !isScalarOrVector) {
    return failure();
  }

  if ((trueBrBranchOp->getSuccessor(0) != mergeBlock) ||
      (falseBrBranchOp->getSuccessor(0) != mergeBlock)) {
    return failure();
  }

  return success();
}
} // namespace

void spirv::SelectionOp::getCanonicalizationPatterns(RewritePatternSet &results,
                                                     MLIRContext *context) {
  results.add<ConvertSelectionOpToSelect>(context);
}