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
use core::fmt;
use std::fmt::Write;

use orzir_core::{
    verify_error,
    ApInt,
    ArenaPtr,
    Context,
    Dialect,
    Op,
    OpMetadata,
    Parse,
    RunVerifiers,
    Value,
    Verify,
};
use orzir_macros::{ControlFlow, DataFlow, Op, Parse, Print, RegionInterface, Verify};
use thiserror::Error;

use super::builtin::{FloatTy, IntTy};
use crate::verifiers::*;

/// An integer constant operation.
///
/// This will generate an integer constant with the given value.
#[derive(Op, DataFlow, RegionInterface, ControlFlow, Parse, Print)]
#[mnemonic = "arith.iconst"]
#[verifiers(NumResults<1>, NumOperands<0>, NumRegions<0>, IntegerLikeResults)]
#[format(pattern = "{value}", kind = "op", num_results = 1)]
pub struct IConstOp {
    #[metadata]
    metadata: OpMetadata,
    /// The result of the operation.
    #[result(0)]
    result: ArenaPtr<Value>,
    /// The value of the integer constant.
    value: ApInt,
}

#[derive(Debug, Error)]
#[error("expected an integer with width {0}, but got {1}")]
pub struct IncompatibleWidthErr(pub usize, pub usize);

impl Verify for IConstOp {
    fn verify(&self, ctx: &Context) -> orzir_core::VerifyResult<()> {
        self.run_verifiers(ctx)?;
        self.result.deref(&ctx.values).verify(ctx)?;
        let result_ty = self.result.deref(&ctx.values).ty(ctx).deref(&ctx.tys);
        if let Some(ty) = result_ty.as_a::<IntTy>() {
            // for `index` type, the width can be arbitrary in verification time
            if ty.width() != self.value.width() {
                return verify_error!(IncompatibleWidthErr(ty.width(), self.value.width())).into();
            }
        }
        Ok(())
    }
}

/// An float constant operation.
///
/// This will generate an float constant with the given value.
#[derive(Op, DataFlow, RegionInterface, ControlFlow, Parse, Print)]
#[mnemonic = "arith.fconst"]
#[verifiers(NumResults<1>, NumOperands<0>, NumRegions<0>, FloatLikeResults)]
#[format(pattern = "{value}", kind = "op", num_results = 1)]
pub struct FConstOp {
    #[metadata]
    metadata: OpMetadata,
    /// The result of the operation.
    #[result(0)]
    result: ArenaPtr<Value>,
    /// The value of the floating-point constant.
    value: f32,
}

#[derive(Debug, Error)]
#[error("expected a floating-point value {0}, but got {1}")]
pub struct IncompatibleValueErr(pub f32, pub f32);

impl Verify for FConstOp {
    fn verify(&self, ctx: &Context) -> orzir_core::VerifyResult<()> {
        self.run_verifiers(ctx)?;
        self.result.deref(&ctx.values).verify(ctx)?;
        let result_ty = self.result.deref(&ctx.values).ty(ctx).deref(&ctx.tys);
        if let Some(ty) = result_ty.as_a::<FloatTy>() {
            // Check if the type of the result matches the type of the constant value
            if ty.width() != 32 {
                return verify_error!(IncompatibleValueErr(32.0, self.value)).into();
            }
        }
        Ok(())
    }
}

/// An integer addition operation.
#[derive(Op, DataFlow, RegionInterface, ControlFlow, Parse, Print, Verify)]
#[mnemonic = "arith.iadd"]
#[verifiers(
    NumResults<1>, NumOperands<2>, NumRegions<0>,
    SameResultTys, SameOperandTys, SameOperandAndResultTys,
    IntegerLikeOperands, IntegerLikeResults,
)]
#[format(pattern = "{lhs}, {rhs}", kind = "op", num_results = 1)]
pub struct IAddOp {
    #[metadata]
    metadata: OpMetadata,
    /// The result of the operation.
    #[result(0)]
    result: ArenaPtr<Value>,
    /// The left-hand side operand.
    #[operand(0)]
    lhs: ArenaPtr<Value>,
    /// The right-hand side operand.
    #[operand(1)]
    rhs: ArenaPtr<Value>,
}

