pliron 0.15.0

Programming Languages Intermediate RepresentatiON
Documentation
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
use pliron::derive::op_interface;
use rustc_hash::FxHashMap;
use thiserror::Error;

use crate::{
    basic_block::BasicBlock,
    builtin::{
        attributes::{OperandSegmentSizesAttr, TypeAttr},
        type_interfaces::FunctionTypeInterface,
    },
    context::{Context, Ptr},
    dict_key,
    graph::walkers::interruptible::{WalkResult, walk_advance, walk_break},
    identifier::Identifier,
    linked_list::ContainsLinkedList,
    location::{Located, Location},
    op::{Op, op_cast},
    operation::Operation,
    printable::Printable,
    region::Region,
    result::Result,
    symbol_table::{SymbolTableCollection, walk_symbol_table},
    r#type::{Type, TypeObj, Typed, type_impls},
    value::Value,
    verify_err, verify_error,
};

use super::attributes::IdentifierAttr;

/// An [Op] implementing this interface is a block terminator.
#[op_interface]
pub trait IsTerminatorInterface {
    fn verify(_op: &dyn Op, _ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        Ok(())
    }
}

#[derive(Error, Debug)]
pub enum BranchOpInterfaceVerifyErr {
    #[error("Branch Op is passing {provided} arguments, but target block expects {expected}")]
    SuccessorOperandsMismatch { provided: usize, expected: usize },
    #[error("Forwarded operand at {idx} is of type {forwarded}, but should've been {expected}")]
    SuccessorOperandTypeMismatch {
        idx: usize,
        forwarded: String,
        expected: String,
    },
}

/// This [terminator](IsTerminatorInterface) [Op] branches to
/// other [BasicBlock]s, possibly passing arguments to the target block.
///
/// This is similar to MLIR's
/// [BranchOpInterface](https://github.com/llvm/llvm-project/blob/b1f04d57f5818914d7db506985e2932f217844bd/mlir/include/mlir/Interfaces/ControlFlowInterfaces.td)
/// but is stricter: (1) Produced operands aren't supported, just forwarded.
/// (2) Type of the value passed is expected to be the same as the target block argument.
#[op_interface]
pub trait BranchOpInterface: IsTerminatorInterface {
    /// Get a list of [Value]s that are forwarded to the target block.
    fn successor_operands(&self, ctx: &Context, succ_idx: usize) -> Vec<Value>;

    /// Add a new operand to be forwarded to the given successor.
    /// The operand is appended after existing operands for the specified successor.
    /// Returns the index of the newly added operand among the operands forwarded to the successor.
    /// The returned index can be used to determine the corresponding target block argument index.
    /// Panics if `succ_idx` is invalid.
    fn add_successor_operand(&self, ctx: &mut Context, succ_idx: usize, operand: Value) -> usize;

    /// Remove and return the operand at `opd_idx` among the operands forwarded to successor `succ_idx`.
    /// Panics if `succ_idx` or `opd_idx` is invalid.
    fn remove_successor_operand(&self, ctx: &mut Context, succ_idx: usize, opd_idx: usize)
    -> Value;

    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let self_op = op_cast::<dyn BranchOpInterface>(op).unwrap();
        // Verify that the values passed to a target block
        // matches the arguments of that block.
        for (succ_idx, succ) in op.get_operation().deref(ctx).successors().enumerate() {
            let succ = &*succ.deref(ctx);
            let operands = self_op.successor_operands(ctx, succ_idx);
            if succ.get_num_arguments() != operands.len() {
                return verify_err!(
                    op.loc(ctx),
                    BranchOpInterfaceVerifyErr::SuccessorOperandsMismatch {
                        provided: operands.len(),
                        expected: succ.get_num_arguments()
                    }
                );
            }
            for (idx, operand) in operands.iter().enumerate() {
                let block_arg = succ.get_argument(idx);
                if operand.get_type(ctx) != block_arg.get_type(ctx) {
                    return verify_err!(
                        op.loc(ctx),
                        BranchOpInterfaceVerifyErr::SuccessorOperandTypeMismatch {
                            idx,
                            forwarded: operand.get_type(ctx).disp(ctx).to_string(),
                            expected: block_arg.get_type(ctx).disp(ctx).to_string(),
                        }
                    );
                }
            }
        }
        Ok(())
    }
}

dict_key!(
    /// Key for the `operand_segment_sizes` attribute.
    ATTR_KEY_OPERAND_SEGMENT_SIZES, "operand_segment_sizes"
);

