lift-core 0.4.8

LIFT compiler framework core: unified SSA intermediate representation (IR) for AI and quantum — types, values, operations, blocks, regions, verifier
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
use crate::blocks::BlockKey;
use crate::context::Context;
use crate::dialect::DialectRegistry;
use crate::operations::OpKey;
use crate::values::ValueKey;
use std::collections::HashSet;
use thiserror::Error;

#[derive(Debug, Error)]
pub enum VerifyError {
    #[error("SSA violation: value {0:?} used but not defined")]
    UndefinedValue(ValueKey),

    #[error("SSA violation: value {0:?} defined more than once")]
    MultipleDefinition(ValueKey),

    #[error("Dominance violation: value {0:?} used before definition in block {1:?}")]
    DominanceViolation(ValueKey, BlockKey),

    #[error("Type mismatch in operation {op:?}: expected {expected}, got {actual}")]
    TypeMismatch {
        op: OpKey,
        expected: String,
        actual: String,
    },

    #[error("Linearity violation: qubit value {0:?} consumed more than once")]
    LinearityViolation(ValueKey),

    #[error("Linearity violation: qubit {0:?} not consumed (leaked)")]
    QubitLeaked(ValueKey),

    #[error("Branch linearity: arms consume different qubit sets at block {0:?}")]
    BranchLinearityMismatch(BlockKey),

    #[error("Dangling reference: {0}")]
    DanglingReference(String),

    #[error("Empty block {0:?} has no terminator")]
    MissingTerminator(BlockKey),

    #[error("Operation {0:?} has no parent block")]
    OrphanedOperation(OpKey),

    #[error("Block {0:?} has no parent region")]
    OrphanedBlock(BlockKey),

    #[error("Invalid operation: {0}")]
    InvalidOperation(String),

    #[error("Semantic error in operation {op:?}: {message}")]
    SemanticError { op: OpKey, message: String },
}

pub struct Verifier<'a> {
    ctx: &'a Context,
    errors: Vec<VerifyError>,
    defined: HashSet<ValueKey>,
    consumed_qubits: HashSet<ValueKey>,
}

impl<'a> Verifier<'a> {
    pub fn new(ctx: &'a Context) -> Self {
        Self {
            ctx,
            errors: Vec::new(),
            defined: HashSet::new(),
            consumed_qubits: HashSet::new(),
        }
    }

    pub fn verify_all(&mut self) -> Result<(), Vec<VerifyError>> {
        self.verify_ssa();
        self.verify_dominance();
        self.verify_well_formedness();
        self.verify_linearity();

        if self.errors.is_empty() {
            Ok(())
        } else {
            Err(std::mem::take(&mut self.errors))
        }
    }

    /// Runs SSA, well-formedness, linearity, and semantic (dialect) checks.
    pub fn verify_all_with_dialects(
        &mut self,
        registry: &DialectRegistry,
    ) -> Result<(), Vec<VerifyError>> {
        self.verify_ssa();
        self.verify_dominance();
        self.verify_well_formedness();
        self.verify_linearity();
        self.verify_semantics(registry);

        if self.errors.is_empty() {
            Ok(())
        } else {
            Err(std::mem::take(&mut self.errors))
        }
    }

    /// Validates each operation against its dialect's signature: the number of
    /// inputs/results and, where the dialect provides it, type compatibility.
    fn verify_semantics(&mut self, registry: &DialectRegistry) {
        for (op_key, op) in &self.ctx.ops {
            let dialect_name = self.ctx.strings.resolve(op.dialect);
            let op_name = self.ctx.strings.resolve(op.name);

            let dialect = match registry.get(dialect_name) {
                Some(d) => d,
                None => {
                    // Unknown dialect: skip semantic checks (core ops are
                    // validated by the core dialect when registered).
                    continue;
                }
            };

            if let Err(msg) = dialect.verify_op(op_name, op.inputs.len(), op.results.len()) {
                self.errors.push(VerifyError::SemanticError {
                    op: op_key,
                    message: msg,
                });
            }
        }
    }

    fn verify_ssa(&mut self) {
        let mut all_defined: HashSet<ValueKey> = HashSet::new();

        // Collect all defined values from block args
        for (block_key, block) in &self.ctx.blocks {
            for &arg_key in &block.args {
                if !all_defined.insert(arg_key) {
                    self.errors.push(VerifyError::MultipleDefinition(arg_key));
                }
            }
            let _ = block_key;
        }

        // Collect all defined values from operation results
        for (_op_key, op) in &self.ctx.ops {
            for &result_key in &op.results {
                if !all_defined.insert(result_key) {
                    self.errors
                        .push(VerifyError::MultipleDefinition(result_key));
                }
            }
        }

        // Verify all uses are defined
        for (_op_key, op) in &self.ctx.ops {
            for &input_key in &op.inputs {
                if !all_defined.contains(&input_key) {
                    self.errors.push(VerifyError::UndefinedValue(input_key));
                }
            }
        }

        self.defined = all_defined;
    }