/// A float addition operation.
#[derive(Op, DataFlow, RegionInterface, ControlFlow, Parse, Print, Verify)]
#[mnemonic = "arith.fadd"]
#[verifiers(
    NumResults<1>, NumOperands<2>, NumRegions<0>,
    SameResultTys, SameOperandTys, SameOperandAndResultTys,
    FloatLikeOperands, FloatLikeResults,
)]
#[format(pattern = "{lhs}, {rhs}", kind = "op", num_results = 1)]
pub struct FAddOp {
    #[metadata]
    metadata: OpMetadata,
    /// The result of the operation.
    #[result(0)]
    result: ArenaPtr<Value>,
    /// The left-hand side operand.
    #[operand(0)]
    lhs: ArenaPtr<Value>,
    /// The right-hand side operand.
    #[operand(1)]
    rhs: ArenaPtr<Value>,
}

/// An integer subtraction operation.
#[derive(Op, DataFlow, RegionInterface, ControlFlow, Parse, Print, Verify)]
#[mnemonic = "arith.isub"]
#[verifiers(
    NumResults<1>, NumOperands<2>, NumRegions<0>,
    SameResultTys, SameOperandTys, SameOperandAndResultTys,
    IntegerLikeOperands, IntegerLikeResults,
)]
#[format(pattern = "{lhs}, {rhs}", kind = "op", num_results = 1)]
pub struct ISubOp {
    #[metadata]
    metadata: OpMetadata,
    /// The result of the operation.
    #[result(0)]
    result: ArenaPtr<Value>,
    /// The left-hand side operand.
    #[operand(0)]
    lhs: ArenaPtr<Value>,
    /// The right-hand side operand.
    #[operand(1)]
    rhs: ArenaPtr<Value>,
}

/// A float subtraction operation.
#[derive(Op, DataFlow, RegionInterface, ControlFlow, Parse, Print, Verify)]
#[mnemonic = "arith.fsub"]
#[verifiers(
    NumResults<1>, NumOperands<2>, NumRegions<0>,
    SameResultTys, SameOperandTys, SameOperandAndResultTys,
    FloatLikeOperands, FloatLikeResults,
)]
#[format(pattern = "{lhs}, {rhs}", kind = "op", num_results = 1)]
pub struct FSubOp {
    #[metadata]
    metadata: OpMetadata,
    /// The result of the operation.
    #[result(0)]
    result: ArenaPtr<Value>,
    /// The left-hand side operand.
    #[operand(0)]
    lhs: ArenaPtr<Value>,
    /// The right-hand side operand.
    #[operand(1)]
    rhs: ArenaPtr<Value>,
}

/// An integer multiplication operation.
#[derive(Op, DataFlow, RegionInterface, ControlFlow, Parse, Print, Verify)]
#[mnemonic = "arith.imul"]
#[verifiers(
    NumResults<1>, NumOperands<2>, NumRegions<0>,
    SameResultTys, SameOperandTys, SameOperandAndResultTys,
    IntegerLikeOperands, IntegerLikeResults,
)]
#[format(pattern = "{lhs}, {rhs}", kind = "op", num_results = 1)]
pub struct IMulOp {
    #[metadata]
    metadata: OpMetadata,
    /// The result of the operation.
    #[result(0)]
    result: ArenaPtr<Value>,
    /// The left-hand side operand.
    #[operand(0)]
    lhs: ArenaPtr<Value>,
    /// The right-hand side operand.
    #[operand(1)]
    rhs: ArenaPtr<Value>,
}

