1#![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#![feature(rustc_private)]
35#![allow(
37 unsafe_code, clippy::enum_glob_use, clippy::todo, mismatched_lifetime_syntaxes,
43 clippy::needless_lifetimes,
44)]
45
46#[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#[cfg(not(rustc_codegen_spirv_disable_pqp_cg_ssa))]
63include!(concat!(env!("OUT_DIR"), "/pqp_cg_ssa.rs"));
64
65#[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#[cfg(rustc_codegen_spirv_disable_pqp_cg_ssa)]
76use rustc_codegen_ssa as maybe_pqp_cg_ssa;
77
78#[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
192struct SpirvModuleBuffer(Vec<u32>);
194
195impl ModuleBufferMethods for SpirvModuleBuffer {
196 fn data(&self) -> &[u8] {
197 spirv_tools::binary::from_binary(&self.0)
198 }
199}
200
201struct 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 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 let unstable_target_features = target_features.clone();
242
243 TargetConfig {
244 target_features,
245 unstable_target_features,
246
247 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 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 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 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 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 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 }
479 };
480 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#[unsafe(no_mangle)]
536pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
537 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
549fn init_logging(sess: &Session) {
551 use std::env::{self, VarError};
552 use std::io::{self, IsTerminal};
553 use tracing_subscriber::layer::SubscriberExt;
554
555 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 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}