    /// Checks that every op's inputs are defined before that op runs, within
    /// its own block's program order (block args count as defined from the
    /// start). `verify_ssa` only checks that a used value is defined
    /// *somewhere* in the whole context, with no ordering — accepting a
    /// value consumed by an op that appears before the op that defines it.
    ///
    /// Only values this same block itself defines (its own args, or results
    /// of its own ops) are checked for ordering here: a value owned by a
    /// different block is left to `verify_ssa`'s existence check. Every
    /// function body today is a single block (no branches yet), so that
    /// scope limit does not miss anything reachable in practice, and it
    /// avoids false positives if a future multi-block construct legitimately
    /// threads a value in from an enclosing scope.
    fn verify_dominance(&mut self) {
        use std::collections::HashMap;

        let mut owner_block: HashMap<ValueKey, BlockKey> = HashMap::new();
        for (block_key, block) in &self.ctx.blocks {
            for &arg in &block.args {
                owner_block.insert(arg, block_key);
            }
            for &op_key in &block.ops {
                if let Some(op) = self.ctx.ops.get(op_key) {
                    for &result in &op.results {
                        owner_block.insert(result, block_key);
                    }
                }
            }
        }

        for (block_key, block) in &self.ctx.blocks {
            let mut visible: HashSet<ValueKey> = block.args.iter().copied().collect();
            for &op_key in &block.ops {
                let Some(op) = self.ctx.ops.get(op_key) else {
                    continue;
                };
                for &input in &op.inputs {
                    if owner_block.get(&input) == Some(&block_key) && !visible.contains(&input) {
                        self.errors
                            .push(VerifyError::DominanceViolation(input, block_key));
                    }
                }
                for &result in &op.results {
                    visible.insert(result);
                }
            }
        }
    }

    fn verify_well_formedness(&mut self) {
        // Verify all operation inputs reference valid values
        for (op_key, op) in &self.ctx.ops {
            for &input in &op.inputs {
                if !self.ctx.values.contains_key(input) {
                    self.errors.push(VerifyError::DanglingReference(format!(
                        "Operation {:?} references non-existent value {:?}",
                        op_key, input
                    )));
                }
            }
            for &result in &op.results {
                if !self.ctx.values.contains_key(result) {
                    self.errors.push(VerifyError::DanglingReference(format!(
                        "Operation {:?} references non-existent result {:?}",
                        op_key, result
                    )));
                }
            }
            for &region in &op.regions {
                if !self.ctx.regions.contains_key(region) {
                    self.errors.push(VerifyError::DanglingReference(format!(
                        "Operation {:?} references non-existent region {:?}",
                        op_key, region
                    )));
                }
            }
        }

        // Verify blocks reference valid operations
        for (block_key, block) in &self.ctx.blocks {
            for &op in &block.ops {
                if !self.ctx.ops.contains_key(op) {
                    self.errors.push(VerifyError::DanglingReference(format!(
                        "Block {:?} references non-existent operation {:?}",
                        block_key, op
                    )));
                }
            }
        }

        // Verify regions reference valid blocks
        for (region_key, region) in &self.ctx.regions {
            for &block in &region.blocks {
                if !self.ctx.blocks.contains_key(block) {
                    self.errors.push(VerifyError::DanglingReference(format!(
                        "Region {:?} references non-existent block {:?}",
                        region_key, block
                    )));
                }
            }
        }
    }

    fn verify_linearity(&mut self) {
        let mut consumed: HashSet<ValueKey> = HashSet::new();
        let mut all_qubits: HashSet<ValueKey> = HashSet::new();

        // Identify all qubit values
        for (val_key, val) in &self.ctx.values {
            if self.ctx.is_qubit_type(val.ty) {
                all_qubits.insert(val_key);
            }
        }

        // Check each operation's inputs for qubit consumption
        for (_op_key, op) in &self.ctx.ops {
            let op_name = self.ctx.strings.resolve(op.name);

            for &input in &op.inputs {
                if let Some(val) = self.ctx.values.get(input) {
                    if self.ctx.is_qubit_type(val.ty) && !consumed.insert(input) {
                        self.errors.push(VerifyError::LinearityViolation(input));
                    }
                }
            }

            // quantum.measure and quantum.reset consume the qubit
            // All gate operations produce new qubit values (SSA)
            if op_name == "quantum.measure" {
                // Qubit is consumed, classical bit produced — no new qubit
            }
        }

        self.consumed_qubits = consumed;
    }

    pub fn errors(&self) -> &[VerifyError] {
        &self.errors
    }
}

pub fn verify(ctx: &Context) -> Result<(), Vec<VerifyError>> {
    let mut verifier = Verifier::new(ctx);
    verifier.verify_all()
}