#[derive(Error, Debug)]
/// Error returned when verifying an [OperandSegmentInterface] operation
pub enum OperandSegmentInterfaceVerifyErr {
    #[error("operand_segment_sizes attribute not found")]
    OperandSegmentSizesAttrErr,
    #[error("operand_segment_sizes total {0} does not match the number of operands {1}")]
    OperandSegmentSizesTotalMismatchErr(u32, u32),
}

/// In the case of variadic operands, sometimes it makes sense to group
/// contiguous operands together into a segment. This interface aids doing that.
/// MLIR achieves this by having ODS (tablegen)' `AttrSizedOperandSegments` generate
/// `getODSOperands()` based on the `operandSegmentSizes` attribute.
///
/// ### Attribute(s):
/// | Name | Static Name Identifier | Type |
/// |------|------------------------| -----|
/// | operand_segment_sizes | [ATTR_KEY_OPERAND_SEGMENT_SIZES] | [OperandSegmentSizesAttr](crate::builtin::attributes::OperandSegmentSizesAttr) |
#[op_interface]
pub trait OperandSegmentInterface {
    /// Given a list of segmented operands, compute the segment sizes and flatten the operands
    /// (ready for use in constructing an operation).
    /// Call `set_operand_segment_sizes` with the computed segment sizes to set the attribute.
    fn compute_segment_sizes(operands: Vec<Vec<Value>>) -> (Vec<Value>, OperandSegmentSizesAttr)
    where
        Self: Sized,
    {
        let sizes = operands
            .iter()
            .map(|seg| seg.len().try_into().unwrap())
            .collect::<Vec<_>>();
        let flat_operands = operands.into_iter().flatten().collect();

        let sizes_attr = OperandSegmentSizesAttr(sizes);
        (flat_operands, sizes_attr)
    }

    /// Get the `seg_idx`th segment of operands.
    fn get_segment(&self, ctx: &Context, seg_idx: usize) -> Vec<Value> {
        let sizes = self.get_operand_segment_sizes(ctx).0;
        if seg_idx >= sizes.len() {
            return vec![];
        }

        let self_op = self.get_operation().deref(ctx);
        let start = sizes[..seg_idx].iter().sum::<u32>() as usize;
        let len = sizes[seg_idx] as usize;
        self_op.operands().skip(start).take(len).collect()
    }

    /// Get the length of the `seg_idx`th segment.
    fn segment_size(&self, ctx: &Context, seg_idx: usize) -> u32 {
        let sizes = self.get_operand_segment_sizes(ctx).0;
        if seg_idx >= sizes.len() {
            return 0;
        }
        sizes[seg_idx]
    }

    /// Get the number of segments.
    fn num_segments(&self, ctx: &Context) -> usize {
        self.get_operand_segment_sizes(ctx).0.len()
    }

    /// Set the `operand_segment_sizes` attribute for this operation.
    fn set_operand_segment_sizes(&self, ctx: &Context, sizes: OperandSegmentSizesAttr) {
        let mut self_op = self.get_operation().deref_mut(ctx);
        self_op
            .attributes
            .set(ATTR_KEY_OPERAND_SEGMENT_SIZES.clone(), sizes);
    }

    /// Get the `operand_segment_sizes` attribute for this operation.
    fn get_operand_segment_sizes(&self, ctx: &Context) -> OperandSegmentSizesAttr {
        let self_op = self.get_operation().deref(ctx);
        self_op
            .attributes
            .get::<OperandSegmentSizesAttr>(&ATTR_KEY_OPERAND_SEGMENT_SIZES)
            .unwrap()
            .clone()
    }

    /// Push a new operand at the end of the `seg_idx`th segment.
    /// Returns the index of the inserted operand within that segment.
    fn push_to_segment(&self, ctx: &mut Context, seg_idx: usize, operand: Value) -> usize {
        let mut sizes = self.get_operand_segment_sizes(ctx).0;
        assert!(
            seg_idx < sizes.len(),
            "Segment index {seg_idx} out of bounds for {} segments",
            sizes.len()
        );

        let seg_opd_idx = sizes[seg_idx] as usize;
        let insert_idx = sizes[..=seg_idx].iter().sum::<u32>() as usize;
        Operation::insert_operand(self.get_operation(), ctx, insert_idx, operand);

        sizes[seg_idx] += 1;
        self.set_operand_segment_sizes(ctx, OperandSegmentSizesAttr(sizes));
        seg_opd_idx
    }

