qirc-compiler 0.1.1

Compiler and state vector simulator for QIR, the Quantum 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
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
use std::collections::BTreeMap;
use std::fmt;
use std::fs;
use std::io::{self, IsTerminal};
use std::panic;
use std::path::PathBuf;
use std::slice;
use std::thread;
use std::time::Duration;
#[cfg(not(target_arch = "wasm32"))]
use std::time::{Instant, SystemTime, UNIX_EPOCH};

use crate::calibration::Calibration;
use crate::codegen;
use crate::cost;
use crate::diag::{Diagnostic, Severity, SourceFile};
use crate::draw;
use crate::equiv;
use crate::ir::Program;
use crate::lower;
use crate::observable::{self, Observable};
use crate::opt::{self, OptStats};
use crate::parse::parse_module;
use crate::provider;
use crate::pulse;
use crate::qasm;
use crate::qasm2;
use crate::reuse::{self, Reused};
use crate::route::{self, Coupling, Relabelled, RouteStats};
use crate::sema;
use crate::simulator::exec::{self, ExecConfig};
use crate::simulator::{mps, state};
use crate::stim;
use crate::synth::{self, Cost};
use crate::transpile::{self, GateSet, TranspileStats};
use crate::verify;

const DIFF_QUBITS: usize = 20;
const COMPILER_STACK: usize = 256 << 20;
const SUBMIT_TIMEOUT: Duration = Duration::from_secs(600);
const MAX_DRAWN: usize = 200_000;

#[derive(PartialEq, Debug)]
pub enum Emit {
    Run,
    Ir,
    Qasm3,
    Qasm2,
    Stim,
    Pulse,
    Schedule,
    Ionq,
    Qir,
    Json,
    Circuit,
    Quantikz,
    Svg,
    Cost,
    Check,
}

impl Emit {
    pub fn parse(text: &str) -> Option<Emit> {
        Some(match text {
            "run" => Emit::Run,
            "ir" => Emit::Ir,
            "qasm" | "qasm3" => Emit::Qasm3,
            "qasm2" => Emit::Qasm2,
            "stim" => Emit::Stim,
            "pulse" | "openpulse" => Emit::Pulse,
            "schedule" => Emit::Schedule,
            "ionq" => Emit::Ionq,
            "qir" | "llvm" => Emit::Qir,
            "json" => Emit::Json,
            "circuit" => Emit::Circuit,
            "quantikz" | "latex" => Emit::Quantikz,
            "svg" => Emit::Svg,
            "cost" => Emit::Cost,
            "check" => Emit::Check,
            _ => return None,
        })
    }
}

#[derive(Clone, Copy)]
pub enum Color {
    Auto,
    Always,
    Never,
}

impl Color {
    fn enabled(self) -> bool {
        match self {
            Color::Always => {
                enable_ansi();
                true
            }
            Color::Never => false,
            Color::Auto => {
                std::env::var_os("NO_COLOR").is_none()
                    && io::stderr().is_terminal()
                    && enable_ansi()
            }
        }
    }
}

#[cfg(windows)]
fn enable_ansi() -> bool {
    use std::os::windows::io::AsRawHandle;

    unsafe extern "system" {
        fn GetConsoleMode(handle: *mut std::ffi::c_void, mode: *mut u32) -> i32;
        fn SetConsoleMode(handle: *mut std::ffi::c_void, mode: u32) -> i32;
    }

    const VIRTUAL_TERMINAL_PROCESSING: u32 = 0x0004;
    let handle = io::stderr().as_raw_handle();
    let mut mode = 0u32;

    unsafe {
        GetConsoleMode(handle, &mut mode) != 0
            && SetConsoleMode(handle, mode | VIRTUAL_TERMINAL_PROCESSING) != 0
    }
}

#[cfg(not(windows))]
fn enable_ansi() -> bool {
    true
}

#[derive(Default)]
pub struct Output {
    pub stdout: String,
    pub stderr: String,
}

impl Output {
    fn print(&mut self, text: impl fmt::Display) {
        self.stdout.push_str(&text.to_string());
    }

    fn println(&mut self, text: impl fmt::Display) {
        self.print(text);
        self.stdout.push('\n');
    }

    fn eprint(&mut self, text: impl fmt::Display) {
        self.stderr.push_str(&text.to_string());
    }