/// Verifies a context including dialect-level semantic checks.
pub fn verify_with_dialects(
    ctx: &Context,
    registry: &DialectRegistry,
) -> Result<(), Vec<VerifyError>> {
    let mut verifier = Verifier::new(ctx);
    verifier.verify_all_with_dialects(registry)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_empty_context_verifies() {
        let ctx = Context::new();
        assert!(verify(&ctx).is_ok());
    }

    #[test]
    fn test_simple_ssa_valid() {
        let mut ctx = Context::new();
        let f32_ty = ctx.make_float_type(32);

        let block = ctx.create_block();
        let arg = ctx.create_block_arg(block, f32_ty);

        let (op, _results) = ctx.create_op(
            "tensor.relu",
            "tensor",
            vec![arg],
            vec![f32_ty],
            crate::attributes::Attributes::new(),
            crate::location::Location::unknown(),
        );
        ctx.add_op_to_block(block, op);

        assert!(verify(&ctx).is_ok());
    }

    /// Regression test: an op consuming a value produced by a *later* op in
    /// the same block (use-before-def / a textbook dominance violation) used
    /// to verify successfully — `verify_ssa` only checked that the value
    /// existed somewhere in the context, never that it was defined before
    /// its use.
    #[test]
    fn test_use_before_def_is_a_dominance_violation() {
        let mut ctx = Context::new();
        let f32_ty = ctx.make_float_type(32);
        let block = ctx.create_block();
        let arg = ctx.create_block_arg(block, f32_ty);

        // Create the op that DEFINES `later_result` first (in slotmap/build
        // order), but only add it to the block AFTER the op that uses it —
        // so in block.ops program order, the use comes before the def.
        let (producer, producer_results) = ctx.create_op(
            "tensor.relu",
            "tensor",
            vec![arg],
            vec![f32_ty],
            crate::attributes::Attributes::new(),
            crate::location::Location::unknown(),
        );
        let (consumer, _) = ctx.create_op(
            "tensor.relu",
            "tensor",
            vec![producer_results[0]],
            vec![f32_ty],
            crate::attributes::Attributes::new(),
            crate::location::Location::unknown(),
        );

        // Program order: consumer, then producer — consumer's input is not
        // yet defined at that point in the block.
        ctx.add_op_to_block(block, consumer);
        ctx.add_op_to_block(block, producer);

        let result = verify(&ctx);
        assert!(result.is_err(), "use-before-def must fail verification");
        let errors = result.unwrap_err();
        assert!(
            errors
                .iter()
                .any(|e| matches!(e, VerifyError::DominanceViolation(_, _))),
            "{:?}",
            errors
        );
    }

    #[test]
    fn test_qubit_linearity_violation() {
        let mut ctx = Context::new();
        let qubit_ty = ctx.make_qubit_type();

        let block = ctx.create_block();
        let q0 = ctx.create_block_arg(block, qubit_ty);

        // First use of q0 — ok
        let (op1, _) = ctx.create_op(
            "quantum.x",
            "quantum",
            vec![q0],
            vec![qubit_ty],
            crate::attributes::Attributes::new(),
            crate::location::Location::unknown(),
        );
        ctx.add_op_to_block(block, op1);

        // Second use of q0 — linearity violation!
        let (op2, _) = ctx.create_op(
            "quantum.h",
            "quantum",
            vec![q0],
            vec![qubit_ty],
            crate::attributes::Attributes::new(),
            crate::location::Location::unknown(),
        );
        ctx.add_op_to_block(block, op2);

        let result = verify(&ctx);
        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert!(errors
            .iter()
            .any(|e| matches!(e, VerifyError::LinearityViolation(_))));
    }

    #[test]
    fn test_semantic_verification_detects_wrong_input_count() {
        use crate::dialect::Dialect;

        #[derive(Debug)]
        struct FakeTensorDialect;
        impl Dialect for FakeTensorDialect {
            fn name(&self) -> &str {
                "tensor"
            }
            fn verify_op(
                &self,
                op_name: &str,
                num_inputs: usize,
                _num_results: usize,
            ) -> Result<(), String> {
                if op_name == "tensor.matmul" && num_inputs != 2 {
                    return Err(format!("matmul expects 2 inputs, got {}", num_inputs));
                }
                Ok(())
            }
        }

        let mut registry = DialectRegistry::new();
        registry.register(Box::new(FakeTensorDialect));

        let mut ctx = Context::new();
        let f32_ty = ctx.make_float_type(32);
        let block = ctx.create_block();
        let a = ctx.create_block_arg(block, f32_ty);
        let b = ctx.create_block_arg(block, f32_ty);
        let c = ctx.create_block_arg(block, f32_ty);

        // matmul with 3 inputs -> should fail semantic check
        let (op, _) = ctx.create_op(
            "tensor.matmul",
            "tensor",
            vec![a, b, c],
            vec![f32_ty],
            crate::attributes::Attributes::new(),
            crate::location::Location::unknown(),
        );
        ctx.add_op_to_block(block, op);

        let result = verify_with_dialects(&ctx, &registry);
        assert!(result.is_err());
        let errors = result.unwrap_err();
        assert!(errors
            .iter()
            .any(|e| matches!(e, VerifyError::SemanticError { .. })));
    }
}