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
//! [Rewriter] extends [Inserter] with more capabilities, such as replace and erase operations.

use std::vec;

use crate::{
    basic_block::BasicBlock,
    common_traits::Named,
    context::{Context, Ptr},
    graph::traversals::region::post_order,
    identifier::{Identifier, underscore},
    irbuild::{
        inserter::{BlockInsertionPoint, IRInserter, Inserter, OpInsertionPoint},
        listener::RewriteListener,
    },
    linked_list::{ContainsLinkedList, LinkedList},
    location::Located,
    op::Op,
    operation::Operation,
    region::Region,
    r#type::{TypeObj, Typed},
    value::Value,
};

/// Rewriter interface for transformations.
/// Use [DummyListener](super::listener::DummyListener) if no listener is needed.
pub trait Rewriter<L: RewriteListener>: Inserter<L> {
    type RewriterConfig: Clone;

    /// Replace an [Operation] (and delete it) with another operation.
    /// Results of the new operation must match the results of the old operation.
    fn replace_operation(&mut self, ctx: &mut Context, op: Ptr<Operation>, new_op: Ptr<Operation>);

    /// Replace an [Operation] (and delete it) with a list of values.
    /// Results of the new operation must match the list of values.
    fn replace_operation_with_values(
        &mut self,
        ctx: &mut Context,
        op: Ptr<Operation>,
        new_values: Vec<Value>,
    );

    /// Replace all uses of a [Value] with another value.
    fn replace_value_uses_with(&mut self, ctx: &Context, old_value: Value, new_value: Value);

    /// Erase an [Operation]. The operation must have no uses.
    fn erase_operation(&mut self, ctx: &mut Context, op: Ptr<Operation>);

    /// Erase a [BasicBlock]. The block must have no uses.
    fn erase_block(&mut self, ctx: &mut Context, block: Ptr<BasicBlock>);

    /// Erase a [Region]. Affects the index of all regions after it.
    fn erase_region(&mut self, ctx: &mut Context, region: Ptr<Region>);

    /// Unlink an [Operation] from its current position
    fn unlink_operation(&mut self, ctx: &Context, op: Ptr<Operation>);

    /// Unlink a [BasicBlock] from its current position
    fn unlink_block(&mut self, ctx: &Context, block: Ptr<BasicBlock>);

    /// Move an [Operation] to a new insertion point.
    fn move_operation(&mut self, ctx: &Context, op: Ptr<Operation>, new_point: OpInsertionPoint);

    /// Move a [BasicBlock] to a new insertion point.
    fn move_block(&mut self, ctx: &Context, block: Ptr<BasicBlock>, new_point: BlockInsertionPoint);

    /// Split a [BasicBlock] at the given position.
    fn split_block(
        &mut self,
        ctx: &mut Context,
        block: Ptr<BasicBlock>,
        position: OpInsertionPoint,
    ) -> Ptr<BasicBlock>;

    /// Inline a [Region] into another [Region] at the given insertion point.
    /// The source region will be empty after this operation. The caller must
    /// take care of transferring control flow and arguments as necessary.
    ///
    fn inline_region(
        &mut self,
        ctx: &Context,
        src_region: Ptr<Region>,
        dest_insertion_point: BlockInsertionPoint,
    );

    /// Change the type of a [Value].
    fn set_value_type(&mut self, ctx: &Context, value: Value, new_type: Ptr<TypeObj>);

    /// Has the IR been modified via this rewriter?
    fn is_modified(&self) -> bool;

    /// Set that the IR has been modified via this rewriter.
    fn set_modified(&mut self);

    /// Clear the modified flag.
    fn clear_modified(&mut self);

    /// Get the configuration for this rewriter.
    fn get_config(&self) -> &Self::RewriterConfig;

    /// Get a mutable reference to the configuration for this rewriter.
    fn get_config_mut(&mut self) -> &mut Self::RewriterConfig;
}

/// An implementation of the rewriter trait.
/// Use [DummyListener](super::listener::DummyListener) if no listener is needed.
pub struct IRRewriter<L: RewriteListener, I: Inserter<L> = IRInserter<L>> {
    inserter: I,
    modified: bool,
    config: IRRewriterConfig,
    _phantom: std::marker::PhantomData<L>,
}

impl<L: RewriteListener, I: Inserter<L>> Default for IRRewriter<L, I>
where
    I: Default,
{
    fn default() -> Self {
        Self {
            inserter: I::default(),
            modified: false,
            config: IRRewriterConfig::default(),
            _phantom: std::marker::PhantomData,
        }
    }
}