    fn eprintln(&mut self, text: impl fmt::Display) {
        self.eprint(text);
        self.stderr.push('\n');
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn timed<T>(work: impl FnOnce() -> T) -> (T, Duration) {
    let started = Instant::now();
    let value = work();
    (value, started.elapsed())
}

#[cfg(target_arch = "wasm32")]
fn timed<T>(work: impl FnOnce() -> T) -> (T, Duration) {
    (work(), Duration::ZERO)
}

#[cfg(not(target_arch = "wasm32"))]
fn clock_seed() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_nanos() as u64)
        .unwrap_or(1)
}

#[cfg(target_arch = "wasm32")]
fn clock_seed() -> u64 {
    1
}

pub struct Options {
    pub input: PathBuf,
    pub emit: Emit,
    pub opt_level: u8,
    pub shots: u64,
    pub seed: Option<u64>,
    pub show_state: bool,
    pub verbose: bool,
    pub output: Option<PathBuf>,
    pub verify_each: bool,
    pub gates: Option<GateSet>,
    pub resynth: Option<usize>,
    pub cost: Cost,
    pub relabel: bool,
    pub reuse: bool,
    pub noisy: bool,
    pub mitigate: bool,
    pub zne: bool,
    pub bond: Option<usize>,
    pub observable: Option<Observable>,
    pub coupling: Option<Coupling>,
    pub calibration: Option<Calibration>,
    pub color: Color,
    pub diff: bool,
    pub submit: bool,
    pub device: String,
    pub other: Option<PathBuf>,
}

impl Options {
    pub fn target(&self) -> Target {
        Target {
            gates: self.gates.clone(),
            coupling: self.coupling.clone(),
            resynth: self.resynth,
            cost: self.cost,
            relabel: self.relabel,
            reuse: self.reuse,
            calibration: self.calibration.clone(),
        }
    }
}

impl Default for Options {
    fn default() -> Self {
        Self {
            input: PathBuf::new(),
            emit: Emit::Run,
            opt_level: 1,
            shots: 0,
            seed: None,
            show_state: true,
            verbose: false,
            output: None,
            verify_each: false,
            gates: None,
            resynth: None,
            cost: Cost::Gates,
            relabel: false,
            reuse: false,
            noisy: false,
            mitigate: false,
            zne: false,
            bond: None,
            observable: None,
            coupling: None,
            calibration: None,
            color: Color::Auto,
            diff: false,
            submit: false,
            device: "simulator".into(),
            other: None,
        }
    }
}

pub const USAGE: &str = "\
qirc: a QIR compiler and state vector simulator

usage:
  qirc <input.ll> [options]
  qirc diff <a.ll> [b.ll] [options]
                    check that b.ll, or a.ll compiled with the options,
                    behaves exactly like a.ll at -O0
  qirc submit <input.ll> [options]
                    run on IonQ with the key in IONQ_API_KEY, on --target
                    (default simulator) with --shots

options:
  --emit <kind>     run | ir | qasm3 | qasm2 | stim | pulse | schedule | ionq | qir | json
                    | circuit | quantikz | svg | cost | check
                    (default: run)
  -O<n>             optimisation level 0 to 3                         (default: 1)
  --shots <n>       sample n measurement outcomes
  --seed <n>        seed the random number generator
  --no-state        do not print the final state vector
  -o <path>         write emitted output to a file
  --color <when>    auto | always | never                              (default: auto)
  --gates <set>     target gate set: rz-sx-cx | rz-ry-cz or a list like rz,sx,cx
  --exclude <list>  leave gates out of the target set, such as h,t
  --basis <name>    same as --gates
  --resynth <n>     replace runs of gates by at most n gates, 1 to 6
                    (default 1 from -O2)
  --cost <model>    what resynthesis minimises: gates | cx | ibm       (default: gates)
  --relabel         remove swaps at the end of the program by permuting qubits
  --reuse           reset measured qubits and reuse them to need fewer qubits
  --noisy           simulate with the error rates from --calibration
  --target <name>   IonQ target for submit and --emit ionq, such as qpu.aria-1
  --bond <n>        simulate as a matrix product state with bonds up to n (default 32
                    above 30 qubits)
  --mitigate        undo the readout errors from --calibration in the counts
  --zne             extrapolate the --observable to zero noise from 1x, 2x and 3x noise
  --observable <p>  print the exact expectation of a Pauli sum such as 'Z0 Z1 + 0.5 X2'
  --calibration <f> device error rates: lines of cx a b e, single q e, readout q e
  --coupling <map>  route onto hardware: line:N | ring:N | grid:RxC | full:N
                    or an explicit edge list such as 0-1,1-2,2-3
  --verify-each     run the IR verifier after lowering and after every pass
  -v, --verbose     report pipeline statistics
  -h, --help        show this message
