cmtir 0.1.2

The intermediate representation for Cement (cmt2) languages and compiler tools.
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
use std::collections::HashMap;

use super::*;

/// Rule signature in `cmtir`.
/// `always` rules have inputs and outputs
/// `method` rules have inputs, outputs, and side effect
#[derive(Debug, Clone, SExpr)]
pub enum RuleSignature {
  #[pp(surrounded)]
  Always {
    inputs: Vec<ValueId>,
    outputs: Vec<ValueId>,
  },
  Method {
    inputs: Vec<ValueId>,
    outputs: Vec<ValueId>,
    side_effect: Option<bool>,
  },
}

impl RuleSignature {
  /// Get all inputs of the rule.
  pub fn inputs(&self) -> impl Iterator<Item = ValueId> {
    match self {
      RuleSignature::Always { inputs, .. } => inputs.clone().into_iter(),
      RuleSignature::Method { inputs, .. } => inputs.clone().into_iter(),
    }
  }
  /// Get all inputs of the rule (mut).
  pub fn inputs_mut(&mut self) -> &mut Vec<ValueId> {
    match self {
      RuleSignature::Always { inputs, .. } => inputs,
      RuleSignature::Method { inputs, .. } => inputs,
    }
  }
  /// Get all outputs of the rule.
  pub fn outputs(&self) -> impl Iterator<Item = ValueId> {
    match self {
      RuleSignature::Always { outputs, .. } => outputs.clone().into_iter(),
      RuleSignature::Method { outputs, .. } => outputs.clone().into_iter(),
    }
  }
  /// Get all outputs of the rule (mut).
  pub fn outputs_mut(&mut self) -> &mut Vec<ValueId> {
    match self {
      RuleSignature::Always { outputs, .. } => outputs,
      RuleSignature::Method { outputs, .. } => outputs,
    }
  }

  pub fn is_method(&self) -> bool {
    matches!(self, RuleSignature::Method { .. })
  }
}

/// Rule timing in `cmtir`.
/// Currently, only single-cycle/FSM/pipeline rules are supported.
/// **multi-cycle rules are not supported yet.**
#[derive(Debug, Clone, SExpr)]
pub enum RuleTiming {
  #[pp(surrounded)]
  SingleCycle,
  MultiCycle {
    // Some(x) means latency-sensitive (x
    // cycles), None means latency-insensitive
    num_cycles: Option<u32>,
    intv: TimingIntv,
  },
  FSM,
  Pipeline,
}

impl RuleTiming {
  pub fn interval(&self) -> TimingIntv {
    match self {
      RuleTiming::SingleCycle => TimingIntv::none(),
      RuleTiming::MultiCycle {
        num_cycles: _,
        intv,
      } => intv.clone(),
      _ => unimplemented!(),
    }
  }
}

/// Rule in `cmtir`.
/// ((ext? <is_ext>) (private? <is_private>) rule "<name>" (<signature>)
/// (<timing>) <enable> <ready> (<guard_ops>) (<ops>)) <annotations>
#[derive(Debug, Clone, SExpr)]
pub struct Rule {
  #[pp(open)]
  #[pp(surrounded = "ext?")]
  pub is_ext: bool,
  #[pp(surrounded = "private?")]
  pub is_private: bool,
  #[pp(kw = "rule")]
  pub name: String,
  pub signature: RuleSignature,
  pub timing: RuleTiming,
  pub enable: Option<String>,
  pub ready: Option<String>,
  #[pp(list_ml)]
  pub guard_ops: Vec<Op>,
  #[pp(list_ml)]
  #[pp(close)]
  pub ops: Vec<Op>,
  pub annotations: json::object::Object,
}

impl Rule {
  /// Check if the rule is external.
  pub fn is_ext(&self) -> bool {
    self.is_ext
  }

  /// Check if the rule is private.
  pub fn is_private(&self) -> bool {
    self.is_private
  }

  /// Set the rule to private.
  pub fn set_private(&mut self, is_private: bool) {
    self.is_private = is_private;
  }