/// A float multiplication operation.
#[derive(Op, DataFlow, RegionInterface, ControlFlow, Parse, Print, Verify)]
#[mnemonic = "arith.fmul"]
#[verifiers(
    NumResults<1>, NumOperands<2>, NumRegions<0>,
    SameResultTys, SameOperandTys, SameOperandAndResultTys,
    FloatLikeOperands, FloatLikeResults,
)]
#[format(pattern = "{lhs}, {rhs}", kind = "op", num_results = 1)]
pub struct FMulOp {
    #[metadata]
    metadata: OpMetadata,
    /// The result of the operation.
    #[result(0)]
    result: ArenaPtr<Value>,
    /// The left-hand side operand.
    #[operand(0)]
    lhs: ArenaPtr<Value>,
    /// The right-hand side operand.
    #[operand(1)]
    rhs: ArenaPtr<Value>,
}

/// A unsigned int division operation
#[derive(Op, DataFlow, RegionInterface, ControlFlow, Parse, Print, Verify)]
#[mnemonic = "arith.udiv"]
#[verifiers(
    NumResults<1>, NumOperands<2>, NumRegions<0>,
    SameResultTys, SameOperandTys, SameOperandAndResultTys,
    IntegerLikeOperands, IntegerLikeResults,
)]
#[format(pattern = "{lhs}, {rhs}", kind = "op", num_results = 1)]
pub struct UDivOp {
    #[metadata]
    metadata: OpMetadata,
    /// The result of the operation.
    #[result(0)]
    result: ArenaPtr<Value>,
    /// The left-hand side operand.
    #[operand(0)]
    lhs: ArenaPtr<Value>,
    /// The right-hand side operand.
    #[operand(1)]
    rhs: ArenaPtr<Value>,
}

/// A signed int division operation
#[derive(Op, DataFlow, RegionInterface, ControlFlow, Parse, Print, Verify)]
#[mnemonic = "arith.sdiv"]
#[verifiers(
    NumResults<1>, NumOperands<2>, NumRegions<0>,
    SameResultTys, SameOperandTys, SameOperandAndResultTys,
    IntegerLikeOperands, IntegerLikeResults,
)]
#[format(pattern = "{lhs}, {rhs}", kind = "op", num_results = 1)]
pub struct SDivOp {
    #[metadata]
    metadata: OpMetadata,
    /// The result of the operation.
    #[result(0)]
    result: ArenaPtr<Value>,
    /// The left-hand side operand.
    #[operand(0)]
    lhs: ArenaPtr<Value>,
    /// The right-hand side operand.
    #[operand(1)]
    rhs: ArenaPtr<Value>,
}

/// A float division operation
#[derive(Op, DataFlow, RegionInterface, ControlFlow, Parse, Print, Verify)]
#[mnemonic = "arith.fdiv"]
#[verifiers(
    NumResults<1>, NumOperands<2>, NumRegions<0>,
    SameResultTys, SameOperandTys, SameOperandAndResultTys,
    FloatLikeOperands, FloatLikeResults,
)]
#[format(pattern = "{lhs}, {rhs}", kind = "op", num_results = 1)]
pub struct FDivOp {
    #[metadata]
    metadata: OpMetadata,
    /// The result of the operation.
    #[result(0)]
    result: ArenaPtr<Value>,
    /// The left-hand side operand.
    #[operand(0)]
    lhs: ArenaPtr<Value>,
    /// The right-hand side operand.
    #[operand(1)]
    rhs: ArenaPtr<Value>,
}

/// An integer and operation
#[derive(Op, DataFlow, RegionInterface, ControlFlow, Parse, Print, Verify)]
#[mnemonic = "arith.iand"]
#[verifiers(
    NumResults<1>, NumOperands<2>, NumRegions<0>,
    SameResultTys, SameOperandTys, SameOperandAndResultTys,
    IntegerLikeOperands, IntegerLikeResults
)]
#[format(pattern = "{lhs}, {rhs}", kind = "op", num_results = 1)]
pub struct IAndOp {
    #[metadata]
    metadata: OpMetadata,
    /// The result of the operation.
    #[result(0)]
    result: ArenaPtr<Value>,
    /// The left-hand side operand.
    #[operand(0)]
    lhs: ArenaPtr<Value>,
    /// The right-hand side operand.
    #[operand(1)]
    rhs: ArenaPtr<Value>,
}