";

pub fn parse_args(args: &[String]) -> Result<Options, String> {
    parse_args_with(args, |path| {
        fs::read_to_string(path).map_err(|error| format!("cannot read calibration {path}: {error}"))
    })
}

pub fn parse_args_with(
    args: &[String],
    read: impl Fn(&str) -> Result<String, String>,
) -> Result<Options, String> {
    let mut options = Options::default();
    let mut input: Option<PathBuf> = None;
    let mut excluded: Option<&str> = None;
    let mut args = args.iter();
    match args.as_slice().first().map(String::as_str) {
        Some("diff") => {
            args.next();
            options.diff = true;
        }
        Some("submit") => {
            args.next();
            options.submit = true;
        }
        _ => {}
    }

    while let Some(arg) = args.next() {
        match arg.as_str() {
            "-h" | "--help" => return Err(String::new()),

            "--emit" => {
                let value = value(&mut args, "--emit needs a kind")?;
                options.emit =
                    Emit::parse(value).ok_or_else(|| format!("unknown emit kind `{value}`"))?;
            }

            "--shots" => {
                let value = value(&mut args, "--shots needs a count")?;
                options.shots = value
                    .parse()
                    .map_err(|_| format!("invalid shot count `{value}`"))?;
            }

            "--seed" => {
                let value = value(&mut args, "--seed needs a number")?;
                options.seed = Some(
                    value
                        .parse()
                        .map_err(|_| format!("invalid seed `{value}`"))?,
                );
            }

            "-o" => {
                let value = value(&mut args, "-o needs a path")?;
                options.output = Some(PathBuf::from(value));
            }

            "--gates" | "--basis" => {
                let value = value(&mut args, "--gates needs a gate set")?;
                options.gates = Some(GateSet::parse(value)?);
            }

            "--exclude" => excluded = Some(value(&mut args, "--exclude needs a list of gates")?),

            "--resynth" => {
                let value = value(&mut args, "--resynth needs a length")?;
                options.resynth = match value.parse() {
                    Ok(n @ 1..=6) => Some(n),
                    _ => return Err(format!("resynthesis length `{value}` must be 1 to 6")),
                };
            }

            "--cost" => {
                let value = value(&mut args, "--cost needs a model")?;
                options.cost = Cost::parse(value).ok_or_else(|| {
                    format!("unknown cost model `{value}`, expected gates, cx or ibm")
                })?;
            }

            "--relabel" => options.relabel = true,

            "--reuse" => options.reuse = true,

            "--noisy" => options.noisy = true,

            "--target" => {
                options.device = value(
                    &mut args,
                    "--target needs a provider target such as simulator",
                )?
                .to_string();
            }

            "--bond" => {
                let value = value(&mut args, "--bond needs a bond dimension")?;
                options.bond = Some(
                    value
                        .parse()
                        .ok()
                        .filter(|&b: &usize| b > 0)
                        .ok_or_else(|| format!("invalid bond dimension `{value}`"))?,
                );
            }

            "--mitigate" => options.mitigate = true,

            "--zne" => options.zne = true,

            "--observable" => {
                let value = value(
                    &mut args,
                    "--observable needs a Pauli sum such as \"Z0 Z1 + 0.5 X2\"",
                )?;
                options.observable = Some(Observable::parse(value)?);
            }

            "--calibration" => {
                let path = value(&mut args, "--calibration needs a file")?;
                let text = read(path)?;
                options.calibration = Some(
                    Calibration::parse(&text)
                        .map_err(|error| format!("calibration {path}: {error}"))?,
                );
            }

            "--coupling" => {
                let value = value(&mut args, "--coupling needs a map")?;
                options.coupling = Some(
                    Coupling::parse(value)
                        .ok_or_else(|| format!("unknown coupling map `{value}`"))?,
                );
            }

            "--color" => {
                let value = value(&mut args, "--color needs auto, always or never")?;
                options.color = match value {
                    "auto" => Color::Auto,
                    "always" => Color::Always,
                    "never" => Color::Never,
                    _ => return Err(format!("unknown color setting `{value}`")),
                };
            }

            "--verify-each" => options.verify_each = true,

            "--no-state" => options.show_state = false,

            "-v" | "--verbose" => options.verbose = true,

            arg if arg.starts_with("-O") => {
                let level = arg[2..]
                    .parse::<u8>()
                    .map_err(|_| format!("invalid optimisation level `{arg}`"))?;
                if level > 3 {
                    return Err(format!("optimisation level {level} is out of range"));
                }
                options.opt_level = level;
            }

            arg if arg.starts_with('-') => return Err(format!("unknown option `{arg}`")),

            path if input.is_none() => input = Some(PathBuf::from(path)),

            path if options.diff && options.other.is_none() => {
                options.other = Some(PathBuf::from(path));
            }

            _ => return Err("too many input files".into()),
        }
    }

    if let Some(list) = excluded {
        options.gates = Some(
            options
                .gates
                .take()
                .unwrap_or_else(GateSet::native)
                .without(list)?,
        );
    }
    options.input = input.ok_or_else(|| "no input file given".to_string())?;
    if (options.noisy || options.mitigate || options.zne) && options.calibration.is_none() {
        return Err("--noisy, --mitigate and --zne need --calibration for its error rates".into());
    }
    if options.zne && options.observable.is_none() {
        return Err("--zne needs --observable for the value to extrapolate".into());
    }
    Ok(options)
}

