moore 0.14.0

A compiler for hardware description languages.
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
// Copyright (c) 2016-2021 Fabian Schuiki

//! A hardware description language compiler.

#[macro_use]
extern crate log;

use clap::{App, Arg, ArgMatches};
use llhd;
use moore_circt::{self as circt, mlir, prelude::*, sys::*};
// use llhd::opt::{Pass, PassContext};
use moore::common::score::NodeRef;
use moore::errors::*;
use moore::name::Name;
use moore::score::{ScoreBoard, ScoreContext};
use moore::source::Span;
use moore::svlog::{ast::AcceptVisitor as _, hir::Visitor as _, QueryDatabase as _};
use moore::*;
use std::path::Path;

#[derive(Debug)]
enum Language {
    Verilog,
    SystemVerilog,
    Vhdl,
}

fn main() {
    // Configure the logger.
    let mut builder = pretty_env_logger::formatted_builder();
    builder.parse_filters(
        std::env::var("MOORE_LOG")
            .ok()
            .as_ref()
            .map(|s| s.as_str())
            .unwrap_or("off"),
    );
    builder.try_init().unwrap();

    // Parse the command-line arguments.
    let matches = App::new(env!("CARGO_PKG_NAME"))
        .version(clap::crate_version!())
        .author(clap::crate_authors!())
        .about(clap::crate_description!())
        .arg(
            Arg::with_name("trace_scoreboard")
                .long("trace-scoreboard")
                .global(true),
        )
        .arg(
            Arg::with_name("verbosity-opts")
                .short("V")
                .help("Sets verbosity settings")
                .takes_value(true)
                .multiple(true)
                .number_of_values(1)
                .possible_values(&[
                    "types",
                    "expr-types",
                    "type-contexts",
                    "typeck",
                    "names",
                    "casts",
                    "ports",
                    "consts",
                    "insts",
                    "func-args",
                    "call-args",
                ])
                .global(true),
        )
        .arg(
            Arg::with_name("inc")
                .short("I")
                .value_name("DIR")
                .help("Add a search path for SystemVerilog includes")
                .multiple(true)
                .takes_value(true)
                .number_of_values(1),
        )
        .arg(
            Arg::with_name("def")
                .short("D")
                .value_name("DEFINE")
                .help("Define a preprocesor macro")
                .multiple(true)
                .takes_value(true)
                .number_of_values(1),
        )
        .arg(
            Arg::with_name("preproc")
                .short("E")
                .help("Write preprocessed input files to stdout"),
        )
        .arg(
            Arg::with_name("dump-ast")
                .long("dump-ast")
                .help("Dump the parsed abstract syntax tree"),
        )
        .arg(
            Arg::with_name("check-syntax")
                .long("syntax")
                .help("Preprocess and check the input for syntax errors"),
        )
        .arg(
            Arg::with_name("emit_pkgs")
                .long("emit-pkgs")
                .help("Dump VHDL packages for debugging"),
        )
        .arg(
            Arg::with_name("opt-level")
                .short("O")
                .long("opt-level")
                .help("Sets optimization level applied to the output")
                .default_value("1")
                .takes_value(true)
                .number_of_values(1),
        )
        .arg(
            Arg::with_name("lib")
                .short("l")
                .long("lib")
                .value_name("LIB")
                .help("Name of the library to compile into")
                .takes_value(true)
                .number_of_values(1),
        )
        .arg(
            Arg::with_name("elaborate")
                .short("e")
                .long("elaborate")
                .value_name("ENTITY")
                .help("Elaborate an entity or module")
                .multiple(true)
                .takes_value(true)
                .number_of_values(1),
        )
        .arg(
            Arg::with_name("output")
                .short("o")
                .long("output")
                .help("Output file (`-` for stdout)")
                .takes_value(true),
        )
        .arg(
            Arg::with_name("output-format")
                .short("f")
                .long("format")
                .help("Output format")
                .takes_value(true)
                .possible_values(&["llhd", "mlir", "mlir-native"]),
        )
        .arg(
            Arg::with_name("debug-info")
                .short("g")
                .long("debug-info")
                .help("Emit location information as part of the output"),
        )
        .arg(
            Arg::with_name("INPUT")
                .help("The input files to compile")
                .multiple(true)
                .required(true),
        )
        .get_matches();

    // Configure the session.
    let mut session = Session::new();
    session.opts.trace_scoreboard = matches.is_present("trace_scoreboard");
    for v in matches
        .values_of("verbosity-opts")
        .into_iter()
        .flat_map(|v| v)
    {
        session.opts.verbosity |= match v {
            "types" => Verbosity::TYPES,
            "expr-types" => Verbosity::EXPR_TYPES,
            "type-contexts" => Verbosity::TYPE_CONTEXTS,
            "typeck" => Verbosity::TYPECK,
            "names" => Verbosity::NAMES,
            "casts" => Verbosity::CASTS,
            "ports" => Verbosity::PORTS,
            "consts" => Verbosity::CONSTS,
            "insts" => Verbosity::INSTS,
            "func-args" => Verbosity::FUNC_ARGS,
            "call-args" => Verbosity::CALL_ARGS,
            _ => unreachable!(),
        };
    }
    session.opts.opt_level = matches.value_of("opt-level").unwrap().parse().unwrap();

    // Invoke the compiler.
    score(&session, &matches);
}