impl<L: RewriteListener, I: Inserter<L>> Inserter<L> for IRRewriter<L, I> {
    fn append_operation(&mut self, ctx: &Context, operation: Ptr<Operation>) {
        self.inserter.append_operation(ctx, operation)
    }

    fn append_op(&mut self, ctx: &Context, op: impl Op) {
        self.inserter.append_op(ctx, op)
    }

    fn insert_operation(&mut self, ctx: &Context, operation: Ptr<Operation>) {
        self.inserter.insert_operation(ctx, operation)
    }

    fn insert_op(&mut self, ctx: &Context, op: impl Op) {
        self.inserter.insert_op(ctx, op)
    }

    fn insert_block(
        &mut self,
        ctx: &Context,
        insertion_point: BlockInsertionPoint,
        block: Ptr<BasicBlock>,
    ) {
        self.inserter.insert_block(ctx, insertion_point, block)
    }

    fn create_block(
        &mut self,
        ctx: &mut Context,
        insertion_point: BlockInsertionPoint,
        label: Option<Identifier>,
        arg_types: Vec<Ptr<TypeObj>>,
    ) -> Ptr<BasicBlock> {
        self.inserter
            .create_block(ctx, insertion_point, label, arg_types)
    }

    fn get_insertion_point(&self) -> OpInsertionPoint {
        self.inserter.get_insertion_point()
    }

    fn get_insertion_block(&self, ctx: &Context) -> Option<Ptr<BasicBlock>> {
        self.inserter.get_insertion_block(ctx)
    }

    fn set_insertion_point(&mut self, point: OpInsertionPoint) {
        self.inserter.set_insertion_point(point)
    }

    fn set_listener(&mut self, listener: L) {
        self.inserter.set_listener(listener);
    }

    fn get_listener(&self) -> &L {
        self.inserter.get_listener()
    }

    fn get_listener_mut(&mut self) -> &mut L {
        self.inserter.get_listener_mut()
    }
}

/// Configuration for [IRRewriter].
#[derive(Clone)]
pub struct IRRewriterConfig {
    /// Whether to set the location of the new operation
    /// to the old operation when replacing an operation.
    pub set_loc_on_operation_replacement: bool,
}

impl Default for IRRewriterConfig {
    fn default() -> Self {
        Self {
            set_loc_on_operation_replacement: true,
        }
    }
}

impl<L: RewriteListener, I: Inserter<L>> Rewriter<L> for IRRewriter<L, I> {
    type RewriterConfig = IRRewriterConfig;

    fn replace_operation(&mut self, ctx: &mut Context, op: Ptr<Operation>, new_op: Ptr<Operation>) {
        if op != new_op && self.config.set_loc_on_operation_replacement {
            new_op.deref_mut(ctx).set_loc(op.deref(ctx).loc());
        }
        let new_values = new_op.deref(ctx).results().collect();
        self.replace_operation_with_values(ctx, op, new_values);
    }

    fn replace_operation_with_values(
        &mut self,
        ctx: &mut Context,
        op: Ptr<Operation>,
        new_values: Vec<Value>,
    ) {
        assert!(
            op.deref(ctx).get_num_results() == new_values.len(),
            "Replacement values must match the number of results of the original operation."
        );

        // We need to collect the results first to avoid `RefCell` borrowing issues.
        let results: Vec<_> = op.deref(ctx).results().zip(new_values).collect();
        for (res, new_res) in results {
            self.get_listener_mut()
                .notify_value_use_replacement(ctx, res, new_res);
            res.replace_all_uses_with(ctx, &new_res);
        }
        self.erase_operation(ctx, op);
        self.set_modified();
    }

    fn replace_value_uses_with(&mut self, ctx: &Context, old_value: Value, new_value: Value) {
        if old_value == new_value {
            return;
        }
        self.get_listener_mut()
            .notify_value_use_replacement(ctx, old_value, new_value);
        old_value.replace_all_uses_with(ctx, &new_value);
        self.set_modified();
    }

    fn erase_operation(&mut self, ctx: &mut Context, op: Ptr<Operation>) {
        // We don't rely on `Operation::erase` below to erase sub-entities
        // because we want the listener to be notified for each erased sub-entity.
        let regions = op.deref(ctx).regions().collect::<Vec<_>>();
        for region in regions.into_iter().rev() {
            self.erase_region(ctx, region);
        }

        self.get_listener_mut().notify_operation_erasure(ctx, op);

        Operation::erase(op, ctx);
        self.set_modified();
    }