fn value<'a>(args: &mut slice::Iter<'a, String>, missing: &str) -> Result<&'a str, String> {
    args.next()
        .map(String::as_str)
        .ok_or_else(|| missing.to_string())
}

#[derive(Default)]
pub struct Target {
    pub gates: Option<GateSet>,
    pub coupling: Option<Coupling>,
    pub resynth: Option<usize>,
    pub cost: Cost,
    pub relabel: bool,
    pub reuse: bool,
    pub calibration: Option<Calibration>,
}

pub struct Compilation {
    pub program: Program,
    pub stats: OptStats,
    pub transpiled: Option<TranspileStats>,
    pub routed: Option<RouteStats>,
    pub relabelled: Option<Relabelled>,
    pub reused: Option<Reused>,
    pub diagnostics: Vec<Diagnostic>,
    pub parse_time: Duration,
    pub lower_time: Duration,
    pub opt_time: Duration,
}

pub fn compile(source: &str, opt_level: u8) -> Compilation {
    compile_for(source, opt_level, false, &Target::default())
}

pub fn compile_for(source: &str, opt_level: u8, verify_each: bool, target: &Target) -> Compilation {
    if cfg!(target_arch = "wasm32") {
        return compile_now(source, opt_level, verify_each, target);
    }
    thread::scope(|scope| {
        thread::Builder::new()
            .stack_size(COMPILER_STACK)
            .spawn_scoped(scope, || {
                compile_now(source, opt_level, verify_each, target)
            })
            .map(|worker| {
                worker
                    .join()
                    .unwrap_or_else(|panic| panic::resume_unwind(panic))
            })
            .unwrap_or_else(|_| compile_now(source, opt_level, verify_each, target))
    })
}