    /// Pop and return the last operand in the `seg_idx`th segment.
    fn pop_from_segment(&self, ctx: &mut Context, seg_idx: usize) -> Value {
        let mut sizes = self.get_operand_segment_sizes(ctx).0;
        assert!(
            seg_idx < sizes.len(),
            "Segment index {seg_idx} out of bounds for {} segments",
            sizes.len()
        );

        let segment_start = sizes[..seg_idx].iter().sum::<u32>() as usize;
        let segment_len = sizes[seg_idx] as usize;
        assert!(segment_len > 0, "Cannot pop from an empty segment");

        let remove_idx = segment_start + segment_len - 1;
        let removed = Operation::remove_operand(self.get_operation(), ctx, remove_idx);

        sizes[seg_idx] -= 1;
        self.set_operand_segment_sizes(ctx, OperandSegmentSizesAttr(sizes));
        removed
    }

    /// Insert an operand at `seg_opd_idx` within the `seg_idx`th segment.
    fn insert_into_segment(
        &self,
        ctx: &mut Context,
        seg_idx: usize,
        seg_opd_idx: usize,
        operand: Value,
    ) {
        let mut sizes = self.get_operand_segment_sizes(ctx).0;
        assert!(
            seg_idx < sizes.len(),
            "Segment index {seg_idx} out of bounds for {} segments",
            sizes.len()
        );

        let segment_start = sizes[..seg_idx].iter().sum::<u32>() as usize;
        let segment_len = sizes[seg_idx] as usize;
        assert!(
            seg_opd_idx <= segment_len,
            "Segment operand index {seg_opd_idx} out of bounds for insertion in segment of length {segment_len}"
        );

        let insert_idx = segment_start + seg_opd_idx;
        Operation::insert_operand(self.get_operation(), ctx, insert_idx, operand);

        sizes[seg_idx] += 1;
        self.set_operand_segment_sizes(ctx, OperandSegmentSizesAttr(sizes));
    }

    /// Remove and return the operand at `seg_opd_idx` in the `seg_idx`th segment.
    fn remove_from_segment(&self, ctx: &mut Context, seg_idx: usize, seg_opd_idx: usize) -> Value {
        let mut sizes = self.get_operand_segment_sizes(ctx).0;
        assert!(
            seg_idx < sizes.len(),
            "Segment index {seg_idx} out of bounds for {} segments",
            sizes.len()
        );

        let segment_start = sizes[..seg_idx].iter().sum::<u32>() as usize;
        let segment_len = sizes[seg_idx] as usize;
        assert!(
            seg_opd_idx < segment_len,
            "Segment operand index {seg_opd_idx} out of bounds for removal in segment of length {segment_len}"
        );

        let remove_idx = segment_start + seg_opd_idx;
        let removed = Operation::remove_operand(self.get_operation(), ctx, remove_idx);

        sizes[seg_idx] -= 1;
        self.set_operand_segment_sizes(ctx, OperandSegmentSizesAttr(sizes));
        removed
    }

    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let self_op = op.get_operation().deref(ctx);
        let Some(attr) = self_op
            .attributes
            .get::<OperandSegmentSizesAttr>(&ATTR_KEY_OPERAND_SEGMENT_SIZES)
        else {
            return verify_err!(
                self_op.loc(),
                OperandSegmentInterfaceVerifyErr::OperandSegmentSizesAttrErr
            );
        };

        let total = attr.0.iter().cloned().sum::<u32>();

        let num_operands: u32 = self_op.get_num_operands().try_into().unwrap();
        if total != num_operands {
            return verify_err!(
                self_op.loc(),
                OperandSegmentInterfaceVerifyErr::OperandSegmentSizesTotalMismatchErr(
                    total,
                    num_operands
                )
            );
        }

        Ok(())
    }
}

/// Describe the abstract semantics of [Regions](crate::region::Region).
///
/// See MLIR's [RegionKind](https://mlir.llvm.org/docs/Interfaces/#regionkindinterfaces).
pub enum RegionKind {
    /// Represents a graph region without control flow semantics.
    Graph,
    /// Represents an [SSA-style control](https://mlir.llvm.org/docs/LangRef/#control-flow-and-ssacfg-regions)
    /// flow region with basic blocks and reachability.
    SSACFG,
}

/// Info on contained [Regions](crate::region::Region).
#[op_interface]
pub trait RegionKindInterface {
    /// Return the kind of the region with the given index inside this operation.
    fn get_region_kind(&self, idx: usize) -> RegionKind;
    /// Return true if the region with the given index inside this operation
    /// must require dominance to hold.
    fn has_ssa_dominance(&self, idx: usize) -> bool {
        matches!(self.get_region_kind(idx), RegionKind::SSACFG)
    }

    fn verify(_op: &dyn Op, _ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        Ok(())
    }
}

#[derive(Error, Debug)]
#[error("Expected {} regions, found {}", .0, .1)]
pub struct NRegionsVerifyErr(usize, usize);