    fn erase_block(&mut self, ctx: &mut Context, block: Ptr<BasicBlock>) {
        // We don't rely on `BasicBlock::erase` below to erase sub-entities
        // because we want the listener to be notified for each erased sub-entity.
        let operations = block.deref(ctx).iter(ctx).collect::<Vec<_>>();
        // We erase operations in reverse order so that uses are erased before defs.
        for op in operations.into_iter().rev() {
            self.erase_operation(ctx, op);
        }

        self.get_listener_mut().notify_block_erasure(ctx, block);

        BasicBlock::erase(block, ctx);
        self.set_modified();
    }

    fn erase_region(&mut self, ctx: &mut Context, region: Ptr<Region>) {
        // We don't rely on `Operation::erase_region` below to erase sub-entities
        // because we want the listener to be notified for each erased sub-entity.

        // We erase blocks in post-order so that uses are erased before defs.
        let blocks = post_order(ctx, &region);
        for block in blocks.iter().rev() {
            // We do not erase the block already because its predecessors
            // (which are its uses) haven't already been erased. We erase
            // only the operations now and the blocks later.
            let operations = block.deref(ctx).iter(ctx).collect::<Vec<_>>();
            // We erase operations in reverse order so that uses are erased before defs.
            for op in operations.into_iter().rev() {
                self.erase_operation(ctx, op);
            }
        }
        // Now erase the blocks.
        for block in blocks {
            self.erase_block(ctx, block);
        }

        self.get_listener_mut().notify_region_erasure(ctx, region);

        let index_in_parent = region.deref(ctx).find_index_in_parent(ctx);
        let parent_op = region.deref(ctx).get_parent_op();
        Operation::erase_region(parent_op, ctx, index_in_parent);
        self.set_modified();
    }

    fn unlink_operation(&mut self, ctx: &Context, op: Ptr<Operation>) {
        self.get_listener_mut().notify_operation_unlinking(ctx, op);
        op.unlink(ctx);
        self.set_modified();
    }

    fn unlink_block(&mut self, ctx: &Context, block: Ptr<BasicBlock>) {
        self.get_listener_mut().notify_block_unlinking(ctx, block);
        block.unlink(ctx);
        self.set_modified();
    }

    fn move_operation(&mut self, ctx: &Context, op: Ptr<Operation>, new_point: OpInsertionPoint) {
        self.unlink_operation(ctx, op);
        ScopedRewriter::new(self, new_point).insert_operation(ctx, op);
    }

    fn move_block(
        &mut self,
        ctx: &Context,
        block: Ptr<BasicBlock>,
        new_point: BlockInsertionPoint,
    ) {
        self.unlink_block(ctx, block);
        self.insert_block(ctx, new_point, block);
    }

    fn split_block(
        &mut self,
        ctx: &mut Context,
        block: Ptr<BasicBlock>,
        position: OpInsertionPoint,
    ) -> Ptr<BasicBlock> {
        // `create_block` below sets the insert point to the new block, so we save and restore it.
        let mut rewriter = ScopedRewriter::new(self, OpInsertionPoint::Unset);
        let label = block
            .deref(ctx)
            .given_name(ctx)
            .map(|label| label + underscore() + "split".try_into().unwrap());

        let new_block =
            rewriter.create_block(ctx, BlockInsertionPoint::AfterBlock(block), label, vec![]);
        let first_op_opt = match position {
            OpInsertionPoint::AtBlockStart(target_block) => {
                target_block.deref(ctx).iter(ctx).next()
            }
            OpInsertionPoint::AtBlockEnd(_target_block) => None,
            OpInsertionPoint::BeforeOperation(op) => Some(op),
            OpInsertionPoint::AfterOperation(op) => op.deref(ctx).get_next(),
            OpInsertionPoint::Unset => panic!("Cannot split block at unset insertion point."),
        };
        let mut current_op_opt = first_op_opt;
        while let Some(current_op) = current_op_opt {
            let next_op = current_op.deref(ctx).get_next();
            rewriter.move_operation(ctx, current_op, OpInsertionPoint::AtBlockEnd(new_block));
            current_op_opt = next_op;
        }
        new_block
    }

