use std::path::{Path, PathBuf};
use std::process::Command;
use proc_macro2::Span;
use super::super::llvm_target_info::llvm_target_info_from_rust_triple;
use crate::utils::{query_rustc_host, run_command, target_from_process_args};
pub(super) fn run_iree_compile(
compile_input: &Path,
vmfb: &Path,
object: &Path,
ir_dump_dir: &Path,
) -> syn::Result<()> {
let rust_target = if let Ok(target) =
std::env::var("CARGO_BUILD_TARGET").or_else(|_| std::env::var("TARGET"))
{
target
} else {
target_from_process_args()
.or_else(|| query_rustc_host().map(Into::into))
.ok_or_else(|| syn::Error::new(Span::call_site(), "Rust target triple is unavailable"))?
.into_string()
.map_err(|_| syn::Error::new(Span::call_site(), "target argument is not valid UTF-8"))?
};
let target_info = llvm_target_info_from_rust_triple(&rust_target).map_err(|error| {
syn::Error::new(
Span::call_site(),
format!("failed to get LLVM target info for Rust target {rust_target}: {error}"),
)
})?;
let llvm_triple = target_info.llvm_triple;
let target_cpu = target_info.cpu.filter(|value| !value.is_empty());
let cpu_features = target_info.features.filter(|value| !value.is_empty());
let mut command = Command::new("iree-compile");
command
.arg(compile_input)
.arg("--iree-hal-target-device=local")
.arg("--iree-hal-local-target-device-backends=llvm-cpu")
.arg(format!("--iree-llvmcpu-target-triple={llvm_triple}"));
if let Some(cpu) = target_cpu {
command.arg(format!("--iree-llvmcpu-target-cpu={cpu}"));
}
if let Some(features) = cpu_features {
command.arg(format!("--iree-llvmcpu-target-cpu-features={features}"));
}
command
.arg("--iree-stream-partitioning-favor=min-peak-memory")
.arg("--iree-llvmcpu-link-embedded=false")
.arg("--iree-llvmcpu-link-static")
.arg(format!(
"--iree-llvmcpu-static-library-output-path={}",
object.display()
))
.arg(format!(
"--dump-compilation-phases-to={}",
ir_dump_dir.display()
))
.arg("-o")
.arg(vmfb);
run_command(&mut command, "iree-compile")
}
pub(super) fn run_converter(
input: &Path,
rust_output: &Path,
json_output: &Path,
) -> syn::Result<()> {
let mut command = Command::new("python");
command
.arg(
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("python")
.join("iree_stream_flow_to_rust_using_re.py"),
)
.arg(input)
.arg("--rust-output")
.arg(rust_output)
.arg("--json-output")
.arg(json_output);
run_command(&mut command, "IREE Stream/Flow converter")
}