/// [Op]s that have a fixed number of regions.
#[op_interface]
pub trait NRegionsInterface<const N: usize> {
    /// Checks that the operation has exactly one region.
    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let self_op = op.get_operation().deref(ctx);
        if self_op.num_regions() != N {
            return verify_err!(self_op.loc(), NRegionsVerifyErr(N, self_op.num_regions()));
        }
        Ok(())
    }
}

/// [Op]s that have exactly one region.
#[op_interface]
pub trait OneRegionInterface: NRegionsInterface<1> {
    /// Get the single region that this [Op] has.
    fn get_region(&self, ctx: &Context) -> Ptr<Region> {
        self.get_operation().deref(ctx).get_region(0)
    }

    fn verify(_op: &dyn Op, _ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        Ok(())
    }
}

#[derive(Error, Debug)]
#[error("At most {0} regions expected, but found {1} regions")]
pub struct AtMostNRegionVerifyErr(usize, usize);

#[op_interface]
pub trait AtMostNRegionsInterface<const N: usize> {
    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let self_op = op.get_operation().deref(ctx);
        let n_regions = self_op.num_regions();
        if n_regions > N {
            return verify_err!(self_op.loc(), AtMostNRegionVerifyErr(N, n_regions));
        }
        Ok(())
    }
}

/// [Op]s that have at most one region.
#[op_interface]
pub trait AtMostOneRegionInterface: AtMostNRegionsInterface<1> {
    fn verify(_op: &dyn Op, _ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        Ok(())
    }

    fn get_region(&self, ctx: &Context) -> Option<Ptr<Region>> {
        let self_op = self.get_operation().deref(ctx);
        self_op.regions().next()
    }
}

#[derive(Error, Debug)]
#[error("Op {0} must only have regions with single block")]
pub struct SingleBlockRegionVerifyErr(String);

/// [Op]s with regions that have a single block.
#[op_interface]
pub trait SingleBlockRegionInterface {
    /// Get the single body block in `region_idx`.
    fn get_body(&self, ctx: &Context, region_idx: usize) -> Ptr<BasicBlock> {
        self.get_operation()
            .deref(ctx)
            .get_region(region_idx)
            .deref(ctx)
            .get_head()
            .expect("Expected SingleBlockRegion Op to contain a block")
    }

    /// Insert an operation at the end of the single block in `region_idx`.
    fn append_operation(&self, ctx: &mut Context, op: Ptr<Operation>, region_idx: usize) {
        op.insert_at_back(self.get_body(ctx, region_idx), ctx);
    }

    /// Checks that the operation has regions with single block.
    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let opr = op.get_operation();
        let self_op = opr.deref(ctx);
        for region in self_op.regions() {
            if region.deref(ctx).iter(ctx).count() != 1 {
                return verify_err!(
                    self_op.loc(),
                    SingleBlockRegionVerifyErr(Operation::get_opid(opr, ctx).to_string())
                );
            }
        }
        Ok(())
    }
}

/// [Op]s whose single-basic-block regions need not have a terminator.
#[op_interface]
pub trait NoTerminatorInterface: SingleBlockRegionInterface {
    fn verify(_op: &dyn Op, _ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        Ok(())
    }
}

dict_key!(
    /// Key for symbol name attribute when the operation defines a symbol.
    ATTR_KEY_SYM_NAME, "sym_name"
);

#[derive(Error, Debug)]
#[error("Op implementing SymbolOpInterface does not have a symbol defined")]
pub struct SymbolOpInterfaceErr;

/// [Op] that defines or declares a [symbol](https://mlir.llvm.org/docs/SymbolsAndSymbolTables/#symbol).
///
/// ### Attribute(s):
/// | Name | Static Name Identifier | Type |
/// |------|------------------------| -----|
/// | sym_name | [ATTR_KEY_SYM_NAME] | [IdentifierAttr](crate::builtin::attributes::IdentifierAttr) |
#[op_interface]
pub trait SymbolOpInterface {
    /// Get the name of the symbol defined by this operation.
    fn get_symbol_name(&self, ctx: &Context) -> Identifier {
        let self_op = self.get_operation().deref(ctx);
        let s_attr = self_op
            .attributes
            .get::<IdentifierAttr>(&ATTR_KEY_SYM_NAME)
            .unwrap();
        s_attr.clone().into()
    }

    /// Set a name for the symbol defined by this operation.
    fn set_symbol_name(&self, ctx: &mut Context, name: Identifier) {
        let name_attr = IdentifierAttr::new(name);
        let mut self_op = self.get_operation().deref_mut(ctx);
        self_op.attributes.set(ATTR_KEY_SYM_NAME.clone(), name_attr);
    }

    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let self_op = op.get_operation().deref(ctx);
        if self_op
            .attributes
            .get::<IdentifierAttr>(&ATTR_KEY_SYM_NAME)
            .is_none()
        {
            return verify_err!(op.loc(ctx), SymbolOpInterfaceErr);
        }
        Ok(())
    }
}