/// An integer or operation
#[derive(Op, DataFlow, RegionInterface, ControlFlow, Parse, Print, Verify)]
#[mnemonic = "arith.ior"]
#[verifiers(
    NumResults<1>, NumOperands<2>, NumRegions<0>,
    SameResultTys, SameOperandTys, SameOperandAndResultTys,
    IntegerLikeOperands, IntegerLikeResults
)]
#[format(pattern = "{lhs}, {rhs}", kind = "op", num_results = 1)]
pub struct IOrOp {
    #[metadata]
    metadata: OpMetadata,
    /// The result of the operation.
    #[result(0)]
    result: ArenaPtr<Value>,
    /// The left-hand side operand.
    #[operand(0)]
    lhs: ArenaPtr<Value>,
    /// The right-hand side operand.
    #[operand(1)]
    rhs: ArenaPtr<Value>,
}

/// An integer xor operation
#[derive(Op, DataFlow, RegionInterface, ControlFlow, Parse, Print, Verify)]
#[mnemonic = "arith.ixor"]
#[verifiers(
    NumResults<1>, NumOperands<2>, NumRegions<0>,
    SameResultTys, SameOperandTys, SameOperandAndResultTys,
    IntegerLikeOperands, IntegerLikeResults
)]
#[format(pattern = "{lhs}, {rhs}", kind = "op", num_results = 1)]
pub struct IXorOp {
    #[metadata]
    metadata: OpMetadata,
    /// The result of the operation.
    #[result(0)]
    result: ArenaPtr<Value>,
    /// The left-hand side operand.
    #[operand(0)]
    lhs: ArenaPtr<Value>,
    /// The right-hand side operand.
    #[operand(1)]
    rhs: ArenaPtr<Value>,
}

/// Bitcast operation.
#[derive(Op, DataFlow, RegionInterface, ControlFlow, Parse, Print, Verify)]
#[mnemonic = "arith.bitcast"]
#[verifiers(
    NumResults<1>, NumOperands<1>, NumRegions<0>,
    SameResultTys, SameOperandTys
)]
#[format(pattern = "{operand}", kind = "op", num_results = 1)]
pub struct BitcastOp {
    #[metadata]
    metadata: OpMetadata,
    /// From value
    #[operand(0)]
    operand: ArenaPtr<Value>,
    /// To value
    ///
    /// The destination type is determined by the type of the result.
    #[result(0)]
    result: ArenaPtr<Value>,
}

/// The icmp predicate for comparison operations.
#[derive(Parse, Print)]
#[format(pattern = "{self}")]
pub enum ICmpPredicate {
    Equal,
    NotEqual,
    SignedLess,
    SignedLessEqual,
    SignedGreater,
    SignedGreaterEqual,
    UnsignedLess,
    UnsignedLessEqual,
    UnsignedGreater,
    UnsignedGreaterEqual,
}

impl fmt::Display for ICmpPredicate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            ICmpPredicate::Equal => "eq",
            ICmpPredicate::NotEqual => "ne",
            ICmpPredicate::SignedLess => "slt",
            ICmpPredicate::SignedLessEqual => "sle",
            ICmpPredicate::SignedGreater => "sgt",
            ICmpPredicate::SignedGreaterEqual => "sge",
            ICmpPredicate::UnsignedLess => "ult",
            ICmpPredicate::UnsignedLessEqual => "ule",
            ICmpPredicate::UnsignedGreater => "ugt",
            ICmpPredicate::UnsignedGreaterEqual => "uge",
        };

        write!(f, "{}", s)
    }
}

#[derive(Debug, Error)]
#[error("invalid icmp predicate: {0}")]
pub struct InvalidICmpPredicate(String);