    fn inline_region(
        &mut self,
        ctx: &Context,
        src_region: Ptr<Region>,
        dest_insertion_point: BlockInsertionPoint,
    ) {
        assert!(
            src_region
                != dest_insertion_point
                    .get_insertion_region(ctx)
                    .expect("Insertion point itself is not in a Region"),
            "Cannot inline a region into itself."
        );
        let blocks: Vec<_> = src_region.deref(ctx).iter(ctx).collect();
        let mut insertion_pt = dest_insertion_point;
        for block in blocks {
            self.move_block(ctx, block, insertion_pt);
            insertion_pt = BlockInsertionPoint::AfterBlock(block);
        }
    }

    fn set_value_type(&mut self, ctx: &Context, value: Value, new_type: Ptr<TypeObj>) {
        let old_type = value.get_type(ctx);
        if old_type == new_type {
            return;
        }
        self.get_listener_mut()
            .notify_value_type_change(ctx, value, old_type, new_type);
        value.set_type(ctx, new_type);
        self.set_modified();
    }

    fn is_modified(&self) -> bool {
        self.modified
    }

    fn set_modified(&mut self) {
        self.modified = true;
    }

    fn clear_modified(&mut self) {
        self.modified = false;
    }

    fn get_config(&self) -> &Self::RewriterConfig {
        &self.config
    }

    fn get_config_mut(&mut self) -> &mut Self::RewriterConfig {
        &mut self.config
    }
}

/// A scoped rewriter that sets the insertion point and configuration for the duration of its lifetime.
/// On drop, it restores the previous insertion point and configuration.
/// Implements [Inserter] and [Rewriter] by forwarding calls to the wrapped rewriter.
/// ```rust
/// # use pliron::{context::Context,
/// #   builtin::{ops::ModuleOp, op_interfaces::SingleBlockRegionInterface}};
/// # use pliron::irbuild::{rewriter::{IRRewriter, ScopedRewriter},
/// #   listener::DummyListener,
/// #   inserter::{Inserter, OpInsertionPoint}};
/// let ctx = &mut Context::new();
/// let module = ModuleOp::new(ctx, "test_module".try_into().unwrap());
/// let mut rewriter = IRRewriter::<DummyListener>::default();
/// rewriter.set_insertion_point(OpInsertionPoint::AtBlockEnd(module.get_body(ctx, 0)));
/// {
///     // We can create a scoped rewriter with a different insertion point,
///     // and it will restore the original insertion point after this block.
///     let mut scoped_rewriter = ScopedRewriter::new(&mut rewriter, OpInsertionPoint::Unset);
///     assert!(!scoped_rewriter.get_insertion_point().is_set());
/// }
/// assert!(rewriter.get_insertion_point().is_set());
/// ```
pub struct ScopedRewriter<'a, L: RewriteListener, R: Rewriter<L>> {
    rewriter: &'a mut R,
    prev_insertion_point: OpInsertionPoint,
    prev_config: R::RewriterConfig,
    _phantom: std::marker::PhantomData<L>,
}

impl<'a, L: RewriteListener, R: Rewriter<L>> ScopedRewriter<'a, L, R> {
    pub fn new(rewriter: &'a mut R, insertion_point: OpInsertionPoint) -> Self {
        let prev_insertion_point = rewriter.get_insertion_point();
        let prev_config = rewriter.get_config().clone();
        rewriter.set_insertion_point(insertion_point);
        Self {
            rewriter,
            prev_insertion_point,
            prev_config,
            _phantom: std::marker::PhantomData,
        }
    }
}

impl<'a, L: RewriteListener, R: Rewriter<L>> Drop for ScopedRewriter<'a, L, R> {
    fn drop(&mut self) {
        self.rewriter.set_insertion_point(self.prev_insertion_point);
        *self.rewriter.get_config_mut() = self.prev_config.clone();
    }
}

impl<'a, L: RewriteListener, R: Rewriter<L>> Inserter<L> for ScopedRewriter<'a, L, R> {
    fn append_operation(&mut self, ctx: &Context, operation: Ptr<Operation>) {
        self.rewriter.append_operation(ctx, operation)
    }

    fn append_op(&mut self, ctx: &Context, op: impl Op) {
        self.rewriter.append_op(ctx, op)
    }

    fn insert_operation(&mut self, ctx: &Context, operation: Ptr<Operation>) {
        self.rewriter.insert_operation(ctx, operation)
    }

    fn insert_op(&mut self, ctx: &Context, op: impl Op) {
        self.rewriter.insert_op(ctx, op)
    }