  /// Check if the rule is always.
  pub fn is_always(&self) -> bool {
    matches!(self.signature, RuleSignature::Always { .. })
  }

  /// Check if the rule is method.
  pub fn is_method(&self) -> bool {
    matches!(self.signature, RuleSignature::Method { .. })
  }

  /// Check if the rule has side effect.
  pub fn has_side_effect(&self) -> bool {
    matches!(self.signature, RuleSignature::Method { side_effect, .. } if side_effect.unwrap_or(false))
  }

  /// Set the rule to have side effect.
  pub fn set_side_effect(&mut self, se: bool) {
    if let RuleSignature::Method { side_effect, .. } = &mut self.signature {
      *side_effect = Some(se);
    }
  }

  /// Check if the rule is single-cycle.
  pub fn is_single_cycle(&self) -> bool {
    matches!(self.timing, RuleTiming::SingleCycle)
  }

  /// Get all guard operations of the rule.
  pub fn guard(&self) -> impl Iterator<Item = &Op> {
    self.guard_ops.iter()
  }

  /// Get all guard operations of the rule (mut).
  pub fn guard_mut(&mut self) -> impl Iterator<Item = &mut Op> {
    self.guard_ops.iter_mut()
  }

  /// Get all operations of the rule.
  pub fn ops(&self) -> impl Iterator<Item = &Op> {
    self.ops.iter()
  }

  /// Get all operations of the rule (mut).
  pub fn ops_mut(&mut self) -> impl Iterator<Item = &mut Op> {
    self.ops.iter_mut()
  }

  /// Get the name of the rule.
  pub fn name(&self) -> &str {
    &self.name
  }

  /// Create a new rule.
  pub fn new(name: String) -> Rule {
    Rule {
      is_ext: false,
      is_private: false,
      name,
      signature: RuleSignature::Always {
        inputs: vec![],
        outputs: vec![],
      },
      timing: RuleTiming::SingleCycle,
      guard_ops: vec![],
      ops: vec![],
      enable: None,
      ready: None,
      annotations: json::object::Object::new(),
    }
  }

  /// Create a new always rule.
  pub fn always(
    name: String,
    inputs: Vec<ValueId>,
    outputs: Vec<ValueId>,
    guard_ops: Vec<Op>,
    ops: Vec<Op>,
    timing: RuleTiming,
  ) -> Rule {
    Rule {
      is_ext: false,
      is_private: false,
      name,
      signature: RuleSignature::Always { inputs, outputs },
      guard_ops,
      timing,
      ops,
      enable: None,
      ready: None,
      annotations: json::object::Object::new(),
    }
  }

  /// Create a new method rule.
  pub fn method(
    name: String,
    inputs: Vec<ValueId>,
    outputs: Vec<ValueId>,
    side_effect: Option<bool>,
    guard_ops: Vec<Op>,
    ops: Vec<Op>,
    timing: RuleTiming,
  ) -> Rule {
    Rule {
      is_ext: false,
      is_private: false,
      name,
      signature: RuleSignature::Method {
        inputs,
        outputs,
        side_effect,
      },
      timing,
      guard_ops,
      ops,
      enable: None,
      ready: None,
      annotations: json::object::Object::new(),
    }
  }

  /// Create a new external rule.
  pub fn ext(
    name: String,
    inputs: Vec<ValueId>,
    outputs: Vec<ValueId>,
    enable: Option<String>,
    ready: Option<String>,
    side_effect: Option<bool>,
  ) -> Rule {
    Rule {
      is_ext: true,
      is_private: false,
      name,
      signature: RuleSignature::Method {
        inputs,
        outputs,
        side_effect,
      },
      guard_ops: vec![],
      timing: RuleTiming::SingleCycle,
      ops: vec![],
      enable,
      ready,
      annotations: json::object::Object::new(),
    }
  }

  /// Set the rule to private.
  pub fn to_be_private(self) -> Rule {
    Rule {
      is_private: true,
      ..self
    }
  }