impl TryFrom<&str> for ICmpPredicate {
    type Error = InvalidICmpPredicate;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "eq" => Ok(ICmpPredicate::Equal),
            "ne" => Ok(ICmpPredicate::NotEqual),
            "slt" => Ok(ICmpPredicate::SignedLess),
            "sle" => Ok(ICmpPredicate::SignedLessEqual),
            "sgt" => Ok(ICmpPredicate::SignedGreater),
            "sge" => Ok(ICmpPredicate::SignedGreaterEqual),
            "ult" => Ok(ICmpPredicate::UnsignedLess),
            "ule" => Ok(ICmpPredicate::UnsignedLessEqual),
            "ugt" => Ok(ICmpPredicate::UnsignedGreater),
            "uge" => Ok(ICmpPredicate::UnsignedGreaterEqual),
            _ => Err(InvalidICmpPredicate(value.to_string())),
        }
    }
}

/// An integer comparison operation
#[derive(Op, DataFlow, RegionInterface, ControlFlow, Parse, Print, Verify)]
#[mnemonic = "arith.icmp"]
#[verifiers(
    NumResults<1>, NumOperands<2>, NumRegions<0>,
    SameResultTys, SameOperandTys, IntegerLikeOperands,
    IntegerLikeResults
)]
#[format(pattern = "{pred} {lhs} , {rhs}", kind = "op", num_results = 1)]
pub struct ICmpOp {
    #[metadata]
    metadata: OpMetadata,
    /// The result of the operation.
    #[result(0)]
    result: ArenaPtr<Value>,
    /// The left-hand side operand.
    #[operand(0)]
    lhs: ArenaPtr<Value>,
    /// The right-hand side operand.
    #[operand(1)]
    rhs: ArenaPtr<Value>,
    /// The predicate for the comparison.
    pred: ICmpPredicate,
}

/// The fcmp predicate for comparison operations.
#[derive(Parse, Print)]
#[format(pattern = "{self}")]
pub enum FCmpPredicate {
    Oeq,
    Ogt,
    Oge,
    Olt,
    Ole,
    One,
    Ord,
    Ueq,
    Ugt,
    Uge,
    Ult,
    Ule,
    Une,
    Uno,
}

impl fmt::Display for FCmpPredicate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            FCmpPredicate::Oeq => "oeq",
            FCmpPredicate::Ogt => "ogt",
            FCmpPredicate::Oge => "oge",
            FCmpPredicate::Olt => "olt",
            FCmpPredicate::Ole => "ole",
            FCmpPredicate::One => "one",
            FCmpPredicate::Ord => "ord",
            FCmpPredicate::Ueq => "ueq",
            FCmpPredicate::Ugt => "ugt",
            FCmpPredicate::Uge => "uge",
            FCmpPredicate::Ult => "ult",
            FCmpPredicate::Ule => "ule",
            FCmpPredicate::Une => "une",
            FCmpPredicate::Uno => "uno",
        };

        write!(f, "{}", s)
    }
}

#[derive(Debug, Error)]
#[error("invalid fcmp predicate: {0}")]
pub struct InvalidFCmpPredicate(String);

impl TryFrom<&str> for FCmpPredicate {
    type Error = InvalidFCmpPredicate;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "oeq" => Ok(FCmpPredicate::Oeq),
            "ogt" => Ok(FCmpPredicate::Ogt),
            "oge" => Ok(FCmpPredicate::Oge),
            "olt" => Ok(FCmpPredicate::Olt),
            "ole" => Ok(FCmpPredicate::Ole),
            "one" => Ok(FCmpPredicate::One),
            "ord" => Ok(FCmpPredicate::Ord),
            "ueq" => Ok(FCmpPredicate::Ueq),
            "ugt" => Ok(FCmpPredicate::Ugt),
            "uge" => Ok(FCmpPredicate::Uge),
            "ult" => Ok(FCmpPredicate::Ult),
            "ule" => Ok(FCmpPredicate::Ule),
            "une" => Ok(FCmpPredicate::Une),
            "uno" => Ok(FCmpPredicate::Uno),
            _ => Err(InvalidFCmpPredicate(value.to_string())),
        }
    }
}