fn compile_now(source: &str, opt_level: u8, verify_each: bool, target: &Target) -> Compilation {
    let mut diagnostics = Vec::new();

    let (mut program, parse_time, lower_time) = if qasm::is_qasm(source) {
        let ((program, errors), time) = timed(|| qasm::lower(source));
        diagnostics.extend(errors);
        (program, time, Duration::ZERO)
    } else {
        let ((module, parse_errors), parse_time) = timed(|| parse_module(source));
        diagnostics.extend(parse_errors);
        let (lowered, lower_time) = timed(|| lower::lower(&module));
        diagnostics.extend(lowered.diagnostics);
        (lowered.program, parse_time, lower_time)
    };
    diagnostics.extend(sema::validate(&program));

    let mut lowering_violations = Vec::new();
    let lowered_cleanly = !diagnostics.iter().any(|d| d.severity == Severity::Error);
    if verify_each && lowered_cleanly {
        for found in verify::verify(&program) {
            lowering_violations.push(format!("after lowering: {found}"));
        }
    }

    let (mut stats, opt_time) =
        timed(|| opt::optimise(&mut program, opt_level, verify_each && lowered_cleanly));

    lowering_violations.append(&mut stats.violations);
    stats.violations = lowering_violations;

    let reused = if target.reuse {
        reuse::reuse(&mut program)
    } else {
        None
    };

    let coupling = target
        .coupling
        .clone()
        .or_else(|| target.calibration.as_ref().map(Calibration::coupling));
    let relabel = target.relabel || coupling.is_some();
    let mut relabelled = relabel.then(|| route::elide_swaps(&mut program));

    let transpiled = target
        .gates
        .as_ref()
        .map(|set| transpile::transpile(&mut program, set));
    if let Some(stats) = &transpiled
        && !stats.leftover.is_empty()
    {
        diagnostics.push(
            Diagnostic::warning(format!(
                "no exact form in gate set {} for {}, left as written",
                stats.set,
                stats.leftover.join(", ")
            ))
            .with_code("QIR0401"),
        );
    }

    let native = GateSet::native();
    let set = target.gates.as_ref().unwrap_or(&native);
    let limit = target.resynth.unwrap_or(usize::from(opt_level >= 2));
    let mut replaced = synth::resynthesize(&mut program, set, limit, target.cost);
    if opt_level > 0 {
        replaced += opt::drop_before_measure(&mut program);
    }
    if let Some(first) = &mut relabelled {
        let again = route::elide_swaps(&mut program);
        first.swaps_removed += again.swaps_removed;
        first.final_layout = first
            .final_layout
            .iter()
            .map(|&w| again.final_layout[w])
            .collect();
    }
    if replaced > 0 {
        stats.applied.push(("resynthesize", replaced));
        stats.gates_after = program.gate_count();
        stats.depth_after = program.depth();
        stats.ops_after = program.op_count();
    }

    let mut routed = None;
    if let Some(coupling) = &coupling {
        if target.gates.is_none() {
            transpile::transpile(&mut program, &GateSet::native().local());
        }
        match route::route(&mut program, coupling, target.calibration.as_ref()) {
            Ok(mut stats) => {
                if let Some(relabelled) = &relabelled {
                    let physical = stats.final_layout.clone();
                    for (q, slot) in stats.final_layout.iter_mut().enumerate() {
                        *slot = physical[relabelled.final_layout.get(q).copied().unwrap_or(q)];
                    }
                }
                routed = Some(stats);
            }
            Err(message) => diagnostics.push(
                Diagnostic::error(format!("cannot route this program: {message}"))
                    .with_code("QIR0400"),
            ),
        }
    }
    if routed.is_some() {
        if let Some(gates) = &target.gates {
            transpile::transpile(&mut program, gates);
        }
        synth::resynthesize(&mut program, set, limit, target.cost);
        if opt_level > 0 {
            opt::drop_before_measure(&mut program);
        }
    }

    if verify_each && (transpiled.is_some() || routed.is_some()) {
        for found in verify::verify(&program) {
            stats.violations.push(format!("after targeting: {found}"));
        }
    }

    Compilation {
        program,
        stats,
        transpiled,
        routed,
        relabelled,
        reused,
        diagnostics,
        parse_time,
        lower_time,
        opt_time,
    }
}

fn read(path: &PathBuf, output: &mut Output) -> Option<SourceFile> {
    match fs::read_to_string(path) {
        Ok(text) => Some(SourceFile::new(path.display().to_string(), text)),
        Err(error) => {
            output.eprintln(format_args!(
                "error: cannot read {}: {error}",
                path.display()
            ));
            None
        }
    }
}

fn report(file: &SourceFile, compilation: &Compilation, color: bool, output: &mut Output) -> bool {
    for violation in &compilation.stats.violations {
        output.eprintln(format_args!("internal error: verifier: {violation}"));
    }

    let mut errors = 0;
    for diagnostic in &compilation.diagnostics {
        output.eprintln(format_args!("{}", diagnostic.render_styled(file, color)));
        if diagnostic.severity == Severity::Error {
            errors += 1;
        }
    }

    if !compilation.stats.violations.is_empty() {
        output.eprintln(format_args!(
            "error: aborting after {} verifier violation(s)",
            compilation.stats.violations.len()
        ));
        return false;
    }

    if errors > 0 {
        output.eprintln(format_args!(
            "error: aborting due to {errors} previous error{}",
            if errors == 1 { "" } else { "s" }
        ));
        return false;
    }

    true
}