fn score(sess: &Session, matches: &ArgMatches) {
    use crate::name::get_name_table;
    let svlog_arenas = svlog::GlobalArenas::default();

    // Prepare a list of include paths.
    let include_paths: Vec<_> = match matches.values_of("inc") {
        Some(args) => args.map(|x| std::path::Path::new(x)).collect(),
        None => Vec::new(),
    };

    let defines: Vec<_> = match matches.values_of("def") {
        Some(args) => args
            .map(|x| {
                let mut iter = x.split("=");
                (iter.next().unwrap(), iter.next())
            })
            .collect(),
        None => Vec::new(),
    };

    // Establish into which library the entities will be compiled. Later on this
    // should be made configurable per entity.
    let lib = get_name_table().intern(matches.value_of("lib").unwrap_or("work"), true);

    // Parse the input files.
    let mut failed = false;
    let mut asts = Vec::new();
    for filename in matches.values_of("INPUT").unwrap() {
        if filename.is_empty() {
            continue;
        }

        // Detect the file type.
        let language = match Path::new(&filename).extension().and_then(|s| s.to_str()) {
            Some("sv") | Some("svh") => Language::SystemVerilog,
            Some("v") | Some("vh") => Language::Verilog,
            Some("vhd") | Some("vhdl") => Language::Vhdl,
            Some(ext) => {
                sess.emit(
                    DiagBuilder2::warning(format!("ignoring `{}`", filename)).add_note(format!(
                        "Cannot determine language from extension `.{}`",
                        ext
                    )),
                );
                continue;
            }
            None => {
                sess.emit(
                    DiagBuilder2::warning(format!("ignoring `{}`", filename)).add_note(format!(
                        "No file extension that can be used to guess language"
                    )),
                );
                continue;
            }
        };

        // Add the file to the source manager.
        let sm = source::get_source_manager();
        let source = match sm.open(&filename) {
            Some(s) => s,
            None => {
                sess.emit(DiagBuilder2::fatal(format!(
                    "unable to open `{}`",
                    filename
                )));
                continue;
            }
        };

        // Parse the file.
        match language {
            Language::SystemVerilog | Language::Verilog => {
                let preproc = svlog::preproc::Preprocessor::new(source, &include_paths, &defines);
                if matches.is_present("preproc") {
                    for token in preproc {
                        print!(
                            "{}",
                            match token {
                                Ok((_token, span)) => span.extract(),
                                Err(diag) => {
                                    sess.emit(diag);
                                    failed = true;
                                    continue;
                                }
                            }
                        );
                    }
                    continue;
                }

                let lexer = svlog::lexer::Lexer::new(preproc);
                match svlog::parser::parse(lexer, &svlog_arenas.ast) {
                    Ok(x) => asts.push(score::Ast::Svlog(x)),
                    Err(()) => failed = true,
                }
            }
            Language::Vhdl => match vhdl::syntax::parse(source) {
                Ok(x) => asts.push(score::Ast::Vhdl(x)),
                Err(()) => failed = true,
            },
        }
    }
    if failed || sess.failed() {
        std::process::exit(1);
    }
    if matches.is_present("preproc") {
        return;
    }

    // Dump the AST if so requested.
    if matches.is_present("dump-ast") {
        println!("{:#99?}", asts);
    }

    if matches.is_present("emit_pkgs") {
        vhdl::debug::emit_pkgs(
            sess,
            asts.iter()
                .flat_map(|ast| match *ast {
                    score::Ast::Vhdl(ref x) => x.iter(),
                    _ => [].iter(),
                })
                .collect(),
        );
    }

    // Stop processing if requested.
    if matches.is_present("check-syntax") {
        std::process::exit(0);
    }

    // Create the scoreboard and add the initial map of libraries.
    let arenas = score::Arenas::new();
    let sb = ScoreBoard::new(&arenas);
    let vhdl_sb = vhdl::score::ScoreBoard::new(&arenas.vhdl);
    let svlog_sb = svlog::GlobalContext::new(&sess, &svlog_arenas);

    // Elaborate the requested entities or modules.
    {
        let vhdl_phases = vhdl::lazy::LazyPhaseTable::new(&vhdl_sb);
        let ctx = ScoreContext {
            sess: sess,
            sb: &sb,
            vhdl: &vhdl_sb,
            vhdl_phases: &vhdl_phases,
            svlog: &svlog_sb,
        };
        let lib_id = ctx.add_library(lib, &asts);

        // Emit the function argument canonicalization details if requested.
        for root in ctx.svlog.roots() {
            if ctx.sess.has_verbosity(Verbosity::FUNC_ARGS) {
                root.accept(&mut svlog::func_args::FuncArgsVerbosityVisitor::new(
                    ctx.svlog,
                ));
            }
        }

        // Emit the call argument mappings if requested.
        for root in ctx.svlog.roots() {
            if ctx.sess.has_verbosity(Verbosity::CALL_ARGS) {
                root.accept(&mut svlog::call_mapping::CallMappingVerbosityVisitor::new(
                    ctx.svlog,
                ));
            }
        }

        // Elaborate what has been requested by the user.
        if let Some(names) = matches.values_of("elaborate") {
            debug!("lib_id = {:?}", lib_id);
            debug!("{:?}", sb);
            for name in names {
                match elaborate_name(matches, &ctx, lib_id, name) {
                    Ok(_) => (),
                    Err(_) => failed = true,
                };
            }
            if sess.failed() {
                failed = true;
            }
        }
    }
    if failed || sess.failed() {
        std::process::exit(1);
    }

    // Extract the populated LLHD modules from the scoreboards and link them
    // together.
    let _vhdl_module = vhdl_sb.llmod.into_inner();

    // Emit the module.
    // TODO: Re-enable this once the VHDL crate has been moved over to llhd v0.8.
    // llhd::assembly::write_module(&mut std::io::stdout().lock(), &vhdl_module);

    if sess.failed() {
        std::process::exit(1);
    }
}