/// A floating-point comparison operation
#[derive(Op, DataFlow, RegionInterface, ControlFlow, Parse, Print, Verify)]
#[mnemonic = "arith.fcmp"]
#[verifiers(
    NumResults<1>, NumOperands<2>, NumRegions<0>,
    SameResultTys, SameOperandTys, FloatLikeOperands, IntegerLikeResults
)]
#[format(pattern = "{pred} {lhs} , {rhs}", kind = "op", num_results = 1)]
pub struct FCmpOp {
    #[metadata]
    metadata: OpMetadata,
    /// The result of the operation.
    #[result(0)]
    result: ArenaPtr<Value>,
    /// The left-hand side operand.
    #[operand(0)]
    lhs: ArenaPtr<Value>,
    /// The right-hand side operand.
    #[operand(1)]
    rhs: ArenaPtr<Value>,
    /// The predicate for the comparison.
    pred: FCmpPredicate,
}

/// A floating-point to signed integer operation
#[derive(Op, DataFlow, RegionInterface, ControlFlow, Parse, Print, Verify)]
#[mnemonic = "arith.fptosi"]
#[verifiers(
    NumResults<1>, NumOperands<1>, NumRegions<0>,
    SameResultTys, SameOperandTys, FloatLikeOperands, IntegerLikeResults
)]
#[format(pattern = "{operand}", kind = "op", num_results = 1)]
pub struct FPToSIOp {
    #[metadata]
    metadata: OpMetadata,
    /// The input value.
    #[operand(0)]
    operand: ArenaPtr<Value>,
    /// The result of the operation.
    #[result(0)]
    result: ArenaPtr<Value>,
}

/// A signed integer to floating-point operation
#[derive(Op, DataFlow, RegionInterface, ControlFlow, Parse, Print, Verify)]
#[mnemonic = "arith.sitofp"]
#[verifiers(
    NumResults<1>, NumOperands<1>, NumRegions<0>,
    SameResultTys, SameOperandTys, IntegerLikeOperands, FloatLikeResults
)]
#[format(pattern = "{operand}", kind = "op", num_results = 1)]
pub struct SIToFPOp {
    #[metadata]
    metadata: OpMetadata,
    /// The input value.
    #[operand(0)]
    operand: ArenaPtr<Value>,
    /// The result of the operation.
    #[result(0)]
    result: ArenaPtr<Value>,
}

/// Floating-point negation
#[derive(Op, DataFlow, RegionInterface, ControlFlow, Parse, Print, Verify)]
#[mnemonic = "arith.fneg"]
#[verifiers(
    NumResults<1>, NumOperands<1>, NumRegions<0>,
    FloatLikeOperands, FloatLikeResults
)]
#[format(pattern = "{operand}", kind = "op", num_results = 1)]
pub struct FNegOp {
    #[metadata]
    metadata: OpMetadata,
    /// The result of the operation.
    #[result(0)]
    result: ArenaPtr<Value>,
    /// The operand to negate.
    #[operand(0)]
    operand: ArenaPtr<Value>,
}