  /// Get all spans of the rule from annotations.
  pub fn span(&self) -> impl Iterator<Item = MySpan> + '_ {
    self.annotations.iter().filter_map(|(k, v)| {
      if k.ends_with("span") {
        MySpan::from_json(v)
      } else {
        None
      }
    })
  }

  /// Get all inputs of the rule.
  pub fn inputs(&self) -> Vec<ValueId> {
    self.signature.inputs().collect()
  }

  /// Get all inputs of the rule (mut).
  pub fn inputs_mut(&mut self) -> &mut Vec<ValueId> {
    self.signature.inputs_mut()
  }

  /// Get all outputs of the rule.
  pub fn outputs(&self) -> Vec<ValueId> {
    self.signature.outputs().collect()
  }

  /// Get all outputs of the rule (mut).
  pub fn outputs_mut(&mut self) -> &mut Vec<ValueId> {
    self.signature.outputs_mut()
  }

  /// Get all return values of the rule.
  pub fn return_values(&self) -> Vec<ValueId> {
    // last op's outputs are the return values
    self
      .ops
      .last()
      .map(|op| op.outputs().collect())
      .unwrap_or_default()
  }

  /// Replace the guard operations of the rule.
  pub fn replace_guard_op(&mut self, index: usize, new_ops: Vec<Op>) {
    if index < self.guard_ops.len() {
      self.guard_ops.splice(index..=index, new_ops);
    } else {
      panic!("Index out of bounds for guard_ops");
    }
  }

  /// Replace the operations of the rule.
  pub fn replace_op(&mut self, index: usize, new_ops: Vec<Op>) {
    if index < self.ops.len() {
      self.ops.splice(index + 1..=index + 1, new_ops);
    } else {
      panic!("Index out of bounds for ops");
    }
  }

  /// Replace all operations of the rule with the given map.
  pub fn replace_all_op_with_map(
    &mut self,
    replacements: &HashMap<ir::ValueId, ir::ValueId>,
  ) {
    for op in self.guard_mut() {
      op.replace_value_with_map(replacements);
    }

    for op in self.ops_mut() {
      op.replace_value_with_map(replacements);
    }
  }

  /// Remove unused operations from the rule.
  pub fn remove_unused_op(&mut self) {
    let mut indices_to_remove = vec![];

    for (index, op) in self.guard_mut().enumerate() {
      if let OpEnum::Assign(AssignOp { res, value }) = op.inner_mut() {
        if res == value {
          indices_to_remove.push(index);
        }
      } else {
        op.remove_unused_op();
      }
    }

    indices_to_remove.sort_unstable_by(|a, b| b.cmp(a));
    for &index in &indices_to_remove {
      self.guard_ops.remove(index);
    }

    indices_to_remove.clear();

    for (index, op) in self.ops_mut().enumerate() {
      if let OpEnum::Assign(AssignOp { res, value }) = op.inner_mut() {
        if res == value {
          indices_to_remove.push(index);
        }
      } else {
        op.remove_unused_op();
      }
    }

    indices_to_remove.sort_unstable_by(|a, b| b.cmp(a));

    for &index in &indices_to_remove {
      self.ops.remove(index);
    }
  }
}

/// Rule relation in `cmtir`.
/// `Method` relations specify constraints on the method rules, including
/// C(conflict), CF(conflict-free), SA(sequence-ahead), and SB(sequence-behind).
/// `Schedule` relations specify the order of the rules for execution.
#[derive(Debug, Clone, SExpr)]
pub enum RuleRel {
  #[pp(surrounded)]
  Method {
    rel: MethodRel,
    lhs: Vec<InstRule>,
    rhs: Vec<InstRule>,
  },
  Schedule(Vec<InstRule>),
}

impl RuleRel {
  /// Create a new method relation.
  pub fn method(
    rel: MethodRel,
    lhs: Vec<InstRule>,
    rhs: Vec<InstRule>,
  ) -> RuleRel {
    RuleRel::Method { rel, lhs, rhs }
  }

  /// Create a new schedule relation.
  pub fn schedule(inst_rules: Vec<InstRule>) -> RuleRel {
    RuleRel::Schedule(inst_rules)
  }
}