/// Resolve an entity/module specificaiton of the form `[lib.]entity[.arch]` for
/// elaboration.
fn elaborate_name(
    matches: &ArgMatches,
    ctx: &ScoreContext,
    lib_id: score::LibRef,
    input_name: &str,
) -> Result<(), ()> {
    let (lib, name, arch) = parse_elaborate_name(input_name)?;
    debug!(
        "parsed `{}` into (lib: {:?}, name: {:?}, arch: {:?})",
        input_name, lib, name, arch
    );

    // Resolve the library name if one was provided.
    let lib = {
        if let Some(lib) = lib {
            let rid = ctx.sb.root;
            let defs = ctx.defs(score::ScopeRef::Root(rid))?;
            match defs.get(&lib) {
                Some(&score::Def::Lib(d)) => d,
                _ => {
                    let mut d = DiagBuilder2::error(format!("Library `{}` does not exist", lib))
                        .add_note("The following libraries do exist:");
                    let mut names: Vec<_> = defs.iter().map(|(&k, _)| k).collect();
                    names.sort(); // sorts by name ID, roughly equivalent to order of declaration
                    for name in names {
                        d = d.add_note(format!("- {}", name));
                    }
                    ctx.sess.emit(d);
                    return Err(());
                }
            }
        } else {
            lib_id
        }
    };
    debug!("using library {:?}", lib);

    // Resolve the entity name.
    // TODO: Make sure that the thing we resolve to actually is a VHDL entity or
    // a SystemVerilog module. Right we happily accept packages as well.
    #[derive(Debug)]
    enum Elaborate {
        VhdlEntity(vhdl::score::EntityRef, vhdl::score::ArchRef),
        VhdlPkg(vhdl::score::PkgDeclRef),
        Svlog(NodeId), // TODO: handle svlog case
    }
    let defs = ctx.defs(lib.into())?;
    let elab = match defs.get(&name) {
        Some(&score::Def::Vhdl(vhdl::score::Def::Entity(entity))) => {
            let archs = ctx
                .vhdl()
                .archs(vhdl::score::LibRef::new(lib.into()))?
                .by_entity
                .get(&entity)
                .unwrap();
            let arch_ref = if let Some(arch) = arch {
                match archs.by_name.get(&arch) {
                    Some(&id) => id,
                    None => {
                        ctx.sess.emit(DiagBuilder2::error(format!(
                            "`{}` is not an architecture of entity `{}`",
                            arch, name
                        )));
                        return Err(());
                    }
                }
            } else {
                match archs.ordered.last() {
                    Some(&id) => id,
                    None => {
                        ctx.sess.emit(DiagBuilder2::error(format!(
                            "Entity `{}` has no architecture defined",
                            name
                        )));
                        return Err(());
                    }
                }
            };
            Elaborate::VhdlEntity(entity, arch_ref)
        }
        Some(&score::Def::Vhdl(vhdl::score::Def::Pkg(p))) => Elaborate::VhdlPkg(p),
        Some(&score::Def::Svlog(e)) => Elaborate::Svlog(e),
        _ => {
            let mut d = DiagBuilder2::error(format!("Item `{}` does not exist", name))
                .add_note("The following items are defined:");
            let mut names: Vec<_> = defs.iter().map(|(&k, _)| k).collect();
            names.sort(); // sorts by name ID, roughly equivalent to order of declaration
            for name in names {
                d = d.add_note(format!("- {}", name));
            }
            ctx.sess.emit(d);
            return Err(());
        }
    };
    debug!("elaborating {:?}", elab);

    // Generate the LLHD definition for whatever we're elaborating.
    match elab {
        Elaborate::VhdlEntity(_entity, arch) => {
            // let decl = ctx.vhdl.lldecl(arch);
            // println!("Architecture declared as {:?}", decl);
            let def = ctx.vhdl().llunit(arch)?;
            eprintln!("Architecture declared as {:?}", def);
        }
        Elaborate::VhdlPkg(pkg) => {
            use moore::vhdl::typeck::{Typeck, TypeckContext};
            let sbc = ctx.vhdl();
            let tyc = TypeckContext::new(&sbc);
            tyc.typeck(pkg);
            // use moore::vhdl::codegen::Codegen;
            // ctx.vhdl().codegen(pkg, &mut ())?;
        }
        Elaborate::Svlog(m) => {
            // Emit the detailed type analysis if requested.
            if ctx.sess.has_verbosity(Verbosity::TYPES) {
                use svlog::Context;
                TypeVerbosityVisitor(ctx.svlog, ctx.svlog.default_param_env())
                    .visit_node_with_id(m, false);
            }

            // Emit the instantiation details if requested.
            if ctx.sess.has_verbosity(Verbosity::INSTS) {
                svlog::InstVerbosityVisitor::new(ctx.svlog).visit_node_with_id(m, false);
            }

            // Create an MLIR context and load the dialects we need.
            let mlir_cx = mlir::OwnedContext::new();
            mlir_cx.load_dialect(circt::std::dialect());
            mlir_cx.load_dialect(circt::hw::dialect());
            mlir_cx.load_dialect(circt::comb::dialect());
            mlir_cx.load_dialect(circt::llhd::dialect());
            mlir_cx.load_dialect(circt::seq::dialect());

            // Attach a custom diagnostic handler to the context such that we
            // can print MLIR diagnostics through Moore's own diagnostics
            // engine.
            unsafe {
                mlirContextAttachDiagnosticHandler(
                    mlir_cx.raw(),
                    Some(moore_mlir_diagnostic_handler),
                    // SAFETY: The session reference in the context must outlive
                    // the MLIR context, which is the case since that context
                    // is dropped at the end of this function.
                    ctx.sess as *const _ as *mut _,
                    None,
                );
            }

            // Create the top-level MLIR module.
            let mlir_module = circt::ModuleOp::new(*mlir_cx);

            let mut cg = svlog::CodeGenerator::new(ctx.svlog, mlir_module);
            for root in ctx.svlog.roots() {
                cg.emit_globals(root)?;
            }
            cg.emit_module(m)?;
            let module = cg.finalize();
            // let mut module = cg.finalize();
            // let pass_ctx = PassContext;
            // if ctx.sess.opts.opt_level > 0 {
            //     llhd::pass::ConstFolding::run_on_module(&pass_ctx, &mut module);
            //     llhd::pass::VarToPhiPromotion::run_on_module(&pass_ctx, &mut module); // broken in llhd 0.13
            //     llhd::pass::DeadCodeElim::run_on_module(&pass_ctx, &mut module);
            //     llhd::pass::GlobalCommonSubexprElim::run_on_module(&pass_ctx, &mut module);
            //     llhd::pass::InstSimplification::run_on_module(&pass_ctx, &mut module);
            //     llhd::pass::DeadCodeElim::run_on_module(&pass_ctx, &mut module);
            // }

            // Verify the module.
            if !mlir_module.verify() {
                ctx.sess.emit(DiagBuilder2::bug(
                    "verification failed for emitted MLIR module",
                ));
                // mlir_module.dump();
                return Err(());
            }

            // Decide what format to use for the output.
            emit_output(matches, ctx, &module, mlir_module)?
        }
    }
    Ok(())
}

