diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 12da1365b2b3e..4559246ce4276 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,7 +34,7 @@ concurrency: # For a given workflow, if we push to the same branch, cancel all previous builds on that branch. # We add an exception for try builds (try branch) and unrolled rollup builds (try-perf), which # are all triggered on the same branch, but which should be able to run concurrently. - group: ${{ github.workflow }}-${{ ((github.ref == 'refs/heads/try' || github.ref == 'refs/heads/try-perf') && github.sha) || github.ref }} + group: ${{ github.workflow }}-${{ ((github.ref == 'refs/heads/try' || github.ref == 'refs/heads/try-perf' || github.ref == 'refs/heads/automation/bors/try') && github.sha) || github.ref }} cancel-in-progress: true env: TOOLSTATE_REPO: "https://github.com/rust-lang-nursery/rust-toolstate" @@ -80,7 +80,7 @@ jobs: # access the environment. # # We only enable the environment for the rust-lang/rust repository, so that CI works on forks. - environment: ${{ ((github.repository == 'rust-lang/rust' && (github.ref == 'refs/heads/try' || github.ref == 'refs/heads/try-perf' || github.ref == 'refs/heads/auto')) && 'bors') || '' }} + environment: ${{ ((github.repository == 'rust-lang/rust' && (github.ref == 'refs/heads/try' || github.ref == 'refs/heads/try-perf' || github.ref == 'refs/heads/automation/bors/try' || github.ref == 'refs/heads/auto')) && 'bors') || '' }} env: CI_JOB_NAME: ${{ matrix.name }} CI_JOB_DOC_URL: ${{ matrix.doc_url }} diff --git a/compiler/rustc_ast/src/mut_visit.rs b/compiler/rustc_ast/src/mut_visit.rs index a2e5e3b57fd7f..1700c701e8e05 100644 --- a/compiler/rustc_ast/src/mut_visit.rs +++ b/compiler/rustc_ast/src/mut_visit.rs @@ -77,7 +77,7 @@ pub trait MutVisitor: Sized { walk_use_tree(self, use_tree); } - fn visit_foreign_item(&mut self, ni: &mut P) { + fn visit_foreign_item(&mut self, ni: &mut ForeignItem) { walk_item(self, ni); } @@ -85,7 +85,7 @@ pub trait MutVisitor: Sized { walk_flat_map_foreign_item(self, ni) } - fn visit_item(&mut self, i: &mut P) { + fn visit_item(&mut self, i: &mut Item) { walk_item(self, i); } @@ -105,7 +105,7 @@ pub trait MutVisitor: Sized { walk_flat_map_field_def(self, fd) } - fn visit_assoc_item(&mut self, i: &mut P, ctxt: AssocCtxt) { + fn visit_assoc_item(&mut self, i: &mut AssocItem, ctxt: AssocCtxt) { walk_assoc_item(self, i, ctxt) } @@ -117,11 +117,11 @@ pub trait MutVisitor: Sized { walk_flat_map_assoc_item(self, i, ctxt) } - fn visit_contract(&mut self, c: &mut P) { + fn visit_contract(&mut self, c: &mut FnContract) { walk_contract(self, c); } - fn visit_fn_decl(&mut self, d: &mut P) { + fn visit_fn_decl(&mut self, d: &mut FnDecl) { walk_fn_decl(self, d); } @@ -138,7 +138,7 @@ pub trait MutVisitor: Sized { walk_closure_binder(self, b); } - fn visit_block(&mut self, b: &mut P) { + fn visit_block(&mut self, b: &mut Block) { walk_block(self, b); } @@ -184,7 +184,7 @@ pub trait MutVisitor: Sized { walk_ty(self, t); } - fn visit_ty_pat(&mut self, t: &mut P) { + fn visit_ty_pat(&mut self, t: &mut TyPat) { walk_ty_pat(self, t); } @@ -240,7 +240,7 @@ pub trait MutVisitor: Sized { walk_parenthesized_parameter_data(self, p); } - fn visit_local(&mut self, l: &mut P) { + fn visit_local(&mut self, l: &mut Local) { walk_local(self, l); } @@ -507,8 +507,8 @@ fn walk_assoc_item_constraint( vis.visit_span(span); } -pub fn walk_ty(vis: &mut T, ty: &mut P) { - let Ty { id, kind, span, tokens: _ } = ty.deref_mut(); +pub fn walk_ty(vis: &mut T, ty: &mut Ty) { + let Ty { id, kind, span, tokens: _ } = ty; vis.visit_id(id); match kind { TyKind::Err(_guar) => {} @@ -559,8 +559,8 @@ pub fn walk_ty(vis: &mut T, ty: &mut P) { vis.visit_span(span); } -pub fn walk_ty_pat(vis: &mut T, ty: &mut P) { - let TyPat { id, kind, span, tokens: _ } = ty.deref_mut(); +pub fn walk_ty_pat(vis: &mut T, ty: &mut TyPat) { + let TyPat { id, kind, span, tokens: _ } = ty; vis.visit_id(id); match kind { TyPatKind::Range(start, end, _include_end) => { @@ -651,8 +651,8 @@ fn walk_parenthesized_parameter_data(vis: &mut T, args: &mut Pare vis.visit_span(inputs_span); } -fn walk_local(vis: &mut T, local: &mut P) { - let Local { id, super_, pat, ty, kind, span, colon_sp, attrs, tokens: _ } = local.deref_mut(); +fn walk_local(vis: &mut T, local: &mut Local) { + let Local { id, super_, pat, ty, kind, span, colon_sp, attrs, tokens: _ } = local; visit_opt(super_, |sp| vis.visit_span(sp)); vis.visit_id(id); visit_attrs(vis, attrs); @@ -789,8 +789,8 @@ fn walk_fn(vis: &mut T, kind: FnKind<'_>) { } } -fn walk_contract(vis: &mut T, contract: &mut P) { - let FnContract { requires, ensures } = contract.deref_mut(); +fn walk_contract(vis: &mut T, contract: &mut FnContract) { + let FnContract { requires, ensures } = contract; if let Some(pred) = requires { vis.visit_expr(pred); } @@ -799,8 +799,8 @@ fn walk_contract(vis: &mut T, contract: &mut P) { } } -fn walk_fn_decl(vis: &mut T, decl: &mut P) { - let FnDecl { inputs, output } = decl.deref_mut(); +fn walk_fn_decl(vis: &mut T, decl: &mut FnDecl) { + let FnDecl { inputs, output } = decl; inputs.flat_map_in_place(|param| vis.flat_map_param(param)); vis.visit_fn_ret_ty(output); } @@ -999,8 +999,8 @@ pub fn walk_flat_map_expr_field( smallvec![f] } -pub fn walk_block(vis: &mut T, block: &mut P) { - let Block { id, stmts, rules: _, span, tokens: _ } = block.deref_mut(); +pub fn walk_block(vis: &mut T, block: &mut Block) { + let Block { id, stmts, rules: _, span, tokens: _ } = block; vis.visit_id(id); stmts.flat_map_in_place(|stmt| vis.flat_map_stmt(stmt)); vis.visit_span(span); @@ -1049,8 +1049,8 @@ pub fn walk_flat_map_assoc_item( smallvec![item] } -pub fn walk_pat(vis: &mut T, pat: &mut P) { - let Pat { id, kind, span, tokens: _ } = pat.deref_mut(); +pub fn walk_pat(vis: &mut T, pat: &mut Pat) { + let Pat { id, kind, span, tokens: _ } = pat; vis.visit_id(id); match kind { PatKind::Err(_guar) => {} diff --git a/compiler/rustc_ast/src/visit.rs b/compiler/rustc_ast/src/visit.rs index 1cc11b58dd97b..e1c2dd053242c 100644 --- a/compiler/rustc_ast/src/visit.rs +++ b/compiler/rustc_ast/src/visit.rs @@ -404,10 +404,10 @@ macro_rules! common_visitor_and_walkers { fn walk_item_ctxt<$($lt,)? V: $Visitor$(<$lt>)?, K: WalkItemKind>( visitor: &mut V, - item: &$($mut P>)? $($lt Item)?, + item: &$($mut)? $($lt)? Item, ctxt: K::Ctxt, ) $(-> >::Result)? { - let Item { attrs, id, kind, vis, span, tokens: _ } = &$($mut *)? *item; + let Item { attrs, id, kind, vis, span, tokens: _ } = item; try_visit!(visit_id(visitor, id)); walk_list!(visitor, visit_attribute, attrs); try_visit!(visitor.visit_vis(vis)); @@ -417,14 +417,14 @@ macro_rules! common_visitor_and_walkers { pub fn walk_item<$($lt,)? V: $Visitor$(<$lt>)?, K: WalkItemKind>( visitor: &mut V, - item: &$($mut P>)? $($lt Item)?, + item: &$($mut)? $($lt)? Item, ) $(-> >::Result)? { walk_item_ctxt(visitor, item, ()) } pub fn walk_assoc_item<$($lt,)? V: $Visitor$(<$lt>)?>( visitor: &mut V, - item: &$($mut P)? $($lt AssocItem)?, + item: &$($mut)? $($lt)? AssocItem, ctxt: AssocCtxt, ) $(-> >::Result)? { walk_item_ctxt(visitor, item, ctxt) diff --git a/compiler/rustc_builtin_macros/src/test_harness.rs b/compiler/rustc_builtin_macros/src/test_harness.rs index 56a67b0534d98..0bc313cbdacb4 100644 --- a/compiler/rustc_builtin_macros/src/test_harness.rs +++ b/compiler/rustc_builtin_macros/src/test_harness.rs @@ -128,9 +128,7 @@ impl<'a> MutVisitor for TestHarnessGenerator<'a> { c.items.push(mk_main(&mut self.cx)); } - fn visit_item(&mut self, item: &mut P) { - let item = &mut **item; - + fn visit_item(&mut self, item: &mut ast::Item) { if let Some(name) = get_test_name(&item) { debug!("this is a test item"); @@ -193,7 +191,7 @@ struct EntryPointCleaner<'a> { } impl<'a> MutVisitor for EntryPointCleaner<'a> { - fn visit_item(&mut self, item: &mut P) { + fn visit_item(&mut self, item: &mut ast::Item) { self.depth += 1; ast::mut_visit::walk_item(self, item); self.depth -= 1; diff --git a/compiler/rustc_codegen_gcc/src/abi.rs b/compiler/rustc_codegen_gcc/src/abi.rs index d882d3eecf49a..0c499ba623794 100644 --- a/compiler/rustc_codegen_gcc/src/abi.rs +++ b/compiler/rustc_codegen_gcc/src/abi.rs @@ -15,7 +15,6 @@ use rustc_target::callconv::{Conv, RiscvInterruptKind}; use crate::builder::Builder; use crate::context::CodegenCx; -use crate::intrinsic::ArgAbiExt; use crate::type_of::LayoutGccExt; impl AbiBuilderMethods for Builder<'_, '_, '_> { @@ -125,7 +124,7 @@ impl<'gcc, 'tcx> FnAbiGccExt<'gcc, 'tcx> for FnAbi<'tcx, Ty<'tcx>> { PassMode::Direct(_) | PassMode::Pair(..) => self.ret.layout.immediate_gcc_type(cx), PassMode::Cast { ref cast, .. } => cast.gcc_type(cx), PassMode::Indirect { .. } => { - argument_tys.push(cx.type_ptr_to(self.ret.memory_ty(cx))); + argument_tys.push(cx.type_ptr_to(self.ret.layout.gcc_type(cx))); cx.type_void() } }; @@ -176,13 +175,13 @@ impl<'gcc, 'tcx> FnAbiGccExt<'gcc, 'tcx> for FnAbi<'tcx, Ty<'tcx>> { PassMode::Indirect { attrs: _, meta_attrs: None, on_stack: true } => { // This is a "byval" argument, so we don't apply the `restrict` attribute on it. on_stack_param_indices.insert(argument_tys.len()); - arg.memory_ty(cx) + arg.layout.gcc_type(cx) } PassMode::Direct(attrs) => { apply_attrs(arg.layout.immediate_gcc_type(cx), &attrs, argument_tys.len()) } PassMode::Indirect { attrs, meta_attrs: None, on_stack: false } => { - apply_attrs(cx.type_ptr_to(arg.memory_ty(cx)), &attrs, argument_tys.len()) + apply_attrs(cx.type_ptr_to(arg.layout.gcc_type(cx)), &attrs, argument_tys.len()) } PassMode::Indirect { attrs, meta_attrs: Some(meta_attrs), on_stack } => { assert!(!on_stack); diff --git a/compiler/rustc_codegen_gcc/src/base.rs b/compiler/rustc_codegen_gcc/src/base.rs index a9d7808c833bb..c105916bbb2b5 100644 --- a/compiler/rustc_codegen_gcc/src/base.rs +++ b/compiler/rustc_codegen_gcc/src/base.rs @@ -219,17 +219,22 @@ pub fn compile_codegen_unit( let mono_items = cgu.items_in_deterministic_order(tcx); for &(mono_item, data) in &mono_items { - mono_item.predefine::>(&cx, data.linkage, data.visibility); + mono_item.predefine::>( + &mut cx, + cgu_name.as_str(), + data.linkage, + data.visibility, + ); } // ... and now that we have everything pre-defined, fill out those definitions. for &(mono_item, item_data) in &mono_items { - mono_item.define::>(&mut cx, item_data); + mono_item.define::>(&mut cx, cgu_name.as_str(), item_data); } // If this codegen unit contains the main function, also create the // wrapper here - maybe_create_entry_wrapper::>(&cx); + maybe_create_entry_wrapper::>(&cx, cx.codegen_unit); // Finalize debuginfo if cx.sess().opts.debuginfo != DebugInfo::None { diff --git a/compiler/rustc_codegen_gcc/src/consts.rs b/compiler/rustc_codegen_gcc/src/consts.rs index 8aed04c836ac6..deb13ddf7558d 100644 --- a/compiler/rustc_codegen_gcc/src/consts.rs +++ b/compiler/rustc_codegen_gcc/src/consts.rs @@ -67,7 +67,7 @@ impl<'gcc, 'tcx> StaticCodegenMethods for CodegenCx<'gcc, 'tcx> { } #[cfg_attr(not(feature = "master"), allow(unused_mut))] - fn codegen_static(&self, def_id: DefId) { + fn codegen_static(&mut self, def_id: DefId) { let attrs = self.tcx.codegen_fn_attrs(def_id); let Ok((value, alloc)) = codegen_static_initializer(self, def_id) else { @@ -160,19 +160,14 @@ impl<'gcc, 'tcx> StaticCodegenMethods for CodegenCx<'gcc, 'tcx> { self.add_used_global(global.to_rvalue()); } } +} +impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { /// Add a global value to a list to be stored in the `llvm.used` variable, an array of i8*. - fn add_used_global(&self, _global: RValue<'gcc>) { + pub fn add_used_global(&mut self, _global: RValue<'gcc>) { // TODO(antoyo) } - fn add_compiler_used_global(&self, global: RValue<'gcc>) { - // NOTE: seems like GCC does not make the distinction between compiler.used and used. - self.add_used_global(global); - } -} - -impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { #[cfg_attr(not(feature = "master"), allow(unused_variables))] pub fn add_used_function(&self, function: Function<'gcc>) { #[cfg(feature = "master")] diff --git a/compiler/rustc_codegen_gcc/src/context.rs b/compiler/rustc_codegen_gcc/src/context.rs index 73718994e6417..c6c43201f2163 100644 --- a/compiler/rustc_codegen_gcc/src/context.rs +++ b/compiler/rustc_codegen_gcc/src/context.rs @@ -470,10 +470,6 @@ impl<'gcc, 'tcx> MiscCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { self.tcx.sess } - fn codegen_unit(&self) -> &'tcx CodegenUnit<'tcx> { - self.codegen_unit - } - fn set_frame_pointer_type(&self, _llfn: RValue<'gcc>) { // TODO(antoyo) } diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs index 1bcb891a2504a..ff1ae2d9d792c 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs @@ -574,14 +574,9 @@ impl<'a, 'gcc, 'tcx> ArgAbiBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tcx> { ) { arg_abi.store(self, val, dst) } - - fn arg_memory_ty(&self, arg_abi: &ArgAbi<'tcx, Ty<'tcx>>) -> Type<'gcc> { - arg_abi.memory_ty(self) - } } pub trait ArgAbiExt<'gcc, 'tcx> { - fn memory_ty(&self, cx: &CodegenCx<'gcc, 'tcx>) -> Type<'gcc>; fn store( &self, bx: &mut Builder<'_, 'gcc, 'tcx>, @@ -597,12 +592,6 @@ pub trait ArgAbiExt<'gcc, 'tcx> { } impl<'gcc, 'tcx> ArgAbiExt<'gcc, 'tcx> for ArgAbi<'tcx, Ty<'tcx>> { - /// Gets the LLVM type for a place of the original Rust type of - /// this argument/return, i.e., the result of `type_of::type_of`. - fn memory_ty(&self, cx: &CodegenCx<'gcc, 'tcx>) -> Type<'gcc> { - self.layout.gcc_type(cx) - } - /// Stores a direct/indirect value described by this ArgAbi into a /// place for the original Rust type of this argument/return. /// Can be used for both storing formal arguments into Rust variables diff --git a/compiler/rustc_codegen_gcc/src/lib.rs b/compiler/rustc_codegen_gcc/src/lib.rs index 6994c385fc831..f79ba2dcfc7ee 100644 --- a/compiler/rustc_codegen_gcc/src/lib.rs +++ b/compiler/rustc_codegen_gcc/src/lib.rs @@ -391,7 +391,7 @@ impl WriteBackendMethods for GccCodegenBackend { unimplemented!() } - unsafe fn optimize( + fn optimize( _cgcx: &CodegenContext, _dcx: DiagCtxtHandle<'_>, module: &mut ModuleCodegen, @@ -409,14 +409,14 @@ impl WriteBackendMethods for GccCodegenBackend { Ok(()) } - unsafe fn optimize_thin( + fn optimize_thin( cgcx: &CodegenContext, thin: ThinModule, ) -> Result, FatalError> { back::lto::optimize_thin_module(thin, cgcx) } - unsafe fn codegen( + fn codegen( cgcx: &CodegenContext, dcx: DiagCtxtHandle<'_>, module: ModuleCodegen, diff --git a/compiler/rustc_codegen_gcc/src/mono_item.rs b/compiler/rustc_codegen_gcc/src/mono_item.rs index a2df7b2596fcf..539e3ac850763 100644 --- a/compiler/rustc_codegen_gcc/src/mono_item.rs +++ b/compiler/rustc_codegen_gcc/src/mono_item.rs @@ -16,7 +16,7 @@ use crate::{attributes, base}; impl<'gcc, 'tcx> PreDefineCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { #[cfg_attr(not(feature = "master"), allow(unused_variables))] fn predefine_static( - &self, + &mut self, def_id: DefId, _linkage: Linkage, visibility: Visibility, @@ -42,7 +42,7 @@ impl<'gcc, 'tcx> PreDefineCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { #[cfg_attr(not(feature = "master"), allow(unused_variables))] fn predefine_fn( - &self, + &mut self, instance: Instance<'tcx>, linkage: Linkage, visibility: Visibility, diff --git a/compiler/rustc_codegen_llvm/src/abi.rs b/compiler/rustc_codegen_llvm/src/abi.rs index 8294e29d07df6..c87e70864e5ad 100644 --- a/compiler/rustc_codegen_llvm/src/abi.rs +++ b/compiler/rustc_codegen_llvm/src/abi.rs @@ -172,7 +172,6 @@ impl LlvmType for CastTarget { } trait ArgAbiExt<'ll, 'tcx> { - fn memory_ty(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type; fn store( &self, bx: &mut Builder<'_, 'll, 'tcx>, @@ -188,12 +187,6 @@ trait ArgAbiExt<'ll, 'tcx> { } impl<'ll, 'tcx> ArgAbiExt<'ll, 'tcx> for ArgAbi<'tcx, Ty<'tcx>> { - /// Gets the LLVM type for a place of the original Rust type of - /// this argument/return, i.e., the result of `type_of::type_of`. - fn memory_ty(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type { - self.layout.llvm_type(cx) - } - /// Stores a direct/indirect value described by this ArgAbi into a /// place for the original Rust type of this argument/return. /// Can be used for both storing formal arguments into Rust variables @@ -302,9 +295,6 @@ impl<'ll, 'tcx> ArgAbiBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { ) { arg_abi.store(self, val, dst) } - fn arg_memory_ty(&self, arg_abi: &ArgAbi<'tcx, Ty<'tcx>>) -> &'ll Type { - arg_abi.memory_ty(self) - } } pub(crate) trait FnAbiLlvmExt<'ll, 'tcx> { diff --git a/compiler/rustc_codegen_llvm/src/back/lto.rs b/compiler/rustc_codegen_llvm/src/back/lto.rs index cb329323f5d72..ee46b49a094c6 100644 --- a/compiler/rustc_codegen_llvm/src/back/lto.rs +++ b/compiler/rustc_codegen_llvm/src/back/lto.rs @@ -799,7 +799,7 @@ impl Drop for ThinBuffer { } } -pub(crate) unsafe fn optimize_thin_module( +pub(crate) fn optimize_thin_module( thin_module: ThinModule, cgcx: &CodegenContext, ) -> Result, FatalError> { diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs index 20721c7460878..bde6a9cf4bc61 100644 --- a/compiler/rustc_codegen_llvm/src/back/write.rs +++ b/compiler/rustc_codegen_llvm/src/back/write.rs @@ -704,7 +704,7 @@ pub(crate) unsafe fn llvm_optimize( } // Unsafe due to LLVM calls. -pub(crate) unsafe fn optimize( +pub(crate) fn optimize( cgcx: &CodegenContext, dcx: DiagCtxtHandle<'_>, module: &mut ModuleCodegen, @@ -815,7 +815,7 @@ pub(crate) fn link( Ok(modules.remove(0)) } -pub(crate) unsafe fn codegen( +pub(crate) fn codegen( cgcx: &CodegenContext, dcx: DiagCtxtHandle<'_>, module: ModuleCodegen, diff --git a/compiler/rustc_codegen_llvm/src/base.rs b/compiler/rustc_codegen_llvm/src/base.rs index e4fac35aa4499..5dda836988c81 100644 --- a/compiler/rustc_codegen_llvm/src/base.rs +++ b/compiler/rustc_codegen_llvm/src/base.rs @@ -86,17 +86,24 @@ pub(crate) fn compile_codegen_unit( let mut cx = CodegenCx::new(tcx, cgu, &llvm_module); let mono_items = cx.codegen_unit.items_in_deterministic_order(cx.tcx); for &(mono_item, data) in &mono_items { - mono_item.predefine::>(&cx, data.linkage, data.visibility); + mono_item.predefine::>( + &mut cx, + cgu_name.as_str(), + data.linkage, + data.visibility, + ); } // ... and now that we have everything pre-defined, fill out those definitions. for &(mono_item, item_data) in &mono_items { - mono_item.define::>(&mut cx, item_data); + mono_item.define::>(&mut cx, cgu_name.as_str(), item_data); } // If this codegen unit contains the main function, also create the // wrapper here - if let Some(entry) = maybe_create_entry_wrapper::>(&cx) { + if let Some(entry) = + maybe_create_entry_wrapper::>(&cx, cx.codegen_unit) + { let attrs = attributes::sanitize_attrs(&cx, SanitizerSet::empty()); attributes::apply_to_llfn(entry, llvm::AttributePlace::Function, &attrs); } @@ -108,14 +115,11 @@ pub(crate) fn compile_codegen_unit( } // Create the llvm.used and llvm.compiler.used variables. - if !cx.used_statics.borrow().is_empty() { - cx.create_used_variable_impl(c"llvm.used", &*cx.used_statics.borrow()); + if !cx.used_statics.is_empty() { + cx.create_used_variable_impl(c"llvm.used", &cx.used_statics); } - if !cx.compiler_used_statics.borrow().is_empty() { - cx.create_used_variable_impl( - c"llvm.compiler.used", - &*cx.compiler_used_statics.borrow(), - ); + if !cx.compiler_used_statics.is_empty() { + cx.create_used_variable_impl(c"llvm.compiler.used", &cx.compiler_used_statics); } // Run replace-all-uses-with for statics that need it. This must diff --git a/compiler/rustc_codegen_llvm/src/consts.rs b/compiler/rustc_codegen_llvm/src/consts.rs index fe2f20273276a..4234352c93a92 100644 --- a/compiler/rustc_codegen_llvm/src/consts.rs +++ b/compiler/rustc_codegen_llvm/src/consts.rs @@ -411,7 +411,7 @@ impl<'ll> CodegenCx<'ll, '_> { g } - fn codegen_static_item(&self, def_id: DefId) { + fn codegen_static_item(&mut self, def_id: DefId) { unsafe { assert!( llvm::LLVMGetInitializer( @@ -557,6 +557,17 @@ impl<'ll> CodegenCx<'ll, '_> { } } } + + /// Add a global value to a list to be stored in the `llvm.used` variable, an array of ptr. + pub(crate) fn add_used_global(&mut self, global: &'ll Value) { + self.used_statics.push(global); + } + + /// Add a global value to a list to be stored in the `llvm.compiler.used` variable, + /// an array of ptr. + pub(crate) fn add_compiler_used_global(&mut self, global: &'ll Value) { + self.compiler_used_statics.push(global); + } } impl<'ll> StaticCodegenMethods for CodegenCx<'ll, '_> { @@ -571,18 +582,7 @@ impl<'ll> StaticCodegenMethods for CodegenCx<'ll, '_> { self.const_pointercast(gv, self.type_ptr()) } - fn codegen_static(&self, def_id: DefId) { + fn codegen_static(&mut self, def_id: DefId) { self.codegen_static_item(def_id) } - - /// Add a global value to a list to be stored in the `llvm.used` variable, an array of ptr. - fn add_used_global(&self, global: &'ll Value) { - self.used_statics.borrow_mut().push(global); - } - - /// Add a global value to a list to be stored in the `llvm.compiler.used` variable, - /// an array of ptr. - fn add_compiler_used_global(&self, global: &'ll Value) { - self.compiler_used_statics.borrow_mut().push(global); - } } diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs index b0d8e11d1fb57..8cc2cb9c333fd 100644 --- a/compiler/rustc_codegen_llvm/src/context.rs +++ b/compiler/rustc_codegen_llvm/src/context.rs @@ -2,7 +2,7 @@ use std::borrow::Borrow; use std::cell::{Cell, RefCell}; use std::ffi::{CStr, c_char, c_uint}; use std::marker::PhantomData; -use std::ops::Deref; +use std::ops::{Deref, DerefMut}; use std::str; use rustc_abi::{HasDataLayout, Size, TargetDataLayout, VariantIdx}; @@ -77,6 +77,13 @@ impl<'ll, T: Borrow>> Deref for GenericCx<'ll, T> { } } +impl<'ll, T: Borrow>> DerefMut for GenericCx<'ll, T> { + #[inline] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + pub(crate) type SimpleCx<'ll> = GenericCx<'ll, SCx<'ll>>; /// There is one `CodegenCx` per codegen unit. Each one has its own LLVM @@ -110,11 +117,11 @@ pub(crate) struct FullCx<'ll, 'tcx> { /// Statics that will be placed in the llvm.used variable /// See for details - pub used_statics: RefCell>, + pub used_statics: Vec<&'ll Value>, /// Statics that will be placed in the llvm.compiler.used variable /// See for details - pub compiler_used_statics: RefCell>, + pub compiler_used_statics: Vec<&'ll Value>, /// Mapping of non-scalar types to llvm types. pub type_lowering: RefCell, Option), &'ll Type>>, @@ -606,8 +613,8 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> { const_str_cache: Default::default(), const_globals: Default::default(), statics_to_rauw: RefCell::new(Vec::new()), - used_statics: RefCell::new(Vec::new()), - compiler_used_statics: RefCell::new(Vec::new()), + used_statics: Vec::new(), + compiler_used_statics: Vec::new(), type_lowering: Default::default(), scalar_lltypes: Default::default(), coverage_cx, @@ -801,10 +808,6 @@ impl<'ll, 'tcx> MiscCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> { self.tcx.sess } - fn codegen_unit(&self) -> &'tcx CodegenUnit<'tcx> { - self.codegen_unit - } - fn set_frame_pointer_type(&self, llfn: &'ll Value) { if let Some(attr) = attributes::frame_pointer_type_attr(self) { attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[attr]); diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs index 55b1e728b70db..a9be833a6439e 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs @@ -2,9 +2,7 @@ use std::sync::Arc; use itertools::Itertools; use rustc_abi::Align; -use rustc_codegen_ssa::traits::{ - BaseTypeCodegenMethods, ConstCodegenMethods, StaticCodegenMethods, -}; +use rustc_codegen_ssa::traits::{BaseTypeCodegenMethods, ConstCodegenMethods}; use rustc_data_structures::fx::FxIndexMap; use rustc_index::IndexVec; use rustc_middle::ty::TyCtxt; @@ -27,7 +25,7 @@ mod unused; /// /// Those sections are then read and understood by LLVM's `llvm-cov` tool, /// which is distributed in the `llvm-tools` rustup component. -pub(crate) fn finalize(cx: &CodegenCx<'_, '_>) { +pub(crate) fn finalize(cx: &mut CodegenCx<'_, '_>) { let tcx = cx.tcx; // Ensure that LLVM is using a version of the coverage mapping format that @@ -62,6 +60,7 @@ pub(crate) fn finalize(cx: &CodegenCx<'_, '_>) { .sorted_by_cached_key(|&instance| tcx.symbol_name(instance).name) .filter_map(|instance| prepare_covfun_record(tcx, instance, true)) .collect::>(); + drop(instances_used); // In a single designated CGU, also prepare covfun records for functions // in this crate that were instrumented for coverage, but are unused. @@ -206,7 +205,7 @@ impl VirtualFileMapping { /// Generates the contents of the covmap record for this CGU, which mostly /// consists of a header and a list of filenames. The record is then stored /// as a global variable in the `__llvm_covmap` section. -fn generate_covmap_record<'ll>(cx: &CodegenCx<'ll, '_>, version: u32, filenames_buffer: &[u8]) { +fn generate_covmap_record<'ll>(cx: &mut CodegenCx<'ll, '_>, version: u32, filenames_buffer: &[u8]) { // A covmap record consists of four target-endian u32 values, followed by // the encoded filenames table. Two of the header fields are unused in // modern versions of the LLVM coverage mapping format, and are always 0. diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen/covfun.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen/covfun.rs index 7bdbc68595290..b704cf2b1cd46 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen/covfun.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen/covfun.rs @@ -8,9 +8,7 @@ use std::ffi::CString; use std::sync::Arc; use rustc_abi::Align; -use rustc_codegen_ssa::traits::{ - BaseTypeCodegenMethods as _, ConstCodegenMethods, StaticCodegenMethods, -}; +use rustc_codegen_ssa::traits::{BaseTypeCodegenMethods as _, ConstCodegenMethods}; use rustc_middle::mir::coverage::{ BasicCoverageBlock, CovTerm, CoverageIdsInfo, Expression, FunctionCoverageInfo, Mapping, MappingKind, Op, @@ -181,7 +179,7 @@ fn fill_region_tables<'tcx>( /// contains the function's coverage mapping data. The record is then stored /// as a global variable in the `__llvm_covfun` section. pub(crate) fn generate_covfun_record<'tcx>( - cx: &CodegenCx<'_, 'tcx>, + cx: &mut CodegenCx<'_, 'tcx>, global_file_table: &GlobalFileTable, covfun: &CovfunRecord<'tcx>, ) { diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs index ea7f581a3cb51..eefbd7cf6c48b 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs @@ -56,7 +56,7 @@ impl<'ll, 'tcx> CguCoverageContext<'ll, 'tcx> { } impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> { - pub(crate) fn coverageinfo_finalize(&self) { + pub(crate) fn coverageinfo_finalize(&mut self) { mapgen::finalize(self) } diff --git a/compiler/rustc_codegen_llvm/src/lib.rs b/compiler/rustc_codegen_llvm/src/lib.rs index 5736314b96a36..fd376ea8d804c 100644 --- a/compiler/rustc_codegen_llvm/src/lib.rs +++ b/compiler/rustc_codegen_llvm/src/lib.rs @@ -189,13 +189,13 @@ impl WriteBackendMethods for LlvmCodegenBackend { ) -> Result<(Vec>, Vec), FatalError> { back::lto::run_thin(cgcx, modules, cached_modules) } - unsafe fn optimize( + fn optimize( cgcx: &CodegenContext, dcx: DiagCtxtHandle<'_>, module: &mut ModuleCodegen, config: &ModuleConfig, ) -> Result<(), FatalError> { - unsafe { back::write::optimize(cgcx, dcx, module, config) } + back::write::optimize(cgcx, dcx, module, config) } fn optimize_fat( cgcx: &CodegenContext, @@ -205,19 +205,19 @@ impl WriteBackendMethods for LlvmCodegenBackend { let dcx = dcx.handle(); back::lto::run_pass_manager(cgcx, dcx, module, false) } - unsafe fn optimize_thin( + fn optimize_thin( cgcx: &CodegenContext, thin: ThinModule, ) -> Result, FatalError> { - unsafe { back::lto::optimize_thin_module(thin, cgcx) } + back::lto::optimize_thin_module(thin, cgcx) } - unsafe fn codegen( + fn codegen( cgcx: &CodegenContext, dcx: DiagCtxtHandle<'_>, module: ModuleCodegen, config: &ModuleConfig, ) -> Result { - unsafe { back::write::codegen(cgcx, dcx, module, config) } + back::write::codegen(cgcx, dcx, module, config) } fn prepare_thin( module: ModuleCodegen, diff --git a/compiler/rustc_codegen_llvm/src/mono_item.rs b/compiler/rustc_codegen_llvm/src/mono_item.rs index fdf62a08065c2..3f38e1e191bf2 100644 --- a/compiler/rustc_codegen_llvm/src/mono_item.rs +++ b/compiler/rustc_codegen_llvm/src/mono_item.rs @@ -16,7 +16,7 @@ use crate::{base, llvm}; impl<'tcx> PreDefineCodegenMethods<'tcx> for CodegenCx<'_, 'tcx> { fn predefine_static( - &self, + &mut self, def_id: DefId, linkage: Linkage, visibility: Visibility, @@ -44,7 +44,7 @@ impl<'tcx> PreDefineCodegenMethods<'tcx> for CodegenCx<'_, 'tcx> { } fn predefine_fn( - &self, + &mut self, instance: Instance<'tcx>, linkage: Linkage, visibility: Visibility, diff --git a/compiler/rustc_codegen_ssa/src/back/lto.rs b/compiler/rustc_codegen_ssa/src/back/lto.rs index 9fd984b6419ee..ce6fe8a191b3b 100644 --- a/compiler/rustc_codegen_ssa/src/back/lto.rs +++ b/compiler/rustc_codegen_ssa/src/back/lto.rs @@ -56,12 +56,7 @@ impl LtoModuleCodegen { } /// Optimize this module within the given codegen context. - /// - /// This function is unsafe as it'll return a `ModuleCodegen` still - /// points to LLVM data structures owned by this `LtoModuleCodegen`. - /// It's intended that the module returned is immediately code generated and - /// dropped, and then this LTO module is dropped. - pub unsafe fn optimize( + pub fn optimize( self, cgcx: &CodegenContext, ) -> Result, FatalError> { @@ -70,7 +65,7 @@ impl LtoModuleCodegen { B::optimize_fat(cgcx, &mut module)?; Ok(module) } - LtoModuleCodegen::Thin(thin) => unsafe { B::optimize_thin(cgcx, thin) }, + LtoModuleCodegen::Thin(thin) => B::optimize_thin(cgcx, thin), } } @@ -85,7 +80,7 @@ impl LtoModuleCodegen { } /// Run autodiff on Fat LTO module - pub unsafe fn autodiff( + pub fn autodiff( self, cgcx: &CodegenContext, diff_fncs: Vec, diff --git a/compiler/rustc_codegen_ssa/src/back/write.rs b/compiler/rustc_codegen_ssa/src/back/write.rs index 0fd4ed8475b49..a41ca8ce28bce 100644 --- a/compiler/rustc_codegen_ssa/src/back/write.rs +++ b/compiler/rustc_codegen_ssa/src/back/write.rs @@ -383,7 +383,7 @@ pub struct CodegenContext { pub coordinator_send: Sender>, /// `true` if the codegen should be run in parallel. /// - /// Depends on [`CodegenBackend::supports_parallel()`] and `-Zno_parallel_backend`. + /// Depends on [`ExtraBackendMethods::supports_parallel()`] and `-Zno_parallel_backend`. pub parallel: bool, } @@ -416,8 +416,7 @@ fn generate_lto_work( B::run_fat_lto(cgcx, needs_fat_lto, import_only_modules).unwrap_or_else(|e| e.raise()); if cgcx.lto == Lto::Fat && !autodiff.is_empty() { let config = cgcx.config(ModuleKind::Regular); - module = - unsafe { module.autodiff(cgcx, autodiff, config).unwrap_or_else(|e| e.raise()) }; + module = module.autodiff(cgcx, autodiff, config).unwrap_or_else(|e| e.raise()); } // We are adding a single work item, so the cost doesn't matter. vec![(WorkItem::LTO(module), 0)] @@ -887,9 +886,7 @@ fn execute_optimize_work_item( let dcx = cgcx.create_dcx(); let dcx = dcx.handle(); - unsafe { - B::optimize(cgcx, dcx, &mut module, module_config)?; - } + B::optimize(cgcx, dcx, &mut module, module_config)?; // After we've done the initial round of optimizations we need to // decide whether to synchronously codegen this module or ship it @@ -1020,7 +1017,7 @@ fn execute_lto_work_item( module: lto::LtoModuleCodegen, module_config: &ModuleConfig, ) -> Result, FatalError> { - let module = unsafe { module.optimize(cgcx)? }; + let module = module.optimize(cgcx)?; finish_intra_module_work(cgcx, module, module_config) } @@ -1036,7 +1033,7 @@ fn finish_intra_module_work( || module.kind == ModuleKind::Metadata || module.kind == ModuleKind::Allocator { - let module = unsafe { B::codegen(cgcx, dcx, module, module_config)? }; + let module = B::codegen(cgcx, dcx, module, module_config)?; Ok(WorkItemResult::Finished(module)) } else { Ok(WorkItemResult::NeedsLink(module)) @@ -1725,9 +1722,8 @@ fn start_executing_work( let dcx = cgcx.create_dcx(); let dcx = dcx.handle(); let module = B::run_link(&cgcx, dcx, needs_link).map_err(|_| ())?; - let module = unsafe { - B::codegen(&cgcx, dcx, module, cgcx.config(ModuleKind::Regular)).map_err(|_| ())? - }; + let module = + B::codegen(&cgcx, dcx, module, cgcx.config(ModuleKind::Regular)).map_err(|_| ())?; compiled_modules.push(module); } diff --git a/compiler/rustc_codegen_ssa/src/base.rs b/compiler/rustc_codegen_ssa/src/base.rs index 1890119dca770..f7863fe4ae264 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -492,6 +492,7 @@ where /// users main function. pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( cx: &'a Bx::CodegenCx, + cgu: &CodegenUnit<'tcx>, ) -> Option { let (main_def_id, entry_type) = cx.tcx().entry_fn(())?; let main_is_local = main_def_id.is_local(); @@ -500,10 +501,10 @@ pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( if main_is_local { // We want to create the wrapper in the same codegen unit as Rust's main // function. - if !cx.codegen_unit().contains_item(&MonoItem::Fn(instance)) { + if !cgu.contains_item(&MonoItem::Fn(instance)) { return None; } - } else if !cx.codegen_unit().is_primary() { + } else if !cgu.is_primary() { // We want to create the wrapper only when the codegen unit is the primary one return None; } diff --git a/compiler/rustc_codegen_ssa/src/mono_item.rs b/compiler/rustc_codegen_ssa/src/mono_item.rs index c2067e52afecd..7b4268abe4b14 100644 --- a/compiler/rustc_codegen_ssa/src/mono_item.rs +++ b/compiler/rustc_codegen_ssa/src/mono_item.rs @@ -11,11 +11,13 @@ pub trait MonoItemExt<'a, 'tcx> { fn define>( &self, cx: &'a mut Bx::CodegenCx, + cgu_name: &str, item_data: MonoItemData, ); fn predefine>( &self, - cx: &'a Bx::CodegenCx, + cx: &'a mut Bx::CodegenCx, + cgu_name: &str, linkage: Linkage, visibility: Visibility, ); @@ -26,14 +28,10 @@ impl<'a, 'tcx: 'a> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> { fn define>( &self, cx: &'a mut Bx::CodegenCx, + cgu_name: &str, item_data: MonoItemData, ) { - debug!( - "BEGIN IMPLEMENTING '{} ({})' in cgu {}", - self, - self.to_raw_string(), - cx.codegen_unit().name() - ); + debug!("BEGIN IMPLEMENTING '{} ({})' in cgu {}", self, self.to_raw_string(), cgu_name); match *self { MonoItem::Static(def_id) => { @@ -56,26 +54,17 @@ impl<'a, 'tcx: 'a> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> { } } - debug!( - "END IMPLEMENTING '{} ({})' in cgu {}", - self, - self.to_raw_string(), - cx.codegen_unit().name() - ); + debug!("END IMPLEMENTING '{} ({})' in cgu {}", self, self.to_raw_string(), cgu_name); } fn predefine>( &self, - cx: &'a Bx::CodegenCx, + cx: &'a mut Bx::CodegenCx, + cgu_name: &str, linkage: Linkage, visibility: Visibility, ) { - debug!( - "BEGIN PREDEFINING '{} ({})' in cgu {}", - self, - self.to_raw_string(), - cx.codegen_unit().name() - ); + debug!("BEGIN PREDEFINING '{} ({})' in cgu {}", self, self.to_raw_string(), cgu_name); let symbol_name = self.symbol_name(cx.tcx()).name; @@ -97,12 +86,7 @@ impl<'a, 'tcx: 'a> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> { MonoItem::GlobalAsm(..) => {} } - debug!( - "END PREDEFINING '{} ({})' in cgu {}", - self, - self.to_raw_string(), - cx.codegen_unit().name() - ); + debug!("END PREDEFINING '{} ({})' in cgu {}", self, self.to_raw_string(), cgu_name); } fn to_raw_string(&self) -> String { diff --git a/compiler/rustc_codegen_ssa/src/traits/backend.rs b/compiler/rustc_codegen_ssa/src/traits/backend.rs index e2f1458d06232..95bf3b16685b9 100644 --- a/compiler/rustc_codegen_ssa/src/traits/backend.rs +++ b/compiler/rustc_codegen_ssa/src/traits/backend.rs @@ -21,12 +21,12 @@ use crate::back::write::TargetMachineFactoryFn; use crate::{CodegenResults, ModuleCodegen, TargetConfig}; pub trait BackendTypes { - type Value: CodegenObject; + type Value: CodegenObject + PartialEq; type Metadata: CodegenObject; type Function: CodegenObject; type BasicBlock: Copy; - type Type: CodegenObject; + type Type: CodegenObject + PartialEq; type Funclet; // FIXME(eddyb) find a common convention for all of the debuginfo-related @@ -97,13 +97,6 @@ pub trait CodegenBackend { fn link(&self, sess: &Session, codegen_results: CodegenResults, outputs: &OutputFilenames) { link_binary(sess, &ArArchiveBuilderBuilder, codegen_results, outputs); } - - /// Returns `true` if this backend can be safely called from multiple threads. - /// - /// Defaults to `true`. - fn supports_parallel(&self) -> bool { - true - } } pub trait ExtraBackendMethods: @@ -144,4 +137,11 @@ pub trait ExtraBackendMethods: { std::thread::Builder::new().name(name).spawn(f) } + + /// Returns `true` if this backend can be safely called from multiple threads. + /// + /// Defaults to `true`. + fn supports_parallel(&self) -> bool { + true + } } diff --git a/compiler/rustc_codegen_ssa/src/traits/builder.rs b/compiler/rustc_codegen_ssa/src/traits/builder.rs index f66309cf340cc..a7f05b2de26e3 100644 --- a/compiler/rustc_codegen_ssa/src/traits/builder.rs +++ b/compiler/rustc_codegen_ssa/src/traits/builder.rs @@ -514,11 +514,11 @@ pub trait BuilderMethods<'a, 'tcx>: fn extract_value(&mut self, agg_val: Self::Value, idx: u64) -> Self::Value; fn insert_value(&mut self, agg_val: Self::Value, elt: Self::Value, idx: u64) -> Self::Value; - fn set_personality_fn(&mut self, personality: Self::Value); + fn set_personality_fn(&mut self, personality: Self::Function); // These are used by everyone except msvc - fn cleanup_landing_pad(&mut self, pers_fn: Self::Value) -> (Self::Value, Self::Value); - fn filter_landing_pad(&mut self, pers_fn: Self::Value) -> (Self::Value, Self::Value); + fn cleanup_landing_pad(&mut self, pers_fn: Self::Function) -> (Self::Value, Self::Value); + fn filter_landing_pad(&mut self, pers_fn: Self::Function) -> (Self::Value, Self::Value); fn resume(&mut self, exn0: Self::Value, exn1: Self::Value); // These are used only by msvc diff --git a/compiler/rustc_codegen_ssa/src/traits/declare.rs b/compiler/rustc_codegen_ssa/src/traits/declare.rs index c1edeac31b0f9..9f735546558b0 100644 --- a/compiler/rustc_codegen_ssa/src/traits/declare.rs +++ b/compiler/rustc_codegen_ssa/src/traits/declare.rs @@ -4,14 +4,14 @@ use rustc_middle::ty::Instance; pub trait PreDefineCodegenMethods<'tcx> { fn predefine_static( - &self, + &mut self, def_id: DefId, linkage: Linkage, visibility: Visibility, symbol_name: &str, ); fn predefine_fn( - &self, + &mut self, instance: Instance<'tcx>, linkage: Linkage, visibility: Visibility, diff --git a/compiler/rustc_codegen_ssa/src/traits/misc.rs b/compiler/rustc_codegen_ssa/src/traits/misc.rs index 4004947b46485..710fab2790166 100644 --- a/compiler/rustc_codegen_ssa/src/traits/misc.rs +++ b/compiler/rustc_codegen_ssa/src/traits/misc.rs @@ -1,7 +1,6 @@ use std::cell::RefCell; use rustc_data_structures::fx::FxHashMap; -use rustc_middle::mir::mono::CodegenUnit; use rustc_middle::ty::{self, Instance, Ty}; use rustc_session::Session; @@ -20,9 +19,8 @@ pub trait MiscCodegenMethods<'tcx>: BackendTypes { } fn get_fn(&self, instance: Instance<'tcx>) -> Self::Function; fn get_fn_addr(&self, instance: Instance<'tcx>) -> Self::Value; - fn eh_personality(&self) -> Self::Value; + fn eh_personality(&self) -> Self::Function; fn sess(&self) -> &Session; - fn codegen_unit(&self) -> &'tcx CodegenUnit<'tcx>; fn set_frame_pointer_type(&self, llfn: Self::Function); fn apply_target_cpu_attr(&self, llfn: Self::Function); /// Declares the extern "C" main function for the entry point. Returns None if the symbol diff --git a/compiler/rustc_codegen_ssa/src/traits/mod.rs b/compiler/rustc_codegen_ssa/src/traits/mod.rs index 239857a4298df..6d1ac717c0b8f 100644 --- a/compiler/rustc_codegen_ssa/src/traits/mod.rs +++ b/compiler/rustc_codegen_ssa/src/traits/mod.rs @@ -50,7 +50,7 @@ pub use self::type_::{ }; pub use self::write::{ModuleBufferMethods, ThinBufferMethods, WriteBackendMethods}; -pub trait CodegenObject = Copy + PartialEq + fmt::Debug; +pub trait CodegenObject = Copy + fmt::Debug; pub trait CodegenMethods<'tcx> = LayoutOf<'tcx, LayoutOfResult = TyAndLayout<'tcx>> + FnAbiOf<'tcx, FnAbiOfResult = &'tcx FnAbi<'tcx, Ty<'tcx>>> diff --git a/compiler/rustc_codegen_ssa/src/traits/statics.rs b/compiler/rustc_codegen_ssa/src/traits/statics.rs index ece0ea1b2ea85..0e1e445c72f35 100644 --- a/compiler/rustc_codegen_ssa/src/traits/statics.rs +++ b/compiler/rustc_codegen_ssa/src/traits/statics.rs @@ -5,19 +5,7 @@ use super::BackendTypes; pub trait StaticCodegenMethods: BackendTypes { fn static_addr_of(&self, cv: Self::Value, align: Align, kind: Option<&str>) -> Self::Value; - fn codegen_static(&self, def_id: DefId); - - /// Mark the given global value as "used", to prevent the compiler and linker from potentially - /// removing a static variable that may otherwise appear unused. - fn add_used_global(&self, global: Self::Value); - - /// Same as add_used_global(), but only prevent the compiler from potentially removing an - /// otherwise unused symbol. The linker is still permitted to drop it. - /// - /// This corresponds to the documented semantics of the `#[used]` attribute, although - /// on some targets (non-ELF), we may use `add_used_global` for `#[used]` statics - /// instead. - fn add_compiler_used_global(&self, global: Self::Value); + fn codegen_static(&mut self, def_id: DefId); } pub trait StaticBuilderMethods: BackendTypes { diff --git a/compiler/rustc_codegen_ssa/src/traits/type_.rs b/compiler/rustc_codegen_ssa/src/traits/type_.rs index 32d9f27d32d34..c3fc21a92854a 100644 --- a/compiler/rustc_codegen_ssa/src/traits/type_.rs +++ b/compiler/rustc_codegen_ssa/src/traits/type_.rs @@ -158,7 +158,6 @@ pub trait ArgAbiBuilderMethods<'tcx>: BackendTypes { val: Self::Value, dst: PlaceRef<'tcx, Self::Value>, ); - fn arg_memory_ty(&self, arg_abi: &ArgAbi<'tcx, Ty<'tcx>>) -> Self::Type; } pub trait TypeCodegenMethods<'tcx> = DerivedTypeCodegenMethods<'tcx> diff --git a/compiler/rustc_codegen_ssa/src/traits/write.rs b/compiler/rustc_codegen_ssa/src/traits/write.rs index c77efdd172876..07a0609fda1a1 100644 --- a/compiler/rustc_codegen_ssa/src/traits/write.rs +++ b/compiler/rustc_codegen_ssa/src/traits/write.rs @@ -6,7 +6,7 @@ use crate::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule}; use crate::back::write::{CodegenContext, FatLtoInput, ModuleConfig}; use crate::{CompiledModule, ModuleCodegen}; -pub trait WriteBackendMethods: 'static + Sized + Clone { +pub trait WriteBackendMethods: Clone + 'static { type Module: Send + Sync; type TargetMachine; type TargetMachineError; @@ -37,7 +37,7 @@ pub trait WriteBackendMethods: 'static + Sized + Clone { ) -> Result<(Vec>, Vec), FatalError>; fn print_pass_timings(&self); fn print_statistics(&self); - unsafe fn optimize( + fn optimize( cgcx: &CodegenContext, dcx: DiagCtxtHandle<'_>, module: &mut ModuleCodegen, @@ -47,11 +47,11 @@ pub trait WriteBackendMethods: 'static + Sized + Clone { cgcx: &CodegenContext, llmod: &mut ModuleCodegen, ) -> Result<(), FatalError>; - unsafe fn optimize_thin( + fn optimize_thin( cgcx: &CodegenContext, thin: ThinModule, ) -> Result, FatalError>; - unsafe fn codegen( + fn codegen( cgcx: &CodegenContext, dcx: DiagCtxtHandle<'_>, module: ModuleCodegen, diff --git a/compiler/rustc_expand/src/config.rs b/compiler/rustc_expand/src/config.rs index 0994813ecb9c5..c50ab5959e25c 100644 --- a/compiler/rustc_expand/src/config.rs +++ b/compiler/rustc_expand/src/config.rs @@ -2,7 +2,6 @@ use std::iter; -use rustc_ast::ptr::P; use rustc_ast::token::{Delimiter, Token, TokenKind}; use rustc_ast::tokenstream::{ AttrTokenStream, AttrTokenTree, LazyAttrTokenStream, Spacing, TokenTree, @@ -433,7 +432,7 @@ impl<'a> StripUnconfigured<'a> { } #[instrument(level = "trace", skip(self))] - pub fn configure_expr(&self, expr: &mut P, method_receiver: bool) { + pub fn configure_expr(&self, expr: &mut ast::Expr, method_receiver: bool) { if !method_receiver { for attr in expr.attrs.iter() { self.maybe_emit_expr_attr_err(attr); diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index e5749ba96a6dd..d6fef766a07bb 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -2304,7 +2304,7 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { self.flat_map_node(AstNodeWrapper::new(node, OptExprTag)) } - fn visit_block(&mut self, node: &mut P) { + fn visit_block(&mut self, node: &mut ast::Block) { let orig_dir_ownership = mem::replace( &mut self.cx.current_expansion.dir_ownership, DirOwnership::UnownedViaBlock, diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs index cfb25deac0e04..a5c0829b8d9e4 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs @@ -81,7 +81,7 @@ pub(crate) struct FnCtxt<'a, 'tcx> { /// you get indicates whether any subexpression that was /// evaluating up to and including `X` diverged. /// - /// We currently use this flag only for diagnostic purposes: + /// We currently use this flag for the following purposes: /// /// - To warn about unreachable code: if, after processing a /// sub-expression but before we have applied the effects of the @@ -94,6 +94,8 @@ pub(crate) struct FnCtxt<'a, 'tcx> { /// warning. This corresponds to something like `{return; /// foo();}` or `{return; 22}`, where we would warn on the /// `foo()` or `22`. + /// - To assign the `!` type to block expressions with diverging + /// statements. /// /// An expression represents dead code if, after checking it, /// the diverges flag is set to something other than `Maybe`. diff --git a/compiler/rustc_metadata/src/locator.rs b/compiler/rustc_metadata/src/locator.rs index 10123cb9a9ddb..79015aab5d304 100644 --- a/compiler/rustc_metadata/src/locator.rs +++ b/compiler/rustc_metadata/src/locator.rs @@ -435,7 +435,7 @@ impl<'a> CrateLocator<'a> { info!("lib candidate: {}", spf.path.display()); let (rlibs, rmetas, dylibs, interfaces) = - candidates.entry(hash.to_string()).or_default(); + candidates.entry(hash).or_default(); { // As a perforamnce optimisation we canonicalize the path and skip // ones we've already seeen. This allows us to ignore crates diff --git a/library/core/src/num/f32.rs b/library/core/src/num/f32.rs index bf67b6ed05afb..6636054a659b5 100644 --- a/library/core/src/num/f32.rs +++ b/library/core/src/num/f32.rs @@ -999,6 +999,7 @@ impl f32 { target_arch = "x86_64", target_arch = "aarch64", all(any(target_arch = "riscv32", target_arch = "riscv64"), target_feature = "d"), + all(target_arch = "loongarch64", target_feature = "d"), all(target_arch = "arm", target_feature = "vfp2"), target_arch = "wasm32", target_arch = "wasm64", diff --git a/library/coretests/tests/floats/f16.rs b/library/coretests/tests/floats/f16.rs index db98181226c85..9246805a72840 100644 --- a/library/coretests/tests/floats/f16.rs +++ b/library/coretests/tests/floats/f16.rs @@ -596,12 +596,15 @@ fn test_total_cmp() { f16::from_bits(f16::NAN.to_bits() | quiet_bit_mask()) } - fn s_nan() -> f16 { - f16::from_bits((f16::NAN.to_bits() & !quiet_bit_mask()) + 42) - } + // FIXME(f16_f128): Tests involving sNaN are disabled because without optimizations, + // `total_cmp` is getting incorrectly lowered to code that includes a `extend`/`trunc` round + // trip, which quiets sNaNs. See: https://github.com/llvm/llvm-project/issues/104915 + // fn s_nan() -> f16 { + // f16::from_bits((f16::NAN.to_bits() & !quiet_bit_mask()) + 42) + // } assert_eq!(Ordering::Equal, (-q_nan()).total_cmp(&-q_nan())); - assert_eq!(Ordering::Equal, (-s_nan()).total_cmp(&-s_nan())); + // assert_eq!(Ordering::Equal, (-s_nan()).total_cmp(&-s_nan())); assert_eq!(Ordering::Equal, (-f16::INFINITY).total_cmp(&-f16::INFINITY)); assert_eq!(Ordering::Equal, (-f16::MAX).total_cmp(&-f16::MAX)); assert_eq!(Ordering::Equal, (-2.5_f16).total_cmp(&-2.5)); @@ -622,11 +625,11 @@ fn test_total_cmp() { assert_eq!(Ordering::Equal, 2.5_f16.total_cmp(&2.5)); assert_eq!(Ordering::Equal, f16::MAX.total_cmp(&f16::MAX)); assert_eq!(Ordering::Equal, f16::INFINITY.total_cmp(&f16::INFINITY)); - assert_eq!(Ordering::Equal, s_nan().total_cmp(&s_nan())); + // assert_eq!(Ordering::Equal, s_nan().total_cmp(&s_nan())); assert_eq!(Ordering::Equal, q_nan().total_cmp(&q_nan())); - assert_eq!(Ordering::Less, (-q_nan()).total_cmp(&-s_nan())); - assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&-f16::INFINITY)); + // assert_eq!(Ordering::Less, (-q_nan()).total_cmp(&-s_nan())); + // assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&-f16::INFINITY)); assert_eq!(Ordering::Less, (-f16::INFINITY).total_cmp(&-f16::MAX)); assert_eq!(Ordering::Less, (-f16::MAX).total_cmp(&-2.5)); assert_eq!(Ordering::Less, (-2.5_f16).total_cmp(&-1.5)); @@ -646,11 +649,11 @@ fn test_total_cmp() { assert_eq!(Ordering::Less, 1.5_f16.total_cmp(&2.5)); assert_eq!(Ordering::Less, 2.5_f16.total_cmp(&f16::MAX)); assert_eq!(Ordering::Less, f16::MAX.total_cmp(&f16::INFINITY)); - assert_eq!(Ordering::Less, f16::INFINITY.total_cmp(&s_nan())); - assert_eq!(Ordering::Less, s_nan().total_cmp(&q_nan())); + // assert_eq!(Ordering::Less, f16::INFINITY.total_cmp(&s_nan())); + // assert_eq!(Ordering::Less, s_nan().total_cmp(&q_nan())); - assert_eq!(Ordering::Greater, (-s_nan()).total_cmp(&-q_nan())); - assert_eq!(Ordering::Greater, (-f16::INFINITY).total_cmp(&-s_nan())); + // assert_eq!(Ordering::Greater, (-s_nan()).total_cmp(&-q_nan())); + // assert_eq!(Ordering::Greater, (-f16::INFINITY).total_cmp(&-s_nan())); assert_eq!(Ordering::Greater, (-f16::MAX).total_cmp(&-f16::INFINITY)); assert_eq!(Ordering::Greater, (-2.5_f16).total_cmp(&-f16::MAX)); assert_eq!(Ordering::Greater, (-1.5_f16).total_cmp(&-2.5)); @@ -670,10 +673,10 @@ fn test_total_cmp() { assert_eq!(Ordering::Greater, 2.5_f16.total_cmp(&1.5)); assert_eq!(Ordering::Greater, f16::MAX.total_cmp(&2.5)); assert_eq!(Ordering::Greater, f16::INFINITY.total_cmp(&f16::MAX)); - assert_eq!(Ordering::Greater, s_nan().total_cmp(&f16::INFINITY)); - assert_eq!(Ordering::Greater, q_nan().total_cmp(&s_nan())); + // assert_eq!(Ordering::Greater, s_nan().total_cmp(&f16::INFINITY)); + // assert_eq!(Ordering::Greater, q_nan().total_cmp(&s_nan())); - assert_eq!(Ordering::Less, (-q_nan()).total_cmp(&-s_nan())); + // assert_eq!(Ordering::Less, (-q_nan()).total_cmp(&-s_nan())); assert_eq!(Ordering::Less, (-q_nan()).total_cmp(&-f16::INFINITY)); assert_eq!(Ordering::Less, (-q_nan()).total_cmp(&-f16::MAX)); assert_eq!(Ordering::Less, (-q_nan()).total_cmp(&-2.5)); @@ -694,29 +697,29 @@ fn test_total_cmp() { assert_eq!(Ordering::Less, (-q_nan()).total_cmp(&2.5)); assert_eq!(Ordering::Less, (-q_nan()).total_cmp(&f16::MAX)); assert_eq!(Ordering::Less, (-q_nan()).total_cmp(&f16::INFINITY)); - assert_eq!(Ordering::Less, (-q_nan()).total_cmp(&s_nan())); - - assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&-f16::INFINITY)); - assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&-f16::MAX)); - assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&-2.5)); - assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&-1.5)); - assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&-1.0)); - assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&-0.5)); - assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&-f16::MIN_POSITIVE)); - assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&-max_subnorm())); - assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&-min_subnorm())); - assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&-0.0)); - assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&0.0)); - assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&min_subnorm())); - assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&max_subnorm())); - assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&f16::MIN_POSITIVE)); - assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&0.5)); - assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&1.0)); - assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&1.5)); - assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&2.5)); - assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&f16::MAX)); - assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&f16::INFINITY)); - assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&s_nan())); + // assert_eq!(Ordering::Less, (-q_nan()).total_cmp(&s_nan())); + + // assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&-f16::INFINITY)); + // assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&-f16::MAX)); + // assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&-2.5)); + // assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&-1.5)); + // assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&-1.0)); + // assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&-0.5)); + // assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&-f16::MIN_POSITIVE)); + // assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&-max_subnorm())); + // assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&-min_subnorm())); + // assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&-0.0)); + // assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&0.0)); + // assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&min_subnorm())); + // assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&max_subnorm())); + // assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&f16::MIN_POSITIVE)); + // assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&0.5)); + // assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&1.0)); + // assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&1.5)); + // assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&2.5)); + // assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&f16::MAX)); + // assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&f16::INFINITY)); + // assert_eq!(Ordering::Less, (-s_nan()).total_cmp(&s_nan())); } #[test] diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index 4b2418a498581..a3f0f3cc55a19 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -585,11 +585,13 @@ pub use alloc_crate::string; #[stable(feature = "rust1", since = "1.0.0")] pub use alloc_crate::vec; -#[unstable(feature = "f128", issue = "116909")] +#[path = "num/f128.rs"] pub mod f128; -#[unstable(feature = "f16", issue = "116909")] +#[path = "num/f16.rs"] pub mod f16; +#[path = "num/f32.rs"] pub mod f32; +#[path = "num/f64.rs"] pub mod f64; #[macro_use] diff --git a/library/std/src/f128.rs b/library/std/src/num/f128.rs similarity index 99% rename from library/std/src/f128.rs rename to library/std/src/num/f128.rs index bb4acde48224c..c0190de089f4a 100644 --- a/library/std/src/f128.rs +++ b/library/std/src/num/f128.rs @@ -4,6 +4,8 @@ //! //! Mathematically significant numbers are provided in the `consts` sub-module. +#![unstable(feature = "f128", issue = "116909")] + #[unstable(feature = "f128", issue = "116909")] pub use core::f128::consts; diff --git a/library/std/src/f16.rs b/library/std/src/num/f16.rs similarity index 99% rename from library/std/src/f16.rs rename to library/std/src/num/f16.rs index 4792eac1f9e28..4a4a8fd839a97 100644 --- a/library/std/src/f16.rs +++ b/library/std/src/num/f16.rs @@ -4,6 +4,8 @@ //! //! Mathematically significant numbers are provided in the `consts` sub-module. +#![unstable(feature = "f16", issue = "116909")] + #[unstable(feature = "f16", issue = "116909")] pub use core::f16::consts; diff --git a/library/std/src/f32.rs b/library/std/src/num/f32.rs similarity index 100% rename from library/std/src/f32.rs rename to library/std/src/num/f32.rs diff --git a/library/std/src/f64.rs b/library/std/src/num/f64.rs similarity index 100% rename from library/std/src/f64.rs rename to library/std/src/num/f64.rs diff --git a/library/std/src/num.rs b/library/std/src/num/mod.rs similarity index 100% rename from library/std/src/num.rs rename to library/std/src/num/mod.rs diff --git a/src/bootstrap/src/lib.rs b/src/bootstrap/src/lib.rs index 9492ffaed7566..7cce14841eb34 100644 --- a/src/bootstrap/src/lib.rs +++ b/src/bootstrap/src/lib.rs @@ -363,19 +363,35 @@ impl Build { let in_tree_llvm_info = config.in_tree_llvm_info.clone(); let in_tree_gcc_info = config.in_tree_gcc_info.clone(); - let initial_target_libdir_str = - config.initial_sysroot.join("lib/rustlib").join(config.build).join("lib"); + let initial_target_libdir = + output(Command::new(&config.initial_rustc).args(["--print", "target-libdir"])) + .trim() + .to_owned(); + + let initial_target_dir = Path::new(&initial_target_libdir) + .parent() + .unwrap_or_else(|| panic!("{initial_target_libdir} has no parent")); - let initial_target_dir = Path::new(&initial_target_libdir_str).parent().unwrap(); let initial_lld = initial_target_dir.join("bin").join("rust-lld"); - let initial_relative_libdir = initial_target_dir - .ancestors() - .nth(2) - .unwrap() - .strip_prefix(&config.initial_sysroot) - .expect("Couldn’t determine initial relative libdir.") - .to_path_buf(); + let initial_relative_libdir = if cfg!(test) { + // On tests, bootstrap uses the shim rustc, not the one from the stage0 toolchain. + PathBuf::default() + } else { + let ancestor = initial_target_dir.ancestors().nth(2).unwrap_or_else(|| { + panic!("Not enough ancestors for {}", initial_target_dir.display()) + }); + + ancestor + .strip_prefix(&config.initial_sysroot) + .unwrap_or_else(|_| { + panic!( + "Couldn’t resolve the initial relative libdir from {}", + initial_target_dir.display() + ) + }) + .to_path_buf() + }; let version = std::fs::read_to_string(src.join("src").join("version")) .expect("failed to read src/version"); diff --git a/src/ci/docker/host-x86_64/mingw-check-tidy/Dockerfile b/src/ci/docker/host-x86_64/mingw-check-tidy/Dockerfile index 9ca8cc740a5c7..d17f7ed7171f8 100644 --- a/src/ci/docker/host-x86_64/mingw-check-tidy/Dockerfile +++ b/src/ci/docker/host-x86_64/mingw-check-tidy/Dockerfile @@ -24,6 +24,13 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ mingw-w64 \ && rm -rf /var/lib/apt/lists/* +COPY scripts/nodejs.sh /scripts/ +RUN sh /scripts/nodejs.sh /node +ENV PATH="/node/bin:${PATH}" + +# Install eslint +COPY host-x86_64/mingw-check-tidy/eslint.version /tmp/ + COPY scripts/sccache.sh /scripts/ RUN sh /scripts/sccache.sh @@ -36,5 +43,5 @@ COPY host-x86_64/mingw-check/validate-error-codes.sh /scripts/ # NOTE: intentionally uses python2 for x.py so we can test it still works. # validate-toolstate only runs in our CI, so it's ok for it to only support python3. -ENV SCRIPT TIDY_PRINT_DIFF=1 python2.7 ../x.py test \ - --stage 0 src/tools/tidy tidyselftest --extra-checks=py,cpp +ENV SCRIPT TIDY_PRINT_DIFF=1 npm install eslint@$(head -n 1 /tmp/eslint.version) && \ + python2.7 ../x.py test --stage 0 src/tools/tidy tidyselftest --extra-checks=py,cpp diff --git a/src/ci/docker/host-x86_64/mingw-check-tidy/eslint.version b/src/ci/docker/host-x86_64/mingw-check-tidy/eslint.version new file mode 100644 index 0000000000000..1acea15afd690 --- /dev/null +++ b/src/ci/docker/host-x86_64/mingw-check-tidy/eslint.version @@ -0,0 +1 @@ +8.6.0 \ No newline at end of file diff --git a/src/ci/docker/host-x86_64/mingw-check/Dockerfile b/src/ci/docker/host-x86_64/mingw-check/Dockerfile index 418408e9242ae..df73c7382b519 100644 --- a/src/ci/docker/host-x86_64/mingw-check/Dockerfile +++ b/src/ci/docker/host-x86_64/mingw-check/Dockerfile @@ -65,7 +65,4 @@ ENV SCRIPT \ python3 ../x.py test collect-license-metadata && \ # Runs checks to ensure that there are no issues in our JS code. es-check es2019 ../src/librustdoc/html/static/js/*.js && \ - eslint -c ../src/librustdoc/html/static/.eslintrc.js ../src/librustdoc/html/static/js/*.js && \ - eslint -c ../src/tools/rustdoc-js/.eslintrc.js ../src/tools/rustdoc-js/tester.js && \ - eslint -c ../src/tools/rustdoc-gui/.eslintrc.js ../src/tools/rustdoc-gui/tester.js && \ tsc --project ../src/librustdoc/html/static/js/tsconfig.json diff --git a/src/tools/tidy/src/lib.rs b/src/tools/tidy/src/lib.rs index ca45f8bb84ba9..e8a12d563358d 100644 --- a/src/tools/tidy/src/lib.rs +++ b/src/tools/tidy/src/lib.rs @@ -82,6 +82,7 @@ pub mod mir_opt_tests; pub mod pal; pub mod rustdoc_css_themes; pub mod rustdoc_gui_tests; +pub mod rustdoc_js; pub mod rustdoc_templates; pub mod style; pub mod target_policy; diff --git a/src/tools/tidy/src/main.rs b/src/tools/tidy/src/main.rs index 48122129b0174..776f1bde2eb71 100644 --- a/src/tools/tidy/src/main.rs +++ b/src/tools/tidy/src/main.rs @@ -35,6 +35,7 @@ fn main() { let library_path = root_path.join("library"); let compiler_path = root_path.join("compiler"); let librustdoc_path = src_path.join("librustdoc"); + let tools_path = src_path.join("tools"); let crashes_path = tests_path.join("crashes"); let args: Vec = env::args().skip(1).collect(); @@ -108,6 +109,7 @@ fn main() { check!(rustdoc_gui_tests, &tests_path); check!(rustdoc_css_themes, &librustdoc_path); check!(rustdoc_templates, &librustdoc_path); + check!(rustdoc_js, &librustdoc_path, &tools_path, &src_path); check!(known_bug, &crashes_path); check!(unknown_revision, &tests_path); diff --git a/src/tools/tidy/src/rustdoc_js.rs b/src/tools/tidy/src/rustdoc_js.rs new file mode 100644 index 0000000000000..2517e2de12ce5 --- /dev/null +++ b/src/tools/tidy/src/rustdoc_js.rs @@ -0,0 +1,99 @@ +//! Tidy check to ensure that rustdoc templates didn't forget a `{# #}` to strip extra whitespace +//! characters. + +use std::ffi::OsStr; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use ignore::DirEntry; + +use crate::walk::walk_no_read; + +fn run_eslint(args: &[PathBuf], config_folder: PathBuf, bad: &mut bool) { + let mut child = match Command::new("npx") + .arg("eslint") + .arg("-c") + .arg(config_folder.join(".eslintrc.js")) + .args(args) + .spawn() + { + Ok(child) => child, + Err(error) => { + *bad = true; + eprintln!("failed to run eslint: {error:?}"); + return; + } + }; + match child.wait() { + Ok(exit_status) => { + if exit_status.success() { + return; + } + eprintln!("eslint command failed"); + } + Err(error) => eprintln!("eslint command failed: {error:?}"), + } + *bad = true; +} + +fn get_eslint_version_inner(global: bool) -> Option { + let mut command = Command::new("npm"); + command.arg("list").arg("--parseable").arg("--long").arg("--depth=0"); + if global { + command.arg("--global"); + } + let output = command.output().ok()?; + let lines = String::from_utf8_lossy(&output.stdout); + lines.lines().find_map(|l| l.split(':').nth(1)?.strip_prefix("eslint@")).map(|v| v.to_owned()) +} + +fn get_eslint_version() -> Option { + get_eslint_version_inner(false).or_else(|| get_eslint_version_inner(true)) +} + +pub fn check(librustdoc_path: &Path, tools_path: &Path, src_path: &Path, bad: &mut bool) { + let eslint_version_path = + src_path.join("ci/docker/host-x86_64/mingw-check-tidy/eslint.version"); + let eslint_version = match std::fs::read_to_string(&eslint_version_path) { + Ok(version) => version.trim().to_string(), + Err(error) => { + *bad = true; + eprintln!("failed to read `{}`: {error:?}", eslint_version_path.display()); + return; + } + }; + match get_eslint_version() { + Some(version) => { + if version != eslint_version { + *bad = true; + eprintln!( + "⚠️ Installed version of eslint (`{version}`) is different than the \ + one used in the CI (`{eslint_version}`)", + ); + eprintln!( + "You can install this version using `npm update eslint` or by using \ + `npm install eslint@{eslint_version}`", + ); + return; + } + } + None => { + eprintln!("`eslint` doesn't seem to be installed. Skipping tidy check for JS files."); + eprintln!("You can install it using `npm install eslint@{eslint_version}`"); + return; + } + } + let mut files_to_check = Vec::new(); + walk_no_read( + &[&librustdoc_path.join("html/static/js")], + |path, is_dir| is_dir || !path.extension().is_some_and(|ext| ext == OsStr::new("js")), + &mut |path: &DirEntry| { + files_to_check.push(path.path().into()); + }, + ); + println!("Running eslint on rustdoc JS files"); + run_eslint(&files_to_check, librustdoc_path.join("html/static"), bad); + + run_eslint(&[tools_path.join("rustdoc-js/tester.js")], tools_path.join("rustdoc-js"), bad); + run_eslint(&[tools_path.join("rustdoc-gui/tester.js")], tools_path.join("rustdoc-gui"), bad); +} diff --git a/triagebot.toml b/triagebot.toml index b74159e5e5f11..a8d529cae77ad 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -1416,8 +1416,10 @@ compiletest = [ "/src/tools/rustdoc-gui-test" = ["bootstrap", "@onur-ozkan"] "/src/tools/libcxx-version" = ["@onur-ozkan"] -# Enable tracking of PR review assignment -# Documentation at: https://forge.rust-lang.org/triagebot/pr-assignment-tracking.html +# Enable review queue tracking +# Documentation at: https://forge.rust-lang.org/triagebot/review-queue-tracking.html +[assign.review_prefs] + [pr-tracking] # Enable issue transfers within the org