rustc_codegen_spirv/
lib.rs

1// HACK(eddyb) start of `rustc_codegen_ssa` crate-level attributes (see `build.rs`).
2#![allow(internal_features)]
3#![allow(rustc::diagnostic_outside_of_impl)]
4#![allow(rustc::untranslatable_diagnostic)]
5#![feature(assert_matches)]
6#![feature(box_patterns)]
7#![feature(file_buffered)]
8#![feature(if_let_guard)]
9#![feature(negative_impls)]
10#![feature(rustdoc_internals)]
11#![feature(string_from_utf8_lossy_owned)]
12#![feature(trait_alias)]
13#![feature(try_blocks)]
14#![recursion_limit = "256"]
15// HACK(eddyb) end of `rustc_codegen_ssa` crate-level attributes (see `build.rs`).
16
17//! Welcome to the API documentation for the `rust-gpu` project, this API is
18//! unstable and mainly intended for developing on the project itself. This is
19//! the API documentation for `rustc_codegen_spirv` which is not that useful on
20//! its own. You might also be interested in the following crates. There's also
21//! the [Rust GPU Dev Guide][gpu-dev-guide] which contains more user-level
22//! information on how to use and setup `rust-gpu`.
23//!
24//! - [`spirv-builder`]
25//! - [`spirv-std`]
26//! - [`spirv-tools`]
27//! - [`spirv-tools-sys`]
28//!
29//! [gpu-dev-guide]: https://rust-gpu.github.io/rust-gpu/book
30//! [`spirv-builder`]: https://rust-gpu.github.io/rust-gpu/api/spirv_builder
31//! [`spirv-std`]: https://rust-gpu.github.io/rust-gpu/api/spirv_std
32//! [`spirv-tools`]: https://rust-gpu.github.io/rust-gpu/api/spirv_tools
33//! [`spirv-tools-sys`]: https://rust-gpu.github.io/rust-gpu/api/spirv_tools_sys
34#![feature(rustc_private)]
35// crate-specific exceptions:
36#![allow(
37    unsafe_code,                // rustc_codegen_ssa requires unsafe functions in traits to be impl'd
38    clippy::enum_glob_use,      // pretty useful pattern with some codegen'd enums (e.g. rspirv::spirv::Op)
39    clippy::todo,               // still lots to implement :)
40
41    // FIXME(eddyb) new warnings from 1.83 rustup, apply their suggested changes.
42    mismatched_lifetime_syntaxes,
43    clippy::needless_lifetimes,
44)]
45
46// Unfortunately, this will not fail fast when compiling, but rather will wait for
47// rustc_codegen_spirv to be compiled. Putting this in build.rs will solve that problem, however,
48// that creates the much worse problem that then running `cargo check` will cause
49// rustc_codegen_spirv to be *compiled* instead of merely checked, something that takes
50// significantly longer. So, the trade-off between detecting a bad configuration slower for a
51// faster `cargo check` is worth it.
52#[cfg(all(feature = "use-compiled-tools", feature = "use-installed-tools"))]
53compile_error!(
54    "Either \"use-compiled-tools\" (enabled by default) or \"use-installed-tools\" may be enabled."
55);
56
57// HACK(eddyb) `build.rs` copies `rustc_codegen_ssa` (from the `rustc-dev` component)
58// and patches it to produce a "pqp" ("pre-`qptr`-patched") version that maintains
59// compatibility with "legacy" Rust-GPU pointer handling (mainly typed `alloca`s).
60//
61// FIXME(eddyb) get rid of this as soon as it's not needed anymore.
62#[cfg(not(rustc_codegen_spirv_disable_pqp_cg_ssa))]
63include!(concat!(env!("OUT_DIR"), "/pqp_cg_ssa.rs"));
64
65// HACK(eddyb) guide `rustc` to finding the right deps in the sysroot, which
66// (sadly) has to be outside `include!` to have any effect whatsoever.
67// FIXME(eddyb) this only really handles `bitflags`, not `object`.
68#[cfg(not(rustc_codegen_spirv_disable_pqp_cg_ssa))]
69mod _rustc_codegen_ssa_transitive_deps_hack {
70    extern crate rustc_codegen_ssa as _;
71}
72
73// NOTE(eddyb) `mod maybe_pqp_cg_ssa` is defined by the above `include`, when
74// in the (default for now) `pqp_cg_ssa` mode (see `build.rs`).
75#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
76use rustc_codegen_ssa as maybe_pqp_cg_ssa;
77
78// FIXME(eddyb) remove all `#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]`
79// as soon as they're not needed anymore (i.e. using `rustc_codegen_ssa` again).
80#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
81extern crate rustc_abi;
82extern crate rustc_apfloat;
83#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
84extern crate rustc_arena;
85#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
86extern crate rustc_ast;
87#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
88extern crate rustc_attr_data_structures;
89#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
90extern crate rustc_attr_parsing;
91#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
92extern crate rustc_codegen_ssa;
93#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
94extern crate rustc_data_structures;
95extern crate rustc_driver;
96#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
97extern crate rustc_errors;
98#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
99extern crate rustc_hashes;
100#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
101extern crate rustc_hir;
102#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
103extern crate rustc_index;
104extern crate rustc_interface;
105#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
106extern crate rustc_metadata;
107#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
108extern crate rustc_middle;
109#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
110extern crate rustc_session;
111#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
112extern crate rustc_span;
113#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
114extern crate rustc_target;
115
116macro_rules! assert_ty_eq {
117    ($codegen_cx:expr, $left:expr, $right:expr) => {
118        assert!(
119            $left == $right,
120            "Expected types to be equal:\n{}\n==\n{}",
121            $codegen_cx.debug_type($left),
122            $codegen_cx.debug_type($right)
123        )
124    };
125}
126
127mod abi;
128mod attr;
129mod builder;
130mod builder_spirv;
131mod codegen_cx;
132mod custom_decorations;
133mod custom_insts;
134mod link;
135mod linker;
136mod spirv_type;
137mod spirv_type_constraints;
138mod symbols;
139mod target;
140mod target_feature;
141
142use builder::Builder;
143use codegen_cx::CodegenCx;
144use maybe_pqp_cg_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule};
145use maybe_pqp_cg_ssa::back::write::{
146    CodegenContext, FatLtoInput, ModuleConfig, OngoingCodegen, TargetMachineFactoryConfig,
147};
148use maybe_pqp_cg_ssa::base::maybe_create_entry_wrapper;
149use maybe_pqp_cg_ssa::mono_item::MonoItemExt;
150use maybe_pqp_cg_ssa::traits::{
151    CodegenBackend, ExtraBackendMethods, ModuleBufferMethods, ThinBufferMethods,
152    WriteBackendMethods,
153};
154use maybe_pqp_cg_ssa::{CodegenResults, CompiledModule, ModuleCodegen, ModuleKind, TargetConfig};
155use rspirv::binary::Assemble;
156use rustc_ast::expand::allocator::AllocatorKind;
157use rustc_ast::expand::autodiff_attrs::AutoDiffItem;
158use rustc_data_structures::fx::FxIndexMap;
159use rustc_errors::{DiagCtxtHandle, FatalError};
160use rustc_metadata::EncodedMetadata;
161use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
162use rustc_middle::mir::mono::{MonoItem, MonoItemData};
163use rustc_middle::mir::pretty::write_mir_pretty;
164use rustc_middle::ty::print::with_no_trimmed_paths;
165use rustc_middle::ty::{InstanceKind, TyCtxt};
166use rustc_session::Session;
167use rustc_session::config::{self, OutputFilenames, OutputType};
168use rustc_span::symbol::Symbol;
169use std::any::Any;
170use std::fs::{File, create_dir_all};
171use std::io::Cursor;
172use std::io::Write;
173use std::path::Path;
174use std::sync::Arc;
175use tracing::{error, warn};
176
177fn dump_mir(tcx: TyCtxt<'_>, mono_items: &[(MonoItem<'_>, MonoItemData)], path: &Path) {
178    create_dir_all(path.parent().unwrap()).unwrap();
179    let mut file = File::create(path).unwrap();
180    for &(mono_item, _) in mono_items {
181        if let MonoItem::Fn(instance) = mono_item
182            && matches!(instance.def, InstanceKind::Item(_))
183        {
184            let mut mir = Cursor::new(Vec::new());
185            if write_mir_pretty(tcx, Some(instance.def_id()), &mut mir).is_ok() {
186                writeln!(file, "{}", String::from_utf8(mir.into_inner()).unwrap()).unwrap();
187            }
188        }
189    }
190}
191
192// TODO: Should this store Vec or Module?
193struct SpirvModuleBuffer(Vec<u32>);
194
195impl ModuleBufferMethods for SpirvModuleBuffer {
196    fn data(&self) -> &[u8] {
197        spirv_tools::binary::from_binary(&self.0)
198    }
199}
200
201// TODO: Should this store Vec or Module?
202struct SpirvThinBuffer(Vec<u32>);
203
204impl ThinBufferMethods for SpirvThinBuffer {
205    fn data(&self) -> &[u8] {
206        spirv_tools::binary::from_binary(&self.0)
207    }
208    fn thin_link_data(&self) -> &[u8] {
209        &[]
210    }
211}
212
213#[derive(Clone)]
214struct SpirvCodegenBackend;
215
216impl CodegenBackend for SpirvCodegenBackend {
217    fn init(&self, sess: &Session) {
218        // Set up logging/tracing. See https://github.com/Rust-GPU/rust-gpu/issues/192.
219        init_logging(sess);
220    }
221
222    fn locale_resource(&self) -> &'static str {
223        rustc_errors::DEFAULT_LOCALE_RESOURCE
224    }
225
226    fn target_config(&self, sess: &Session) -> TargetConfig {
227        let cmdline = sess.opts.cg.target_feature.split(',');
228        let cfg = sess.target.options.features.split(',');
229
230        let target_features: Vec<_> = cfg
231            .chain(cmdline)
232            .filter(|l| l.starts_with('+'))
233            .map(|l| &l[1..])
234            .filter(|l| !l.is_empty())
235            .map(Symbol::intern)
236            .collect();
237
238        // HACK(eddyb) this should be a superset of `target_features`,
239        // which *additionally* also includes unstable target features,
240        // but there is no reason to make a distinction for SPIR-V ones.
241        let unstable_target_features = target_features.clone();
242
243        TargetConfig {
244            target_features,
245            unstable_target_features,
246
247            // FIXME(eddyb) support and/or emulate `f16` and `f128`.
248            has_reliable_f16: false,
249            has_reliable_f16_math: false,
250            has_reliable_f128: false,
251            has_reliable_f128_math: false,
252        }
253    }
254
255    fn provide(&self, providers: &mut rustc_middle::util::Providers) {
256        // FIXME(eddyb) this is currently only passed back to us, specifically
257        // into `target_machine_factory` (which is a noop), but it might make
258        // sense to move some of the target feature parsing into here.
259        providers.global_backend_features = |_tcx, ()| vec![];
260
261        crate::abi::provide(providers);
262        crate::attr::provide(providers);
263    }
264
265    fn codegen_crate(&self, tcx: TyCtxt<'_>) -> Box<dyn Any> {
266        Box::new(maybe_pqp_cg_ssa::base::codegen_crate(
267            Self,
268            tcx,
269            tcx.sess
270                .opts
271                .cg
272                .target_cpu
273                .clone()
274                .unwrap_or_else(|| tcx.sess.target.cpu.to_string()),
275        ))
276    }
277
278    fn join_codegen(
279        &self,
280        ongoing_codegen: Box<dyn Any>,
281        sess: &Session,
282        _outputs: &OutputFilenames,
283    ) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
284        ongoing_codegen
285            .downcast::<OngoingCodegen<Self>>()
286            .expect("Expected OngoingCodegen, found Box<Any>")
287            .join(sess)
288    }
289
290    fn link(
291        &self,
292        sess: &Session,
293        codegen_results: CodegenResults,
294        metadata: EncodedMetadata,
295        outputs: &OutputFilenames,
296    ) {
297        let timer = sess.timer("link_crate");
298        link::link(
299            sess,
300            &codegen_results,
301            &metadata,
302            outputs,
303            codegen_results.crate_info.local_crate_name.as_str(),
304        );
305        drop(timer);
306    }
307}
308
309impl WriteBackendMethods for SpirvCodegenBackend {
310    type Module = Vec<u32>;
311    type TargetMachine = ();
312    type TargetMachineError = String;
313    type ModuleBuffer = SpirvModuleBuffer;
314    type ThinData = ();
315    type ThinBuffer = SpirvThinBuffer;
316
317    fn run_link(
318        _cgcx: &CodegenContext<Self>,
319        _diag_handler: DiagCtxtHandle<'_>,
320        _modules: Vec<ModuleCodegen<Self::Module>>,
321    ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
322        todo!()
323    }
324
325    fn run_fat_lto(
326        _: &CodegenContext<Self>,
327        _: Vec<FatLtoInput<Self>>,
328        _: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
329    ) -> Result<LtoModuleCodegen<Self>, FatalError> {
330        todo!()
331    }
332
333    fn run_thin_lto(
334        cgcx: &CodegenContext<Self>,
335        modules: Vec<(String, Self::ThinBuffer)>,
336        cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
337    ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
338        link::run_thin(cgcx, modules, cached_modules)
339    }
340
341    fn print_pass_timings(&self) {
342        warn!("TODO: Implement print_pass_timings");
343    }
344
345    fn print_statistics(&self) {
346        warn!("TODO: Implement print_statistics");
347    }
348
349    fn optimize(
350        _: &CodegenContext<Self>,
351        _: DiagCtxtHandle<'_>,
352        _: &mut ModuleCodegen<Self::Module>,
353        _: &ModuleConfig,
354    ) -> Result<(), FatalError> {
355        // TODO: Implement
356        Ok(())
357    }
358
359    fn optimize_thin(
360        _cgcx: &CodegenContext<Self>,
361        thin_module: ThinModule<Self>,
362    ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
363        let module = ModuleCodegen {
364            module_llvm: spirv_tools::binary::to_binary(thin_module.data())
365                .unwrap()
366                .to_vec(),
367            name: thin_module.name().to_string(),
368            kind: ModuleKind::Regular,
369            thin_lto_buffer: None,
370        };
371        Ok(module)
372    }
373
374    fn optimize_fat(
375        _: &CodegenContext<Self>,
376        _: &mut ModuleCodegen<Self::Module>,
377    ) -> Result<(), FatalError> {
378        todo!()
379    }
380
381    fn codegen(
382        cgcx: &CodegenContext<Self>,
383        _diag_handler: DiagCtxtHandle<'_>,
384        module: ModuleCodegen<Self::Module>,
385        _config: &ModuleConfig,
386    ) -> Result<CompiledModule, FatalError> {
387        let path = cgcx.output_filenames.temp_path_for_cgu(
388            OutputType::Object,
389            &module.name,
390            cgcx.invocation_temp.as_deref(),
391        );
392        // Note: endianness doesn't matter, readers deduce endianness from magic header.
393        let spirv_module = spirv_tools::binary::from_binary(&module.module_llvm);
394        File::create(&path)
395            .unwrap()
396            .write_all(spirv_module)
397            .unwrap();
398        Ok(CompiledModule {
399            name: module.name,
400            kind: module.kind,
401            object: Some(path),
402            dwarf_object: None,
403            bytecode: None,
404            assembly: None,
405            llvm_ir: None,
406            links_from_incr_cache: vec![],
407        })
408    }
409
410    fn prepare_thin(
411        module: ModuleCodegen<Self::Module>,
412        _want_summary: bool,
413    ) -> (String, Self::ThinBuffer) {
414        (module.name, SpirvThinBuffer(module.module_llvm))
415    }
416
417    fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
418        (module.name, SpirvModuleBuffer(module.module_llvm))
419    }
420
421    fn autodiff(
422        _cgcx: &CodegenContext<Self>,
423        _module: &ModuleCodegen<Self::Module>,
424        _diff_fncs: Vec<AutoDiffItem>,
425        _config: &ModuleConfig,
426    ) -> Result<(), FatalError> {
427        todo!()
428    }
429}
430
431impl ExtraBackendMethods for SpirvCodegenBackend {
432    fn codegen_allocator(
433        &self,
434        _: TyCtxt<'_>,
435        _: &str,
436        _: AllocatorKind,
437        _: AllocatorKind,
438    ) -> Self::Module {
439        todo!()
440    }
441
442    fn compile_codegen_unit<'tcx>(
443        &self,
444        tcx: TyCtxt<'tcx>,
445        cgu_name: Symbol,
446    ) -> (ModuleCodegen<Self::Module>, u64) {
447        let _timer = tcx
448            .prof
449            .verbose_generic_activity_with_arg("codegen_module", cgu_name.to_string());
450
451        // TODO: Do dep_graph stuff
452        let cgu = tcx.codegen_unit(cgu_name);
453
454        let mut cx = CodegenCx::new(tcx, cgu);
455        let do_codegen = |cx: &mut CodegenCx<'tcx>| {
456            let mono_items = cgu.items_in_deterministic_order(cx.tcx);
457
458            if let Some(dir) = &cx.codegen_args.dump_mir {
459                dump_mir(tcx, mono_items.as_slice(), &dir.join(cgu_name.to_string()));
460            }
461
462            for &(mono_item, mono_item_data) in mono_items.iter() {
463                mono_item.predefine::<Builder<'_, '_>>(
464                    cx,
465                    cgu_name.as_str(),
466                    mono_item_data.linkage,
467                    mono_item_data.visibility,
468                );
469            }
470
471            // ... and now that we have everything pre-defined, fill out those definitions.
472            for &(mono_item, mono_item_data) in &mono_items {
473                mono_item.define::<Builder<'_, '_>>(cx, cgu_name.as_str(), mono_item_data);
474            }
475
476            if let Some(_entry) = maybe_create_entry_wrapper::<Builder<'_, '_>>(cx, cgu) {
477                // attributes::sanitize(&cx, SanitizerSet::empty(), entry);
478            }
479        };
480        // HACK(eddyb) mutable access needed for `mono_item.define::<...>(cx, ...)`
481        // but that alone leads to needless cloning and smuggling a mutable borrow
482        // through `DumpModuleOnPanic` (for both its `Drop` impl and `do_codegen`).
483        if let Some(path) = cx.codegen_args.dump_module_on_panic.clone() {
484            let module_dumper = DumpModuleOnPanic {
485                cx: &mut cx,
486                path: &path,
487            };
488            with_no_trimmed_paths!(do_codegen(module_dumper.cx));
489            drop(module_dumper);
490        } else {
491            with_no_trimmed_paths!(do_codegen(&mut cx));
492        }
493        let spirv_module = cx.finalize_module().assemble();
494
495        (
496            ModuleCodegen {
497                name: cgu_name.to_string(),
498                module_llvm: spirv_module,
499                kind: ModuleKind::Regular,
500                thin_lto_buffer: None,
501            },
502            0,
503        )
504    }
505
506    fn target_machine_factory(
507        &self,
508        _sess: &Session,
509        _opt_level: config::OptLevel,
510        _target_features: &[String],
511    ) -> Arc<(dyn Fn(TargetMachineFactoryConfig) -> Result<(), String> + Send + Sync + 'static)>
512    {
513        Arc::new(|_| Ok(()))
514    }
515}
516
517struct DumpModuleOnPanic<'a, 'cx, 'tcx> {
518    cx: &'cx mut CodegenCx<'tcx>,
519    path: &'a Path,
520}
521
522impl Drop for DumpModuleOnPanic<'_, '_, '_> {
523    fn drop(&mut self) {
524        if std::thread::panicking() {
525            if self.path.has_root() {
526                self.cx.builder.dump_module(self.path);
527            } else {
528                error!("{}", self.cx.builder.dump_module_str());
529            }
530        }
531    }
532}
533
534/// This is the entrypoint for a hot plugged `rustc_codegen_spirv`
535#[unsafe(no_mangle)]
536pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
537    // Tweak rustc's default ICE panic hook, to direct people to `rust-gpu`.
538    rustc_driver::install_ice_hook("https://github.com/rust-gpu/rust-gpu/issues/new", |dcx| {
539        dcx.handle().note(concat!(
540            "`rust-gpu` version `",
541            env!("CARGO_PKG_VERSION"),
542            "`"
543        ));
544    });
545
546    Box::new(SpirvCodegenBackend)
547}
548
549// Set up logging/tracing. See https://github.com/Rust-GPU/rust-gpu/issues/192.
550fn init_logging(sess: &Session) {
551    use std::env::{self, VarError};
552    use std::io::{self, IsTerminal};
553    use tracing_subscriber::layer::SubscriberExt;
554
555    // Set up the default subscriber with optional filtering.
556    let filter = tracing_subscriber::EnvFilter::from_env("RUSTGPU_LOG");
557    #[cfg(not(rustc_codegen_spirv_disable_pqp_cg_ssa))]
558    let filter = filter.add_directive("rustc_codegen_spirv::maybe_pqp_cg_ssa=off".parse().unwrap());
559    let subscriber = tracing_subscriber::Registry::default().with(filter);
560
561    #[derive(Debug, Default)]
562    enum OutputFormat {
563        #[default]
564        Tree,
565        Flat,
566        Json,
567    }
568
569    let output_format = match env::var("RUSTGPU_LOG_FORMAT").as_deref() {
570        Ok("tree") | Err(VarError::NotPresent) => OutputFormat::Tree,
571        Ok("flat") => OutputFormat::Flat,
572        Ok("json") => OutputFormat::Json,
573        Ok(value) => sess.dcx().fatal(format!(
574            "invalid output format value '{value}': expected one of tree, flat, or json",
575        )),
576        Err(VarError::NotUnicode(value)) => sess.dcx().fatal(format!(
577            "invalid output format value '{}': expected one of tree, flat, or json",
578            value.to_string_lossy()
579        )),
580    };
581
582    let subscriber: Box<dyn tracing::Subscriber + Send + Sync> = match output_format {
583        OutputFormat::Tree => {
584            // TODO(@LegNeato): Query dcx color support when rustc exposes it.
585            let color_logs = match env::var("RUSTGPU_LOG_COLOR").as_deref() {
586                Ok("always") => true,
587                Ok("never") => false,
588                Ok("auto") | Err(VarError::NotPresent) => io::stderr().is_terminal(),
589                Ok(value) => sess.dcx().fatal(format!(
590                    "invalid log color value '{value}': expected one of always, never, or auto",
591                )),
592                Err(VarError::NotUnicode(value)) => sess.dcx().fatal(format!(
593                    "invalid log color value '{}': expected one of always, never, or auto",
594                    value.to_string_lossy()
595                )),
596            };
597
598            let tree_layer = tracing_tree::HierarchicalLayer::default()
599                .with_writer(io::stderr)
600                .with_ansi(color_logs)
601                .with_targets(true)
602                .with_wraparound(10)
603                .with_verbose_exit(true)
604                .with_verbose_entry(true)
605                .with_indent_amount(2);
606
607            #[cfg(debug_assertions)]
608            let tree_layer = tree_layer.with_thread_ids(true).with_thread_names(true);
609
610            Box::new(subscriber.with(tree_layer))
611        }
612        OutputFormat::Flat => Box::new(subscriber),
613        OutputFormat::Json => Box::new(subscriber.with(tracing_subscriber::fmt::layer().json())),
614    };
615    tracing::subscriber::set_global_default(subscriber).unwrap();
616}