fn diff(options: &Options, left: &SourceFile, right: &SourceFile, output: &mut Output) -> i32 {
    let color = options.color.enabled();

    let reference = compile_for(&left.text, 0, false, &Target::default());
    let candidate = compile_for(
        &right.text,
        options.opt_level,
        options.verify_each,
        &options.target(),
    );
    if !report(left, &reference, color, output) || !report(right, &candidate, color, output) {
        return 1;
    }

    for program in [&reference.program, &candidate.program] {
        if program.num_qubits as usize > DIFF_QUBITS && !exec::stabilizer(program) {
            output.eprintln(format_args!(
                "error: diff follows every branch and supports at most {DIFF_QUBITS} qubits unless the program only uses Clifford gates"
            ));
            return 1;
        }
    }

    let states = options.coupling.is_none()
        && options.calibration.is_none()
        && !options.relabel
        && !options.reuse;
    let (a, b) = (
        equiv::explore(&reference.program),
        equiv::explore(&candidate.program),
    );
    let differences = equiv::compare(&a, &b, states);

    let unexplored = a.unexplored.max(b.unexplored);
    let complete = unexplored <= 1e-9;
    let count = a.branches.len();
    let noun = if count == 1 {
        "outcome agrees"
    } else {
        "outcomes agree"
    };
    let checked = if states {
        "probability and final state"
    } else {
        "probability"
    };

    if !differences.is_empty() {
        output.println(format_args!("different:"));
        for difference in differences.iter().take(8) {
            output.println(format_args!("  {difference}"));
        }
    } else if complete {
        output.println(format_args!("equivalent: {count} {noun} in {checked}"));
    } else {
        output.println(format_args!(
            "inconclusive: {count} {noun} in {checked}, but {unexplored:.2e} of the probability was not explored"
        ));
    }
    if !states {
        output.println(format_args!(
            "note: final states are not compared because the compiled program moves qubits"
        ));
    }

    match (differences.is_empty(), complete) {
        (false, _) => 1,
        (true, true) => 0,
        (true, false) => 2,
    }
}

pub fn run(options: Options) -> i32 {
    let mut output = Output::default();
    let code = match read(&options.input, &mut output) {
        Some(file) => match &options.other {
            Some(path) => match read(path, &mut output) {
                Some(other) => run_source(&options, &file, Some(&other), &mut output),
                None => 1,
            },
            None => run_source(&options, &file, None, &mut output),
        },
        None => 1,
    };
    eprint!("{}", output.stderr);
    print!("{}", output.stdout);
    code
}

pub fn run_source(
    options: &Options,
    file: &SourceFile,
    other: Option<&SourceFile>,
    output: &mut Output,
) -> i32 {
    if options.diff {
        return diff(options, file, other.unwrap_or(file), output);
    }

    let compilation = compile_for(
        &file.text,
        options.opt_level,
        options.verify_each,
        &options.target(),
    );

    let color = options.color.enabled();
    if !report(file, &compilation, color, output) {
        return 1;
    }

    let program = &compilation.program;

    if options.submit {
        let shots = options.shots.max(1);
        let mut progress = |line: &str| output.eprintln(line);
        return match provider::submit(
            program,
            &options.device,
            shots,
            SUBMIT_TIMEOUT,
            &mut progress,
        ) {
            Ok(counts) => {
                let note = format!(" on IonQ {}", options.device);
                print_tally(output, "measurement", &note, &counts);
                0
            }
            Err(reason) => {
                output.eprintln(format_args!("error: {reason}"));
                1
            }
        };
    }

    if options.verbose {
        output.eprintln(format_args!(
            "parse {:?}, lower {:?}, optimise {:?}",
            compilation.parse_time, compilation.lower_time, compilation.opt_time
        ));
        output.eprint(format_args!("{}", compilation.stats));
        if let Some(stats) = &compilation.transpiled {
            output.eprintln(format_args!("{stats}"));
        }
        if let Some(stats) = &compilation.reused {
            output.eprintln(stats);
        }
        if let Some(stats) = &compilation.relabelled {
            output.eprintln(stats);
        }
        if let Some(stats) = &compilation.routed {
            output.eprintln(format_args!("{stats}"));
        }
    }

    let emitted = match options.emit {
        Emit::Check => {
            output.println(format_args!("ok: {}", summary(program)));
            return 0;
        }
        Emit::Ir => format!("{program}"),
        Emit::Qasm3 => match codegen::emit_qasm3(program) {
            Ok(text) => text,
            Err(reason) => {
                output.eprintln(format_args!("error: cannot emit OpenQASM 3: {reason}"));
                output.eprintln(format_args!("note: --emit qir keeps the whole program"));
                return 1;
            }
        },
        Emit::Qasm2 => match qasm2::emit(program) {
            Ok(text) => text,
            Err(reason) => {
                output.eprintln(format_args!("error: cannot emit OpenQASM 2: {reason}"));
                return 1;
            }
        },
        Emit::Stim => {
            let noise = options.calibration.as_ref().filter(|_| options.noisy);
            match stim::emit(program, noise) {
                Ok(text) => text,
                Err(reason) => {
                    output.eprintln(format_args!("error: cannot emit Stim: {reason}"));
                    return 1;
                }
            }
        }
        Emit::Ionq => match provider::ionq(program, &options.device, options.shots.max(1)) {
            Ok(text) => text + "\n",
            Err(reason) => {
                output.eprintln(format_args!("error: cannot write an IonQ job: {reason}"));
                return 1;
            }
        },
        Emit::Pulse | Emit::Schedule => {
            let Some(calibration) = &options.calibration else {
                output.eprintln(format_args!(
                    "error: a pulse schedule needs --calibration for gate times and frequencies"
                ));
                return 1;
            };
            let emitted = if options.emit == Emit::Pulse {
                pulse::emit(program, calibration)
            } else {
                pulse::schedule(program, calibration)
            };
            match emitted {
                Ok(text) => text,
                Err(reason) => {
                    output.eprintln(format_args!("error: cannot schedule pulses: {reason}"));
                    return 1;
                }
            }
        }
        Emit::Qir => match codegen::emit_qir(program) {
            Ok(text) => text,
            Err(reason) => {
                output.eprintln(format_args!("error: cannot emit QIR: {reason}"));
                return 1;
            }
        },
        Emit::Json => codegen::emit_json(program),
        Emit::Circuit => codegen::emit_circuit(program),
        Emit::Quantikz => draw::quantikz(program),
        Emit::Svg => draw::svg(program),
        Emit::Cost => cost::analyse(program, options.calibration.as_ref()).to_string(),
        Emit::Run => return execute(options, &compilation, output),
    };

    match &options.output {
        Some(path) => {
            if let Err(error) = fs::write(path, &emitted) {
                output.eprintln(format_args!(
                    "error: cannot write {}: {error}",
                    path.display()
                ));
                return 1;
            }
            output.eprintln(format_args!("wrote {}", path.display()));
        }
        None => output.print(emitted),
    }

    0
}