/// Register the `arith` dialect.
pub fn register(ctx: &mut Context) {
    let dialect = Dialect::new("arith".into());
    ctx.register_dialect(dialect);

    IConstOp::register(ctx, IConstOp::parse);
    FConstOp::register(ctx, FConstOp::parse);
    IAddOp::register(ctx, IAddOp::parse);
    FAddOp::register(ctx, FAddOp::parse);
    ISubOp::register(ctx, ISubOp::parse);
    FSubOp::register(ctx, FSubOp::parse);
    IMulOp::register(ctx, IMulOp::parse);
    FMulOp::register(ctx, FMulOp::parse);
    UDivOp::register(ctx, UDivOp::parse);
    SDivOp::register(ctx, SDivOp::parse);
    FDivOp::register(ctx, FDivOp::parse);
    IAndOp::register(ctx, IAndOp::parse);
    IOrOp::register(ctx, IOrOp::parse);
    IXorOp::register(ctx, IXorOp::parse);
    ICmpOp::register(ctx, ICmpOp::parse);
    FCmpOp::register(ctx, FCmpOp::parse);
    FNegOp::register(ctx, FNegOp::parse);
    FPToSIOp::register(ctx, FPToSIOp::parse);
    SIToFPOp::register(ctx, SIToFPOp::parse);
}

#[cfg(test)]
mod tests {
    use orzir_core::{
        Context,
        OpObj,
        Parse,
        ParseState,
        Print,
        PrintState,
        RegionInterface,
        TokenStream,
    };

    use crate::dialects::std::{builtin::ModuleOp, register_std_dialects};

    /// Test for int items(iconst, iadd, isub, imul)
    #[test]
    fn test_int_items() {
        let src = r#"
        module {
            func.func @intitem : fn () -> unit {
            ^entry:
                // nothing here
                %0 = arith.iconst true : int<1>
                %1 = arith.iconst false : int<1>
                %2 = arith.iadd %0, %1 : int<1>
                %3 = arith.isub %0, %1 : int<1>
                %aaaa = arith.iconst -0x123i32 : int<32>

                %b = arith.iconst 0b101i32 : int<32>
                %c = arith.iconst 0o123i32 : int<32>
                %d = arith.iconst 123i32 : int<32>
                %e = arith.iadd %b, %c : int<32>
                %f = arith.isub %c, %d : int<32>
                %k = arith.imul %e, %f : int<32>
                %x = arith.udiv %b, %c : int<32>
                %y = arith.sdiv %b, %c : int<32>
            }
        }
        "#;

        let stream = TokenStream::new(src);
        let mut state = ParseState::new(stream);
        let mut ctx = Context::default();

        register_std_dialects(&mut ctx);

        let op = OpObj::parse(&mut ctx, &mut state).unwrap();
        let mut state = PrintState::new("    ");
        op.deref(&ctx.ops).as_ref().verify(&ctx).unwrap();
        op.deref(&ctx.ops).print(&ctx, &mut state).unwrap();
        println!("{}", state.buffer);

        let module_op = op.deref(&ctx.ops).as_a::<ModuleOp>().unwrap();
        assert!(module_op
            .get_region(0)
            .unwrap()
            .deref(&ctx.regions)
            .lookup_symbol(&ctx, "intitem")
            .is_some());
    }

    /// Test for float items(fconst, fadd, fsub, fmul, fneg, fdiv)
    #[test]
    fn test_float_items() {
        let src = r#"
        module {
            func.func @floatitem : fn () -> float {
            ^entry:
                %0 = arith.fconst 1.0 : float
                %1 = arith.fconst 2.0 : float
                %2 = arith.fadd %0, %1 : float
                %3 = arith.fsub %0, %1 : float   
                %4 = arith.fmul %2, %3 : float
                %5 = arith.fneg %4 : float
                %6 = arith.fdiv %3, %4 : float
            }
        }
        "#;

        let stream = TokenStream::new(src);
        let mut state = ParseState::new(stream);
        let mut ctx = Context::default();

        register_std_dialects(&mut ctx);

        let op = OpObj::parse(&mut ctx, &mut state).unwrap();
        let mut state = PrintState::new("    ");
        op.deref(&ctx.ops).as_ref().verify(&ctx).unwrap();
        op.deref(&ctx.ops).print(&ctx, &mut state).unwrap();
        println!("{}", state.buffer);

        let module_op = op.deref(&ctx.ops).as_a::<ModuleOp>().unwrap();
        assert!(module_op
            .get_region(0)
            .unwrap()
            .deref(&ctx.regions)
            .lookup_symbol(&ctx, "floatitem")
            .is_some());
    }