/// A custom handler for MLIR diagnostics, which prints them through Moore's own
/// diagnostic engine.
unsafe extern "C" fn moore_mlir_diagnostic_handler(
    diag: MlirDiagnostic,
    sess: *mut std::ffi::c_void,
) -> MlirLogicalResult {
    let sess: &Session = (sess as *const Session).as_ref().unwrap();

    // Map the severity from MLIR to Moore.
    #[allow(non_upper_case_globals)]
    let severity = match mlirDiagnosticGetSeverity(diag) {
        MlirDiagnosticSeverity_MlirDiagnosticError => Severity::Error,
        MlirDiagnosticSeverity_MlirDiagnosticWarning => Severity::Warning,
        MlirDiagnosticSeverity_MlirDiagnosticNote | MlirDiagnosticSeverity_MlirDiagnosticRemark => {
            Severity::Note
        }
        _ => panic!("unsupported MLIR diagnostic severity"),
    };

    // Create the main diagnostic message and attach location information if
    // possible.
    let mut d = DiagBuilder2::new(severity, mlir_diagnostic_to_string(diag));
    let main_loc = mlirDiagnosticGetLocation(diag);
    if let Some(main_span) = mlir_location_to_span(main_loc) {
        d = d.span(main_span);
    }

    // Add additional notes.
    let mut notes_todo = vec![diag];
    while let Some(note) = notes_todo.pop() {
        if note.ptr != diag.ptr {
            let msg = mlir_diagnostic_to_string(note);
            let loc = mlirDiagnosticGetLocation(note);
            d = d.add_note(msg);
            if !loc.ptr.is_null() && main_loc.ptr != loc.ptr {
                if let Some(span) = mlir_location_to_span(loc) {
                    d = d.span(span);
                }
            }
        }
        let num_notes = mlirDiagnosticGetNumNotes(note);
        for i in (0..num_notes).rev() {
            notes_todo.push(mlirDiagnosticGetNote(note, i));
        }
    }

    sess.emit(d);
    MlirLogicalResult { value: 1 }
}