#[derive(Error, Debug)]
pub enum SymbolTableInterfaceErr {
    #[error("Multiple definitions of Symbol {0}")]
    SymbolRedefined(String),
}

// Any [Op] that holds a symbol table.
#[op_interface]
pub trait SymbolTableInterface: SingleBlockRegionInterface + OneRegionInterface {
    /// Lookup a symbol in this symbol table op. Linear search.
    fn lookup(&self, ctx: &Context, sym: &Identifier) -> Option<Ptr<Operation>> {
        for op in self.get_body(ctx, 0).deref(ctx).iter(ctx) {
            if let Some(sym_op) =
                op_cast::<dyn SymbolOpInterface>(Operation::get_op_dyn(op, ctx).as_ref())
                && &sym_op.get_symbol_name(ctx) == sym
            {
                return Some(op);
            }
        }
        None
    }

    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let op = op_cast::<dyn SymbolTableInterface>(op).unwrap();

        // Check that every symbol is defined only once.
        let mut seen = FxHashMap::<Identifier, Location>::default();
        let table_ops_block = op.get_body(ctx, 0);
        for op in table_ops_block.deref(ctx).iter(ctx) {
            if let Some(sym_op) =
                op_cast::<dyn SymbolOpInterface>(Operation::get_op_dyn(op, ctx).as_ref())
            {
                let sym = sym_op.get_symbol_name(ctx);
                if let Some(prev_loc) = seen.insert(sym.clone(), op.deref(ctx).loc()) {
                    return verify_err!(
                        op.deref(ctx).loc(),
                        verify_error!(
                            prev_loc,
                            SymbolTableInterfaceErr::SymbolRedefined(sym.to_string())
                        )
                    );
                }
            }
        }

        struct State {
            symbol_table_collection: SymbolTableCollection,
            res: Result<()>,
        }
        // Verify Ops inside that implement [SymbolUserOpInterface].
        fn callback(ctx: &Context, state: &mut State, op: Ptr<Operation>) -> WalkResult<()> {
            if let Some(sym_user_op) =
                op_cast::<dyn SymbolUserOpInterface>(Operation::get_op_dyn(op, ctx).as_ref())
                && let Err(err) =
                    sym_user_op.verify_symbol_uses(ctx, &mut state.symbol_table_collection)
            {
                state.res = Err(err);
                return walk_break(());
            }
            walk_advance()
        }

        let mut state = State {
            symbol_table_collection: SymbolTableCollection::new(),
            res: Ok(()),
        };
        walk_symbol_table(dyn_clone::clone_box(op), ctx, &mut state, callback);
        state.res
    }
}

#[op_interface]
pub trait SymbolUserOpInterface {
    /// Verify the symbol uses held by this operation. This is called when verifying
    /// a symbol table operation that (possibly transitively) contains this operation.
    fn verify_symbol_uses(
        &self,
        ctx: &Context,
        symbol_tables: &mut SymbolTableCollection,
    ) -> Result<()>;

    /// Returns the list of symbols used by this operation.
    fn used_symbols(&self, ctx: &Context) -> Vec<Identifier>;

    /// Nothing (by default) to verify for symbol users. Override if needed.
    fn verify(_op: &dyn Op, _ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        Ok(())
    }
}

#[derive(Error, Debug)]
#[error("Expected {0} results, but found {1} results")]
pub struct NResultsVerifyErr(pub usize, pub usize);

/// An [Op] having exactly N results.
#[op_interface]
pub trait NResultsInterface<const N: usize> {
    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let opr = op.get_operation();
        let op = &*opr.deref(ctx);
        if op.get_num_results() != N {
            return verify_err!(op.loc(), NResultsVerifyErr(N, op.get_num_results()));
        }
        Ok(())
    }
}

#[derive(Error, Debug)]
#[error("At most {0} results expected, but found {1} results")]
pub struct AtMostNResultsVerifyErr(usize, usize);

#[op_interface]
pub trait AtMostNResultsInterface<const N: usize> {
    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let self_op = op.get_operation().deref(ctx);
        let n_results = self_op.get_num_results();
        if n_results > N {
            return verify_err!(self_op.loc(), AtMostNResultsVerifyErr(N, n_results));
        }
        Ok(())
    }
}

#[op_interface]
pub trait OptionalResultInterface: AtMostNResultsInterface<1> {
    fn verify(_op: &dyn Op, _ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        Ok(())
    }