    fn insert_block(
        &mut self,
        ctx: &Context,
        insertion_point: BlockInsertionPoint,
        block: Ptr<BasicBlock>,
    ) {
        self.rewriter.insert_block(ctx, insertion_point, block)
    }

    fn create_block(
        &mut self,
        ctx: &mut Context,
        insertion_point: BlockInsertionPoint,
        label: Option<Identifier>,
        arg_types: Vec<Ptr<TypeObj>>,
    ) -> Ptr<BasicBlock> {
        self.rewriter
            .create_block(ctx, insertion_point, label, arg_types)
    }

    fn get_insertion_point(&self) -> OpInsertionPoint {
        self.rewriter.get_insertion_point()
    }

    fn get_insertion_block(&self, ctx: &Context) -> Option<Ptr<BasicBlock>> {
        self.rewriter.get_insertion_block(ctx)
    }

    fn set_insertion_point(&mut self, point: OpInsertionPoint) {
        self.rewriter.set_insertion_point(point)
    }

    fn set_listener(&mut self, listener: L) {
        self.rewriter.set_listener(listener)
    }

    fn get_listener(&self) -> &L {
        self.rewriter.get_listener()
    }

    fn get_listener_mut(&mut self) -> &mut L {
        self.rewriter.get_listener_mut()
    }
}

impl<'a, L: RewriteListener, R: Rewriter<L>> Rewriter<L> for ScopedRewriter<'a, L, R> {
    type RewriterConfig = R::RewriterConfig;

    fn replace_operation(&mut self, ctx: &mut Context, op: Ptr<Operation>, new_op: Ptr<Operation>) {
        self.rewriter.replace_operation(ctx, op, new_op)
    }

    fn replace_operation_with_values(
        &mut self,
        ctx: &mut Context,
        op: Ptr<Operation>,
        new_values: Vec<Value>,
    ) {
        self.rewriter
            .replace_operation_with_values(ctx, op, new_values)
    }

    fn replace_value_uses_with(&mut self, ctx: &Context, old_value: Value, new_value: Value) {
        self.rewriter
            .replace_value_uses_with(ctx, old_value, new_value)
    }

    fn erase_operation(&mut self, ctx: &mut Context, op: Ptr<Operation>) {
        self.rewriter.erase_operation(ctx, op)
    }

    fn erase_block(&mut self, ctx: &mut Context, block: Ptr<BasicBlock>) {
        self.rewriter.erase_block(ctx, block)
    }

    fn erase_region(&mut self, ctx: &mut Context, region: Ptr<Region>) {
        self.rewriter.erase_region(ctx, region)
    }

    fn unlink_operation(&mut self, ctx: &Context, op: Ptr<Operation>) {
        self.rewriter.unlink_operation(ctx, op)
    }

    fn unlink_block(&mut self, ctx: &Context, block: Ptr<BasicBlock>) {
        self.rewriter.unlink_block(ctx, block)
    }

    fn move_operation(&mut self, ctx: &Context, op: Ptr<Operation>, new_point: OpInsertionPoint) {
        self.rewriter.move_operation(ctx, op, new_point)
    }

    fn move_block(
        &mut self,
        ctx: &Context,
        block: Ptr<BasicBlock>,
        new_point: BlockInsertionPoint,
    ) {
        self.rewriter.move_block(ctx, block, new_point)
    }

    fn split_block(
        &mut self,
        ctx: &mut Context,
        block: Ptr<BasicBlock>,
        position: OpInsertionPoint,
    ) -> Ptr<BasicBlock> {
        self.rewriter.split_block(ctx, block, position)
    }

    fn inline_region(
        &mut self,
        ctx: &Context,
        src_region: Ptr<Region>,
        dest_insertion_point: BlockInsertionPoint,
    ) {
        self.rewriter
            .inline_region(ctx, src_region, dest_insertion_point)
    }

    fn set_value_type(&mut self, ctx: &Context, value: Value, new_type: Ptr<TypeObj>) {
        self.rewriter.set_value_type(ctx, value, new_type)
    }

    fn is_modified(&self) -> bool {
        self.rewriter.is_modified()
    }

    fn set_modified(&mut self) {
        self.rewriter.set_modified()
    }

    fn clear_modified(&mut self) {
        self.rewriter.clear_modified()
    }

    fn get_config(&self) -> &Self::RewriterConfig {
        self.rewriter.get_config()
    }

    fn get_config_mut(&mut self) -> &mut Self::RewriterConfig {
        self.rewriter.get_config_mut()
    }
}