/// Convert the message in an MLIR diagnostic to a string.
unsafe fn mlir_diagnostic_to_string(diag: MlirDiagnostic) -> String {
    unsafe extern "C" fn stringify_callback(string: MlirStringRef, to: *mut std::ffi::c_void) {
        let to: &mut String = (to as *mut String).as_mut().unwrap();
        to.push_str(
            std::str::from_utf8(std::slice::from_raw_parts(
                string.data as *const _,
                string.length as usize,
            ))
            .expect("utf8 string"),
        );
    }
    let mut string = String::new();
    mlirDiagnosticPrint(
        diag,
        Some(stringify_callback),
        &mut string as *mut _ as *mut _,
    );
    string
}

unsafe fn mlir_location_to_span(loc: MlirLocation) -> Option<Span> {
    if loc.ptr.is_null() {
        return None;
    }
    if mlirLocationIsFileLineCol(loc) {
        let filename = mlirStringRefToStr(mlirFileLineColLocGetFilename(loc), String::from);
        let line = mlirFileLineColLocGetLine(loc) as usize;
        let column = mlirFileLineColLocGetColumn(loc) as usize;
        let source = source::get_source_manager().open(&filename).unwrap();
        let loc = source::Location::with_line_and_column(source, line, column);
        Some(loc.into())
    } else {
        None
    }
}