    /// Get the single result defined by this [Op], if any.
    fn get_result(&self, ctx: &Context) -> Option<Value> {
        let self_op = self.get_operation().deref(ctx);
        (self_op.get_num_results() == 1).then(|| self_op.get_result(0))
    }
}

#[derive(Error, Debug)]
#[error("Expected at least {0} results, but found {1} results")]
pub struct AtLeastNResultsVerifyErr(usize, usize);

/// An [Op] having at least N results.
#[op_interface]
pub trait AtLeastNResultsInterface<const N: usize> {
    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let self_op = op.get_operation().deref(ctx);
        let n_results = self_op.get_num_results();
        if n_results < N {
            return verify_err!(self_op.loc(), AtLeastNResultsVerifyErr(N, n_results));
        }
        Ok(())
    }
}

/// An [Op] having exactly one result.
#[op_interface]
pub trait OneResultInterface: NResultsInterface<1> {
    /// Get the single result defined by this [Op].
    fn get_result(&self, ctx: &Context) -> Value {
        self.get_operation().deref(ctx).get_result(0)
    }

    /// Get the type of the single result defined by this [Op].
    fn result_type(&self, ctx: &Context) -> Ptr<TypeObj> {
        self.get_operation().deref(ctx).get_type(0)
    }

    fn verify(_op: &dyn Op, _ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        Ok(())
    }
}

#[derive(Error, Debug)]
#[error("Expected {} operands, but found {}", .0, .1)]
pub struct NOpdsVerifyErr(pub usize, pub usize);

/// An [Op] having exactly N operands.
#[op_interface]
pub trait NOpdsInterface<const N: usize> {
    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let opr = op.get_operation();
        let op = &*opr.deref(ctx);
        if op.get_num_operands() != N {
            return verify_err!(op.loc(), NOpdsVerifyErr(N, op.get_num_operands()));
        }
        Ok(())
    }
}

#[derive(Error, Debug)]
#[error("At most {0} operands expected, but found {1} operands")]
pub struct AtMostNOpdsVerifyErr(usize, usize);

#[op_interface]
pub trait AtMostNOpdsInterface<const N: usize> {
    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let self_op = op.get_operation().deref(ctx);
        let n_operands = self_op.get_num_operands();
        if n_operands > N {
            return verify_err!(self_op.loc(), AtMostNOpdsVerifyErr(N, n_operands));
        }
        Ok(())
    }
}

#[op_interface]
pub trait OptionalOpdInterface: AtMostNOpdsInterface<1> {
    fn verify(_op: &dyn Op, _ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        Ok(())
    }

    fn get_operand(&self, ctx: &Context) -> Option<Value> {
        let self_op = self.get_operation().deref(ctx);
        (self_op.get_num_operands() == 1).then(|| self_op.get_operand(0))
    }
}

#[derive(Error, Debug)]
#[error("Expected at least {0} operands, but found {1} operands")]
pub struct AtLeastNOpdsVerifyErr(usize, usize);

/// An [Op] having at least N operands.
#[op_interface]
pub trait AtLeastNOpdsInterface<const N: usize> {
    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let self_op = op.get_operation().deref(ctx);
        let n_operands = self_op.get_num_operands();
        if n_operands < N {
            return verify_err!(self_op.loc(), AtLeastNOpdsVerifyErr(N, n_operands));
        }
        Ok(())
    }
}

/// An [Op] having exactly one operand.
#[op_interface]
pub trait OneOpdInterface: NOpdsInterface<1> {
    /// Get the single operand used by this [Op].
    fn get_operand(&self, ctx: &Context) -> Value {
        self.get_operation().deref(ctx).get_operand(0)
    }

    /// Get the type of the single operand used by this [Op].
    fn operand_type(&self, ctx: &Context) -> Ptr<TypeObj> {
        self.get_operand(ctx).get_type(ctx)
    }

    fn verify(_op: &dyn Op, _ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        Ok(())
    }
}

/// An [Op] whose regions's SSA names are isolated from above.
/// This is similar to (but not the same as) MLIR's
/// [IsolatedFromAbove](https://mlir.llvm.org/docs/Traits/#isolatedfromabove) trait.
/// Definition: all regions that are reachable / traversible in any
/// direction in the region hierarchy without passing an `IsolatedFromAbove`
/// barrier, share the same SSA name space.
/// i.e., a region that is not `IsolatedFromAbove` cannot have any SSA name
/// in common with that of any of its ancestors or siblings or cousins etc.
#[op_interface]
pub trait IsolatedFromAboveInterface {
    fn verify(_op: &dyn Op, _ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        Ok(())
    }
}