    /// Test for cmp op(icmp, fcmp)
    #[test]
    fn test_cmp() {
        let src = r#"
        module {
            func.func @cmp : fn () -> int<1> {
            ^entry:
                %0 = arith.iconst 1i32 : int<32>
                %1 = arith.iconst 2i32 : int<32>
                %2 = arith.icmp slt %0, %1 : int<1>
                %a = arith.fconst 1.0 : float
                %b = arith.fconst 2.0 : float
                %c = arith.fcmp olt %a, %b : int<1>                
                func.return %2
            }
        }
        "#;

        let stream = TokenStream::new(src);
        let mut state = ParseState::new(stream);
        let mut ctx = Context::default();

        register_std_dialects(&mut ctx);

        let op = OpObj::parse(&mut ctx, &mut state).unwrap();
        let mut state = PrintState::new("    ");
        op.deref(&ctx.ops).as_ref().verify(&ctx).unwrap();
        op.deref(&ctx.ops).print(&ctx, &mut state).unwrap();
        println!("{}", state.buffer);

        let module_op = op.deref(&ctx.ops).as_a::<ModuleOp>().unwrap();
        assert!(module_op
            .get_region(0)
            .unwrap()
            .deref(&ctx.regions)
            .lookup_symbol(&ctx, "cmp")
            .is_some());
    }

    /// Test for bit items(iand, ior, ixor)
    #[test]
    fn test_bititem() {
        let src = r#"
        module {
            func.func @bititem : fn () -> int<32> {
            ^entry:
                %0 = arith.iconst 3i32 : int<32>
                %1 = arith.iconst 4i32 : int<32>
                %2 = arith.iand %0, %1 : int<32>
                %3 = arith.ior %0, %1 : int<32>
                %4 = arith.ixor %0, %1 : int<32>               
                func.return %2
            }
        }
        "#;

        let stream = TokenStream::new(src);
        let mut state = ParseState::new(stream);
        let mut ctx = Context::default();

        register_std_dialects(&mut ctx);

        let op = OpObj::parse(&mut ctx, &mut state).unwrap();
        let mut state = PrintState::new("    ");
        op.deref(&ctx.ops).as_ref().verify(&ctx).unwrap();
        op.deref(&ctx.ops).print(&ctx, &mut state).unwrap();
        println!("{}", state.buffer);

        let module_op = op.deref(&ctx.ops).as_a::<ModuleOp>().unwrap();
        assert!(module_op
            .get_region(0)
            .unwrap()
            .deref(&ctx.regions)
            .lookup_symbol(&ctx, "bititem")
            .is_some());
    }

    /// Test for type casting(fp2si, si2fp)
    #[test]
    fn test_tycast() {
        let src = r#"
        module {
            func.func @tycast : fn () -> int<32> {
            ^entry:
                %0 = arith.iconst 3i32 : int<32>
                %1 = arith.fconst 2.0 : float
                %2 = arith.fptosi %1 : int<32>
                %3 = arith.sitofp %0 : float
                func.return %0
            }
        }
        "#;

        let stream = TokenStream::new(src);
        let mut state = ParseState::new(stream);
        let mut ctx = Context::default();

        register_std_dialects(&mut ctx);

        let op = OpObj::parse(&mut ctx, &mut state).unwrap();
        let mut state = PrintState::new("    ");
        op.deref(&ctx.ops).as_ref().verify(&ctx).unwrap();
        op.deref(&ctx.ops).print(&ctx, &mut state).unwrap();
        println!("{}", state.buffer);

        let module_op = op.deref(&ctx.ops).as_a::<ModuleOp>().unwrap();
        assert!(module_op
            .get_region(0)
            .unwrap()
            .deref(&ctx.regions)
            .lookup_symbol(&ctx, "tycast")
            .is_some());
    }
}