#[derive(Debug)]
enum OutputFormat {
    Llhd,
    Mlir,
    MlirNative,
}

fn emit_output(
    matches: &ArgMatches,
    ctx: &ScoreContext,
    module: &llhd::ir::Module,
    mlir_module: circt::ModuleOp,
) -> Result<(), ()> {
    // Check if the user has provided an explicit output format.
    let fmt = match matches.value_of("output-format") {
        Some("llhd") => Some(OutputFormat::Llhd),
        Some("mlir") => Some(OutputFormat::Mlir),
        Some("mlir-native") => Some(OutputFormat::MlirNative),
        Some(x) => {
            ctx.sess.emit(DiagBuilder2::fatal(format!(
                "unknown output format: `{}`",
                x
            )));
            return Err(());
        }
        _ => None,
    };

    // Check if the output format can be inferred from the output file suffix.
    let fmt = fmt.or_else(|| {
        match matches
            .value_of("output")
            .and_then(|x| Path::new(x).extension())
            .and_then(|x| x.to_str())
        {
            Some("llhd") => Some(OutputFormat::Llhd),
            Some("mlir") => Some(OutputFormat::Mlir),
            _ => None,
        }
    });

    // Otherwise fall back to the LLHD default output format.
    let fmt = fmt.unwrap_or(OutputFormat::Llhd);
    debug!("Using {:?} output format", fmt);

    // Open the output.
    let stdout = std::io::stdout();
    let output: Box<dyn std::io::Write> = match matches.value_of("output") {
        Some("-") | None => Box::new(stdout.lock()),
        Some(x) => Box::new(std::fs::File::create(x).map_err(|e| {
            ctx.sess.emit(
                DiagBuilder2::fatal(format!("unable to create file: `{}`", x))
                    .add_note(format!("{}", e)),
            );
            ()
        })?),
    };

    // Emit the appropriate output.
    match fmt {
        OutputFormat::Llhd => llhd::assembly::write_module(output, &module),
        OutputFormat::Mlir => llhd::mlir::write_module(output, &module),
        OutputFormat::MlirNative => mlir_module.print(output, matches.is_present("debug-info")),
    };
    Ok(())
}