#[derive(Error, Debug)]
#[error("Op has different operand types")]
pub struct SameOperandsTypeVerifyErr;

/// An [Op] with at least one operand, and them all having the same type.
#[op_interface]
pub trait SameOperandsType: AtLeastNOpdsInterface<1> {
    /// Get the common type of the operands.
    fn operand_type(&self, ctx: &Context) -> Ptr<TypeObj> {
        self.get_operation().deref(ctx).get_operand(0).get_type(ctx)
    }

    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let op = op.get_operation().deref(ctx);

        let mut opds = op.operands();
        let ty = opds.next().unwrap().get_type(ctx);
        for opd in opds {
            if opd.get_type(ctx) != ty {
                return verify_err!(op.loc(), SameOperandsTypeVerifyErr);
            }
        }

        Ok(())
    }
}

#[derive(Error, Debug)]
#[error("Expected operand type {0}, but found {1}")]
pub struct AllOperandsOfTypeVerifyErr(String, String);

/// An [Op] with all operands having the specified type.
#[op_interface]
pub trait AllOperandsOfType<T: Type> {
    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let op = op.get_operation().deref(ctx);

        for opd in op.operands() {
            let opd_ty = &*opd.get_type(ctx).deref(ctx);
            if !opd_ty.as_any().is::<T>() {
                return verify_err!(
                    op.loc(),
                    AllOperandsOfTypeVerifyErr(
                        T::get_type_id_static().disp(ctx).to_string(),
                        opd_ty.disp(ctx).to_string()
                    )
                );
            }
        }

        Ok(())
    }
}

#[derive(Error, Debug)]
pub enum OperandNOfTypeError {
    #[error("Op has only {} operands, but expected at least {}", .0, .1)]
    NotEnoughOperands(usize, usize),
    #[error("Expected operand type {0}, but found {1}")]
    AllOperandsOfTypeVerifyErr(String, String),
}

/// An [Op] whose N-th operand (0-indexed) has the specified type.
#[op_interface]
pub trait OperandNOfType<const N: usize, T: Type> {
    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let op = op.get_operation().deref(ctx);
        if op.get_num_operands() <= N {
            return verify_err!(
                op.loc(),
                OperandNOfTypeError::NotEnoughOperands(op.get_num_operands(), N)
            );
        }
        let opd_n = op.get_operand(N);
        let opd_n_ty = &*opd_n.get_type(ctx).deref(ctx);
        if !opd_n_ty.as_any().is::<T>() {
            return verify_err!(
                op.loc(),
                OperandNOfTypeError::AllOperandsOfTypeVerifyErr(
                    T::get_type_id_static().disp(ctx).to_string(),
                    opd_n_ty.get_type_id().disp(ctx).to_string()
                )
            );
        }

        Ok(())
    }
}

#[derive(Error, Debug)]
#[error("Op has different result types")]
pub struct SameResultsTypeVerifyErr;

// An [Op] with at least one result, and them all having the same type.
#[op_interface]
pub trait SameResultsType: AtLeastNResultsInterface<1> {
    /// Get the common type of the results.
    fn result_type(&self, ctx: &Context) -> Ptr<TypeObj> {
        self.get_operation().deref(ctx).get_result(0).get_type(ctx)
    }

    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let op = op.get_operation().deref(ctx);

        let mut results = op.results();
        let ty = results.next().unwrap().get_type(ctx);
        for res in results {
            if res.get_type(ctx) != ty {
                return verify_err!(op.loc(), SameResultsTypeVerifyErr);
            }
        }
        Ok(())
    }
}

#[derive(Error, Debug)]
#[error("Expected result type {0}, but found {1}")]
pub struct AllResultsOfTypeVerifyErr(String, String);

/// An [Op] with all results having the specified type.
#[op_interface]
pub trait AllResultsOfType<T: Type> {
    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let op = op.get_operation().deref(ctx);
        for res in op.results() {
            let res_ty = &*res.get_type(ctx).deref(ctx);
            if !res_ty.as_any().is::<T>() {
                return verify_err!(
                    op.loc(),
                    AllResultsOfTypeVerifyErr(
                        T::get_type_id_static().disp(ctx).to_string(),
                        res_ty.disp(ctx).to_string()
                    )
                );
            }
        }
        Ok(())
    }
}

#[derive(Error, Debug)]
pub enum ResultNOfTypeError {
    #[error("Op has only {} results, but expected at least {}", .0, .1)]
    NotEnoughResults(usize, usize),
    #[error("Expected result type {0}, but found {1}")]
    AllResultsOfTypeVerifyErr(String, String),
}