fn execute(options: &Options, compilation: &Compilation, output: &mut Output) -> i32 {
    let program = &compilation.program;

    let qubits = program.num_qubits as usize;
    if qubits > state::MAX_QUBITS && !exec::scalable(program) {
        if let Some(observable) = &options.observable {
            return if expectation(output, program, observable) {
                0
            } else {
                1
            };
        }
        output.eprintln(format_args!(
            "error: this program needs {qubits} qubits, but the simulator supports at most {}",
            state::MAX_QUBITS
        ));
        match state::memory_required(qubits) {
            Some(bytes) => output.eprintln(format_args!(
                "note: a {qubits} qubit state vector would need {:.1} GiB of memory",
                bytes as f64 / (1024.0 * 1024.0 * 1024.0)
            )),
            None => output.eprintln(format_args!(
                "note: a {qubits} qubit state vector does not fit in memory"
            )),
        }
        output.eprintln(format_args!(
            "note: use --emit qir, qasm3, json or circuit to compile without simulating"
        ));
        return 1;
    }

    let seed = options.seed.unwrap_or_else(clock_seed);

    output.println(format_args!("source:  {}", options.input.display()));
    let kernel = match options.bond {
        Some(_) => "matrix product state",
        None => exec::kernel(program),
    };
    output.println(format_args!("kernel:  {kernel}"));
    output.println(format_args!("program: {}", summary(program)));

    if compilation.stats.changed() {
        output.println(format_args!(
            "optimised: {} gates removed ({} -> {})",
            compilation.stats.gates_removed(),
            compilation.stats.gates_before,
            compilation.stats.gates_after
        ));
    }

    output.println("");
    let depth = program.depth();
    if program.num_qubits as usize * depth <= MAX_DRAWN {
        output.print(format_args!("{}", codegen::emit_circuit(program)));
    } else {
        output.println(format_args!(
            "circuit: {} qubits by depth {depth} is too large to draw here, use --emit circuit",
            program.num_qubits
        ));
    }

    let config = ExecConfig {
        shots: options.shots,
        seed,
        keep_state: options.show_state,
    };
    let (outcome, elapsed) = timed(
        || match (&options.calibration, options.noisy, options.bond) {
            (Some(calibration), true, _) => exec::execute_noisy(program, config, calibration),
            (_, _, Some(bond)) => exec::execute_bonded(program, config, bond)
                .unwrap_or_else(|| exec::execute(program, config)),
            _ => exec::execute(program, config),
        },
    );
    if options.noisy {
        output.println("noise:   calibration error rates applied to every gate and measurement");
    }
    if outcome.discarded > 0.0 {
        output.println(format_args!(
            "truncation: bonds were capped at {}, discarding {:.2e} of the weight, so the counts are approximate",
            options.bond.unwrap_or(mps::DEFAULT_BOND),
            outcome.discarded
        ));
    }

    if outcome.aborted {
        output.eprintln(format_args!(
            "error: execution did not terminate within the step limit"
        ));
        return 1;
    }

    if let Some(state) = &outcome.final_state {
        output.println("");
        if !outcome.sampled {
            output.println(format_args!("state after the last shot:"));
        }
        output.print(format_args!("{state}"));

        output.println("");
        for qubit in 0..program.num_qubits as usize {
            output.println(format_args!(
                "  P(q{qubit} = 1) = {:.6}",
                state.qubit_probability(qubit)
            ));
        }
    }

    if !outcome.messages.is_empty() {
        output.println("");
        for message in &outcome.messages {
            output.println(format_args!("message: {message}"));
        }
    }

    if !outcome.outputs.is_empty() {
        output.println("");
        output.println(format_args!("output recording:"));
        for record in &outcome.outputs {
            output.println(format_args!("  {record}"));
        }
    }

    print_tally(output, "returned", "", &outcome.returns);
    print_tally(
        output,
        "measurement",
        if outcome.sampled {
            " (sampled from the final state)"
        } else {
            " (simulated per shot)"
        },
        &outcome.counts,
    );

    if let (true, Some(calibration)) = (options.mitigate, &options.calibration) {
        match calibration.mitigate(program, &outcome.counts) {
            Some(rows) if !rows.is_empty() => {
                let width = rows.iter().map(|(key, _)| key.len()).max().unwrap_or(0);
                output.println("");
                output.println("mitigated measurement, readout errors undone:");
                for (key, share) in rows {
                    output.println(format_args!("  {key:<width$}  {share:.4}"));
                }
            }
            _ => output.eprintln(format_args!(
                "note: readout mitigation needs between 1 and 20 measured results"
            )),
        }
    }

    if let Some(observable) = &options.observable {
        output.println("");
        expectation(output, program, observable);
        if let (true, Some(calibration)) = (options.zne, &options.calibration) {
            let shots = options.shots.max(1000);
            match observable::extrapolate(program, observable, calibration, shots, seed) {
                Ok(([one, two, three], zero)) => {
                    output.println(format_args!(
                        "noisy expectation at 1x, 2x and 3x noise over {shots} shots: {one:.6}, {two:.6}, {three:.6}"
                    ));
                    output.println(format_args!("zero noise extrapolation: {:.6}", zero + 0.0));
                }
                Err(reason) => output.eprintln(format_args!("error: cannot extrapolate: {reason}")),
            }
        }
    }

    if !elapsed.is_zero() {
        output.println("");
        output.println(format_args!("simulated in {elapsed:.3?}"));
    }
    0
}