/// Parse an entity name of the form `(first\.)?second((arch))?` for
/// elaboration.
fn parse_elaborate_name<S: AsRef<str>>(name: S) -> Result<(Option<Name>, Name, Option<Name>), ()> {
    use self::name::get_name_table;
    let name = name.as_ref();
    let nt = get_name_table();

    // Isolate the first name.
    let x: &[_] = &['.', '('];
    let (first, rest) = {
        if let Some(pos) = name.find(x) {
            let (a, b) = name.split_at(pos);
            (a, Some(b))
        } else {
            (name, None)
        }
    };
    let first = nt.intern(first, true);

    // Isolate the second name.
    let (second, rest) = {
        if let Some(rest) = rest {
            if rest.starts_with('.') {
                let rest = &rest[1..];
                if let Some(pos) = rest.find('(') {
                    let (a, b) = rest.split_at(pos);
                    (Some(a), Some(b))
                } else {
                    (Some(rest), None)
                }
            } else {
                (None, Some(rest))
            }
        } else {
            (None, None)
        }
    };
    let second = second.map(|s| nt.intern(s, true));

    // Isolate the architecture name.
    let third = {
        if let Some(rest) = rest {
            if rest.starts_with('(') && rest.ends_with(')') {
                Some(&rest[1..rest.len() - 1])
            } else {
                None
            }
        } else {
            None
        }
    };
    let third = third.map(|t| nt.intern(t, true));

    // Return the names in the appropriate order.
    let (lib, ent) = {
        if let Some(second) = second {
            (Some(first), second)
        } else {
            (None, first)
        }
    };

    Ok((lib, ent, third))
}

/// A visitor that emits detailed type information to stdout.
pub struct TypeVerbosityVisitor<'a, 'gcx>(&'a svlog::GlobalContext<'gcx>, svlog::ParamEnv);

impl<'a, 'gcx> svlog::hir::Visitor<'gcx> for TypeVerbosityVisitor<'a, 'gcx> {
    type Context = svlog::GlobalContext<'gcx>;

    fn context(&self) -> &Self::Context {
        self.0
    }

    fn visit_expr(&mut self, expr: &'gcx svlog::hir::Expr<'gcx>, lvalue: bool) {
        self.print(expr.id);
        svlog::hir::walk_expr(self, expr, lvalue);
    }

    fn visit_var_decl(&mut self, decl: &'gcx svlog::hir::VarDecl) {
        self.print(decl.id);
        svlog::hir::walk_var_decl(self, decl);
    }
}

impl<'a, 'gcx> TypeVerbosityVisitor<'a, 'gcx> {
    fn print(&mut self, id: NodeId) {
        use svlog::Context;
        let span = self.0.span(id);
        let ext = span.extract();
        let line = span.begin().human_line();

        // Report the type.
        if let Ok(ty) = self.0.type_of(id, self.1) {
            println!("{}: type({}) = {}", line, ext, ty);
        }

        // Report the cast type.
        if let Some(cast) = self.0.cast_type(id, self.1) {
            println!("{}: cast_type({}) = {}", line, ext, cast.ty);
            println!("{}: cast_chain({}) = {}", line, ext, cast);
        }

        // Report the self-determined type.
        if let Some(ty) = self.0.self_determined_type(id, self.1) {
            println!("{}: self_type({}) = {}", line, ext, ty);
        }

        // Report the operation type.
        if let Some(ty) = self.0.operation_type(id, self.1) {
            println!("{}: operation_type({}) = {}", line, ext, ty);
        }

        // Report the type context.
        if let Some(expr) = self.0.ast_for_id(id).as_all().get_expr() {
            if let Some(ty) = self.0.type_context(svlog::Ref(expr), self.1) {
                println!(
                    "{}: type_context({}) = {}",
                    line,
                    ext,
                    match ty {
                        svlog::typeck::TypeContext::Type(ty) => format!("{}", ty),
                        svlog::typeck::TypeContext::Bool => "<bool>".to_string(),
                    }
                );
            }
        }
    }
}