/// An [Op] whose N-th result (0-indexed) has the specified type.
#[op_interface]
pub trait ResultNOfType<const N: usize, T: Type> {
    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let op = op.get_operation().deref(ctx);
        if op.get_num_results() <= N {
            return verify_err!(
                op.loc(),
                ResultNOfTypeError::NotEnoughResults(op.get_num_results(), N)
            );
        }
        let res_n = op.get_result(N);
        let res_n_ty = &*res_n.get_type(ctx).deref(ctx);
        if !res_n_ty.as_any().is::<T>() {
            return verify_err!(
                op.loc(),
                ResultNOfTypeError::AllResultsOfTypeVerifyErr(
                    T::get_type_id_static().disp(ctx).to_string(),
                    res_n_ty.get_type_id().disp(ctx).to_string()
                )
            );
        }
        Ok(())
    }
}

#[derive(Error, Debug)]
#[error("Op has different operand and result types")]
pub struct SameOperandsAndResultTypeVerifyErr;

/// An [Op] with at least one result and one operand, and them all having the same type.
/// See MLIR's [SameOperandsAndResultType](https://mlir.llvm.org/doxygen/classmlir_1_1OpTrait_1_1SameOperandsAndResultType.html).
#[op_interface]
pub trait SameOperandsAndResultType: SameOperandsType + SameResultsType {
    /// Get the common type of results / operands.
    fn get_type(&self, ctx: &Context) -> Ptr<TypeObj> {
        self.result_type(ctx)
    }

    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let res_ty = op_cast::<dyn SameResultsType>(op)
            .expect("Op must impl SameResultsType")
            .result_type(ctx);
        let opd_ty = op_cast::<dyn SameOperandsType>(op)
            .expect("Op must impl SameOperandsType")
            .operand_type(ctx);

        if res_ty != opd_ty {
            return verify_err!(op.loc(ctx), SameOperandsAndResultTypeVerifyErr);
        }

        Ok(())
    }
}

/// A callable object is either a
///   - direct callee, expressed as a symbol)
///   - indirect callee, a [Value] pointing to the function to be called.
#[derive(Clone)]
pub enum CallOpCallable {
    Direct(Identifier),
    Indirect(Value),
}

#[derive(Error, Debug)]
pub enum CallOpInterfaceErr {
    #[error("Callee type attribute not found")]
    CalleeTypeAttrNotFoundErr,
    #[error("Callee type attribute must impl FunctionTypeInterface")]
    CalleeTypeAttrIncorrectTypeErr,
}

dict_key!(ATTR_KEY_CALLEE_TYPE, "callee_type");

/// A call-like op: Transfers control from one function to another.
/// See MLIR's [CallOpInterface](https://mlir.llvm.org/docs/Interfaces/#callinterfaces).
///
/// ### Attribute(s):
///
/// | Name | Static Name Identifier | Type |
/// |------|------------------------| -----|
/// | callee_type | [ATTR_KEY_CALLEE_TYPE] | [TypeAttr](crate::builtin::attributes::TypeAttr) |
#[op_interface]
pub trait CallOpInterface {
    fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
    where
        Self: Sized,
    {
        let op = op.get_operation().deref(ctx);
        let Some(callee_type_attr) = op.attributes.get::<TypeAttr>(&ATTR_KEY_CALLEE_TYPE) else {
            return verify_err!(op.loc(), CallOpInterfaceErr::CalleeTypeAttrNotFoundErr);
        };
        if !type_impls::<dyn FunctionTypeInterface>(&**callee_type_attr.get_type(ctx).deref(ctx)) {
            return verify_err!(op.loc(), CallOpInterfaceErr::CalleeTypeAttrIncorrectTypeErr);
        }
        Ok(())
    }

    /// Get the function that this call op is calling
    ///   - A symbol if this is a direct call
    ///   - A value if this is an indirect call
    fn callee(&self, ctx: &Context) -> CallOpCallable;

    /// Get arguments passed to callee
    fn args(&self, ctx: &Context) -> Vec<Value>;

    /// Type of the callee
    fn callee_type(&self, ctx: &Context) -> Ptr<TypeObj> {
        let self_op = self.get_operation().deref(ctx);
        self_op
            .attributes
            .get::<TypeAttr>(&ATTR_KEY_CALLEE_TYPE)
            .unwrap()
            .get_type(ctx)
    }

    /// Set callee type
    fn set_callee_type(&self, ctx: &mut Context, callee_ty: Ptr<TypeObj>) {
        let mut self_op = self.get_operation().deref_mut(ctx);
        let ty_attr = TypeAttr::new(callee_ty);
        self_op
            .attributes
            .set(ATTR_KEY_CALLEE_TYPE.clone(), ty_attr);
    }
}