fn expectation(output: &mut Output, program: &Program, observable: &Observable) -> bool {
    match observable::expectation(program, observable) {
        Ok(value) => {
            output.println(format_args!(
                "expectation of {observable}: {:.6}",
                value + 0.0
            ));
            true
        }
        Err(reason) => {
            output.eprintln(format_args!(
                "error: cannot compute the expectation: {reason}"
            ));
            false
        }
    }
}

fn summary(program: &Program) -> String {
    format!(
        "{} qubits, {} results, {} gates, depth {}, profile {}",
        program.num_qubits,
        program.num_results,
        program.gate_count(),
        program.depth(),
        program.profile.name()
    )
}

fn print_tally(output: &mut Output, name: &str, note: &str, tally: &BTreeMap<String, u64>) {
    if tally.is_empty() {
        return;
    }

    let total: u64 = tally.values().sum();
    let width = tally.keys().map(String::len).max().unwrap_or(0);
    let mut rows: Vec<(&String, &u64)> = tally.iter().collect();
    rows.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));

    output.println("");
    output.println(format_args!("{name} over {total} shots{note}:"));
    for (key, count) in rows {
        output.println(format_args!(
            "  {key:<width$}  {count:>8}   {:.4}",
            *count as f64 / total as f64
        ));
    }
}