From 6649219c3f218408b630d14d03271c9038901000 Mon Sep 17 00:00:00 2001
From: Jubilee Young <workingjubilee@gmail.com>
Date: Sat, 28 Oct 2023 22:29:46 -0700
Subject: [PATCH 01/34] Remove asmjs from library

---
 library/core/src/ffi/mod.rs         |  6 ------
 library/std/build.rs                |  1 -
 library/std/src/os/l4re/raw.rs      |  1 -
 library/std/src/os/linux/raw.rs     |  1 -
 library/std/src/sys/common/alloc.rs |  1 -
 library/std/src/sys/unix/env.rs     | 11 -----------
 6 files changed, 21 deletions(-)

diff --git a/library/core/src/ffi/mod.rs b/library/core/src/ffi/mod.rs
index 6908c824f44b6..7340ad90da509 100644
--- a/library/core/src/ffi/mod.rs
+++ b/library/core/src/ffi/mod.rs
@@ -241,7 +241,6 @@ impl fmt::Debug for c_void {
     ),
     all(target_arch = "aarch64", any(target_os = "macos", target_os = "ios", target_os = "tvos")),
     target_family = "wasm",
-    target_arch = "asmjs",
     target_os = "uefi",
     windows,
 ))]
@@ -270,7 +269,6 @@ pub struct VaListImpl<'f> {
     ),
     all(target_arch = "aarch64", any(target_os = "macos", target_os = "ios", target_os = "tvos")),
     target_family = "wasm",
-    target_arch = "asmjs",
     target_os = "uefi",
     windows,
 ))]
@@ -395,7 +393,6 @@ pub struct VaList<'a, 'f: 'a> {
             any(target_os = "macos", target_os = "ios", target_os = "tvos")
         ),
         target_family = "wasm",
-        target_arch = "asmjs",
         target_os = "uefi",
         windows,
     ))]
@@ -413,7 +410,6 @@ pub struct VaList<'a, 'f: 'a> {
             not(any(target_os = "macos", target_os = "ios", target_os = "tvos"))
         ),
         not(target_family = "wasm"),
-        not(target_arch = "asmjs"),
         not(target_os = "uefi"),
         not(windows),
     ))]
@@ -431,7 +427,6 @@ pub struct VaList<'a, 'f: 'a> {
     ),
     all(target_arch = "aarch64", any(target_os = "macos", target_os = "ios", target_os = "tvos")),
     target_family = "wasm",
-    target_arch = "asmjs",
     target_os = "uefi",
     windows,
 ))]
@@ -461,7 +456,6 @@ impl<'f> VaListImpl<'f> {
         not(any(target_os = "macos", target_os = "ios", target_os = "tvos"))
     ),
     not(target_family = "wasm"),
-    not(target_arch = "asmjs"),
     not(target_os = "uefi"),
     not(windows),
 ))]
diff --git a/library/std/build.rs b/library/std/build.rs
index ad0a82eab8ca1..11ba29766c17e 100644
--- a/library/std/build.rs
+++ b/library/std/build.rs
@@ -25,7 +25,6 @@ fn main() {
         || target.contains("vxworks")
         || target.contains("wasm32")
         || target.contains("wasm64")
-        || target.contains("asmjs")
         || target.contains("espidf")
         || target.contains("solid")
         || target.contains("nintendo-3ds")
diff --git a/library/std/src/os/l4re/raw.rs b/library/std/src/os/l4re/raw.rs
index 12c0293285a5e..8fb6e99ecfa1e 100644
--- a/library/std/src/os/l4re/raw.rs
+++ b/library/std/src/os/l4re/raw.rs
@@ -31,7 +31,6 @@ pub use self::arch::{blkcnt_t, blksize_t, ino_t, nlink_t, off_t, stat, time_t};
     target_arch = "powerpc",
     target_arch = "sparc",
     target_arch = "arm",
-    target_arch = "asmjs",
     target_arch = "wasm32"
 ))]
 mod arch {
diff --git a/library/std/src/os/linux/raw.rs b/library/std/src/os/linux/raw.rs
index a568f9b26baa9..c29dd62bc06f0 100644
--- a/library/std/src/os/linux/raw.rs
+++ b/library/std/src/os/linux/raw.rs
@@ -31,7 +31,6 @@ pub use self::arch::{blkcnt_t, blksize_t, ino_t, nlink_t, off_t, stat, time_t};
     target_arch = "powerpc",
     target_arch = "sparc",
     target_arch = "arm",
-    target_arch = "asmjs",
     target_arch = "wasm32"
 ))]
 mod arch {
diff --git a/library/std/src/sys/common/alloc.rs b/library/std/src/sys/common/alloc.rs
index d58aa6c27b8cd..b7357460f3931 100644
--- a/library/std/src/sys/common/alloc.rs
+++ b/library/std/src/sys/common/alloc.rs
@@ -14,7 +14,6 @@ use crate::ptr;
     target_arch = "powerpc",
     target_arch = "powerpc64",
     target_arch = "sparc",
-    target_arch = "asmjs",
     target_arch = "wasm32",
     target_arch = "hexagon",
     all(target_arch = "riscv32", not(target_os = "espidf")),
diff --git a/library/std/src/sys/unix/env.rs b/library/std/src/sys/unix/env.rs
index 3bb492fa98bcf..3d4ba509829d3 100644
--- a/library/std/src/sys/unix/env.rs
+++ b/library/std/src/sys/unix/env.rs
@@ -174,17 +174,6 @@ pub mod os {
     pub const EXE_EXTENSION: &str = "elf";
 }
 
-#[cfg(all(target_os = "emscripten", target_arch = "asmjs"))]
-pub mod os {
-    pub const FAMILY: &str = "unix";
-    pub const OS: &str = "emscripten";
-    pub const DLL_PREFIX: &str = "lib";
-    pub const DLL_SUFFIX: &str = ".so";
-    pub const DLL_EXTENSION: &str = "so";
-    pub const EXE_SUFFIX: &str = ".js";
-    pub const EXE_EXTENSION: &str = "js";
-}
-
 #[cfg(all(target_os = "emscripten", target_arch = "wasm32"))]
 pub mod os {
     pub const FAMILY: &str = "unix";

From e9a009fd1a9ce00ee07eeb17bc8e9985815a1296 Mon Sep 17 00:00:00 2001
From: Jubilee Young <workingjubilee@gmail.com>
Date: Sat, 28 Oct 2023 23:11:03 -0700
Subject: [PATCH 02/34] Remove asmjs from tests

---
 .../stack-protector/stack-protector-target-support.rs        | 5 ++---
 tests/incremental/commandline-args.rs                        | 1 -
 tests/incremental/remapped_paths_cc/main.rs                  | 1 -
 tests/incremental/span_hash_stable/main.rs                   | 1 -
 tests/incremental/spans_in_type_debuginfo.rs                 | 1 -
 tests/incremental/spans_significant_w_debuginfo.rs           | 1 -
 tests/ui/abi/variadic-ffi.rs                                 | 5 -----
 tests/ui/async-await/issue-60709.rs                          | 1 -
 tests/ui/binding/match-arm-statics.rs                        | 1 -
 tests/ui/cfg/conditional-compile-arch.rs                     | 3 ---
 tests/ui/coroutine/issue-58888.rs                            | 1 -
 tests/ui/coroutine/size-moved-locals.rs                      | 1 -
 tests/ui/extern/extern-const.fixed                           | 1 -
 tests/ui/extern/extern-const.rs                              | 1 -
 tests/ui/extern/extern-const.stderr                          | 2 +-
 tests/ui/issues/issue-18804/main.rs                          | 1 -
 tests/ui/issues/issue-23477.rs                               | 1 -
 tests/ui/issues/issue-24687-embed-debuginfo/main.rs          | 1 -
 tests/ui/issues/issue-24945-repeat-dash-opts.rs              | 1 -
 tests/ui/issues/issue-26484.rs                               | 1 -
 tests/ui/issues/issue-33096.rs                               | 1 -
 tests/ui/issues/issue-34569.rs                               | 1 -
 tests/ui/issues/issue-36856.rs                               | 1 -
 tests/ui/issues/issue-42210.rs                               | 1 -
 tests/ui/issues/issue-45731.rs                               | 1 -
 tests/ui/issues/issue-58463.rs                               | 1 -
 tests/ui/lto/debuginfo-lto.rs                                | 1 -
 tests/ui/parser/issues/issue-48508.rs                        | 1 -
 tests/ui/sepcomp/sepcomp-lib-lto.rs                          | 1 -
 tests/ui/unboxed-closures/unboxed-closures-unique-type-id.rs | 1 -
 30 files changed, 3 insertions(+), 38 deletions(-)

diff --git a/tests/assembly/stack-protector/stack-protector-target-support.rs b/tests/assembly/stack-protector/stack-protector-target-support.rs
index e5cbace80b1e2..c6528ac7c8d16 100644
--- a/tests/assembly/stack-protector/stack-protector-target-support.rs
+++ b/tests/assembly/stack-protector/stack-protector-target-support.rs
@@ -2,7 +2,7 @@
 // targets, with the exception of nvptx64-nvidia-cuda
 //
 // revisions: r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23
-// revisions: r24 r25 r26 r27 r28 r29 r30 r31 r32 r33 r34 r35 r36 r37 r38 r39 r40 r41 r42 r43 r44
+// revisions: r24 r25 r26 r27 r28 r29 r30 r31 r32 r33     r35 r36 r37 r38 r39 r40 r41 r42 r43 r44
 // revisions: r45 r46 r47 r48 r49 r50 r51 r52 r53 r54 r55 r56 r57 r58 r59 r60 r61 r62 r63 r64 r65
 // revisions: r66 r67 r68 r69 r70 r71 r72 r73 r74 r75 r76 r77 r78 r79 r80 r81 r82 r83 r84
 // assembly-output: emit-asm
@@ -72,8 +72,7 @@
 // [r32] needs-llvm-components: arm
 // [r33] compile-flags: --target armv7-unknown-linux-musleabihf
 // [r33] needs-llvm-components: arm
-// [r34] compile-flags: --target asmjs-unknown-emscripten
-// [r34] needs-llvm-components: webassembly
+
 // [r35] compile-flags: --target i586-pc-windows-msvc
 // [r35] needs-llvm-components: x86
 // [r36] compile-flags: --target i586-unknown-linux-gnu
diff --git a/tests/incremental/commandline-args.rs b/tests/incremental/commandline-args.rs
index 35b7183db7fac..e17e6feae0745 100644
--- a/tests/incremental/commandline-args.rs
+++ b/tests/incremental/commandline-args.rs
@@ -1,7 +1,6 @@
 // Test that changing a tracked commandline argument invalidates
 // the cache while changing an untracked one doesn't.
 
-// ignore-asmjs wasm2js does not support source maps yet
 // revisions:rpass1 rpass2 rpass3 rpass4
 // compile-flags: -Z query-dep-graph
 
diff --git a/tests/incremental/remapped_paths_cc/main.rs b/tests/incremental/remapped_paths_cc/main.rs
index b01f02444eae8..12411a928799f 100644
--- a/tests/incremental/remapped_paths_cc/main.rs
+++ b/tests/incremental/remapped_paths_cc/main.rs
@@ -2,7 +2,6 @@
 // compile-flags: -Z query-dep-graph -g
 // aux-build:extern_crate.rs
 
-// ignore-asmjs wasm2js does not support source maps yet
 // This test case makes sure that we detect if paths emitted into debuginfo
 // are changed, even when the change happens in an external crate.
 
diff --git a/tests/incremental/span_hash_stable/main.rs b/tests/incremental/span_hash_stable/main.rs
index 367416430f86b..f1d7de1455938 100644
--- a/tests/incremental/span_hash_stable/main.rs
+++ b/tests/incremental/span_hash_stable/main.rs
@@ -3,7 +3,6 @@
 // the spans and this test makes sure that we handle them correctly by hashing
 // file:line:column instead of raw byte offset.
 
-// ignore-asmjs wasm2js does not support source maps yet
 // revisions:rpass1 rpass2
 // compile-flags: -g -Z query-dep-graph
 
diff --git a/tests/incremental/spans_in_type_debuginfo.rs b/tests/incremental/spans_in_type_debuginfo.rs
index f5cae15a4bc7c..8ed469db6e633 100644
--- a/tests/incremental/spans_in_type_debuginfo.rs
+++ b/tests/incremental/spans_in_type_debuginfo.rs
@@ -1,7 +1,6 @@
 // Test that moving a type definition within a source file does not affect
 // re-compilation.
 
-// ignore-asmjs wasm2js does not support source maps yet
 // revisions:rpass1 rpass2
 // compile-flags: -Z query-dep-graph -g
 
diff --git a/tests/incremental/spans_significant_w_debuginfo.rs b/tests/incremental/spans_significant_w_debuginfo.rs
index 38ab28461911b..a036d3e69fe4a 100644
--- a/tests/incremental/spans_significant_w_debuginfo.rs
+++ b/tests/incremental/spans_significant_w_debuginfo.rs
@@ -3,7 +3,6 @@
 
 // revisions:rpass1 rpass2
 
-// ignore-asmjs wasm2js does not support source maps yet
 // compile-flags: -g -Z query-dep-graph
 
 #![feature(rustc_attrs)]
diff --git a/tests/ui/abi/variadic-ffi.rs b/tests/ui/abi/variadic-ffi.rs
index a952ea0779329..1862177005f93 100644
--- a/tests/ui/abi/variadic-ffi.rs
+++ b/tests/ui/abi/variadic-ffi.rs
@@ -8,11 +8,6 @@ use std::ffi::VaList;
 extern "C" {
     fn rust_interesting_average(_: u64, ...) -> f64;
 
-    // FIXME: we need to disable this lint for `VaList`,
-    // since it contains a `MaybeUninit<i32>` on the asmjs target,
-    // and this type isn't FFI-safe. This is OK for now,
-    // since the type is layout-compatible with `i32`.
-    #[cfg_attr(target_arch = "asmjs", allow(improper_ctypes))]
     fn rust_valist_interesting_average(_: u64, _: VaList) -> f64;
 }
 
diff --git a/tests/ui/async-await/issue-60709.rs b/tests/ui/async-await/issue-60709.rs
index 2cda40e9e11ba..c206f01b98f78 100644
--- a/tests/ui/async-await/issue-60709.rs
+++ b/tests/ui/async-await/issue-60709.rs
@@ -3,7 +3,6 @@
 // compile-flags: -Copt-level=z -Cdebuginfo=2 --edition=2018
 
 // run-pass
-// ignore-asmjs wasm2js does not support source maps yet
 
 use std::future::Future;
 use std::task::Poll;
diff --git a/tests/ui/binding/match-arm-statics.rs b/tests/ui/binding/match-arm-statics.rs
index e6d17def1477e..5f7e357eeb2a9 100644
--- a/tests/ui/binding/match-arm-statics.rs
+++ b/tests/ui/binding/match-arm-statics.rs
@@ -1,7 +1,6 @@
 // run-pass
 #![allow(dead_code)]
 // compile-flags: -g
-// ignore-asmjs wasm2js does not support source maps yet
 
 #[derive(PartialEq, Eq)]
 struct NewBool(bool);
diff --git a/tests/ui/cfg/conditional-compile-arch.rs b/tests/ui/cfg/conditional-compile-arch.rs
index e59e06f801b78..c6ecf4807364d 100644
--- a/tests/ui/cfg/conditional-compile-arch.rs
+++ b/tests/ui/cfg/conditional-compile-arch.rs
@@ -28,9 +28,6 @@ pub fn main() { }
 #[cfg(target_arch = "s390x")]
 pub fn main() { }
 
-#[cfg(target_arch = "asmjs")]
-pub fn main() { }
-
 #[cfg(target_arch = "wasm32")]
 pub fn main() { }
 
diff --git a/tests/ui/coroutine/issue-58888.rs b/tests/ui/coroutine/issue-58888.rs
index af8e60ce460cd..9c699c7bb8292 100644
--- a/tests/ui/coroutine/issue-58888.rs
+++ b/tests/ui/coroutine/issue-58888.rs
@@ -1,6 +1,5 @@
 // run-pass
 // compile-flags: -g
-// ignore-asmjs wasm2js does not support source maps yet
 
 #![feature(coroutines, coroutine_trait)]
 
diff --git a/tests/ui/coroutine/size-moved-locals.rs b/tests/ui/coroutine/size-moved-locals.rs
index cfbbb9c1b318f..10f988cc06665 100644
--- a/tests/ui/coroutine/size-moved-locals.rs
+++ b/tests/ui/coroutine/size-moved-locals.rs
@@ -11,7 +11,6 @@
 
 // edition:2018
 // ignore-wasm32 issue #62807
-// ignore-asmjs issue #62807
 // needs-unwind Size of Closures change on panic=abort
 
 #![feature(coroutines, coroutine_trait)]
diff --git a/tests/ui/extern/extern-const.fixed b/tests/ui/extern/extern-const.fixed
index 9d96b4f63fb6c..248efc93d008a 100644
--- a/tests/ui/extern/extern-const.fixed
+++ b/tests/ui/extern/extern-const.fixed
@@ -6,7 +6,6 @@
 
 // run-rustfix
 // ignore-wasm32-bare no external library to link to.
-// ignore-asmjs wasm2js does not support source maps yet
 // compile-flags: -g
 #![feature(rustc_private)]
 extern crate libc;
diff --git a/tests/ui/extern/extern-const.rs b/tests/ui/extern/extern-const.rs
index 7cef5b3497b5a..d3b3bef6dae6f 100644
--- a/tests/ui/extern/extern-const.rs
+++ b/tests/ui/extern/extern-const.rs
@@ -6,7 +6,6 @@
 
 // run-rustfix
 // ignore-wasm32-bare no external library to link to.
-// ignore-asmjs wasm2js does not support source maps yet
 // compile-flags: -g
 #![feature(rustc_private)]
 extern crate libc;
diff --git a/tests/ui/extern/extern-const.stderr b/tests/ui/extern/extern-const.stderr
index 7f67adbdb19c7..a296751994ea2 100644
--- a/tests/ui/extern/extern-const.stderr
+++ b/tests/ui/extern/extern-const.stderr
@@ -1,5 +1,5 @@
 error: extern items cannot be `const`
-  --> $DIR/extern-const.rs:16:11
+  --> $DIR/extern-const.rs:15:11
    |
 LL |     const rust_dbg_static_mut: libc::c_int;
    |     ------^^^^^^^^^^^^^^^^^^^
diff --git a/tests/ui/issues/issue-18804/main.rs b/tests/ui/issues/issue-18804/main.rs
index c36048ea54503..47c3f13d23cad 100644
--- a/tests/ui/issues/issue-18804/main.rs
+++ b/tests/ui/issues/issue-18804/main.rs
@@ -2,7 +2,6 @@
 // Test for issue #18804, #[linkage] does not propagate through generic
 // functions. Failure results in a linker error.
 
-// ignore-asmjs no weak symbol support
 // ignore-emscripten no weak symbol support
 // ignore-windows no extern_weak linkage
 // ignore-macos no extern_weak linkage
diff --git a/tests/ui/issues/issue-23477.rs b/tests/ui/issues/issue-23477.rs
index 988ebe03ccf66..1ce05ba390d76 100644
--- a/tests/ui/issues/issue-23477.rs
+++ b/tests/ui/issues/issue-23477.rs
@@ -1,5 +1,4 @@
 // build-pass
-// ignore-asmjs wasm2js does not support source maps yet
 // compile-flags: -g
 
 pub struct Dst {
diff --git a/tests/ui/issues/issue-24687-embed-debuginfo/main.rs b/tests/ui/issues/issue-24687-embed-debuginfo/main.rs
index f08bcdfe6d16c..773792c7a3f1f 100644
--- a/tests/ui/issues/issue-24687-embed-debuginfo/main.rs
+++ b/tests/ui/issues/issue-24687-embed-debuginfo/main.rs
@@ -1,7 +1,6 @@
 // run-pass
 // aux-build:issue-24687-lib.rs
 // compile-flags:-g
-// ignore-asmjs wasm2js does not support source maps yet
 
 extern crate issue_24687_lib as d;
 
diff --git a/tests/ui/issues/issue-24945-repeat-dash-opts.rs b/tests/ui/issues/issue-24945-repeat-dash-opts.rs
index 0f92fc2f7f31a..cf3834952c6a6 100644
--- a/tests/ui/issues/issue-24945-repeat-dash-opts.rs
+++ b/tests/ui/issues/issue-24945-repeat-dash-opts.rs
@@ -3,7 +3,6 @@
 // as options to the compiler.
 
 // compile-flags:-g -g -O -O
-// ignore-asmjs wasm2js does not support source maps yet
 
 fn main() {
     assert_eq!(1, 1);
diff --git a/tests/ui/issues/issue-26484.rs b/tests/ui/issues/issue-26484.rs
index 2a8750d3e431f..3b40b3dd8f075 100644
--- a/tests/ui/issues/issue-26484.rs
+++ b/tests/ui/issues/issue-26484.rs
@@ -1,6 +1,5 @@
 // run-pass
 // compile-flags:-g
-// ignore-asmjs wasm2js does not support source maps yet
 
 fn helper<F: FnOnce(usize) -> bool>(_f: F) {
     print!("");
diff --git a/tests/ui/issues/issue-33096.rs b/tests/ui/issues/issue-33096.rs
index 2501e1430b3d1..f0b472e2fe821 100644
--- a/tests/ui/issues/issue-33096.rs
+++ b/tests/ui/issues/issue-33096.rs
@@ -1,6 +1,5 @@
 // run-pass
 // compile-flags: -g
-// ignore-asmjs wasm2js does not support source maps yet
 
 use std::ops::Deref;
 
diff --git a/tests/ui/issues/issue-34569.rs b/tests/ui/issues/issue-34569.rs
index 88dcdd4113807..1f68560509e8c 100644
--- a/tests/ui/issues/issue-34569.rs
+++ b/tests/ui/issues/issue-34569.rs
@@ -1,6 +1,5 @@
 // run-pass
 // compile-flags:-g
-// ignore-asmjs wasm2js does not support source maps yet
 
 // In this test we just want to make sure that the code below does not lead to
 // a debuginfo verification assertion during compilation. This was caused by the
diff --git a/tests/ui/issues/issue-36856.rs b/tests/ui/issues/issue-36856.rs
index 5657ba69f9449..f2dfaf3dd367e 100644
--- a/tests/ui/issues/issue-36856.rs
+++ b/tests/ui/issues/issue-36856.rs
@@ -2,7 +2,6 @@
 // Regression test for #36856.
 
 // compile-flags:-g
-// ignore-asmjs wasm2js does not support source maps yet
 
 fn g() -> bool {
     false
diff --git a/tests/ui/issues/issue-42210.rs b/tests/ui/issues/issue-42210.rs
index 01a5d563639b5..318e3099f98ba 100644
--- a/tests/ui/issues/issue-42210.rs
+++ b/tests/ui/issues/issue-42210.rs
@@ -2,7 +2,6 @@
 // Regression test for #42210.
 
 // compile-flags: -g
-// ignore-asmjs wasm2js does not support source maps yet
 
 trait Foo {
     fn foo() { }
diff --git a/tests/ui/issues/issue-45731.rs b/tests/ui/issues/issue-45731.rs
index 5c5ac59873a3a..d20c07276a8c5 100644
--- a/tests/ui/issues/issue-45731.rs
+++ b/tests/ui/issues/issue-45731.rs
@@ -1,7 +1,6 @@
 // run-pass
 #![allow(unused_variables)]
 // compile-flags:--test -g
-// ignore-asmjs wasm2js does not support source maps yet
 
 #[cfg(target_os = "macos")]
 #[test]
diff --git a/tests/ui/issues/issue-58463.rs b/tests/ui/issues/issue-58463.rs
index af93f76221d4e..9573c9b703aa3 100644
--- a/tests/ui/issues/issue-58463.rs
+++ b/tests/ui/issues/issue-58463.rs
@@ -1,6 +1,5 @@
 // run-pass
 // compile-flags:-C debuginfo=2
-// ignore-asmjs wasm2js does not support source maps yet
 
 fn foo() -> impl Copy {
     foo
diff --git a/tests/ui/lto/debuginfo-lto.rs b/tests/ui/lto/debuginfo-lto.rs
index 43f75b0344be7..e4beee9e737ba 100644
--- a/tests/ui/lto/debuginfo-lto.rs
+++ b/tests/ui/lto/debuginfo-lto.rs
@@ -7,7 +7,6 @@
 // aux-build:debuginfo-lto-aux.rs
 // compile-flags: -C lto -g
 // no-prefer-dynamic
-// ignore-asmjs wasm2js does not support source maps yet
 
 extern crate debuginfo_lto_aux;
 
diff --git a/tests/ui/parser/issues/issue-48508.rs b/tests/ui/parser/issues/issue-48508.rs
index 1e7db9df814b4..b66e09620f4eb 100644
--- a/tests/ui/parser/issues/issue-48508.rs
+++ b/tests/ui/parser/issues/issue-48508.rs
@@ -7,7 +7,6 @@
 // issue-48508-aux.rs
 
 // compile-flags:-g
-// ignore-asmjs wasm2js does not support source maps yet
 
 #![allow(uncommon_codepoints)]
 
diff --git a/tests/ui/sepcomp/sepcomp-lib-lto.rs b/tests/ui/sepcomp/sepcomp-lib-lto.rs
index 51a572899f819..164ae79c254fa 100644
--- a/tests/ui/sepcomp/sepcomp-lib-lto.rs
+++ b/tests/ui/sepcomp/sepcomp-lib-lto.rs
@@ -4,7 +4,6 @@
 
 // aux-build:sepcomp_lib.rs
 // compile-flags: -C lto -g
-// ignore-asmjs wasm2js does not support source maps yet
 // no-prefer-dynamic
 
 extern crate sepcomp_lib;
diff --git a/tests/ui/unboxed-closures/unboxed-closures-unique-type-id.rs b/tests/ui/unboxed-closures/unboxed-closures-unique-type-id.rs
index 4b7016def9d60..94bb44d2cf50c 100644
--- a/tests/ui/unboxed-closures/unboxed-closures-unique-type-id.rs
+++ b/tests/ui/unboxed-closures/unboxed-closures-unique-type-id.rs
@@ -10,7 +10,6 @@
 // This is a regression test for issue #17021.
 //
 // compile-flags: -g
-// ignore-asmjs wasm2js does not support source maps yet
 
 use std::ptr;
 

From c88fc2ec6a1a8dfcb97d64e359c05c53ae93ab3f Mon Sep 17 00:00:00 2001
From: Jubilee Young <workingjubilee@gmail.com>
Date: Sat, 28 Oct 2023 23:13:23 -0700
Subject: [PATCH 03/34] Remove asmjs from CI

---
 .../host-x86_64/disabled/asmjs/Dockerfile     | 43 -------------------
 .../host-x86_64/dist-various-1/Dockerfile     |  3 +-
 2 files changed, 1 insertion(+), 45 deletions(-)
 delete mode 100644 src/ci/docker/host-x86_64/disabled/asmjs/Dockerfile

diff --git a/src/ci/docker/host-x86_64/disabled/asmjs/Dockerfile b/src/ci/docker/host-x86_64/disabled/asmjs/Dockerfile
deleted file mode 100644
index 07dcb9ea928f8..0000000000000
--- a/src/ci/docker/host-x86_64/disabled/asmjs/Dockerfile
+++ /dev/null
@@ -1,43 +0,0 @@
-FROM ubuntu:16.04
-
-RUN apt-get update && apt-get install -y --no-install-recommends \
-  g++ \
-  make \
-  ninja-build \
-  file \
-  curl \
-  ca-certificates \
-  python3 \
-  git \
-  cmake \
-  sudo \
-  gdb \
-  xz-utils \
-  bzip2
-
-COPY scripts/emscripten.sh /scripts/
-RUN bash /scripts/emscripten.sh
-
-COPY scripts/sccache.sh /scripts/
-RUN sh /scripts/sccache.sh
-
-ENV PATH=$PATH:/emsdk-portable
-ENV PATH=$PATH:/emsdk-portable/upstream/emscripten/
-ENV PATH=$PATH:/emsdk-portable/node/12.9.1_64bit/bin/
-ENV BINARYEN_ROOT=/emsdk-portable/upstream/
-
-ENV TARGETS=asmjs-unknown-emscripten
-
-# Use -O1 optimizations in the link step to reduce time spent optimizing JS.
-ENV EMCC_CFLAGS=-O1
-
-# Emscripten installation is user-specific
-ENV NO_CHANGE_USER=1
-
-ENV SCRIPT python3 ../x.py --stage 2 test --host='' --target $TARGETS
-
-# This is almost identical to the wasm32-unknown-emscripten target, so
-# running with assertions again is not useful
-ENV NO_DEBUG_ASSERTIONS=1
-ENV NO_LLVM_ASSERTIONS=1
-ENV NO_OVERFLOW_CHECKS=1
diff --git a/src/ci/docker/host-x86_64/dist-various-1/Dockerfile b/src/ci/docker/host-x86_64/dist-various-1/Dockerfile
index 3372baed999ac..341e2de223aa5 100644
--- a/src/ci/docker/host-x86_64/dist-various-1/Dockerfile
+++ b/src/ci/docker/host-x86_64/dist-various-1/Dockerfile
@@ -75,8 +75,7 @@ ENV RUN_MAKE_TARGETS=$RUN_MAKE_TARGETS,thumbv7m-none-eabi
 ENV RUN_MAKE_TARGETS=$RUN_MAKE_TARGETS,thumbv7em-none-eabi
 ENV RUN_MAKE_TARGETS=$RUN_MAKE_TARGETS,thumbv7em-none-eabihf
 
-ENV TARGETS=asmjs-unknown-emscripten
-ENV TARGETS=$TARGETS,wasm32-unknown-emscripten
+ENV TARGETS=wasm32-unknown-emscripten
 ENV TARGETS=$TARGETS,arm-unknown-linux-musleabi
 ENV TARGETS=$TARGETS,arm-unknown-linux-musleabihf
 ENV TARGETS=$TARGETS,armv5te-unknown-linux-gnueabi

From e8a027433b205af1d0815d17dbf4bde0f48fa592 Mon Sep 17 00:00:00 2001
From: Jubilee Young <workingjubilee@gmail.com>
Date: Sat, 28 Oct 2023 23:15:30 -0700
Subject: [PATCH 04/34] Remove asmjs from miri

---
 src/tools/miri/src/shims/foreign_items.rs | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/tools/miri/src/shims/foreign_items.rs b/src/tools/miri/src/shims/foreign_items.rs
index 2d5df3037452f..329a30a9faf3b 100644
--- a/src/tools/miri/src/shims/foreign_items.rs
+++ b/src/tools/miri/src/shims/foreign_items.rs
@@ -345,7 +345,7 @@ trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
         // List taken from `library/std/src/sys/common/alloc.rs`.
         // This list should be kept in sync with the one from libstd.
         let min_align = match this.tcx.sess.target.arch.as_ref() {
-            "x86" | "arm" | "mips" | "mips32r6" | "powerpc" | "powerpc64" | "asmjs" | "wasm32" => 8,
+            "x86" | "arm" | "mips" | "mips32r6" | "powerpc" | "powerpc64" | "wasm32" => 8,
             "x86_64" | "aarch64" | "mips64" | "mips64r6" | "s390x" | "sparc64" | "loongarch64" =>
                 16,
             arch => bug!("unsupported target architecture for malloc: `{}`", arch),

From ca4d6d15ff0ef8002aaaaf12938775e215ff6aa8 Mon Sep 17 00:00:00 2001
From: Jubilee Young <workingjubilee@gmail.com>
Date: Sat, 28 Oct 2023 23:17:39 -0700
Subject: [PATCH 05/34] Remove asmjs from tools

---
 src/librustdoc/clean/cfg.rs               | 1 -
 src/tools/build-manifest/src/main.rs      | 1 -
 src/tools/compiletest/src/common.rs       | 3 ---
 src/tools/compiletest/src/header/cfg.rs   | 8 +-------
 src/tools/compiletest/src/header/tests.rs | 5 -----
 5 files changed, 1 insertion(+), 17 deletions(-)

diff --git a/src/librustdoc/clean/cfg.rs b/src/librustdoc/clean/cfg.rs
index ab5aec12fe7cb..a5fa9980ce072 100644
--- a/src/librustdoc/clean/cfg.rs
+++ b/src/librustdoc/clean/cfg.rs
@@ -516,7 +516,6 @@ impl<'a> fmt::Display for Display<'a> {
                     (sym::target_arch, Some(arch)) => match arch.as_str() {
                         "aarch64" => "AArch64",
                         "arm" => "ARM",
-                        "asmjs" => "JavaScript",
                         "loongarch64" => "LoongArch LA64",
                         "m68k" => "M68k",
                         "csky" => "CSKY",
diff --git a/src/tools/build-manifest/src/main.rs b/src/tools/build-manifest/src/main.rs
index 2c795ebb21487..88f940c7678ac 100644
--- a/src/tools/build-manifest/src/main.rs
+++ b/src/tools/build-manifest/src/main.rs
@@ -82,7 +82,6 @@ static TARGETS: &[&str] = &[
     "armv7r-none-eabi",
     "armv7r-none-eabihf",
     "armv7s-apple-ios",
-    "asmjs-unknown-emscripten",
     "bpfeb-unknown-none",
     "bpfel-unknown-none",
     "i386-apple-ios",
diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs
index 0e1bf0c6c2dce..11e51ef6e4ba3 100644
--- a/src/tools/compiletest/src/common.rs
+++ b/src/tools/compiletest/src/common.rs
@@ -396,9 +396,6 @@ impl Config {
 
     pub fn matches_arch(&self, arch: &str) -> bool {
         self.target_cfg().arch == arch ||
-        // Shorthand for convenience. The arch for
-        // asmjs-unknown-emscripten is actually wasm32.
-        (arch == "asmjs" && self.target.starts_with("asmjs")) ||
         // Matching all the thumb variants as one can be convenient.
         // (thumbv6m, thumbv7em, thumbv7m, etc.)
         (arch == "thumb" && self.target.starts_with("thumb"))
diff --git a/src/tools/compiletest/src/header/cfg.rs b/src/tools/compiletest/src/header/cfg.rs
index 77c2866b366a6..3a1b9dff3a6b5 100644
--- a/src/tools/compiletest/src/header/cfg.rs
+++ b/src/tools/compiletest/src/header/cfg.rs
@@ -146,19 +146,13 @@ pub(super) fn parse_cfg_name_directive<'a>(
     }
 
     // `wasm32-bare` is an alias to refer to just wasm32-unknown-unknown
-    // (in contrast to `wasm32` which also matches non-bare targets like
-    // asmjs-unknown-emscripten).
+    // (in contrast to `wasm32` which also matches non-bare targets)
     condition! {
         name: "wasm32-bare",
         condition: config.target == "wasm32-unknown-unknown",
         message: "when the target is WASM"
     }
 
-    condition! {
-        name: "asmjs",
-        condition: config.target.starts_with("asmjs"),
-        message: "when the architecture is asm.js",
-    }
     condition! {
         name: "thumb",
         condition: config.target.starts_with("thumb"),
diff --git a/src/tools/compiletest/src/header/tests.rs b/src/tools/compiletest/src/header/tests.rs
index 2fd80b52ceeee..ab600f179137e 100644
--- a/src/tools/compiletest/src/header/tests.rs
+++ b/src/tools/compiletest/src/header/tests.rs
@@ -396,8 +396,6 @@ fn ignore_arch() {
         ("x86_64-unknown-linux-gnu", "x86_64"),
         ("i686-unknown-linux-gnu", "x86"),
         ("nvptx64-nvidia-cuda", "nvptx64"),
-        ("asmjs-unknown-emscripten", "wasm32"),
-        ("asmjs-unknown-emscripten", "asmjs"),
         ("thumbv7m-none-eabi", "thumb"),
     ];
     for (target, arch) in archs {
@@ -490,9 +488,6 @@ fn wasm_special() {
         ("wasm32-unknown-unknown", "wasm32", true),
         ("wasm32-unknown-unknown", "wasm32-bare", true),
         ("wasm32-unknown-unknown", "wasm64", false),
-        ("asmjs-unknown-emscripten", "emscripten", true),
-        ("asmjs-unknown-emscripten", "wasm32", true),
-        ("asmjs-unknown-emscripten", "wasm32-bare", false),
         ("wasm32-unknown-emscripten", "emscripten", true),
         ("wasm32-unknown-emscripten", "wasm32", true),
         ("wasm32-unknown-emscripten", "wasm32-bare", false),

From 0c1a452304a832428c629e083d61d58e4a077018 Mon Sep 17 00:00:00 2001
From: Jubilee Young <workingjubilee@gmail.com>
Date: Sat, 28 Oct 2023 23:20:14 -0700
Subject: [PATCH 06/34] Remove asmjs from bootstrap

---
 src/bootstrap/src/lib.rs | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/bootstrap/src/lib.rs b/src/bootstrap/src/lib.rs
index 8dd1a698dfa8e..c65954ed2545f 100644
--- a/src/bootstrap/src/lib.rs
+++ b/src/bootstrap/src/lib.rs
@@ -97,7 +97,7 @@ const EXTRA_CHECK_CFGS: &[(Option<Mode>, &str, Option<&[&'static str]>)] = &[
     /* Extra values not defined in the built-in targets yet, but used in std */
     (Some(Mode::Std), "target_env", Some(&["libnx"])),
     // (Some(Mode::Std), "target_os", Some(&[])),
-    (Some(Mode::Std), "target_arch", Some(&["asmjs", "spirv", "nvptx", "xtensa"])),
+    (Some(Mode::Std), "target_arch", Some(&["spirv", "nvptx", "xtensa"])),
     /* Extra names used by dependencies */
     // FIXME: Used by serde_json, but we should not be triggering on external dependencies.
     (Some(Mode::Rustc), "no_btreemap_remove_entry", None),

From 208f378ef18aa1d8d9482caa7fa5ab8ab190d2f3 Mon Sep 17 00:00:00 2001
From: Jubilee Young <workingjubilee@gmail.com>
Date: Sat, 28 Oct 2023 23:20:55 -0700
Subject: [PATCH 07/34] Remove asmjs from compiler

---
 compiler/rustc_codegen_llvm/src/back/write.rs              | 6 +-----
 compiler/rustc_codegen_ssa/src/back/link.rs                | 6 +++---
 compiler/rustc_target/src/abi/call/mod.rs                  | 1 -
 compiler/rustc_target/src/spec/asmjs_unknown_emscripten.rs | 7 -------
 compiler/rustc_target/src/spec/mod.rs                      | 5 -----
 5 files changed, 4 insertions(+), 21 deletions(-)
 delete mode 100644 compiler/rustc_target/src/spec/asmjs_unknown_emscripten.rs

diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs
index 9d5204034def0..8d335ff17183c 100644
--- a/compiler/rustc_codegen_llvm/src/back/write.rs
+++ b/compiler/rustc_codegen_llvm/src/back/write.rs
@@ -990,11 +990,7 @@ unsafe fn embed_bitcode(
     // reason (see issue #90326 for historical background).
     let is_aix = target_is_aix(cgcx);
     let is_apple = target_is_apple(cgcx);
-    if is_apple
-        || is_aix
-        || cgcx.opts.target_triple.triple().starts_with("wasm")
-        || cgcx.opts.target_triple.triple().starts_with("asmjs")
-    {
+    if is_apple || is_aix || cgcx.opts.target_triple.triple().starts_with("wasm") {
         // We don't need custom section flags, create LLVM globals.
         let llconst = common::bytes_in_context(llcx, bitcode);
         let llglobal = llvm::LLVMAddGlobal(
diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs
index bcbb75d959976..61f36cb912d29 100644
--- a/compiler/rustc_codegen_ssa/src/back/link.rs
+++ b/compiler/rustc_codegen_ssa/src/back/link.rs
@@ -2251,9 +2251,9 @@ fn linker_with_args<'a>(
     // ------------ Late order-dependent options ------------
 
     // Doesn't really make sense.
-    // FIXME: In practice built-in target specs use this for arbitrary order-independent options,
-    // introduce a target spec option for order-independent linker options, migrate built-in specs
-    // to it and remove the option.
+    // FIXME: In practice built-in target specs use this for arbitrary order-independent options.
+    // Introduce a target spec option for order-independent linker options, migrate built-in specs
+    // to it and remove the option. Currently the last holdout is wasm32-unknown-emscripten.
     add_post_link_args(cmd, sess, flavor);
 
     Ok(cmd.take_cmd())
diff --git a/compiler/rustc_target/src/abi/call/mod.rs b/compiler/rustc_target/src/abi/call/mod.rs
index 5efd171b9dd76..1aa24f6b84a8d 100644
--- a/compiler/rustc_target/src/abi/call/mod.rs
+++ b/compiler/rustc_target/src/abi/call/mod.rs
@@ -836,7 +836,6 @@ impl<'a, Ty> FnAbi<'a, Ty> {
                     wasm::compute_c_abi_info(cx, self)
                 }
             }
-            "asmjs" => wasm::compute_c_abi_info(cx, self),
             "bpf" => bpf::compute_abi_info(self),
             arch => {
                 return Err(AdjustForForeignAbiError::Unsupported {
diff --git a/compiler/rustc_target/src/spec/asmjs_unknown_emscripten.rs b/compiler/rustc_target/src/spec/asmjs_unknown_emscripten.rs
deleted file mode 100644
index f492c3451a418..0000000000000
--- a/compiler/rustc_target/src/spec/asmjs_unknown_emscripten.rs
+++ /dev/null
@@ -1,7 +0,0 @@
-use super::{wasm32_unknown_emscripten, LinkerFlavor, Target};
-
-pub fn target() -> Target {
-    let mut target = wasm32_unknown_emscripten::target();
-    target.add_post_link_args(LinkerFlavor::EmCc, &["-sWASM=0", "--memory-init-file", "0"]);
-    target
-}
diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs
index 31f538d8b612c..915b5aa288f76 100644
--- a/compiler/rustc_target/src/spec/mod.rs
+++ b/compiler/rustc_target/src/spec/mod.rs
@@ -1641,7 +1641,6 @@ supported_targets! {
     ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc),
     ("thumbv7a-uwp-windows-msvc", thumbv7a_uwp_windows_msvc),
 
-    ("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
     ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
     ("wasm32-unknown-unknown", wasm32_unknown_unknown),
     ("wasm32-wasi", wasm32_wasi),
@@ -2276,10 +2275,6 @@ impl TargetOptions {
         add_link_args(&mut self.pre_link_args, flavor, args);
     }
 
-    fn add_post_link_args(&mut self, flavor: LinkerFlavor, args: &[&'static str]) {
-        add_link_args(&mut self.post_link_args, flavor, args);
-    }
-
     fn update_from_cli(&mut self) {
         self.linker_flavor = LinkerFlavor::from_cli_json(
             self.linker_flavor_json,

From dbb250046d20da4eaa0320b3ecb52befce3dd419 Mon Sep 17 00:00:00 2001
From: Jubilee Young <workingjubilee@gmail.com>
Date: Sat, 28 Oct 2023 23:12:19 -0700
Subject: [PATCH 08/34] Officially remove asmjs platform support

---
 src/doc/rustc/src/platform-support.md | 1 -
 1 file changed, 1 deletion(-)

diff --git a/src/doc/rustc/src/platform-support.md b/src/doc/rustc/src/platform-support.md
index ae514ff38fa0a..2a8e6a8124fd6 100644
--- a/src/doc/rustc/src/platform-support.md
+++ b/src/doc/rustc/src/platform-support.md
@@ -148,7 +148,6 @@ target | std | notes
 `armv7a-none-eabi` | * | Bare ARMv7-A
 `armv7r-none-eabi` | * | Bare ARMv7-R
 `armv7r-none-eabihf` | * | Bare ARMv7-R, hardfloat
-`asmjs-unknown-emscripten` | ✓ | asm.js via Emscripten
 `i586-pc-windows-msvc` | * | 32-bit Windows w/o SSE [^x86_32-floats-x87]
 `i586-unknown-linux-gnu` | ✓ | 32-bit Linux w/o SSE (kernel 3.2, glibc 2.17) [^x86_32-floats-x87]
 `i586-unknown-linux-musl` | ✓ | 32-bit Linux w/o SSE, MUSL [^x86_32-floats-x87]

From e6779d98eef749832c5626c94c3391aa057a941b Mon Sep 17 00:00:00 2001
From: DaniPopes <57450786+DaniPopes@users.noreply.github.com>
Date: Fri, 3 Nov 2023 17:11:39 +0100
Subject: [PATCH 09/34] library: use `copied` instead of manual `map`

---
 library/core/src/array/mod.rs            | 2 +-
 library/core/src/iter/adapters/copied.rs | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/library/core/src/array/mod.rs b/library/core/src/array/mod.rs
index ebd4a8c05fe30..4c48b199f0f27 100644
--- a/library/core/src/array/mod.rs
+++ b/library/core/src/array/mod.rs
@@ -206,7 +206,7 @@ where
 
     #[inline]
     fn try_from(slice: &[T]) -> Result<[T; N], TryFromSliceError> {
-        <&Self>::try_from(slice).map(|r| *r)
+        <&Self>::try_from(slice).copied()
     }
 }
 
diff --git a/library/core/src/iter/adapters/copied.rs b/library/core/src/iter/adapters/copied.rs
index 8f6b2904eae42..7a2c9d839b7e4 100644
--- a/library/core/src/iter/adapters/copied.rs
+++ b/library/core/src/iter/adapters/copied.rs
@@ -193,7 +193,7 @@ where
     T: Copy,
 {
     default fn spec_next_chunk(&mut self) -> Result<[T; N], array::IntoIter<T, N>> {
-        array::iter_next_chunk(&mut self.map(|e| *e))
+        array::iter_next_chunk(&mut self.copied())
     }
 }
 

From 27364309a52fb7bc2df365cb26b4d6227aaa0e15 Mon Sep 17 00:00:00 2001
From: DaniPopes <57450786+DaniPopes@users.noreply.github.com>
Date: Fri, 3 Nov 2023 17:18:19 +0100
Subject: [PATCH 10/34] compiler: use `copied` instead of manual `map`

---
 compiler/rustc_ast_lowering/src/expr.rs               | 3 +--
 compiler/rustc_ast_lowering/src/lib.rs                | 4 ++--
 compiler/rustc_infer/src/infer/error_reporting/mod.rs | 2 +-
 compiler/rustc_lint/src/context.rs                    | 2 +-
 compiler/rustc_middle/src/mir/pretty.rs               | 2 +-
 compiler/rustc_ty_utils/src/assoc.rs                  | 4 ++--
 6 files changed, 8 insertions(+), 9 deletions(-)

diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs
index 93805710cb544..88e44e10a13f7 100644
--- a/compiler/rustc_ast_lowering/src/expr.rs
+++ b/compiler/rustc_ast_lowering/src/expr.rs
@@ -41,8 +41,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
                     }
                     // Merge attributes into the inner expression.
                     if !e.attrs.is_empty() {
-                        let old_attrs =
-                            self.attrs.get(&ex.hir_id.local_id).map(|la| *la).unwrap_or(&[]);
+                        let old_attrs = self.attrs.get(&ex.hir_id.local_id).copied().unwrap_or(&[]);
                         self.attrs.insert(
                             ex.hir_id.local_id,
                             &*self.arena.alloc_from_iter(
diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs
index bc656585d4783..69ccf739af3c7 100644
--- a/compiler/rustc_ast_lowering/src/lib.rs
+++ b/compiler/rustc_ast_lowering/src/lib.rs
@@ -505,7 +505,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
     /// Given the id of some node in the AST, finds the `LocalDefId` associated with it by the name
     /// resolver (if any).
     fn orig_opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
-        self.resolver.node_id_to_def_id.get(&node).map(|local_def_id| *local_def_id)
+        self.resolver.node_id_to_def_id.get(&node).copied()
     }
 
     /// Given the id of some node in the AST, finds the `LocalDefId` associated with it by the name
@@ -548,7 +548,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
         self.generics_def_id_map
             .iter()
             .rev()
-            .find_map(|map| map.get(&local_def_id).map(|local_def_id| *local_def_id))
+            .find_map(|map| map.get(&local_def_id).copied())
             .unwrap_or(local_def_id)
     }
 
diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs
index e4be435fded30..5fd846d0845e8 100644
--- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs
+++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs
@@ -860,7 +860,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
                         self.suggest_boxing_for_return_impl_trait(
                             err,
                             ret_sp,
-                            prior_arms.iter().chain(std::iter::once(&arm_span)).map(|s| *s),
+                            prior_arms.iter().chain(std::iter::once(&arm_span)).copied(),
                         );
                     }
                 }
diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs
index 5b7ba03d9adfc..1df1deca65cf0 100644
--- a/compiler/rustc_lint/src/context.rs
+++ b/compiler/rustc_lint/src/context.rs
@@ -715,7 +715,7 @@ pub trait LintContext: Sized {
                     db.note("see the asm section of Rust By Example <https://doc.rust-lang.org/nightly/rust-by-example/unsafe/asm.html#labels> for more information");
                 },
                 BuiltinLintDiagnostics::UnexpectedCfgName((name, name_span), value) => {
-                    let possibilities: Vec<Symbol> = sess.parse_sess.check_config.expecteds.keys().map(|s| *s).collect();
+                    let possibilities: Vec<Symbol> = sess.parse_sess.check_config.expecteds.keys().copied().collect();
 
                     // Suggest the most probable if we found one
                     if let Some(best_match) = find_best_match_for_name(&possibilities, name, None) {
diff --git a/compiler/rustc_middle/src/mir/pretty.rs b/compiler/rustc_middle/src/mir/pretty.rs
index debd85dad2e02..2136752e63913 100644
--- a/compiler/rustc_middle/src/mir/pretty.rs
+++ b/compiler/rustc_middle/src/mir/pretty.rs
@@ -1337,7 +1337,7 @@ pub fn write_allocations<'tcx>(
     fn alloc_ids_from_alloc(
         alloc: ConstAllocation<'_>,
     ) -> impl DoubleEndedIterator<Item = AllocId> + '_ {
-        alloc.inner().provenance().ptrs().values().map(|id| *id)
+        alloc.inner().provenance().ptrs().values().copied()
     }
 
     fn alloc_ids_from_const_val(val: ConstValue<'_>) -> impl Iterator<Item = AllocId> + '_ {
diff --git a/compiler/rustc_ty_utils/src/assoc.rs b/compiler/rustc_ty_utils/src/assoc.rs
index 3e140793b5a5a..ffeeae668587e 100644
--- a/compiler/rustc_ty_utils/src/assoc.rs
+++ b/compiler/rustc_ty_utils/src/assoc.rs
@@ -43,7 +43,7 @@ fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &[DefId] {
                                     trait_fn_def_id,
                                 )
                             })
-                            .map(|def_id| *def_id),
+                            .copied(),
                     ),
             )
         }
@@ -69,7 +69,7 @@ fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &[DefId] {
                                     impl_fn_def_id,
                                 )
                             })
-                            .map(|def_id| *def_id)
+                            .copied()
                     })),
             )
         }

From b7a98e359596f2d572e7f4735627e16d11e3031e Mon Sep 17 00:00:00 2001
From: David Carlier <devnexen@gmail.com>
Date: Sun, 12 Nov 2023 21:08:47 +0000
Subject: [PATCH 11/34] freebsd adding getentropy interception support

---
 src/tools/miri/ci.sh                            |  2 +-
 .../src/shims/unix/freebsd/foreign_items.rs     | 17 +++++++++++++++++
 .../tests/pass-dep/shims/libc-getentropy.rs     | 11 +++++++++++
 3 files changed, 29 insertions(+), 1 deletion(-)
 create mode 100644 src/tools/miri/tests/pass-dep/shims/libc-getentropy.rs

diff --git a/src/tools/miri/ci.sh b/src/tools/miri/ci.sh
index f0917556c64f8..ff45dc6a42aad 100755
--- a/src/tools/miri/ci.sh
+++ b/src/tools/miri/ci.sh
@@ -108,7 +108,7 @@ case $HOST_TARGET in
     MIRI_TEST_TARGET=aarch64-unknown-linux-gnu run_tests
     MIRI_TEST_TARGET=aarch64-apple-darwin run_tests
     MIRI_TEST_TARGET=i686-pc-windows-gnu run_tests
-    MIRI_TEST_TARGET=x86_64-unknown-freebsd run_tests_minimal hello integer vec panic/panic concurrency/simple pthreads atomic env/var
+    MIRI_TEST_TARGET=x86_64-unknown-freebsd run_tests_minimal hello integer vec panic/panic concurrency/simple pthreads libc-getentropy atomic env/var
     MIRI_TEST_TARGET=aarch64-linux-android run_tests_minimal hello integer vec panic/panic
     MIRI_TEST_TARGET=wasm32-wasi run_tests_minimal no_std integer strings wasm
     MIRI_TEST_TARGET=wasm32-unknown-unknown run_tests_minimal no_std integer strings wasm
diff --git a/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs b/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs
index 96e322c4cf536..f81710a41a6f9 100644
--- a/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs
+++ b/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs
@@ -47,6 +47,23 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
                     this.read_scalar(len)?,
                 )?;
             }
+            "getentropy" => {
+                let [buf, bufsize] =
+                    this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
+                let buf = this.read_pointer(buf)?;
+                let bufsize = this.read_target_usize(bufsize)?;
+
+                // getentropy sets errno to EIO when the buffer size exceeds 256 bytes.
+                // https://man.freebsd.org/cgi/man.cgi?query=getentropy&sektion=3&format=html
+                if bufsize > 256 {
+                    let err = this.eval_libc("EIO");
+                    this.set_last_error(err)?;
+                    this.write_scalar(Scalar::from_i32(-1), dest)?
+                } else {
+                    this.gen_random(buf, bufsize)?;
+                    this.write_scalar(Scalar::from_i32(0), dest)?;
+                }
+            }
 
             // errno
             "__error" => {
diff --git a/src/tools/miri/tests/pass-dep/shims/libc-getentropy.rs b/src/tools/miri/tests/pass-dep/shims/libc-getentropy.rs
new file mode 100644
index 0000000000000..468727f70e0d1
--- /dev/null
+++ b/src/tools/miri/tests/pass-dep/shims/libc-getentropy.rs
@@ -0,0 +1,11 @@
+//@only-target-freebsd
+
+fn main() {
+    let mut buf1 = [0u8; 256];
+    let mut buf2 = [0u8; 257];
+    unsafe {
+        assert_eq!(libc::getentropy(buf1.as_mut_ptr() as *mut libc::c_void, buf1.len()), 0);
+        assert_eq!(libc::getentropy(buf2.as_mut_ptr() as *mut libc::c_void, buf2.len()), -1);
+        assert_eq!(std::io::Error::last_os_error().raw_os_error().unwrap(), libc::EIO);
+    }
+}

From 6e907fa6ec15bd51ff4de34e4e36edd655abfc26 Mon Sep 17 00:00:00 2001
From: Ralf Jung <post@ralfj.de>
Date: Mon, 13 Nov 2023 08:40:40 +0100
Subject: [PATCH 12/34] organize pass-dep tests more by the crate they test

---
 src/tools/miri/test_dependencies/Cargo.toml          |  4 ++--
 src/tools/miri/tests/pass-dep/getrandom.rs           |  9 +++++++++
 src/tools/miri/tests/pass-dep/getrandom_1.rs         |  8 --------
 src/tools/miri/tests/pass-dep/{random.rs => rand.rs} | 11 +++++++----
 4 files changed, 18 insertions(+), 14 deletions(-)
 create mode 100644 src/tools/miri/tests/pass-dep/getrandom.rs
 delete mode 100644 src/tools/miri/tests/pass-dep/getrandom_1.rs
 rename src/tools/miri/tests/pass-dep/{random.rs => rand.rs} (61%)

diff --git a/src/tools/miri/test_dependencies/Cargo.toml b/src/tools/miri/test_dependencies/Cargo.toml
index 670f5c895cbd6..d54560608dc1e 100644
--- a/src/tools/miri/test_dependencies/Cargo.toml
+++ b/src/tools/miri/test_dependencies/Cargo.toml
@@ -12,8 +12,8 @@ edition = "2021"
 libc = "0.2"
 num_cpus = "1.10.1"
 
-getrandom_1 = { package = "getrandom", version = "0.1" }
-getrandom = { version = "0.2", features = ["js"] }
+getrandom_01 = { package = "getrandom", version = "0.1" }
+getrandom_02 = { package = "getrandom", version = "0.2", features = ["js"] }
 rand = { version = "0.8", features = ["small_rng"] }
 
 [target.'cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))'.dependencies]
diff --git a/src/tools/miri/tests/pass-dep/getrandom.rs b/src/tools/miri/tests/pass-dep/getrandom.rs
new file mode 100644
index 0000000000000..60d6dd31e7999
--- /dev/null
+++ b/src/tools/miri/tests/pass-dep/getrandom.rs
@@ -0,0 +1,9 @@
+// mac-os `getrandom_01` does some pointer shenanigans
+//@compile-flags: -Zmiri-permissive-provenance
+
+/// Test direct calls of getrandom 0.1 and 0.2
+fn main() {
+    let mut data = vec![0; 16];
+    getrandom_01::getrandom(&mut data).unwrap();
+    getrandom_02::getrandom(&mut data).unwrap();
+}
diff --git a/src/tools/miri/tests/pass-dep/getrandom_1.rs b/src/tools/miri/tests/pass-dep/getrandom_1.rs
deleted file mode 100644
index 2c7bd93fbdb38..0000000000000
--- a/src/tools/miri/tests/pass-dep/getrandom_1.rs
+++ /dev/null
@@ -1,8 +0,0 @@
-// mac-os `getrandom_1` does some pointer shenanigans
-//@compile-flags: -Zmiri-permissive-provenance
-
-/// Test old version of `getrandom`.
-fn main() {
-    let mut data = vec![0; 16];
-    getrandom_1::getrandom(&mut data).unwrap();
-}
diff --git a/src/tools/miri/tests/pass-dep/random.rs b/src/tools/miri/tests/pass-dep/rand.rs
similarity index 61%
rename from src/tools/miri/tests/pass-dep/random.rs
rename to src/tools/miri/tests/pass-dep/rand.rs
index 0cd8b06d63d8a..0dce6d86cf481 100644
--- a/src/tools/miri/tests/pass-dep/random.rs
+++ b/src/tools/miri/tests/pass-dep/rand.rs
@@ -1,10 +1,13 @@
 //@compile-flags: -Zmiri-strict-provenance
-use rand::{rngs::SmallRng, Rng, SeedableRng};
+use rand::prelude::*;
 
+// Test using the `rand` crate to generate randomness.
 fn main() {
-    // Test `getrandom` directly.
-    let mut data = vec![0; 16];
-    getrandom::getrandom(&mut data).unwrap();
+    // Fully deterministic seeding.
+    let mut rng = SmallRng::seed_from_u64(42);
+    let _val = rng.gen::<i32>();
+    let _val = rng.gen::<isize>();
+    let _val = rng.gen::<i128>();
 
     // Try seeding with "real" entropy.
     let mut rng = SmallRng::from_entropy();

From edb4c0aece550d652503f440388a45ea99fe0f94 Mon Sep 17 00:00:00 2001
From: Ralf Jung <post@ralfj.de>
Date: Mon, 13 Nov 2023 18:30:39 +0100
Subject: [PATCH 13/34] share getentropy shim across various unixes

---
 .../miri/src/shims/unix/foreign_items.rs      | 33 ++++++++++++++++++-
 .../src/shims/unix/freebsd/foreign_items.rs   | 17 ----------
 .../src/shims/unix/macos/foreign_items.rs     | 16 ++-------
 src/tools/miri/tests/pass-dep/getrandom.rs    |  3 +-
 .../tests/pass-dep/shims/libc-getentropy.rs   | 15 +++++++--
 5 files changed, 48 insertions(+), 36 deletions(-)

diff --git a/src/tools/miri/src/shims/unix/foreign_items.rs b/src/tools/miri/src/shims/unix/foreign_items.rs
index c013d27502927..f993afa67ad83 100644
--- a/src/tools/miri/src/shims/unix/foreign_items.rs
+++ b/src/tools/miri/src/shims/unix/foreign_items.rs
@@ -27,6 +27,8 @@ fn is_dyn_sym(name: &str, target_os: &str) -> bool {
         // `signal` is set up as a weak symbol in `init_extern_statics` (on Android) so we might as
         // well allow it in `dlsym`.
         "signal" => true,
+        // needed at least on macOS to avoid file-based fallback in getrandom
+        "getentropy" => true,
         // Give specific OSes a chance to allow their symbols.
         _ =>
             match target_os {
@@ -525,6 +527,34 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
                 let result = this.getpid()?;
                 this.write_scalar(Scalar::from_i32(result), dest)?;
             }
+            "getentropy" => {
+                // This function is non-standard but exists with the same signature and behavior on
+                // Linux, macOS, and FreeBSD.
+                if !matches!(&*this.tcx.sess.target.os, "linux" | "macos" | "freebsd") {
+                    throw_unsup_format!(
+                        "`getentropy` is not supported on {}",
+                        this.tcx.sess.target.os
+                    );
+                }
+
+                let [buf, bufsize] =
+                    this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
+                let buf = this.read_pointer(buf)?;
+                let bufsize = this.read_target_usize(bufsize)?;
+
+                // getentropy sets errno to EIO when the buffer size exceeds 256 bytes.
+                // FreeBSD: https://man.freebsd.org/cgi/man.cgi?query=getentropy&sektion=3&format=html
+                // Linux: https://man7.org/linux/man-pages/man3/getentropy.3.html
+                // macOS: https://keith.github.io/xcode-man-pages/getentropy.2.html
+                if bufsize > 256 {
+                    let err = this.eval_libc("EIO");
+                    this.set_last_error(err)?;
+                    this.write_scalar(Scalar::from_i32(-1), dest)?
+                } else {
+                    this.gen_random(buf, bufsize)?;
+                    this.write_scalar(Scalar::from_i32(0), dest)?;
+                }
+            }
 
             // Incomplete shims that we "stub out" just to get pre-main initialization code to work.
             // These shims are enabled only when the caller is in the standard library.
@@ -594,7 +624,8 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
                 this.write_int(super::UID, dest)?;
             }
 
-            "getpwuid_r" if this.frame_in_std() => {
+            "getpwuid_r"
+            if this.frame_in_std() => {
                 let [uid, pwd, buf, buflen, result] =
                     this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
                 this.check_no_isolation("`getpwuid_r`")?;
diff --git a/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs b/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs
index f81710a41a6f9..96e322c4cf536 100644
--- a/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs
+++ b/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs
@@ -47,23 +47,6 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
                     this.read_scalar(len)?,
                 )?;
             }
-            "getentropy" => {
-                let [buf, bufsize] =
-                    this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
-                let buf = this.read_pointer(buf)?;
-                let bufsize = this.read_target_usize(bufsize)?;
-
-                // getentropy sets errno to EIO when the buffer size exceeds 256 bytes.
-                // https://man.freebsd.org/cgi/man.cgi?query=getentropy&sektion=3&format=html
-                if bufsize > 256 {
-                    let err = this.eval_libc("EIO");
-                    this.set_last_error(err)?;
-                    this.write_scalar(Scalar::from_i32(-1), dest)?
-                } else {
-                    this.gen_random(buf, bufsize)?;
-                    this.write_scalar(Scalar::from_i32(0), dest)?;
-                }
-            }
 
             // errno
             "__error" => {
diff --git a/src/tools/miri/src/shims/unix/macos/foreign_items.rs b/src/tools/miri/src/shims/unix/macos/foreign_items.rs
index 5881a3f46f295..e8f35e7ba5786 100644
--- a/src/tools/miri/src/shims/unix/macos/foreign_items.rs
+++ b/src/tools/miri/src/shims/unix/macos/foreign_items.rs
@@ -6,8 +6,8 @@ use shims::foreign_items::EmulateForeignItemResult;
 use shims::unix::fs::EvalContextExt as _;
 use shims::unix::thread::EvalContextExt as _;
 
-pub fn is_dyn_sym(name: &str) -> bool {
-    matches!(name, "getentropy")
+pub fn is_dyn_sym(_name: &str) -> bool {
+    false
 }
 
 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {}
@@ -113,18 +113,6 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
                 this.write_scalar(result, dest)?;
             }
 
-            // Random generation related shims
-            "getentropy" => {
-                let [buf, bufsize] =
-                    this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
-                let buf = this.read_pointer(buf)?;
-                let bufsize = this.read_target_usize(bufsize)?;
-
-                this.gen_random(buf, bufsize)?;
-
-                this.write_scalar(Scalar::from_i32(0), dest)?; // KERN_SUCCESS
-            }
-
             // Access to command-line arguments
             "_NSGetArgc" => {
                 let [] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
diff --git a/src/tools/miri/tests/pass-dep/getrandom.rs b/src/tools/miri/tests/pass-dep/getrandom.rs
index 60d6dd31e7999..c0d9296a9a6d9 100644
--- a/src/tools/miri/tests/pass-dep/getrandom.rs
+++ b/src/tools/miri/tests/pass-dep/getrandom.rs
@@ -1,7 +1,8 @@
 // mac-os `getrandom_01` does some pointer shenanigans
 //@compile-flags: -Zmiri-permissive-provenance
 
-/// Test direct calls of getrandom 0.1 and 0.2
+/// Test direct calls of getrandom 0.1 and 0.2.
+/// Make sure they work even with isolation enabled (i.e., we do not hit a file-based fallback path).
 fn main() {
     let mut data = vec![0; 16];
     getrandom_01::getrandom(&mut data).unwrap();
diff --git a/src/tools/miri/tests/pass-dep/shims/libc-getentropy.rs b/src/tools/miri/tests/pass-dep/shims/libc-getentropy.rs
index 468727f70e0d1..4b863f6851618 100644
--- a/src/tools/miri/tests/pass-dep/shims/libc-getentropy.rs
+++ b/src/tools/miri/tests/pass-dep/shims/libc-getentropy.rs
@@ -1,11 +1,20 @@
-//@only-target-freebsd
+//@ignore-target-windows: no libc
+
+// on macOS this is not in the `libc` crate.
+#[cfg(target_os = "macos")]
+extern "C" {
+    fn getentropy(bytes: *mut libc::c_void, count: libc::size_t) -> libc::c_int;
+}
+
+#[cfg(not(target_os = "macos"))]
+use libc::getentropy;
 
 fn main() {
     let mut buf1 = [0u8; 256];
     let mut buf2 = [0u8; 257];
     unsafe {
-        assert_eq!(libc::getentropy(buf1.as_mut_ptr() as *mut libc::c_void, buf1.len()), 0);
-        assert_eq!(libc::getentropy(buf2.as_mut_ptr() as *mut libc::c_void, buf2.len()), -1);
+        assert_eq!(getentropy(buf1.as_mut_ptr() as *mut libc::c_void, buf1.len()), 0);
+        assert_eq!(getentropy(buf2.as_mut_ptr() as *mut libc::c_void, buf2.len()), -1);
         assert_eq!(std::io::Error::last_os_error().raw_os_error().unwrap(), libc::EIO);
     }
 }

From 9840525ccf9bc730e8ed4c278fa747b419d1a1fc Mon Sep 17 00:00:00 2001
From: Ralf Jung <post@ralfj.de>
Date: Mon, 13 Nov 2023 20:39:17 +0100
Subject: [PATCH 14/34] don't expose all the borrow tracker stuff to the entire
 crate

---
 src/tools/miri/src/borrow_tracker/mod.rs | 58 ++++++++++++++++++------
 src/tools/miri/src/machine.rs            | 30 +-----------
 2 files changed, 47 insertions(+), 41 deletions(-)

diff --git a/src/tools/miri/src/borrow_tracker/mod.rs b/src/tools/miri/src/borrow_tracker/mod.rs
index a95571572d684..f9cc3acbd51bc 100644
--- a/src/tools/miri/src/borrow_tracker/mod.rs
+++ b/src/tools/miri/src/borrow_tracker/mod.rs
@@ -59,7 +59,7 @@ impl fmt::Debug for BorTag {
 #[derive(Debug)]
 pub struct FrameState {
     /// The ID of the call this frame corresponds to.
-    pub call_id: CallId,
+    call_id: CallId,
 
     /// If this frame is protecting any tags, they are listed here. We use this list to do
     /// incremental updates of the global list of protected tags stored in the
@@ -72,7 +72,7 @@ pub struct FrameState {
     ///
     /// This will contain one tag per reference passed to the function, so
     /// a size of 2 is enough for the vast majority of functions.
-    pub protected_tags: SmallVec<[(AllocId, BorTag); 2]>,
+    protected_tags: SmallVec<[(AllocId, BorTag); 2]>,
 }
 
 impl VisitTags for FrameState {
@@ -85,29 +85,29 @@ impl VisitTags for FrameState {
 #[derive(Debug)]
 pub struct GlobalStateInner {
     /// Borrow tracker method currently in use.
-    pub borrow_tracker_method: BorrowTrackerMethod,
+    borrow_tracker_method: BorrowTrackerMethod,
     /// Next unused pointer ID (tag).
-    pub next_ptr_tag: BorTag,
+    next_ptr_tag: BorTag,
     /// Table storing the "base" tag for each allocation.
     /// The base tag is the one used for the initial pointer.
     /// We need this in a separate table to handle cyclic statics.
-    pub base_ptr_tags: FxHashMap<AllocId, BorTag>,
+    base_ptr_tags: FxHashMap<AllocId, BorTag>,
     /// Next unused call ID (for protectors).
-    pub next_call_id: CallId,
+    next_call_id: CallId,
     /// All currently protected tags.
     /// An item is protected if its tag is in this set, *and* it has the "protected" bit set.
     /// We add tags to this when they are created with a protector in `reborrow`, and
     /// we remove tags from this when the call which is protecting them returns, in
     /// `GlobalStateInner::end_call`. See `Stack::item_popped` for more details.
-    pub protected_tags: FxHashMap<BorTag, ProtectorKind>,
+    protected_tags: FxHashMap<BorTag, ProtectorKind>,
     /// The pointer ids to trace
-    pub tracked_pointer_tags: FxHashSet<BorTag>,
+    tracked_pointer_tags: FxHashSet<BorTag>,
     /// The call ids to trace
-    pub tracked_call_ids: FxHashSet<CallId>,
+    tracked_call_ids: FxHashSet<CallId>,
     /// Whether to recurse into datatypes when searching for pointers to retag.
-    pub retag_fields: RetagFields,
+    retag_fields: RetagFields,
     /// Whether `core::ptr::Unique` gets special (`Box`-like) handling.
-    pub unique_is_unique: bool,
+    unique_is_unique: bool,
 }
 
 impl VisitTags for GlobalStateInner {
@@ -194,7 +194,7 @@ impl GlobalStateInner {
     }
 
     /// Generates a new pointer tag. Remember to also check track_pointer_tags and log its creation!
-    pub fn new_ptr(&mut self) -> BorTag {
+    fn new_ptr(&mut self) -> BorTag {
         let id = self.next_ptr_tag;
         self.next_ptr_tag = id.succ().unwrap();
         id
@@ -210,7 +210,7 @@ impl GlobalStateInner {
         FrameState { call_id, protected_tags: SmallVec::new() }
     }
 
-    pub fn end_call(&mut self, frame: &machine::FrameExtra<'_>) {
+    fn end_call(&mut self, frame: &machine::FrameExtra<'_>) {
         for (_, tag) in &frame
             .borrow_tracker
             .as_ref()
@@ -355,6 +355,38 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
             BorrowTrackerMethod::TreeBorrows => this.print_tree(alloc_id, show_unnamed),
         }
     }
+
+    fn on_stack_pop(
+        &self,
+        frame: &Frame<'mir, 'tcx, Provenance, FrameExtra<'tcx>>,
+    ) -> InterpResult<'tcx> {
+        let this = self.eval_context_ref();
+        let borrow_tracker = this.machine.borrow_tracker.as_ref().unwrap();
+        // The body of this loop needs `borrow_tracker` immutably
+        // so we can't move this code inside the following `end_call`.
+        for (alloc_id, tag) in &frame
+            .extra
+            .borrow_tracker
+            .as_ref()
+            .expect("we should have borrow tracking data")
+            .protected_tags
+        {
+            // Just because the tag is protected doesn't guarantee that
+            // the allocation still exists (weak protectors allow deallocations)
+            // so we must check that the allocation exists.
+            // If it does exist, then we have the guarantee that the
+            // pointer is readable, and the implicit read access inserted
+            // will never cause UB on the pointer itself.
+            let (_, _, kind) = this.get_alloc_info(*alloc_id);
+            if matches!(kind, AllocKind::LiveData) {
+                let alloc_extra = this.get_alloc_extra(*alloc_id).unwrap();
+                let alloc_borrow_tracker = &alloc_extra.borrow_tracker.as_ref().unwrap();
+                alloc_borrow_tracker.release_protector(&this.machine, borrow_tracker, *tag)?;
+            }
+        }
+        borrow_tracker.borrow_mut().end_call(&frame.extra);
+        Ok(())
+    }
 }
 
 /// Extra per-allocation data for borrow tracking
diff --git a/src/tools/miri/src/machine.rs b/src/tools/miri/src/machine.rs
index d5775912eabea..2085df7d06f84 100644
--- a/src/tools/miri/src/machine.rs
+++ b/src/tools/miri/src/machine.rs
@@ -1409,34 +1409,8 @@ impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> {
     ) -> InterpResult<'tcx> {
         // We want this *before* the return value copy, because the return place itself is protected
         // until we do `end_call` here.
-        if let Some(global_borrow_tracker) = &ecx.machine.borrow_tracker {
-            // The body of this loop needs `global_borrow_tracker` immutably
-            // so we can't move this code inside the following `end_call`.
-            for (alloc_id, tag) in &frame
-                .extra
-                .borrow_tracker
-                .as_ref()
-                .expect("we should have borrow tracking data")
-                .protected_tags
-            {
-                // Just because the tag is protected doesn't guarantee that
-                // the allocation still exists (weak protectors allow deallocations)
-                // so we must check that the allocation exists.
-                // If it does exist, then we have the guarantee that the
-                // pointer is readable, and the implicit read access inserted
-                // will never cause UB on the pointer itself.
-                let (_, _, kind) = ecx.get_alloc_info(*alloc_id);
-                if matches!(kind, AllocKind::LiveData) {
-                    let alloc_extra = ecx.get_alloc_extra(*alloc_id).unwrap();
-                    let alloc_borrow_tracker = &alloc_extra.borrow_tracker.as_ref().unwrap();
-                    alloc_borrow_tracker.release_protector(
-                        &ecx.machine,
-                        global_borrow_tracker,
-                        *tag,
-                    )?;
-                }
-            }
-            global_borrow_tracker.borrow_mut().end_call(&frame.extra);
+        if ecx.machine.borrow_tracker.is_some() {
+            ecx.on_stack_pop(frame)?;
         }
         Ok(())
     }

From 39e142ffd53c81cabfb170c15d9c35b980f7ffd0 Mon Sep 17 00:00:00 2001
From: The Miri Conjob Bot <miri@cron.bot>
Date: Wed, 15 Nov 2023 05:05:53 +0000
Subject: [PATCH 15/34] Preparing for merge from rustc

---
 src/tools/miri/rust-version | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/tools/miri/rust-version b/src/tools/miri/rust-version
index 2beb3bfef9e5f..0d677d36e3627 100644
--- a/src/tools/miri/rust-version
+++ b/src/tools/miri/rust-version
@@ -1 +1 @@
-3aaa0f57b7b877ef58532a8de075d1e5a79142bf
+6d069a0ac7a423db87d86320edd39974f9f0c492

From c3fd57d1852b79ed407bc067742c57a681e4b23e Mon Sep 17 00:00:00 2001
From: David Carlier <devnexen@gmail.com>
Date: Mon, 13 Nov 2023 22:18:47 +0000
Subject: [PATCH 16/34] freebsd adding getrandom interception.

note that os support was added in same time as getentropy.
---
 src/tools/miri/ci.sh                              |  2 +-
 .../miri/src/shims/unix/freebsd/foreign_items.rs  | 15 +++++++++++++++
 .../miri/tests/pass-dep/shims/libc-getrandom.rs   |  5 ++++-
 3 files changed, 20 insertions(+), 2 deletions(-)

diff --git a/src/tools/miri/ci.sh b/src/tools/miri/ci.sh
index ff45dc6a42aad..5c6351d019284 100755
--- a/src/tools/miri/ci.sh
+++ b/src/tools/miri/ci.sh
@@ -108,7 +108,7 @@ case $HOST_TARGET in
     MIRI_TEST_TARGET=aarch64-unknown-linux-gnu run_tests
     MIRI_TEST_TARGET=aarch64-apple-darwin run_tests
     MIRI_TEST_TARGET=i686-pc-windows-gnu run_tests
-    MIRI_TEST_TARGET=x86_64-unknown-freebsd run_tests_minimal hello integer vec panic/panic concurrency/simple pthreads libc-getentropy atomic env/var
+    MIRI_TEST_TARGET=x86_64-unknown-freebsd run_tests_minimal hello integer vec panic/panic concurrency/simple pthreads libc-getentropy libc-getrandom atomic env/var
     MIRI_TEST_TARGET=aarch64-linux-android run_tests_minimal hello integer vec panic/panic
     MIRI_TEST_TARGET=wasm32-wasi run_tests_minimal no_std integer strings wasm
     MIRI_TEST_TARGET=wasm32-unknown-unknown run_tests_minimal no_std integer strings wasm
diff --git a/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs b/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs
index 96e322c4cf536..7c843e106eacf 100644
--- a/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs
+++ b/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs
@@ -47,6 +47,21 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
                     this.read_scalar(len)?,
                 )?;
             }
+            "getrandom" => {
+                let [ptr, len, flags] =
+                    this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
+                let ptr = this.read_pointer(ptr)?;
+                let len = this.read_target_usize(len)?;
+                let _flags = this.read_scalar(flags)?.to_i32()?;
+                // flags on freebsd does not really matter
+                // in practice, GRND_RANDOM does not particularly draw from /dev/random
+                // since it is the same as to /dev/urandom.
+                // GRND_INSECURE is only an alias of GRND_NONBLOCK, which
+                // does not affect the RNG.
+                // https://man.freebsd.org/cgi/man.cgi?query=getrandom&sektion=2&n=1
+                this.gen_random(ptr, len)?;
+                this.write_scalar(Scalar::from_target_usize(len, this), dest)?;
+            }
 
             // errno
             "__error" => {
diff --git a/src/tools/miri/tests/pass-dep/shims/libc-getrandom.rs b/src/tools/miri/tests/pass-dep/shims/libc-getrandom.rs
index a1436c7319d33..9c670cbd5070e 100644
--- a/src/tools/miri/tests/pass-dep/shims/libc-getrandom.rs
+++ b/src/tools/miri/tests/pass-dep/shims/libc-getrandom.rs
@@ -1,10 +1,12 @@
-//@only-target-linux
+//@ignore-target-windows: no libc
+//@ignore-target-apple: no getrandom
 
 use std::ptr;
 
 fn main() {
     let mut buf = [0u8; 5];
     unsafe {
+        #[cfg(target_os = "linux")]
         assert_eq!(
             libc::syscall(
                 libc::SYS_getrandom,
@@ -14,6 +16,7 @@ fn main() {
             ),
             0,
         );
+        #[cfg(target_os = "linux")]
         assert_eq!(
             libc::syscall(
                 libc::SYS_getrandom,

From 890ce26213c1cdc12ae269a91a62e3502a3165cc Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Esteban=20K=C3=BCber?= <esteban@kuber.com.ar>
Date: Thu, 16 Nov 2023 06:07:33 +0000
Subject: [PATCH 17/34] When using existing fn as module, don't claim it
 doesn't exist

Tweak wording of module not found in resolve, when the name exists but
belongs to a non-`mod` item.

Fix #81232.
---
 compiler/rustc_resolve/src/diagnostics.rs        | 14 +++++++++++++-
 tests/ui/suggestions/crate-or-module-typo.rs     |  2 +-
 tests/ui/suggestions/crate-or-module-typo.stderr |  4 ++--
 3 files changed, 16 insertions(+), 4 deletions(-)

diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs
index 93db6cfc4635d..28e6fe9b4b739 100644
--- a/compiler/rustc_resolve/src/diagnostics.rs
+++ b/compiler/rustc_resolve/src/diagnostics.rs
@@ -2028,7 +2028,19 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
                     },
                 )
             });
-            (format!("use of undeclared crate or module `{ident}`"), suggestion)
+            if let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
+                ident,
+                ScopeSet::All(ValueNS),
+                parent_scope,
+                None,
+                false,
+                ignore_binding,
+            ) {
+                let descr = binding.res().descr();
+                (format!("{descr} `{ident}` is not a crate or module"), suggestion)
+            } else {
+                (format!("use of undeclared crate or module `{ident}`"), suggestion)
+            }
         }
     }
 
diff --git a/tests/ui/suggestions/crate-or-module-typo.rs b/tests/ui/suggestions/crate-or-module-typo.rs
index 2471b11c61efd..b12ad495e9fd5 100644
--- a/tests/ui/suggestions/crate-or-module-typo.rs
+++ b/tests/ui/suggestions/crate-or-module-typo.rs
@@ -3,7 +3,7 @@
 use st::cell::Cell; //~ ERROR failed to resolve: use of undeclared crate or module `st`
 
 mod bar {
-    pub fn bar() { bar::baz(); } //~ ERROR failed to resolve: use of undeclared crate or module `bar`
+    pub fn bar() { bar::baz(); } //~ ERROR failed to resolve: function `bar` is not a crate or module
 
     fn baz() {}
 }
diff --git a/tests/ui/suggestions/crate-or-module-typo.stderr b/tests/ui/suggestions/crate-or-module-typo.stderr
index 9ece31e76f005..457d779064682 100644
--- a/tests/ui/suggestions/crate-or-module-typo.stderr
+++ b/tests/ui/suggestions/crate-or-module-typo.stderr
@@ -42,11 +42,11 @@ LL -     bar: st::cell::Cell<bool>
 LL +     bar: cell::Cell<bool>
    |
 
-error[E0433]: failed to resolve: use of undeclared crate or module `bar`
+error[E0433]: failed to resolve: function `bar` is not a crate or module
   --> $DIR/crate-or-module-typo.rs:6:20
    |
 LL |     pub fn bar() { bar::baz(); }
-   |                    ^^^ use of undeclared crate or module `bar`
+   |                    ^^^ function `bar` is not a crate or module
 
 error: aborting due to 4 previous errors
 

From 9c8c2d13b8e76187a33bf3e78c6233f159d5e579 Mon Sep 17 00:00:00 2001
From: Ralf Jung <post@ralfj.de>
Date: Thu, 16 Nov 2023 10:26:19 +0100
Subject: [PATCH 18/34] Preparing for merge from rustc

---
 src/tools/miri/rust-version | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/tools/miri/rust-version b/src/tools/miri/rust-version
index 0d677d36e3627..673e11163c85e 100644
--- a/src/tools/miri/rust-version
+++ b/src/tools/miri/rust-version
@@ -1 +1 @@
-6d069a0ac7a423db87d86320edd39974f9f0c492
+525c91d096194decbfa70245743d697fb010ac91

From ca67d7fa6aa36492c03225a411bf48b3c2a53afb Mon Sep 17 00:00:00 2001
From: Ralf Jung <post@ralfj.de>
Date: Thu, 16 Nov 2023 10:43:27 +0100
Subject: [PATCH 19/34] get rid of our last uses of set_var

---
 src/tools/miri/tests/compiletest.rs | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/src/tools/miri/tests/compiletest.rs b/src/tools/miri/tests/compiletest.rs
index dbf559631eacb..91df4985c0f0c 100644
--- a/src/tools/miri/tests/compiletest.rs
+++ b/src/tools/miri/tests/compiletest.rs
@@ -79,6 +79,11 @@ fn test_config(target: &str, path: &str, mode: Mode, with_dependencies: bool) ->
         program.args.push(flag);
     }
 
+    // Add a test env var to do environment communication tests.
+    program.envs.push(("MIRI_ENV_VAR_TEST".into(), Some("0".into())));
+    // Let the tests know where to store temp files (they might run for a different target, which can make this hard to find).
+    program.envs.push(("MIRI_TEMP".into(), Some(env::temp_dir().into())));
+
     let mut config = Config {
         target: Some(target.to_owned()),
         stderr_filters: STDERR.clone(),
@@ -232,11 +237,6 @@ fn main() -> Result<()> {
         }
     }
 
-    // Add a test env var to do environment communication tests.
-    env::set_var("MIRI_ENV_VAR_TEST", "0");
-    // Let the tests know where to store temp files (they might run for a different target, which can make this hard to find).
-    env::set_var("MIRI_TEMP", env::temp_dir());
-
     ui(Mode::Pass, "tests/pass", &target, WithoutDependencies)?;
     ui(Mode::Pass, "tests/pass-dep", &target, WithDependencies)?;
     ui(Mode::Panic, "tests/panic", &target, WithDependencies)?;

From c6acc058c0cb260b75cacdbe72e653770815f7d6 Mon Sep 17 00:00:00 2001
From: David Carlier <devnexen@gmail.com>
Date: Wed, 15 Nov 2023 22:46:40 +0000
Subject: [PATCH 20/34] reallocarray shim linux/freebsd support proposal.

---
 src/tools/miri/ci.sh                          |  2 +-
 .../miri/src/shims/unix/foreign_items.rs      | 31 +++++++++++++++++++
 .../tests/pass-dep/shims/libc-reallocarray.rs | 16 ++++++++++
 3 files changed, 48 insertions(+), 1 deletion(-)
 create mode 100644 src/tools/miri/tests/pass-dep/shims/libc-reallocarray.rs

diff --git a/src/tools/miri/ci.sh b/src/tools/miri/ci.sh
index 5c6351d019284..dd57319a54c2b 100755
--- a/src/tools/miri/ci.sh
+++ b/src/tools/miri/ci.sh
@@ -108,7 +108,7 @@ case $HOST_TARGET in
     MIRI_TEST_TARGET=aarch64-unknown-linux-gnu run_tests
     MIRI_TEST_TARGET=aarch64-apple-darwin run_tests
     MIRI_TEST_TARGET=i686-pc-windows-gnu run_tests
-    MIRI_TEST_TARGET=x86_64-unknown-freebsd run_tests_minimal hello integer vec panic/panic concurrency/simple pthreads libc-getentropy libc-getrandom atomic env/var
+    MIRI_TEST_TARGET=x86_64-unknown-freebsd run_tests_minimal hello integer vec panic/panic concurrency/simple pthreads libc-getentropy libc-getrandom libc-reallocarray atomic env/var
     MIRI_TEST_TARGET=aarch64-linux-android run_tests_minimal hello integer vec panic/panic
     MIRI_TEST_TARGET=wasm32-wasi run_tests_minimal no_std integer strings wasm
     MIRI_TEST_TARGET=wasm32-unknown-unknown run_tests_minimal no_std integer strings wasm
diff --git a/src/tools/miri/src/shims/unix/foreign_items.rs b/src/tools/miri/src/shims/unix/foreign_items.rs
index f993afa67ad83..d155623eb7b68 100644
--- a/src/tools/miri/src/shims/unix/foreign_items.rs
+++ b/src/tools/miri/src/shims/unix/foreign_items.rs
@@ -252,6 +252,37 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
                 this.write_scalar(result, dest)?;
             }
 
+            "reallocarray" => {
+                // Currently this function does not exist on all Unixes, e.g. on macOS.
+                if !matches!(&*this.tcx.sess.target.os, "linux" | "freebsd") {
+                    throw_unsup_format!(
+                        "`reallocarray` is not supported on {}",
+                        this.tcx.sess.target.os
+                    );
+                }
+                let [ptr, nmemb, size] =
+                    this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
+                let ptr = this.read_pointer(ptr)?;
+                let nmemb = this.read_target_usize(nmemb)?;
+                let size = this.read_target_usize(size)?;
+                // reallocarray checks a possible overflow and returns ENOMEM
+                // if that happens.
+                //
+                // Linux: https://www.unix.com/man-page/linux/3/reallocarray/
+                // FreeBSD: https://man.freebsd.org/cgi/man.cgi?query=reallocarray
+                match nmemb.checked_mul(size) {
+                    None => {
+                        let einval = this.eval_libc("ENOMEM");
+                        this.set_last_error(einval)?;
+                        this.write_null(dest)?;
+                    }
+                    Some(len) => {
+                        let res = this.realloc(ptr, len, MiriMemoryKind::C)?;
+                        this.write_pointer(res, dest)?;
+                    }
+                }
+            }
+
             // Dynamic symbol loading
             "dlsym" => {
                 let [handle, symbol] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
diff --git a/src/tools/miri/tests/pass-dep/shims/libc-reallocarray.rs b/src/tools/miri/tests/pass-dep/shims/libc-reallocarray.rs
new file mode 100644
index 0000000000000..29a3a5908526c
--- /dev/null
+++ b/src/tools/miri/tests/pass-dep/shims/libc-reallocarray.rs
@@ -0,0 +1,16 @@
+//@ignore-target-windows: no libc
+//@ignore-target-apple: no support (yet)
+
+use core::ptr;
+
+fn main() {
+    unsafe {
+        let mut p = libc::reallocarray(ptr::null_mut(), 4096, 2);
+        assert!(!p.is_null());
+        libc::free(p);
+        p = libc::malloc(16);
+        let r = libc::reallocarray(p, 2, 32);
+        assert!(!r.is_null());
+        libc::free(r);
+    }
+}

From 7338c55052edd113a1933228167ffcda7ed3bb1b Mon Sep 17 00:00:00 2001
From: Ralf Jung <post@ralfj.de>
Date: Thu, 16 Nov 2023 19:30:12 +0100
Subject: [PATCH 21/34] split thread test into synchronization primitives and
 threadname

---
 src/tools/miri/ci.sh                          |  2 +-
 .../shims/{pthreads.rs => pthread-sync.rs}    | 60 -------------------
 .../pass-dep/shims/pthread-threadname.rs      | 51 ++++++++++++++++
 3 files changed, 52 insertions(+), 61 deletions(-)
 rename src/tools/miri/tests/pass-dep/shims/{pthreads.rs => pthread-sync.rs} (71%)
 create mode 100644 src/tools/miri/tests/pass-dep/shims/pthread-threadname.rs

diff --git a/src/tools/miri/ci.sh b/src/tools/miri/ci.sh
index dd57319a54c2b..5f55f1af73f51 100755
--- a/src/tools/miri/ci.sh
+++ b/src/tools/miri/ci.sh
@@ -108,7 +108,7 @@ case $HOST_TARGET in
     MIRI_TEST_TARGET=aarch64-unknown-linux-gnu run_tests
     MIRI_TEST_TARGET=aarch64-apple-darwin run_tests
     MIRI_TEST_TARGET=i686-pc-windows-gnu run_tests
-    MIRI_TEST_TARGET=x86_64-unknown-freebsd run_tests_minimal hello integer vec panic/panic concurrency/simple pthreads libc-getentropy libc-getrandom libc-reallocarray atomic env/var
+    MIRI_TEST_TARGET=x86_64-unknown-freebsd run_tests_minimal hello integer vec panic/panic concurrency/simple pthreads-threadname libc-getentropy libc-getrandom libc-reallocarray atomic env/var
     MIRI_TEST_TARGET=aarch64-linux-android run_tests_minimal hello integer vec panic/panic
     MIRI_TEST_TARGET=wasm32-wasi run_tests_minimal no_std integer strings wasm
     MIRI_TEST_TARGET=wasm32-unknown-unknown run_tests_minimal no_std integer strings wasm
diff --git a/src/tools/miri/tests/pass-dep/shims/pthreads.rs b/src/tools/miri/tests/pass-dep/shims/pthread-sync.rs
similarity index 71%
rename from src/tools/miri/tests/pass-dep/shims/pthreads.rs
rename to src/tools/miri/tests/pass-dep/shims/pthread-sync.rs
index 3bb6f83ec2af9..4cc5b7d68a3cc 100644
--- a/src/tools/miri/tests/pass-dep/shims/pthreads.rs
+++ b/src/tools/miri/tests/pass-dep/shims/pthread-sync.rs
@@ -1,26 +1,15 @@
 //@ignore-target-windows: No libc on Windows
-use std::ffi::CStr;
-#[cfg(not(target_os = "freebsd"))]
-use std::ffi::CString;
-use std::thread;
 
 fn main() {
-    test_named_thread_truncation();
-
-    #[cfg(not(target_os = "freebsd"))]
     test_mutex_libc_init_recursive();
-    #[cfg(not(target_os = "freebsd"))]
     test_mutex_libc_init_normal();
-    #[cfg(not(target_os = "freebsd"))]
     test_mutex_libc_init_errorcheck();
-    #[cfg(not(target_os = "freebsd"))]
     test_rwlock_libc_static_initializer();
 
     #[cfg(target_os = "linux")]
     test_mutex_libc_static_initializer_recursive();
 }
 
-#[cfg(not(target_os = "freebsd"))]
 fn test_mutex_libc_init_recursive() {
     unsafe {
         let mut attr: libc::pthread_mutexattr_t = std::mem::zeroed();
@@ -45,7 +34,6 @@ fn test_mutex_libc_init_recursive() {
     }
 }
 
-#[cfg(not(target_os = "freebsd"))]
 fn test_mutex_libc_init_normal() {
     unsafe {
         let mut mutexattr: libc::pthread_mutexattr_t = std::mem::zeroed();
@@ -68,7 +56,6 @@ fn test_mutex_libc_init_normal() {
     }
 }
 
-#[cfg(not(target_os = "freebsd"))]
 fn test_mutex_libc_init_errorcheck() {
     unsafe {
         let mut mutexattr: libc::pthread_mutexattr_t = std::mem::zeroed();
@@ -114,7 +101,6 @@ fn test_mutex_libc_static_initializer_recursive() {
 // Testing the behavior of std::sync::RwLock does not fully exercise the pthread rwlock shims, we
 // need to go a layer deeper and test the behavior of the libc functions, because
 // std::sys::unix::rwlock::RWLock itself keeps track of write_locked and num_readers.
-#[cfg(not(target_os = "freebsd"))]
 fn test_rwlock_libc_static_initializer() {
     let rw = std::cell::UnsafeCell::new(libc::PTHREAD_RWLOCK_INITIALIZER);
     unsafe {
@@ -139,49 +125,3 @@ fn test_rwlock_libc_static_initializer() {
         assert_eq!(libc::pthread_rwlock_destroy(rw.get()), 0);
     }
 }
-
-fn test_named_thread_truncation() {
-    let long_name = std::iter::once("test_named_thread_truncation")
-        .chain(std::iter::repeat(" yada").take(100))
-        .collect::<String>();
-
-    fn set_thread_name(name: &CStr) -> i32 {
-        #[cfg(target_os = "linux")]
-        return unsafe { libc::pthread_setname_np(libc::pthread_self(), name.as_ptr().cast()) };
-        #[cfg(target_os = "freebsd")]
-        unsafe {
-            // pthread_set_name_np does not return anything
-            libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr().cast());
-            return 0;
-        };
-        #[cfg(target_os = "macos")]
-        return unsafe { libc::pthread_setname_np(name.as_ptr().cast()) };
-    }
-
-    let result = thread::Builder::new().name(long_name.clone()).spawn(move || {
-        // Rust remembers the full thread name itself.
-        assert_eq!(thread::current().name(), Some(long_name.as_str()));
-
-        // But the system is limited -- make sure we successfully set a truncation.
-        let mut buf = vec![0u8; long_name.len() + 1];
-        #[cfg(not(target_os = "freebsd"))]
-        unsafe {
-            libc::pthread_getname_np(libc::pthread_self(), buf.as_mut_ptr().cast(), buf.len())
-        };
-        #[cfg(target_os = "freebsd")]
-        unsafe {
-            libc::pthread_get_name_np(libc::pthread_self(), buf.as_mut_ptr().cast(), buf.len())
-        };
-        let cstr = CStr::from_bytes_until_nul(&buf).unwrap();
-        assert!(cstr.to_bytes().len() >= 15, "name is too short: len={}", cstr.to_bytes().len()); // POSIX seems to promise at least 15 chars
-        assert!(long_name.as_bytes().starts_with(cstr.to_bytes()));
-
-        // Also test directly calling pthread_setname to check its return value.
-        assert_eq!(set_thread_name(&cstr), 0);
-        // But with a too long name it should fail (except on FreeBSD where the
-        // function has no return, hence cannot indicate failure).
-        #[cfg(not(target_os = "freebsd"))]
-        assert_ne!(set_thread_name(&CString::new(long_name).unwrap()), 0);
-    });
-    result.unwrap().join().unwrap();
-}
diff --git a/src/tools/miri/tests/pass-dep/shims/pthread-threadname.rs b/src/tools/miri/tests/pass-dep/shims/pthread-threadname.rs
new file mode 100644
index 0000000000000..bc782044d4d80
--- /dev/null
+++ b/src/tools/miri/tests/pass-dep/shims/pthread-threadname.rs
@@ -0,0 +1,51 @@
+//@ignore-target-windows: No libc on Windows
+use std::ffi::CStr;
+#[cfg(not(target_os = "freebsd"))]
+use std::ffi::CString;
+use std::thread;
+
+fn main() {
+    let long_name = std::iter::once("test_named_thread_truncation")
+        .chain(std::iter::repeat(" yada").take(100))
+        .collect::<String>();
+
+    fn set_thread_name(name: &CStr) -> i32 {
+        #[cfg(target_os = "linux")]
+        return unsafe { libc::pthread_setname_np(libc::pthread_self(), name.as_ptr().cast()) };
+        #[cfg(target_os = "freebsd")]
+        unsafe {
+            // pthread_set_name_np does not return anything
+            libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr().cast());
+            return 0;
+        };
+        #[cfg(target_os = "macos")]
+        return unsafe { libc::pthread_setname_np(name.as_ptr().cast()) };
+    }
+
+    let result = thread::Builder::new().name(long_name.clone()).spawn(move || {
+        // Rust remembers the full thread name itself.
+        assert_eq!(thread::current().name(), Some(long_name.as_str()));
+
+        // But the system is limited -- make sure we successfully set a truncation.
+        let mut buf = vec![0u8; long_name.len() + 1];
+        #[cfg(not(target_os = "freebsd"))]
+        unsafe {
+            libc::pthread_getname_np(libc::pthread_self(), buf.as_mut_ptr().cast(), buf.len())
+        };
+        #[cfg(target_os = "freebsd")]
+        unsafe {
+            libc::pthread_get_name_np(libc::pthread_self(), buf.as_mut_ptr().cast(), buf.len())
+        };
+        let cstr = CStr::from_bytes_until_nul(&buf).unwrap();
+        assert!(cstr.to_bytes().len() >= 15, "name is too short: len={}", cstr.to_bytes().len()); // POSIX seems to promise at least 15 chars
+        assert!(long_name.as_bytes().starts_with(cstr.to_bytes()));
+
+        // Also test directly calling pthread_setname to check its return value.
+        assert_eq!(set_thread_name(&cstr), 0);
+        // But with a too long name it should fail (except on FreeBSD where the
+        // function has no return, hence cannot indicate failure).
+        #[cfg(not(target_os = "freebsd"))]
+        assert_ne!(set_thread_name(&CString::new(long_name).unwrap()), 0);
+    });
+    result.unwrap().join().unwrap();
+}

From 6985431923ccd3111cc16680db441c55f9aaf6b4 Mon Sep 17 00:00:00 2001
From: Ralf Jung <post@ralfj.de>
Date: Thu, 16 Nov 2023 19:32:27 +0100
Subject: [PATCH 22/34] make libc-misc pass under FreeBSD

---
 src/tools/miri/ci.sh                             | 2 +-
 src/tools/miri/tests/pass-dep/shims/libc-misc.rs | 7 +++++++
 2 files changed, 8 insertions(+), 1 deletion(-)

diff --git a/src/tools/miri/ci.sh b/src/tools/miri/ci.sh
index 5f55f1af73f51..2bb151c3464b0 100755
--- a/src/tools/miri/ci.sh
+++ b/src/tools/miri/ci.sh
@@ -108,7 +108,7 @@ case $HOST_TARGET in
     MIRI_TEST_TARGET=aarch64-unknown-linux-gnu run_tests
     MIRI_TEST_TARGET=aarch64-apple-darwin run_tests
     MIRI_TEST_TARGET=i686-pc-windows-gnu run_tests
-    MIRI_TEST_TARGET=x86_64-unknown-freebsd run_tests_minimal hello integer vec panic/panic concurrency/simple pthreads-threadname libc-getentropy libc-getrandom libc-reallocarray atomic env/var
+    MIRI_TEST_TARGET=x86_64-unknown-freebsd run_tests_minimal hello integer vec panic/panic concurrency/simple pthreads-threadname libc-getentropy libc-getrandom libc-reallocarray libc-misc atomic env/var
     MIRI_TEST_TARGET=aarch64-linux-android run_tests_minimal hello integer vec panic/panic
     MIRI_TEST_TARGET=wasm32-wasi run_tests_minimal no_std integer strings wasm
     MIRI_TEST_TARGET=wasm32-unknown-unknown run_tests_minimal no_std integer strings wasm
diff --git a/src/tools/miri/tests/pass-dep/shims/libc-misc.rs b/src/tools/miri/tests/pass-dep/shims/libc-misc.rs
index 40d3fa19e5301..0374158ea56a1 100644
--- a/src/tools/miri/tests/pass-dep/shims/libc-misc.rs
+++ b/src/tools/miri/tests/pass-dep/shims/libc-misc.rs
@@ -172,6 +172,7 @@ fn test_thread_local_errno() {
 }
 
 /// Tests whether clock support exists at all
+#[cfg(not(target_os = "freebsd"))]
 fn test_clocks() {
     let mut tp = std::mem::MaybeUninit::<libc::timespec>::uninit();
     let is_error = unsafe { libc::clock_gettime(libc::CLOCK_REALTIME, tp.as_mut_ptr()) };
@@ -237,6 +238,7 @@ fn test_isatty() {
     }
 }
 
+#[cfg(not(target_os = "freebsd"))]
 fn test_posix_mkstemp() {
     use std::ffi::CString;
     use std::ffi::OsStr;
@@ -390,6 +392,8 @@ fn test_dlsym() {
 
 fn main() {
     test_posix_gettimeofday();
+
+    #[cfg(not(target_os = "freebsd"))] // FIXME we should support this on FreeBSD as well
     test_posix_mkstemp();
 
     test_posix_realpath_alloc();
@@ -399,7 +403,10 @@ fn main() {
     test_thread_local_errno();
 
     test_isatty();
+
+    #[cfg(not(target_os = "freebsd"))] // FIXME we should support this on FreeBSD as well
     test_clocks();
+
     test_dlsym();
 
     test_memcpy();

From 70cc63958063a42418858be21f5b19c6b0a3f4a4 Mon Sep 17 00:00:00 2001
From: Ralf Jung <post@ralfj.de>
Date: Thu, 16 Nov 2023 19:35:13 +0100
Subject: [PATCH 23/34] move reallocarray test into libc-misc

---
 src/tools/miri/ci.sh                            |  2 +-
 .../miri/tests/pass-dep/shims/libc-misc.rs      | 17 +++++++++++++++++
 .../tests/pass-dep/shims/libc-reallocarray.rs   | 16 ----------------
 3 files changed, 18 insertions(+), 17 deletions(-)
 delete mode 100644 src/tools/miri/tests/pass-dep/shims/libc-reallocarray.rs

diff --git a/src/tools/miri/ci.sh b/src/tools/miri/ci.sh
index 2bb151c3464b0..dbfb4eca3f335 100755
--- a/src/tools/miri/ci.sh
+++ b/src/tools/miri/ci.sh
@@ -108,7 +108,7 @@ case $HOST_TARGET in
     MIRI_TEST_TARGET=aarch64-unknown-linux-gnu run_tests
     MIRI_TEST_TARGET=aarch64-apple-darwin run_tests
     MIRI_TEST_TARGET=i686-pc-windows-gnu run_tests
-    MIRI_TEST_TARGET=x86_64-unknown-freebsd run_tests_minimal hello integer vec panic/panic concurrency/simple pthreads-threadname libc-getentropy libc-getrandom libc-reallocarray libc-misc atomic env/var
+    MIRI_TEST_TARGET=x86_64-unknown-freebsd run_tests_minimal hello integer vec panic/panic concurrency/simple pthreads-threadname libc-getentropy libc-getrandom libc-misc atomic env/var
     MIRI_TEST_TARGET=aarch64-linux-android run_tests_minimal hello integer vec panic/panic
     MIRI_TEST_TARGET=wasm32-wasi run_tests_minimal no_std integer strings wasm
     MIRI_TEST_TARGET=wasm32-unknown-unknown run_tests_minimal no_std integer strings wasm
diff --git a/src/tools/miri/tests/pass-dep/shims/libc-misc.rs b/src/tools/miri/tests/pass-dep/shims/libc-misc.rs
index 0374158ea56a1..de1acb13cbeb8 100644
--- a/src/tools/miri/tests/pass-dep/shims/libc-misc.rs
+++ b/src/tools/miri/tests/pass-dep/shims/libc-misc.rs
@@ -390,6 +390,19 @@ fn test_dlsym() {
     assert_eq!(errno, libc::EBADF);
 }
 
+#[cfg(not(target_os = "macos"))]
+fn test_reallocarray() {
+    unsafe {
+        let mut p = libc::reallocarray(std::ptr::null_mut(), 4096, 2);
+        assert!(!p.is_null());
+        libc::free(p);
+        p = libc::malloc(16);
+        let r = libc::reallocarray(p, 2, 32);
+        assert!(!r.is_null());
+        libc::free(r);
+    }
+}
+
 fn main() {
     test_posix_gettimeofday();
 
@@ -412,6 +425,10 @@ fn main() {
     test_memcpy();
     test_strcpy();
 
+    #[cfg(not(target_os = "macos"))] // reallocarray does not exist on macOS
+    test_reallocarray();
+
+    // These are Linux-specific
     #[cfg(target_os = "linux")]
     {
         test_posix_fadvise();
diff --git a/src/tools/miri/tests/pass-dep/shims/libc-reallocarray.rs b/src/tools/miri/tests/pass-dep/shims/libc-reallocarray.rs
deleted file mode 100644
index 29a3a5908526c..0000000000000
--- a/src/tools/miri/tests/pass-dep/shims/libc-reallocarray.rs
+++ /dev/null
@@ -1,16 +0,0 @@
-//@ignore-target-windows: no libc
-//@ignore-target-apple: no support (yet)
-
-use core::ptr;
-
-fn main() {
-    unsafe {
-        let mut p = libc::reallocarray(ptr::null_mut(), 4096, 2);
-        assert!(!p.is_null());
-        libc::free(p);
-        p = libc::malloc(16);
-        let r = libc::reallocarray(p, 2, 32);
-        assert!(!r.is_null());
-        libc::free(r);
-    }
-}

From 8edb0ad33b281bbe8bae827d1cdae782714d19a2 Mon Sep 17 00:00:00 2001
From: Ralf Jung <post@ralfj.de>
Date: Thu, 16 Nov 2023 19:38:50 +0100
Subject: [PATCH 24/34] actually all the 'env' tests work on FreeBSD, as well
 as posix_memalign

---
 src/tools/miri/ci.sh | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/tools/miri/ci.sh b/src/tools/miri/ci.sh
index dbfb4eca3f335..7808c9acf931c 100755
--- a/src/tools/miri/ci.sh
+++ b/src/tools/miri/ci.sh
@@ -108,7 +108,7 @@ case $HOST_TARGET in
     MIRI_TEST_TARGET=aarch64-unknown-linux-gnu run_tests
     MIRI_TEST_TARGET=aarch64-apple-darwin run_tests
     MIRI_TEST_TARGET=i686-pc-windows-gnu run_tests
-    MIRI_TEST_TARGET=x86_64-unknown-freebsd run_tests_minimal hello integer vec panic/panic concurrency/simple pthreads-threadname libc-getentropy libc-getrandom libc-misc atomic env/var
+    MIRI_TEST_TARGET=x86_64-unknown-freebsd run_tests_minimal hello integer vec panic/panic concurrency/simple pthread-threadname libc-getentropy libc-getrandom libc-misc atomic env align
     MIRI_TEST_TARGET=aarch64-linux-android run_tests_minimal hello integer vec panic/panic
     MIRI_TEST_TARGET=wasm32-wasi run_tests_minimal no_std integer strings wasm
     MIRI_TEST_TARGET=wasm32-unknown-unknown run_tests_minimal no_std integer strings wasm

From b7c27454db29689a933c2735b8d578dbb8ac7619 Mon Sep 17 00:00:00 2001
From: Ben Kimock <kimockb@gmail.com>
Date: Thu, 16 Nov 2023 16:20:16 -0500
Subject: [PATCH 25/34] Preparing for merge from rustc

---
 src/tools/miri/rust-version | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/tools/miri/rust-version b/src/tools/miri/rust-version
index 673e11163c85e..2a19781775bab 100644
--- a/src/tools/miri/rust-version
+++ b/src/tools/miri/rust-version
@@ -1 +1 @@
-525c91d096194decbfa70245743d697fb010ac91
+820f06b21f8373060ff7b515715b8440a6a6c197

From ae179a04b64d56fa4d648fccf3db661301550797 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?O=C4=9Fuz=20A=C4=9Fcayaz=C4=B1?= <ouz.agz@gmail.com>
Date: Wed, 8 Nov 2023 12:37:26 +0300
Subject: [PATCH 26/34] emit basic smir

---
 compiler/rustc_driver_impl/Cargo.toml         |   1 +
 compiler/rustc_driver_impl/src/pretty.rs      |   6 +
 compiler/rustc_session/src/config.rs          |  10 +-
 compiler/rustc_smir/src/rustc_internal/mod.rs |   7 +
 .../rustc_smir/src/rustc_internal/pretty.rs   | 133 ++++++++++++++++++
 compiler/rustc_smir/src/rustc_smir/mod.rs     |   6 +-
 compiler/stable_mir/src/mir/body.rs           |   2 +
 7 files changed, 160 insertions(+), 5 deletions(-)
 create mode 100644 compiler/rustc_smir/src/rustc_internal/pretty.rs

diff --git a/compiler/rustc_driver_impl/Cargo.toml b/compiler/rustc_driver_impl/Cargo.toml
index da7c2440faad4..e9b5a32842204 100644
--- a/compiler/rustc_driver_impl/Cargo.toml
+++ b/compiler/rustc_driver_impl/Cargo.toml
@@ -44,6 +44,7 @@ rustc_query_system = { path = "../rustc_query_system" }
 rustc_resolve = { path = "../rustc_resolve" }
 rustc_session = { path = "../rustc_session" }
 rustc_span = { path = "../rustc_span" }
+rustc_smir ={ path = "../rustc_smir" }
 rustc_symbol_mangling = { path = "../rustc_symbol_mangling" }
 rustc_target = { path = "../rustc_target" }
 rustc_trait_selection = { path = "../rustc_trait_selection" }
diff --git a/compiler/rustc_driver_impl/src/pretty.rs b/compiler/rustc_driver_impl/src/pretty.rs
index cc533b9941ab4..84f8941ff662d 100644
--- a/compiler/rustc_driver_impl/src/pretty.rs
+++ b/compiler/rustc_driver_impl/src/pretty.rs
@@ -9,6 +9,7 @@ use rustc_middle::mir::{write_mir_graphviz, write_mir_pretty};
 use rustc_middle::ty::{self, TyCtxt};
 use rustc_session::config::{OutFileName, PpHirMode, PpMode, PpSourceMode};
 use rustc_session::Session;
+use rustc_smir::rustc_internal::pretty::write_smir_pretty;
 use rustc_span::symbol::Ident;
 use rustc_span::FileName;
 
@@ -325,6 +326,11 @@ pub fn print<'tcx>(sess: &Session, ppm: PpMode, ex: PrintExtra<'tcx>) {
             write_mir_graphviz(ex.tcx(), None, &mut out).unwrap();
             String::from_utf8(out).unwrap()
         }
+        Smir => {
+            let mut out = Vec::new();
+            write_smir_pretty(ex.tcx(), &mut out).unwrap();
+            String::from_utf8(out).unwrap()
+        }
         ThirTree => {
             let tcx = ex.tcx();
             let mut out = String::new();
diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs
index add40b83d21d3..54335645e43e2 100644
--- a/compiler/rustc_session/src/config.rs
+++ b/compiler/rustc_session/src/config.rs
@@ -2926,6 +2926,7 @@ fn parse_pretty(handler: &EarlyErrorHandler, unstable_opts: &UnstableOptions) ->
         "thir-tree" => ThirTree,
         "thir-flat" => ThirFlat,
         "mir" => Mir,
+        "smir" => Smir,
         "mir-cfg" => MirCFG,
         name => handler.early_error(format!(
             "argument to `unpretty` must be one of `normal`, `identified`, \
@@ -3106,6 +3107,8 @@ pub enum PpMode {
     Mir,
     /// `-Zunpretty=mir-cfg`
     MirCFG,
+    /// `-Zunpretty=smir`
+    Smir,
 }
 
 impl PpMode {
@@ -3122,7 +3125,8 @@ impl PpMode {
             | ThirTree
             | ThirFlat
             | Mir
-            | MirCFG => true,
+            | MirCFG
+            | Smir => true,
         }
     }
     pub fn needs_hir(&self) -> bool {
@@ -3130,13 +3134,13 @@ impl PpMode {
         match *self {
             Source(_) | AstTree | AstTreeExpanded => false,
 
-            Hir(_) | HirTree | ThirTree | ThirFlat | Mir | MirCFG => true,
+            Hir(_) | HirTree | ThirTree | ThirFlat | Mir | MirCFG | Smir => true,
         }
     }
 
     pub fn needs_analysis(&self) -> bool {
         use PpMode::*;
-        matches!(*self, Hir(PpHirMode::Typed) | Mir | MirCFG | ThirTree | ThirFlat)
+        matches!(*self, Hir(PpHirMode::Typed) | Mir | Smir | MirCFG | ThirTree | ThirFlat)
     }
 }
 
diff --git a/compiler/rustc_smir/src/rustc_internal/mod.rs b/compiler/rustc_smir/src/rustc_internal/mod.rs
index c82f948f195e6..7957c3ce61703 100644
--- a/compiler/rustc_smir/src/rustc_internal/mod.rs
+++ b/compiler/rustc_smir/src/rustc_internal/mod.rs
@@ -21,6 +21,7 @@ use std::hash::Hash;
 use std::ops::Index;
 
 mod internal;
+pub mod pretty;
 
 pub fn stable<'tcx, S: Stable<'tcx>>(item: S) -> S::T {
     with_tables(|tables| item.stable(tables))
@@ -299,4 +300,10 @@ impl<K: PartialEq + Hash + Eq, V: Copy + Debug + PartialEq + IndexedVal> Index<V
 pub trait RustcInternal<'tcx> {
     type T;
     fn internal(&self, tables: &mut Tables<'tcx>) -> Self::T;
+
+    /// Use this when you want to convert to a rustc counterpart in user-code.
+    /// Do not use this within the smir crates themselves.
+    fn internal_via_tls(&self) -> Self::T {
+        with_tables(|tables| self.internal(tables))
+    }
 }
diff --git a/compiler/rustc_smir/src/rustc_internal/pretty.rs b/compiler/rustc_smir/src/rustc_internal/pretty.rs
new file mode 100644
index 0000000000000..e9af5081353ee
--- /dev/null
+++ b/compiler/rustc_smir/src/rustc_internal/pretty.rs
@@ -0,0 +1,133 @@
+use std::io;
+
+use rustc_middle::ty::TyCtxt;
+use stable_mir::{
+    ty::{RigidTy, TyKind},
+    CrateItem, mir::Mutability,
+};
+
+
+use super::{run, RustcInternal};
+
+pub fn write_smir_pretty<'tcx>(tcx: TyCtxt<'tcx>, w: &mut dyn io::Write) -> io::Result<()> { 
+    run(tcx, || {
+        let items = stable_mir::all_local_items();
+        items.iter().for_each(|item| {
+            // Because we can't return a Result from a closure, we have to unwrap here.
+            writeln!(w, "{}", function_name(*item,tcx)).unwrap();
+            writeln!(w, "{}", function_body(*item,tcx)).unwrap();
+        })
+    });
+    Ok(())
+}
+
+pub fn function_name(item: CrateItem,tcx: TyCtxt<'_>) -> String {
+    let mut name = String::new();
+    let body  = item.body();
+    name.push_str("fn ");
+    name.push_str(item.name().as_str());
+    if body.arg_locals().is_empty() {
+        name.push_str("()");
+    }else{
+        name.push_str("(");
+    }
+    body.arg_locals().iter().for_each(|local| {
+        name.push_str(format!("_{}: ",local.local).as_str());
+        name.push_str(&pretty_ty(local.ty.kind(), tcx));
+    });
+    if !body.arg_locals().is_empty() {
+        name.push_str(")");
+    }
+    let return_local = body.ret_local();
+    name.push_str(" -> ");
+    name.push_str(&pretty_ty(return_local.ty.kind(), tcx));
+    name.push_str(" {");
+    name
+}
+
+pub fn function_body(item: CrateItem,_tcx: TyCtxt<'_>) -> String {
+    let mut body_str = String::new();
+    let body  = item.body();
+    body.inner_locals().iter().for_each(|local| {
+        body_str.push_str("    ");
+        body_str.push_str(format!("let {}",ret_mutability(&local.mutability)).as_str());
+        body_str.push_str(format!("_{}: ",local.local).as_str());
+        body_str.push_str(format!("{}",pretty_ty(local.ty.kind(), _tcx)).as_str());
+        body_str.push_str(";\n");
+
+    });
+    body_str.push_str("}");
+    body_str
+
+}
+
+pub fn ret_mutability(mutability: &Mutability) -> String {
+    match mutability {
+        Mutability::Not => "".to_string(),
+        Mutability::Mut => "mut ".to_string(),
+    }
+}
+
+pub fn pretty_ty<'tcx>(ty: TyKind,tcx: TyCtxt<'tcx>) -> String {
+    let mut pretty = String::new();
+    pretty.push_str("");
+    match ty {
+        TyKind::RigidTy(rigid_ty) => match rigid_ty {
+            RigidTy::Bool => "bool".to_string(),
+            RigidTy::Char => "char".to_string(),
+            RigidTy::Int(i) => match i {
+                stable_mir::ty::IntTy::Isize => "isize".to_string(),
+                stable_mir::ty::IntTy::I8 => "i8".to_string(),
+                stable_mir::ty::IntTy::I16 => "i16".to_string(),
+                stable_mir::ty::IntTy::I32 => "i32".to_string(),
+                stable_mir::ty::IntTy::I64 => "i64".to_string(),
+                stable_mir::ty::IntTy::I128 => "i128".to_string(),
+            },
+            RigidTy::Uint(u) => match u {
+                stable_mir::ty::UintTy::Usize => "usize".to_string(),
+                stable_mir::ty::UintTy::U8 => "u8".to_string(),
+                stable_mir::ty::UintTy::U16 => "u16".to_string(),
+                stable_mir::ty::UintTy::U32 => "u32".to_string(),
+                stable_mir::ty::UintTy::U64 => "u64".to_string(),
+                stable_mir::ty::UintTy::U128 => "u128".to_string(),
+            },
+            RigidTy::Float(f) => match f {
+                stable_mir::ty::FloatTy::F32 => "f32".to_string(),
+                stable_mir::ty::FloatTy::F64 => "f64".to_string(),
+            },
+            RigidTy::Adt(def, _) => format!("{:#?}", tcx.type_of(def.0.internal_via_tls()).instantiate_identity()),
+            RigidTy::Foreign(_) => format!("{:#?}", rigid_ty),
+            RigidTy::Str => "str".to_string(),
+            RigidTy::Array(_ty, len) => {
+                format!("[{};{:#?}]", 1,len.internal_via_tls())},
+            RigidTy::Slice(ty) => pretty_ty(ty.kind(),tcx),
+            RigidTy::RawPtr(_, _) => format!("{:#?}", rigid_ty),
+            RigidTy::Ref(_, ty, _) => pretty_ty(ty.kind(),tcx),
+            RigidTy::FnDef(_, _) => format!("{:#?}", rigid_ty),
+            RigidTy::FnPtr(_) => format!("{:#?}", rigid_ty),
+            RigidTy::Closure(_, _) => format!("{:#?}", rigid_ty),
+            RigidTy::Coroutine(_, _, _) => format!("{:#?}", rigid_ty),
+            RigidTy::Dynamic(_, _, _) => format!("{:#?}", rigid_ty),
+            RigidTy::Never => "!".to_string(),
+            RigidTy::Tuple(tuple) => {
+                if tuple.is_empty(){
+                    "()".to_string()
+                }else {
+                    let mut tuple_str = String::new();
+                    tuple_str.push_str("(");
+                    tuple.iter().enumerate().for_each(|(i,ty)| {
+                        tuple_str.push_str(&pretty_ty(ty.kind(),tcx));
+                        if i != tuple.len() - 1 {
+                            tuple_str.push_str(", ");
+                        }
+                    });
+                    tuple_str.push_str(")");
+                    tuple_str
+                }
+            },
+        },
+        TyKind::Alias(_, _) => format!("{:#?}", ty),
+        TyKind::Param(_) => format!("{:#?}", ty),
+        TyKind::Bound(_, _) => format!("{:#?}", ty),
+    }
+}
diff --git a/compiler/rustc_smir/src/rustc_smir/mod.rs b/compiler/rustc_smir/src/rustc_smir/mod.rs
index 3df09cef1c7dc..69b0c0bb80d55 100644
--- a/compiler/rustc_smir/src/rustc_smir/mod.rs
+++ b/compiler/rustc_smir/src/rustc_smir/mod.rs
@@ -400,10 +400,12 @@ impl<'tcx> Stable<'tcx> for mir::Body<'tcx> {
                 })
                 .collect(),
             self.local_decls
-                .iter()
-                .map(|decl| stable_mir::mir::LocalDecl {
+                .iter_enumerated()
+                .map(|(local, decl)| stable_mir::mir::LocalDecl {
                     ty: decl.ty.stable(tables),
                     span: decl.source_info.span.stable(tables),
+                    local: local.as_usize(),
+                    mutability: decl.mutability.stable(tables),
                 })
                 .collect(),
             self.arg_count,
diff --git a/compiler/stable_mir/src/mir/body.rs b/compiler/stable_mir/src/mir/body.rs
index 351e7bb69c3f7..2981d6a8bb5c6 100644
--- a/compiler/stable_mir/src/mir/body.rs
+++ b/compiler/stable_mir/src/mir/body.rs
@@ -64,6 +64,8 @@ type LocalDecls = Vec<LocalDecl>;
 pub struct LocalDecl {
     pub ty: Ty,
     pub span: Span,
+    pub local: Local,
+    pub mutability: Mutability,
 }
 
 #[derive(Clone, Debug)]

From 0f0e9baf199d022c6a93bb36353358a101c4b4f5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?O=C4=9Fuz=20A=C4=9Fcayaz=C4=B1?= <ouz.agz@gmail.com>
Date: Wed, 8 Nov 2023 15:25:48 +0300
Subject: [PATCH 27/34] cover statements

---
 .../rustc_smir/src/rustc_internal/pretty.rs   | 181 +++++++++++++++---
 1 file changed, 155 insertions(+), 26 deletions(-)

diff --git a/compiler/rustc_smir/src/rustc_internal/pretty.rs b/compiler/rustc_smir/src/rustc_internal/pretty.rs
index e9af5081353ee..ea0ccfe3e4eba 100644
--- a/compiler/rustc_smir/src/rustc_internal/pretty.rs
+++ b/compiler/rustc_smir/src/rustc_internal/pretty.rs
@@ -2,37 +2,43 @@ use std::io;
 
 use rustc_middle::ty::TyCtxt;
 use stable_mir::{
+    mir::{Mutability, Operand, Rvalue, StatementKind},
     ty::{RigidTy, TyKind},
-    CrateItem, mir::Mutability,
+    CrateItem,
 };
 
-
 use super::{run, RustcInternal};
 
-pub fn write_smir_pretty<'tcx>(tcx: TyCtxt<'tcx>, w: &mut dyn io::Write) -> io::Result<()> { 
+pub fn write_smir_pretty<'tcx>(tcx: TyCtxt<'tcx>, w: &mut dyn io::Write) -> io::Result<()> {
     run(tcx, || {
         let items = stable_mir::all_local_items();
         items.iter().for_each(|item| {
             // Because we can't return a Result from a closure, we have to unwrap here.
-            writeln!(w, "{}", function_name(*item,tcx)).unwrap();
-            writeln!(w, "{}", function_body(*item,tcx)).unwrap();
+            writeln!(w, "{}", function_name(*item, tcx)).unwrap();
+            writeln!(w, "{}", function_body(*item, tcx)).unwrap();
+            writeln!(w, "------------------").unwrap();
+            item.body().blocks.iter().for_each(|block| {
+                block.statements.iter().for_each(|statement| {
+                    writeln!(w, "{}", pretty_statement(&statement.kind, tcx)).unwrap();
+                });
+            })
         })
     });
     Ok(())
 }
 
-pub fn function_name(item: CrateItem,tcx: TyCtxt<'_>) -> String {
+pub fn function_name(item: CrateItem, tcx: TyCtxt<'_>) -> String {
     let mut name = String::new();
-    let body  = item.body();
+    let body = item.body();
     name.push_str("fn ");
     name.push_str(item.name().as_str());
     if body.arg_locals().is_empty() {
         name.push_str("()");
-    }else{
+    } else {
         name.push_str("(");
     }
     body.arg_locals().iter().for_each(|local| {
-        name.push_str(format!("_{}: ",local.local).as_str());
+        name.push_str(format!("_{}: ", local.local).as_str());
         name.push_str(&pretty_ty(local.ty.kind(), tcx));
     });
     if !body.arg_locals().is_empty() {
@@ -45,20 +51,18 @@ pub fn function_name(item: CrateItem,tcx: TyCtxt<'_>) -> String {
     name
 }
 
-pub fn function_body(item: CrateItem,_tcx: TyCtxt<'_>) -> String {
+pub fn function_body(item: CrateItem, _tcx: TyCtxt<'_>) -> String {
     let mut body_str = String::new();
-    let body  = item.body();
+    let body = item.body();
     body.inner_locals().iter().for_each(|local| {
         body_str.push_str("    ");
-        body_str.push_str(format!("let {}",ret_mutability(&local.mutability)).as_str());
-        body_str.push_str(format!("_{}: ",local.local).as_str());
-        body_str.push_str(format!("{}",pretty_ty(local.ty.kind(), _tcx)).as_str());
+        body_str.push_str(format!("let {}", ret_mutability(&local.mutability)).as_str());
+        body_str.push_str(format!("_{}: ", local.local).as_str());
+        body_str.push_str(format!("{}", pretty_ty(local.ty.kind(), _tcx)).as_str());
         body_str.push_str(";\n");
-
     });
     body_str.push_str("}");
     body_str
-
 }
 
 pub fn ret_mutability(mutability: &Mutability) -> String {
@@ -68,7 +72,129 @@ pub fn ret_mutability(mutability: &Mutability) -> String {
     }
 }
 
-pub fn pretty_ty<'tcx>(ty: TyKind,tcx: TyCtxt<'tcx>) -> String {
+pub fn pretty_statement(statement: &StatementKind, tcx: TyCtxt<'_>) -> String {
+    let mut pretty = String::new();
+    match statement {
+        StatementKind::Assign(place, rval) => {
+            pretty.push_str(format!("_{} = ", place.local).as_str());
+            pretty.push_str(&pretty_rvalue(rval, tcx))
+        }
+        StatementKind::FakeRead(_, _) => todo!(),
+        StatementKind::SetDiscriminant { .. } => todo!(),
+        StatementKind::Deinit(_) => todo!(),
+        StatementKind::StorageLive(_) => todo!(),
+        StatementKind::StorageDead(_) => todo!(),
+        StatementKind::Retag(_, _) => todo!(),
+        StatementKind::PlaceMention(_) => todo!(),
+        StatementKind::AscribeUserType { .. } => todo!(),
+        StatementKind::Coverage(_) => todo!(),
+        StatementKind::Intrinsic(_) => todo!(),
+        StatementKind::ConstEvalCounter => (),
+        StatementKind::Nop => (),
+    }
+    pretty
+}
+
+pub fn pretty_operand(operand: &Operand, _tcx: TyCtxt<'_>) -> String {
+    let mut pretty = String::new();
+    match operand {
+        Operand::Copy(copy) => {
+            pretty.push_str("");
+            pretty.push_str(format!("{}", copy.local).as_str());
+        }
+        Operand::Move(mv) => {
+            pretty.push_str("move");
+            pretty.push_str(format!("{}", mv.local).as_str());
+        }
+        Operand::Constant(cnst) => {
+            pretty.push_str("const ");
+            pretty.push_str(cnst.literal.internal_via_tls().to_string().as_str());
+        }
+    }
+    pretty
+}
+
+pub fn pretty_rvalue(rval: &Rvalue, tcx: TyCtxt<'_>) -> String {
+    let mut pretty = String::new();
+    match rval {
+        Rvalue::AddressOf(muta, addr) => {
+            pretty.push_str("address_of");
+            pretty.push_str(&ret_mutability(&muta));
+            pretty.push_str(format!("{}", addr.local).as_str());
+        }
+        Rvalue::Aggregate(aggregatekind, operands) => {
+            pretty.push_str(format!("{:#?}", aggregatekind).as_str());
+            pretty.push_str("(");
+            operands.iter().enumerate().for_each(|(i, op)| {
+                pretty.push_str(&pretty_operand(op, tcx));
+                if i != operands.len() - 1 {
+                    pretty.push_str(", ");
+                }
+            });
+            pretty.push_str(")");
+        }
+        Rvalue::BinaryOp(bin, op, op2) => {
+            pretty.push_str(&pretty_operand(op, tcx));
+            pretty.push_str(" ");
+            pretty.push_str(format!("{:#?}", bin).as_str());
+            pretty.push_str(" ");
+            pretty.push_str(&pretty_operand(op2, tcx));
+        }
+        Rvalue::Cast(_, op, ty) => {
+            pretty.push_str(&pretty_operand(op, tcx));
+            pretty.push_str(" as ");
+            pretty.push_str(&pretty_ty(ty.kind(), tcx));
+        }
+        Rvalue::CheckedBinaryOp(bin, op1, op2) => {
+            pretty.push_str(&pretty_operand(op1, tcx));
+            pretty.push_str(" ");
+            pretty.push_str(format!("{:#?}", bin).as_str());
+            pretty.push_str(" ");
+            pretty.push_str(&pretty_operand(op2, tcx));
+        }
+        Rvalue::CopyForDeref(deref) => {
+            pretty.push_str("CopyForDeref");
+            pretty.push_str(format!("{}", deref.local).as_str());
+        }
+        Rvalue::Discriminant(place) => {
+            pretty.push_str("discriminant");
+            pretty.push_str(format!("{}", place.local).as_str());
+        }
+        Rvalue::Len(len) => {
+            pretty.push_str("len");
+            pretty.push_str(format!("{}", len.local).as_str());
+        }
+        Rvalue::Ref(_, borrowkind, place) => {
+            pretty.push_str("ref");
+            pretty.push_str(format!("{:#?}", borrowkind).as_str());
+            pretty.push_str(format!("{}", place.local).as_str());
+        }
+        Rvalue::Repeat(op, cnst) => {
+            pretty.push_str(&pretty_operand(op, tcx));
+            pretty.push_str(" ");
+            pretty.push_str(&pretty_ty(cnst.ty().kind(), tcx));
+        }
+        Rvalue::ShallowInitBox(_, _) => todo!(),
+        Rvalue::ThreadLocalRef(item) => {
+            pretty.push_str("thread_local_ref");
+            pretty.push_str(format!("{:#?}", item).as_str());
+        }
+        Rvalue::NullaryOp(nul, ty) => {
+            pretty.push_str(format!("{:#?}", nul).as_str());
+            pretty.push_str(&&pretty_ty(ty.kind(), tcx));
+            pretty.push_str(" ");
+        }
+        Rvalue::UnaryOp(un, op) => {
+            pretty.push_str(&pretty_operand(op, tcx));
+            pretty.push_str(" ");
+            pretty.push_str(format!("{:#?}", un).as_str());
+        }
+        Rvalue::Use(op) => pretty.push_str(&pretty_operand(op, tcx)),
+    }
+    pretty
+}
+
+pub fn pretty_ty(ty: TyKind, tcx: TyCtxt<'_>) -> String {
     let mut pretty = String::new();
     pretty.push_str("");
     match ty {
@@ -95,14 +221,17 @@ pub fn pretty_ty<'tcx>(ty: TyKind,tcx: TyCtxt<'tcx>) -> String {
                 stable_mir::ty::FloatTy::F32 => "f32".to_string(),
                 stable_mir::ty::FloatTy::F64 => "f64".to_string(),
             },
-            RigidTy::Adt(def, _) => format!("{:#?}", tcx.type_of(def.0.internal_via_tls()).instantiate_identity()),
+            RigidTy::Adt(def, _) => {
+                format!("{:#?}", tcx.type_of(def.0.internal_via_tls()).instantiate_identity())
+            }
             RigidTy::Foreign(_) => format!("{:#?}", rigid_ty),
             RigidTy::Str => "str".to_string(),
             RigidTy::Array(_ty, len) => {
-                format!("[{};{:#?}]", 1,len.internal_via_tls())},
-            RigidTy::Slice(ty) => pretty_ty(ty.kind(),tcx),
+                format!("[{};{:#?}]", 1, len.internal_via_tls())
+            }
+            RigidTy::Slice(ty) => pretty_ty(ty.kind(), tcx),
             RigidTy::RawPtr(_, _) => format!("{:#?}", rigid_ty),
-            RigidTy::Ref(_, ty, _) => pretty_ty(ty.kind(),tcx),
+            RigidTy::Ref(_, ty, _) => pretty_ty(ty.kind(), tcx),
             RigidTy::FnDef(_, _) => format!("{:#?}", rigid_ty),
             RigidTy::FnPtr(_) => format!("{:#?}", rigid_ty),
             RigidTy::Closure(_, _) => format!("{:#?}", rigid_ty),
@@ -110,13 +239,13 @@ pub fn pretty_ty<'tcx>(ty: TyKind,tcx: TyCtxt<'tcx>) -> String {
             RigidTy::Dynamic(_, _, _) => format!("{:#?}", rigid_ty),
             RigidTy::Never => "!".to_string(),
             RigidTy::Tuple(tuple) => {
-                if tuple.is_empty(){
+                if tuple.is_empty() {
                     "()".to_string()
-                }else {
+                } else {
                     let mut tuple_str = String::new();
                     tuple_str.push_str("(");
-                    tuple.iter().enumerate().for_each(|(i,ty)| {
-                        tuple_str.push_str(&pretty_ty(ty.kind(),tcx));
+                    tuple.iter().enumerate().for_each(|(i, ty)| {
+                        tuple_str.push_str(&pretty_ty(ty.kind(), tcx));
                         if i != tuple.len() - 1 {
                             tuple_str.push_str(", ");
                         }
@@ -124,7 +253,7 @@ pub fn pretty_ty<'tcx>(ty: TyKind,tcx: TyCtxt<'tcx>) -> String {
                     tuple_str.push_str(")");
                     tuple_str
                 }
-            },
+            }
         },
         TyKind::Alias(_, _) => format!("{:#?}", ty),
         TyKind::Param(_) => format!("{:#?}", ty),

From ebd9c145f600245ec66d0ddf4c0129874c10ecb8 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?O=C4=9Fuz=20A=C4=9Fcayaz=C4=B1?= <ouz.agz@gmail.com>
Date: Thu, 9 Nov 2023 12:11:41 +0300
Subject: [PATCH 28/34] better formatting for statements

---
 Cargo.lock                                    |  1 +
 compiler/rustc_driver_impl/Cargo.toml         |  2 +-
 compiler/rustc_smir/src/rustc_internal/mod.rs |  6 --
 .../rustc_smir/src/rustc_internal/pretty.rs   | 63 ++++++++++++++-----
 compiler/stable_mir/src/mir/visit.rs          |  2 +-
 5 files changed, 49 insertions(+), 25 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock
index 92bac995bc615..9fe70870140d8 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3815,6 +3815,7 @@ dependencies = [
  "rustc_query_system",
  "rustc_resolve",
  "rustc_session",
+ "rustc_smir",
  "rustc_span",
  "rustc_symbol_mangling",
  "rustc_target",
diff --git a/compiler/rustc_driver_impl/Cargo.toml b/compiler/rustc_driver_impl/Cargo.toml
index e9b5a32842204..545ff32e598ae 100644
--- a/compiler/rustc_driver_impl/Cargo.toml
+++ b/compiler/rustc_driver_impl/Cargo.toml
@@ -43,8 +43,8 @@ rustc_privacy = { path = "../rustc_privacy" }
 rustc_query_system = { path = "../rustc_query_system" }
 rustc_resolve = { path = "../rustc_resolve" }
 rustc_session = { path = "../rustc_session" }
-rustc_span = { path = "../rustc_span" }
 rustc_smir ={ path = "../rustc_smir" }
+rustc_span = { path = "../rustc_span" }
 rustc_symbol_mangling = { path = "../rustc_symbol_mangling" }
 rustc_target = { path = "../rustc_target" }
 rustc_trait_selection = { path = "../rustc_trait_selection" }
diff --git a/compiler/rustc_smir/src/rustc_internal/mod.rs b/compiler/rustc_smir/src/rustc_internal/mod.rs
index 7957c3ce61703..fa75fd3076ce0 100644
--- a/compiler/rustc_smir/src/rustc_internal/mod.rs
+++ b/compiler/rustc_smir/src/rustc_internal/mod.rs
@@ -300,10 +300,4 @@ impl<K: PartialEq + Hash + Eq, V: Copy + Debug + PartialEq + IndexedVal> Index<V
 pub trait RustcInternal<'tcx> {
     type T;
     fn internal(&self, tables: &mut Tables<'tcx>) -> Self::T;
-
-    /// Use this when you want to convert to a rustc counterpart in user-code.
-    /// Do not use this within the smir crates themselves.
-    fn internal_via_tls(&self) -> Self::T {
-        with_tables(|tables| self.internal(tables))
-    }
 }
diff --git a/compiler/rustc_smir/src/rustc_internal/pretty.rs b/compiler/rustc_smir/src/rustc_internal/pretty.rs
index ea0ccfe3e4eba..45917630cf3e9 100644
--- a/compiler/rustc_smir/src/rustc_internal/pretty.rs
+++ b/compiler/rustc_smir/src/rustc_internal/pretty.rs
@@ -7,20 +7,23 @@ use stable_mir::{
     CrateItem,
 };
 
-use super::{run, RustcInternal};
+use super::{internal, run};
 
 pub fn write_smir_pretty<'tcx>(tcx: TyCtxt<'tcx>, w: &mut dyn io::Write) -> io::Result<()> {
+    writeln!(w, "// WARNING: This is highly experimental output it's intended for stable-mir developers only.").unwrap();
+    writeln!(w, "// If you find a bug or want to improve the output open a issue at https://github.com/rust-lang/project-stable-mir.").unwrap();
     run(tcx, || {
         let items = stable_mir::all_local_items();
         items.iter().for_each(|item| {
             // Because we can't return a Result from a closure, we have to unwrap here.
             writeln!(w, "{}", function_name(*item, tcx)).unwrap();
             writeln!(w, "{}", function_body(*item, tcx)).unwrap();
-            writeln!(w, "------------------").unwrap();
-            item.body().blocks.iter().for_each(|block| {
+            item.body().blocks.iter().enumerate().for_each(|(index, block)| {
+                writeln!(w, "    bb{}: {{", index).unwrap();
                 block.statements.iter().for_each(|statement| {
                     writeln!(w, "{}", pretty_statement(&statement.kind, tcx)).unwrap();
                 });
+                writeln!(w, "    }}").unwrap();
             })
         })
     });
@@ -76,8 +79,8 @@ pub fn pretty_statement(statement: &StatementKind, tcx: TyCtxt<'_>) -> String {
     let mut pretty = String::new();
     match statement {
         StatementKind::Assign(place, rval) => {
-            pretty.push_str(format!("_{} = ", place.local).as_str());
-            pretty.push_str(&pretty_rvalue(rval, tcx))
+            pretty.push_str(format!("        _{} = ", place.local).as_str());
+            pretty.push_str(format!("{}", &pretty_rvalue(rval, tcx)).as_str());
         }
         StatementKind::FakeRead(_, _) => todo!(),
         StatementKind::SetDiscriminant { .. } => todo!(),
@@ -103,12 +106,12 @@ pub fn pretty_operand(operand: &Operand, _tcx: TyCtxt<'_>) -> String {
             pretty.push_str(format!("{}", copy.local).as_str());
         }
         Operand::Move(mv) => {
-            pretty.push_str("move");
-            pretty.push_str(format!("{}", mv.local).as_str());
+            pretty.push_str("move ");
+            pretty.push_str(format!("_{}", mv.local).as_str());
         }
         Operand::Constant(cnst) => {
             pretty.push_str("const ");
-            pretty.push_str(cnst.literal.internal_via_tls().to_string().as_str());
+            pretty.push_str(internal(&cnst.literal).to_string().as_str());
         }
     }
     pretty
@@ -118,9 +121,9 @@ pub fn pretty_rvalue(rval: &Rvalue, tcx: TyCtxt<'_>) -> String {
     let mut pretty = String::new();
     match rval {
         Rvalue::AddressOf(muta, addr) => {
-            pretty.push_str("address_of");
+            pretty.push_str("&raw ");
             pretty.push_str(&ret_mutability(&muta));
-            pretty.push_str(format!("{}", addr.local).as_str());
+            pretty.push_str(format!("(*_{})", addr.local).as_str());
         }
         Rvalue::Aggregate(aggregatekind, operands) => {
             pretty.push_str(format!("{:#?}", aggregatekind).as_str());
@@ -222,21 +225,45 @@ pub fn pretty_ty(ty: TyKind, tcx: TyCtxt<'_>) -> String {
                 stable_mir::ty::FloatTy::F64 => "f64".to_string(),
             },
             RigidTy::Adt(def, _) => {
-                format!("{:#?}", tcx.type_of(def.0.internal_via_tls()).instantiate_identity())
+                format!("{}", tcx.type_of(internal(&def.0)).instantiate_identity())
             }
             RigidTy::Foreign(_) => format!("{:#?}", rigid_ty),
             RigidTy::Str => "str".to_string(),
-            RigidTy::Array(_ty, len) => {
-                format!("[{};{:#?}]", 1, len.internal_via_tls())
+            RigidTy::Array(ty, len) => {
+                format!(
+                    "[{}; {}]",
+                    pretty_ty(ty.kind(), tcx),
+                    internal(&len).try_to_scalar().unwrap()
+                )
+            }
+            RigidTy::Slice(ty) => {
+                format!("[{}]", pretty_ty(ty.kind(), tcx))
+            }
+            RigidTy::RawPtr(ty, mutability) => {
+                pretty.push_str("*");
+                match mutability {
+                    Mutability::Not => pretty.push_str("const "),
+                    Mutability::Mut => pretty.push_str("mut "),
+                }
+                pretty.push_str(&pretty_ty(ty.kind(), tcx));
+                pretty
             }
-            RigidTy::Slice(ty) => pretty_ty(ty.kind(), tcx),
-            RigidTy::RawPtr(_, _) => format!("{:#?}", rigid_ty),
             RigidTy::Ref(_, ty, _) => pretty_ty(ty.kind(), tcx),
             RigidTy::FnDef(_, _) => format!("{:#?}", rigid_ty),
             RigidTy::FnPtr(_) => format!("{:#?}", rigid_ty),
             RigidTy::Closure(_, _) => format!("{:#?}", rigid_ty),
             RigidTy::Coroutine(_, _, _) => format!("{:#?}", rigid_ty),
-            RigidTy::Dynamic(_, _, _) => format!("{:#?}", rigid_ty),
+            RigidTy::Dynamic(data, region, repr) => {
+                // FIXME: Fix binder printing, it looks ugly now
+                pretty.push_str("(");
+                match repr {
+                    stable_mir::ty::DynKind::Dyn => pretty.push_str("dyn "),
+                    stable_mir::ty::DynKind::DynStar => pretty.push_str("dyn* "),
+                }
+                pretty.push_str(format!("{:#?}", data).as_str());
+                pretty.push_str(format!(" +  {:#?} )", region).as_str());
+                pretty
+            }
             RigidTy::Never => "!".to_string(),
             RigidTy::Tuple(tuple) => {
                 if tuple.is_empty() {
@@ -256,7 +283,9 @@ pub fn pretty_ty(ty: TyKind, tcx: TyCtxt<'_>) -> String {
             }
         },
         TyKind::Alias(_, _) => format!("{:#?}", ty),
-        TyKind::Param(_) => format!("{:#?}", ty),
+        TyKind::Param(param_ty) => {
+            format!("{:#?}", param_ty.name)
+        }
         TyKind::Bound(_, _) => format!("{:#?}", ty),
     }
 }
diff --git a/compiler/stable_mir/src/mir/visit.rs b/compiler/stable_mir/src/mir/visit.rs
index d6304d3ea398d..40bedd67352f7 100644
--- a/compiler/stable_mir/src/mir/visit.rs
+++ b/compiler/stable_mir/src/mir/visit.rs
@@ -157,7 +157,7 @@ pub trait MirVisitor {
 
     fn super_local_decl(&mut self, local: Local, decl: &LocalDecl) {
         let _ = local;
-        let LocalDecl { ty, span } = decl;
+        let LocalDecl { ty, span, .. } = decl;
         self.visit_ty(ty, Location(*span));
     }
 

From c821603484e1f0eb2d314a5e4ca842f38ac6dfab Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?O=C4=9Fuz=20A=C4=9Fcayaz=C4=B1?= <ouz.agz@gmail.com>
Date: Tue, 14 Nov 2023 13:06:58 +0300
Subject: [PATCH 29/34] remove unwrap

---
 .../rustc_smir/src/rustc_internal/pretty.rs   | 25 +++++++++++--------
 1 file changed, 15 insertions(+), 10 deletions(-)

diff --git a/compiler/rustc_smir/src/rustc_internal/pretty.rs b/compiler/rustc_smir/src/rustc_internal/pretty.rs
index 45917630cf3e9..67995b1811046 100644
--- a/compiler/rustc_smir/src/rustc_internal/pretty.rs
+++ b/compiler/rustc_smir/src/rustc_internal/pretty.rs
@@ -12,20 +12,25 @@ use super::{internal, run};
 pub fn write_smir_pretty<'tcx>(tcx: TyCtxt<'tcx>, w: &mut dyn io::Write) -> io::Result<()> {
     writeln!(w, "// WARNING: This is highly experimental output it's intended for stable-mir developers only.").unwrap();
     writeln!(w, "// If you find a bug or want to improve the output open a issue at https://github.com/rust-lang/project-stable-mir.").unwrap();
+
     run(tcx, || {
         let items = stable_mir::all_local_items();
-        items.iter().for_each(|item| {
+        let _ = items.iter().map(|item| -> io::Result<()> {
             // Because we can't return a Result from a closure, we have to unwrap here.
-            writeln!(w, "{}", function_name(*item, tcx)).unwrap();
-            writeln!(w, "{}", function_body(*item, tcx)).unwrap();
-            item.body().blocks.iter().enumerate().for_each(|(index, block)| {
-                writeln!(w, "    bb{}: {{", index).unwrap();
-                block.statements.iter().for_each(|statement| {
-                    writeln!(w, "{}", pretty_statement(&statement.kind, tcx)).unwrap();
-                });
+            writeln!(w, "{}", function_name(*item, tcx))?;
+            writeln!(w, "{}", function_body(*item, tcx))?;
+            let _ = item.body().blocks.iter().enumerate().map(|(index, block)| -> io::Result<()> {
+                writeln!(w, "    bb{}: {{", index)?;
+                let _ = block.statements.iter().map(|statement| -> io::Result<()> {
+                    writeln!(w, "{}", pretty_statement(&statement.kind, tcx))?;
+                    Ok(())
+                }).collect::<Vec<_>>();
                 writeln!(w, "    }}").unwrap();
-            })
-        })
+                Ok(())
+            }).collect::<Vec<_>>();
+            Ok(())
+        }).collect::<Vec<_>>();
+        
     });
     Ok(())
 }

From 3883645a9b228cf5b91f8766692ff57455ad6123 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?O=C4=9Fuz=20A=C4=9Fcayaz=C4=B1?= <ouz.agz@gmail.com>
Date: Tue, 14 Nov 2023 16:21:55 +0300
Subject: [PATCH 30/34] change smir to StableMir

---
 compiler/rustc_driver_impl/src/pretty.rs      |  2 +-
 compiler/rustc_session/src/config.rs          | 14 +++----
 .../rustc_smir/src/rustc_internal/pretty.rs   | 42 ++++++++++++-------
 3 files changed, 35 insertions(+), 23 deletions(-)

diff --git a/compiler/rustc_driver_impl/src/pretty.rs b/compiler/rustc_driver_impl/src/pretty.rs
index 84f8941ff662d..7cd63bc6422c3 100644
--- a/compiler/rustc_driver_impl/src/pretty.rs
+++ b/compiler/rustc_driver_impl/src/pretty.rs
@@ -326,7 +326,7 @@ pub fn print<'tcx>(sess: &Session, ppm: PpMode, ex: PrintExtra<'tcx>) {
             write_mir_graphviz(ex.tcx(), None, &mut out).unwrap();
             String::from_utf8(out).unwrap()
         }
-        Smir => {
+        StableMir => {
             let mut out = Vec::new();
             write_smir_pretty(ex.tcx(), &mut out).unwrap();
             String::from_utf8(out).unwrap()
diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs
index 54335645e43e2..d4f9122e7e384 100644
--- a/compiler/rustc_session/src/config.rs
+++ b/compiler/rustc_session/src/config.rs
@@ -2926,13 +2926,13 @@ fn parse_pretty(handler: &EarlyErrorHandler, unstable_opts: &UnstableOptions) ->
         "thir-tree" => ThirTree,
         "thir-flat" => ThirFlat,
         "mir" => Mir,
-        "smir" => Smir,
+        "stable-mir" => StableMir,
         "mir-cfg" => MirCFG,
         name => handler.early_error(format!(
             "argument to `unpretty` must be one of `normal`, `identified`, \
                             `expanded`, `expanded,identified`, `expanded,hygiene`, \
                             `ast-tree`, `ast-tree,expanded`, `hir`, `hir,identified`, \
-                            `hir,typed`, `hir-tree`, `thir-tree`, `thir-flat`, `mir` or \
+                            `hir,typed`, `hir-tree`, `thir-tree`, `thir-flat`, `mir`, `stable-mir`, or \
                             `mir-cfg`; got {name}"
         )),
     };
@@ -3107,8 +3107,8 @@ pub enum PpMode {
     Mir,
     /// `-Zunpretty=mir-cfg`
     MirCFG,
-    /// `-Zunpretty=smir`
-    Smir,
+    /// `-Zunpretty=stable-mir`
+    StableMir,
 }
 
 impl PpMode {
@@ -3126,7 +3126,7 @@ impl PpMode {
             | ThirFlat
             | Mir
             | MirCFG
-            | Smir => true,
+            | StableMir => true,
         }
     }
     pub fn needs_hir(&self) -> bool {
@@ -3134,13 +3134,13 @@ impl PpMode {
         match *self {
             Source(_) | AstTree | AstTreeExpanded => false,
 
-            Hir(_) | HirTree | ThirTree | ThirFlat | Mir | MirCFG | Smir => true,
+            Hir(_) | HirTree | ThirTree | ThirFlat | Mir | MirCFG | StableMir => true,
         }
     }
 
     pub fn needs_analysis(&self) -> bool {
         use PpMode::*;
-        matches!(*self, Hir(PpHirMode::Typed) | Mir | Smir | MirCFG | ThirTree | ThirFlat)
+        matches!(*self, Hir(PpHirMode::Typed) | Mir | StableMir | MirCFG | ThirTree | ThirFlat)
     }
 }
 
diff --git a/compiler/rustc_smir/src/rustc_internal/pretty.rs b/compiler/rustc_smir/src/rustc_internal/pretty.rs
index 67995b1811046..1c2662fe85f20 100644
--- a/compiler/rustc_smir/src/rustc_internal/pretty.rs
+++ b/compiler/rustc_smir/src/rustc_internal/pretty.rs
@@ -15,22 +15,34 @@ pub fn write_smir_pretty<'tcx>(tcx: TyCtxt<'tcx>, w: &mut dyn io::Write) -> io::
 
     run(tcx, || {
         let items = stable_mir::all_local_items();
-        let _ = items.iter().map(|item| -> io::Result<()> {
-            // Because we can't return a Result from a closure, we have to unwrap here.
-            writeln!(w, "{}", function_name(*item, tcx))?;
-            writeln!(w, "{}", function_body(*item, tcx))?;
-            let _ = item.body().blocks.iter().enumerate().map(|(index, block)| -> io::Result<()> {
-                writeln!(w, "    bb{}: {{", index)?;
-                let _ = block.statements.iter().map(|statement| -> io::Result<()> {
-                    writeln!(w, "{}", pretty_statement(&statement.kind, tcx))?;
-                    Ok(())
-                }).collect::<Vec<_>>();
-                writeln!(w, "    }}").unwrap();
+        let _ = items
+            .iter()
+            .map(|item| -> io::Result<()> {
+                // Because we can't return a Result from a closure, we have to unwrap here.
+                writeln!(w, "{}", function_name(*item, tcx))?;
+                writeln!(w, "{}", function_body(*item, tcx))?;
+                let _ = item
+                    .body()
+                    .blocks
+                    .iter()
+                    .enumerate()
+                    .map(|(index, block)| -> io::Result<()> {
+                        writeln!(w, "    bb{}: {{", index)?;
+                        let _ = block
+                            .statements
+                            .iter()
+                            .map(|statement| -> io::Result<()> {
+                                writeln!(w, "{}", pretty_statement(&statement.kind, tcx))?;
+                                Ok(())
+                            })
+                            .collect::<Vec<_>>();
+                        writeln!(w, "    }}").unwrap();
+                        Ok(())
+                    })
+                    .collect::<Vec<_>>();
                 Ok(())
-            }).collect::<Vec<_>>();
-            Ok(())
-        }).collect::<Vec<_>>();
-        
+            })
+            .collect::<Vec<_>>();
     });
     Ok(())
 }

From 71c990470a958b14b78f9627d4aba2b1d6c79144 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?O=C4=9Fuz=20A=C4=9Fcayaz=C4=B1?= <ouz.agz@gmail.com>
Date: Wed, 15 Nov 2023 10:12:17 +0300
Subject: [PATCH 31/34] move pretty into stable_mir

---
 .../rustc_smir/src/rustc_internal/pretty.rs   | 310 +-----------------
 compiler/rustc_smir/src/rustc_smir/mod.rs     |   5 +-
 compiler/stable_mir/src/lib.rs                |   9 +-
 compiler/stable_mir/src/mir.rs                |   1 +
 compiler/stable_mir/src/mir/body.rs           |  27 +-
 compiler/stable_mir/src/mir/pretty.rs         | 261 +++++++++++++++
 6 files changed, 308 insertions(+), 305 deletions(-)
 create mode 100644 compiler/stable_mir/src/mir/pretty.rs

diff --git a/compiler/rustc_smir/src/rustc_internal/pretty.rs b/compiler/rustc_smir/src/rustc_internal/pretty.rs
index 1c2662fe85f20..19baf490a5d29 100644
--- a/compiler/rustc_smir/src/rustc_internal/pretty.rs
+++ b/compiler/rustc_smir/src/rustc_internal/pretty.rs
@@ -1,308 +1,20 @@
 use std::io;
 
+use super::run;
 use rustc_middle::ty::TyCtxt;
-use stable_mir::{
-    mir::{Mutability, Operand, Rvalue, StatementKind},
-    ty::{RigidTy, TyKind},
-    CrateItem,
-};
-
-use super::{internal, run};
-
-pub fn write_smir_pretty<'tcx>(tcx: TyCtxt<'tcx>, w: &mut dyn io::Write) -> io::Result<()> {
-    writeln!(w, "// WARNING: This is highly experimental output it's intended for stable-mir developers only.").unwrap();
-    writeln!(w, "// If you find a bug or want to improve the output open a issue at https://github.com/rust-lang/project-stable-mir.").unwrap();
 
+pub fn write_smir_pretty<'tcx, W: io::Write>(tcx: TyCtxt<'tcx>, w: &mut W) -> io::Result<()> {
+    writeln!(
+        w,
+        "// WARNING: This is highly experimental output it's intended for stable-mir developers only."
+    )?;
+    writeln!(
+        w,
+        "// If you find a bug or want to improve the output open a issue at https://github.com/rust-lang/project-stable-mir."
+    )?;
     run(tcx, || {
         let items = stable_mir::all_local_items();
-        let _ = items
-            .iter()
-            .map(|item| -> io::Result<()> {
-                // Because we can't return a Result from a closure, we have to unwrap here.
-                writeln!(w, "{}", function_name(*item, tcx))?;
-                writeln!(w, "{}", function_body(*item, tcx))?;
-                let _ = item
-                    .body()
-                    .blocks
-                    .iter()
-                    .enumerate()
-                    .map(|(index, block)| -> io::Result<()> {
-                        writeln!(w, "    bb{}: {{", index)?;
-                        let _ = block
-                            .statements
-                            .iter()
-                            .map(|statement| -> io::Result<()> {
-                                writeln!(w, "{}", pretty_statement(&statement.kind, tcx))?;
-                                Ok(())
-                            })
-                            .collect::<Vec<_>>();
-                        writeln!(w, "    }}").unwrap();
-                        Ok(())
-                    })
-                    .collect::<Vec<_>>();
-                Ok(())
-            })
-            .collect::<Vec<_>>();
+        let _ = items.iter().map(|item| -> io::Result<()> { item.dump(w) }).collect::<Vec<_>>();
     });
     Ok(())
 }
-
-pub fn function_name(item: CrateItem, tcx: TyCtxt<'_>) -> String {
-    let mut name = String::new();
-    let body = item.body();
-    name.push_str("fn ");
-    name.push_str(item.name().as_str());
-    if body.arg_locals().is_empty() {
-        name.push_str("()");
-    } else {
-        name.push_str("(");
-    }
-    body.arg_locals().iter().for_each(|local| {
-        name.push_str(format!("_{}: ", local.local).as_str());
-        name.push_str(&pretty_ty(local.ty.kind(), tcx));
-    });
-    if !body.arg_locals().is_empty() {
-        name.push_str(")");
-    }
-    let return_local = body.ret_local();
-    name.push_str(" -> ");
-    name.push_str(&pretty_ty(return_local.ty.kind(), tcx));
-    name.push_str(" {");
-    name
-}
-
-pub fn function_body(item: CrateItem, _tcx: TyCtxt<'_>) -> String {
-    let mut body_str = String::new();
-    let body = item.body();
-    body.inner_locals().iter().for_each(|local| {
-        body_str.push_str("    ");
-        body_str.push_str(format!("let {}", ret_mutability(&local.mutability)).as_str());
-        body_str.push_str(format!("_{}: ", local.local).as_str());
-        body_str.push_str(format!("{}", pretty_ty(local.ty.kind(), _tcx)).as_str());
-        body_str.push_str(";\n");
-    });
-    body_str.push_str("}");
-    body_str
-}
-
-pub fn ret_mutability(mutability: &Mutability) -> String {
-    match mutability {
-        Mutability::Not => "".to_string(),
-        Mutability::Mut => "mut ".to_string(),
-    }
-}
-
-pub fn pretty_statement(statement: &StatementKind, tcx: TyCtxt<'_>) -> String {
-    let mut pretty = String::new();
-    match statement {
-        StatementKind::Assign(place, rval) => {
-            pretty.push_str(format!("        _{} = ", place.local).as_str());
-            pretty.push_str(format!("{}", &pretty_rvalue(rval, tcx)).as_str());
-        }
-        StatementKind::FakeRead(_, _) => todo!(),
-        StatementKind::SetDiscriminant { .. } => todo!(),
-        StatementKind::Deinit(_) => todo!(),
-        StatementKind::StorageLive(_) => todo!(),
-        StatementKind::StorageDead(_) => todo!(),
-        StatementKind::Retag(_, _) => todo!(),
-        StatementKind::PlaceMention(_) => todo!(),
-        StatementKind::AscribeUserType { .. } => todo!(),
-        StatementKind::Coverage(_) => todo!(),
-        StatementKind::Intrinsic(_) => todo!(),
-        StatementKind::ConstEvalCounter => (),
-        StatementKind::Nop => (),
-    }
-    pretty
-}
-
-pub fn pretty_operand(operand: &Operand, _tcx: TyCtxt<'_>) -> String {
-    let mut pretty = String::new();
-    match operand {
-        Operand::Copy(copy) => {
-            pretty.push_str("");
-            pretty.push_str(format!("{}", copy.local).as_str());
-        }
-        Operand::Move(mv) => {
-            pretty.push_str("move ");
-            pretty.push_str(format!("_{}", mv.local).as_str());
-        }
-        Operand::Constant(cnst) => {
-            pretty.push_str("const ");
-            pretty.push_str(internal(&cnst.literal).to_string().as_str());
-        }
-    }
-    pretty
-}
-
-pub fn pretty_rvalue(rval: &Rvalue, tcx: TyCtxt<'_>) -> String {
-    let mut pretty = String::new();
-    match rval {
-        Rvalue::AddressOf(muta, addr) => {
-            pretty.push_str("&raw ");
-            pretty.push_str(&ret_mutability(&muta));
-            pretty.push_str(format!("(*_{})", addr.local).as_str());
-        }
-        Rvalue::Aggregate(aggregatekind, operands) => {
-            pretty.push_str(format!("{:#?}", aggregatekind).as_str());
-            pretty.push_str("(");
-            operands.iter().enumerate().for_each(|(i, op)| {
-                pretty.push_str(&pretty_operand(op, tcx));
-                if i != operands.len() - 1 {
-                    pretty.push_str(", ");
-                }
-            });
-            pretty.push_str(")");
-        }
-        Rvalue::BinaryOp(bin, op, op2) => {
-            pretty.push_str(&pretty_operand(op, tcx));
-            pretty.push_str(" ");
-            pretty.push_str(format!("{:#?}", bin).as_str());
-            pretty.push_str(" ");
-            pretty.push_str(&pretty_operand(op2, tcx));
-        }
-        Rvalue::Cast(_, op, ty) => {
-            pretty.push_str(&pretty_operand(op, tcx));
-            pretty.push_str(" as ");
-            pretty.push_str(&pretty_ty(ty.kind(), tcx));
-        }
-        Rvalue::CheckedBinaryOp(bin, op1, op2) => {
-            pretty.push_str(&pretty_operand(op1, tcx));
-            pretty.push_str(" ");
-            pretty.push_str(format!("{:#?}", bin).as_str());
-            pretty.push_str(" ");
-            pretty.push_str(&pretty_operand(op2, tcx));
-        }
-        Rvalue::CopyForDeref(deref) => {
-            pretty.push_str("CopyForDeref");
-            pretty.push_str(format!("{}", deref.local).as_str());
-        }
-        Rvalue::Discriminant(place) => {
-            pretty.push_str("discriminant");
-            pretty.push_str(format!("{}", place.local).as_str());
-        }
-        Rvalue::Len(len) => {
-            pretty.push_str("len");
-            pretty.push_str(format!("{}", len.local).as_str());
-        }
-        Rvalue::Ref(_, borrowkind, place) => {
-            pretty.push_str("ref");
-            pretty.push_str(format!("{:#?}", borrowkind).as_str());
-            pretty.push_str(format!("{}", place.local).as_str());
-        }
-        Rvalue::Repeat(op, cnst) => {
-            pretty.push_str(&pretty_operand(op, tcx));
-            pretty.push_str(" ");
-            pretty.push_str(&pretty_ty(cnst.ty().kind(), tcx));
-        }
-        Rvalue::ShallowInitBox(_, _) => todo!(),
-        Rvalue::ThreadLocalRef(item) => {
-            pretty.push_str("thread_local_ref");
-            pretty.push_str(format!("{:#?}", item).as_str());
-        }
-        Rvalue::NullaryOp(nul, ty) => {
-            pretty.push_str(format!("{:#?}", nul).as_str());
-            pretty.push_str(&&pretty_ty(ty.kind(), tcx));
-            pretty.push_str(" ");
-        }
-        Rvalue::UnaryOp(un, op) => {
-            pretty.push_str(&pretty_operand(op, tcx));
-            pretty.push_str(" ");
-            pretty.push_str(format!("{:#?}", un).as_str());
-        }
-        Rvalue::Use(op) => pretty.push_str(&pretty_operand(op, tcx)),
-    }
-    pretty
-}
-
-pub fn pretty_ty(ty: TyKind, tcx: TyCtxt<'_>) -> String {
-    let mut pretty = String::new();
-    pretty.push_str("");
-    match ty {
-        TyKind::RigidTy(rigid_ty) => match rigid_ty {
-            RigidTy::Bool => "bool".to_string(),
-            RigidTy::Char => "char".to_string(),
-            RigidTy::Int(i) => match i {
-                stable_mir::ty::IntTy::Isize => "isize".to_string(),
-                stable_mir::ty::IntTy::I8 => "i8".to_string(),
-                stable_mir::ty::IntTy::I16 => "i16".to_string(),
-                stable_mir::ty::IntTy::I32 => "i32".to_string(),
-                stable_mir::ty::IntTy::I64 => "i64".to_string(),
-                stable_mir::ty::IntTy::I128 => "i128".to_string(),
-            },
-            RigidTy::Uint(u) => match u {
-                stable_mir::ty::UintTy::Usize => "usize".to_string(),
-                stable_mir::ty::UintTy::U8 => "u8".to_string(),
-                stable_mir::ty::UintTy::U16 => "u16".to_string(),
-                stable_mir::ty::UintTy::U32 => "u32".to_string(),
-                stable_mir::ty::UintTy::U64 => "u64".to_string(),
-                stable_mir::ty::UintTy::U128 => "u128".to_string(),
-            },
-            RigidTy::Float(f) => match f {
-                stable_mir::ty::FloatTy::F32 => "f32".to_string(),
-                stable_mir::ty::FloatTy::F64 => "f64".to_string(),
-            },
-            RigidTy::Adt(def, _) => {
-                format!("{}", tcx.type_of(internal(&def.0)).instantiate_identity())
-            }
-            RigidTy::Foreign(_) => format!("{:#?}", rigid_ty),
-            RigidTy::Str => "str".to_string(),
-            RigidTy::Array(ty, len) => {
-                format!(
-                    "[{}; {}]",
-                    pretty_ty(ty.kind(), tcx),
-                    internal(&len).try_to_scalar().unwrap()
-                )
-            }
-            RigidTy::Slice(ty) => {
-                format!("[{}]", pretty_ty(ty.kind(), tcx))
-            }
-            RigidTy::RawPtr(ty, mutability) => {
-                pretty.push_str("*");
-                match mutability {
-                    Mutability::Not => pretty.push_str("const "),
-                    Mutability::Mut => pretty.push_str("mut "),
-                }
-                pretty.push_str(&pretty_ty(ty.kind(), tcx));
-                pretty
-            }
-            RigidTy::Ref(_, ty, _) => pretty_ty(ty.kind(), tcx),
-            RigidTy::FnDef(_, _) => format!("{:#?}", rigid_ty),
-            RigidTy::FnPtr(_) => format!("{:#?}", rigid_ty),
-            RigidTy::Closure(_, _) => format!("{:#?}", rigid_ty),
-            RigidTy::Coroutine(_, _, _) => format!("{:#?}", rigid_ty),
-            RigidTy::Dynamic(data, region, repr) => {
-                // FIXME: Fix binder printing, it looks ugly now
-                pretty.push_str("(");
-                match repr {
-                    stable_mir::ty::DynKind::Dyn => pretty.push_str("dyn "),
-                    stable_mir::ty::DynKind::DynStar => pretty.push_str("dyn* "),
-                }
-                pretty.push_str(format!("{:#?}", data).as_str());
-                pretty.push_str(format!(" +  {:#?} )", region).as_str());
-                pretty
-            }
-            RigidTy::Never => "!".to_string(),
-            RigidTy::Tuple(tuple) => {
-                if tuple.is_empty() {
-                    "()".to_string()
-                } else {
-                    let mut tuple_str = String::new();
-                    tuple_str.push_str("(");
-                    tuple.iter().enumerate().for_each(|(i, ty)| {
-                        tuple_str.push_str(&pretty_ty(ty.kind(), tcx));
-                        if i != tuple.len() - 1 {
-                            tuple_str.push_str(", ");
-                        }
-                    });
-                    tuple_str.push_str(")");
-                    tuple_str
-                }
-            }
-        },
-        TyKind::Alias(_, _) => format!("{:#?}", ty),
-        TyKind::Param(param_ty) => {
-            format!("{:#?}", param_ty.name)
-        }
-        TyKind::Bound(_, _) => format!("{:#?}", ty),
-    }
-}
diff --git a/compiler/rustc_smir/src/rustc_smir/mod.rs b/compiler/rustc_smir/src/rustc_smir/mod.rs
index 69b0c0bb80d55..69e556ff3ec5a 100644
--- a/compiler/rustc_smir/src/rustc_smir/mod.rs
+++ b/compiler/rustc_smir/src/rustc_smir/mod.rs
@@ -400,11 +400,10 @@ impl<'tcx> Stable<'tcx> for mir::Body<'tcx> {
                 })
                 .collect(),
             self.local_decls
-                .iter_enumerated()
-                .map(|(local, decl)| stable_mir::mir::LocalDecl {
+                .iter()
+                .map(|decl| stable_mir::mir::LocalDecl {
                     ty: decl.ty.stable(tables),
                     span: decl.source_info.span.stable(tables),
-                    local: local.as_usize(),
                     mutability: decl.mutability.stable(tables),
                 })
                 .collect(),
diff --git a/compiler/stable_mir/src/lib.rs b/compiler/stable_mir/src/lib.rs
index 0262fb536e785..dca43a2c090d7 100644
--- a/compiler/stable_mir/src/lib.rs
+++ b/compiler/stable_mir/src/lib.rs
@@ -19,9 +19,9 @@
 
 use crate::mir::mono::InstanceDef;
 use crate::mir::Body;
-use std::cell::Cell;
 use std::fmt;
 use std::fmt::Debug;
+use std::{cell::Cell, io};
 
 use self::ty::{
     GenericPredicates, Generics, ImplDef, ImplTrait, IndexedVal, LineInfo, Span, TraitDecl,
@@ -37,6 +37,8 @@ pub mod ty;
 pub mod visitor;
 
 use crate::ty::{AdtDef, AdtKind, ClosureDef, ClosureKind};
+use crate::mir::pretty::function_name;
+use crate::mir::Mutability;
 pub use error::*;
 use mir::mono::Instance;
 use ty::{FnDef, GenericArgs};
@@ -137,6 +139,11 @@ impl CrateItem {
     pub fn ty(&self) -> Ty {
         with(|cx| cx.def_ty(self.0))
     }
+    
+    pub fn dump<W: io::Write>(&self, w: &mut W) -> io::Result<()> {
+        writeln!(w, "{}", function_name(*self))?;
+        self.body().dump(w)
+    }
 }
 
 /// Return the function where execution starts if the current
diff --git a/compiler/stable_mir/src/mir.rs b/compiler/stable_mir/src/mir.rs
index 2e1714b49c184..2cbe6eb4ad117 100644
--- a/compiler/stable_mir/src/mir.rs
+++ b/compiler/stable_mir/src/mir.rs
@@ -1,5 +1,6 @@
 mod body;
 pub mod mono;
+pub mod pretty;
 pub mod visit;
 
 pub use body::*;
diff --git a/compiler/stable_mir/src/mir/body.rs b/compiler/stable_mir/src/mir/body.rs
index 2981d6a8bb5c6..b1ba8b97418e7 100644
--- a/compiler/stable_mir/src/mir/body.rs
+++ b/compiler/stable_mir/src/mir/body.rs
@@ -1,7 +1,8 @@
+use crate::mir::pretty::{function_body, pretty_statement};
 use crate::ty::{AdtDef, ClosureDef, Const, CoroutineDef, GenericArgs, Movability, Region, Ty};
 use crate::Opaque;
 use crate::Span;
-
+use std::io;
 /// The SMIR representation of a single function.
 #[derive(Clone, Debug)]
 pub struct Body {
@@ -56,6 +57,29 @@ impl Body {
     pub fn locals(&self) -> &[LocalDecl] {
         &self.locals
     }
+
+    pub fn dump<W: io::Write>(&self, w: &mut W) -> io::Result<()> {
+        writeln!(w, "{}", function_body(self))?;
+        let _ = self
+            .blocks
+            .iter()
+            .enumerate()
+            .map(|(index, block)| -> io::Result<()> {
+                writeln!(w, "    bb{}: {{", index)?;
+                let _ = block
+                    .statements
+                    .iter()
+                    .map(|statement| -> io::Result<()> {
+                        writeln!(w, "{}", pretty_statement(&statement.kind))?;
+                        Ok(())
+                    })
+                    .collect::<Vec<_>>();
+                writeln!(w, "    }}").unwrap();
+                Ok(())
+            })
+            .collect::<Vec<_>>();
+        Ok(())
+    }
 }
 
 type LocalDecls = Vec<LocalDecl>;
@@ -64,7 +88,6 @@ type LocalDecls = Vec<LocalDecl>;
 pub struct LocalDecl {
     pub ty: Ty,
     pub span: Span,
-    pub local: Local,
     pub mutability: Mutability,
 }
 
diff --git a/compiler/stable_mir/src/mir/pretty.rs b/compiler/stable_mir/src/mir/pretty.rs
new file mode 100644
index 0000000000000..2bdcabb1bf522
--- /dev/null
+++ b/compiler/stable_mir/src/mir/pretty.rs
@@ -0,0 +1,261 @@
+use crate::mir::{Operand, Rvalue, StatementKind};
+use crate::ty::{DynKind, FloatTy, IntTy, RigidTy, TyKind, UintTy};
+use crate::{Body, CrateItem, Mutability};
+
+pub fn function_name(item: CrateItem) -> String {
+    let mut pretty_name = String::new();
+    let body = item.body();
+    pretty_name.push_str("fn ");
+    pretty_name.push_str(item.name().as_str());
+    if body.arg_locals().is_empty() {
+        pretty_name.push_str("()");
+    } else {
+        pretty_name.push_str("(");
+    }
+    body.arg_locals().iter().enumerate().for_each(|(index, local)| {
+        pretty_name.push_str(format!("_{}: ", index).as_str());
+        pretty_name.push_str(&pretty_ty(local.ty.kind()));
+    });
+    if !body.arg_locals().is_empty() {
+        pretty_name.push_str(")");
+    }
+    let return_local = body.ret_local();
+    pretty_name.push_str(" -> ");
+    pretty_name.push_str(&pretty_ty(return_local.ty.kind()));
+    pretty_name.push_str(" {");
+    pretty_name
+}
+
+pub fn function_body(body: &Body) -> String {
+    let mut pretty_body = String::new();
+    body.inner_locals().iter().enumerate().for_each(|(index, local)| {
+        pretty_body.push_str("    ");
+        pretty_body.push_str(format!("let {}", ret_mutability(&local.mutability)).as_str());
+        pretty_body.push_str(format!("_{}: ", index).as_str());
+        pretty_body.push_str(format!("{}", pretty_ty(local.ty.kind())).as_str());
+        pretty_body.push_str(";\n");
+    });
+    pretty_body.push_str("}");
+    pretty_body
+}
+
+pub fn ret_mutability(mutability: &Mutability) -> String {
+    match mutability {
+        Mutability::Not => "".to_string(),
+        Mutability::Mut => "mut ".to_string(),
+    }
+}
+
+pub fn pretty_statement(statement: &StatementKind) -> String {
+    let mut pretty = String::new();
+    match statement {
+        StatementKind::Assign(place, rval) => {
+            pretty.push_str(format!("        _{} = ", place.local).as_str());
+            pretty.push_str(format!("{}", &pretty_rvalue(rval)).as_str());
+        }
+        StatementKind::FakeRead(_, _) => todo!(),
+        StatementKind::SetDiscriminant { .. } => todo!(),
+        StatementKind::Deinit(_) => todo!(),
+        StatementKind::StorageLive(_) => todo!(),
+        StatementKind::StorageDead(_) => todo!(),
+        StatementKind::Retag(_, _) => todo!(),
+        StatementKind::PlaceMention(_) => todo!(),
+        StatementKind::AscribeUserType { .. } => todo!(),
+        StatementKind::Coverage(_) => todo!(),
+        StatementKind::Intrinsic(_) => todo!(),
+        StatementKind::ConstEvalCounter => (),
+        StatementKind::Nop => (),
+    }
+    pretty
+}
+
+pub fn pretty_operand(operand: &Operand) -> String {
+    let mut pretty = String::new();
+    match operand {
+        Operand::Copy(copy) => {
+            pretty.push_str("");
+            pretty.push_str(format!("{}", copy.local).as_str());
+        }
+        Operand::Move(mv) => {
+            pretty.push_str("move ");
+            pretty.push_str(format!("_{}", mv.local).as_str());
+        }
+        Operand::Constant(_) => {
+            // FIXME: Once https://github.com/rust-lang/rust/pull/117688 we will have ability to replace this
+            pretty.push_str("const ");
+            //pretty.push_str(internal(&cnst.literal).to_string().as_str());
+        }
+    }
+    pretty
+}
+
+pub fn pretty_rvalue(rval: &Rvalue) -> String {
+    let mut pretty = String::new();
+    match rval {
+        Rvalue::AddressOf(muta, addr) => {
+            pretty.push_str("&raw ");
+            pretty.push_str(&ret_mutability(&muta));
+            pretty.push_str(format!("(*_{})", addr.local).as_str());
+        }
+        Rvalue::Aggregate(aggregatekind, operands) => {
+            pretty.push_str(format!("{:#?}", aggregatekind).as_str());
+            pretty.push_str("(");
+            operands.iter().enumerate().for_each(|(i, op)| {
+                pretty.push_str(&pretty_operand(op));
+                if i != operands.len() - 1 {
+                    pretty.push_str(", ");
+                }
+            });
+            pretty.push_str(")");
+        }
+        Rvalue::BinaryOp(bin, op, op2) => {
+            pretty.push_str(&pretty_operand(op));
+            pretty.push_str(" ");
+            pretty.push_str(format!("{:#?}", bin).as_str());
+            pretty.push_str(" ");
+            pretty.push_str(&pretty_operand(op2));
+        }
+        Rvalue::Cast(_, op, ty) => {
+            pretty.push_str(&pretty_operand(op));
+            pretty.push_str(" as ");
+            pretty.push_str(&pretty_ty(ty.kind()));
+        }
+        Rvalue::CheckedBinaryOp(bin, op1, op2) => {
+            pretty.push_str(&pretty_operand(op1));
+            pretty.push_str(" ");
+            pretty.push_str(format!("{:#?}", bin).as_str());
+            pretty.push_str(" ");
+            pretty.push_str(&pretty_operand(op2));
+        }
+        Rvalue::CopyForDeref(deref) => {
+            pretty.push_str("CopyForDeref");
+            pretty.push_str(format!("{}", deref.local).as_str());
+        }
+        Rvalue::Discriminant(place) => {
+            pretty.push_str("discriminant");
+            pretty.push_str(format!("{}", place.local).as_str());
+        }
+        Rvalue::Len(len) => {
+            pretty.push_str("len");
+            pretty.push_str(format!("{}", len.local).as_str());
+        }
+        Rvalue::Ref(_, borrowkind, place) => {
+            pretty.push_str("ref");
+            pretty.push_str(format!("{:#?}", borrowkind).as_str());
+            pretty.push_str(format!("{}", place.local).as_str());
+        }
+        Rvalue::Repeat(op, cnst) => {
+            pretty.push_str(&pretty_operand(op));
+            pretty.push_str(" ");
+            pretty.push_str(&pretty_ty(cnst.ty().kind()));
+        }
+        Rvalue::ShallowInitBox(_, _) => todo!(),
+        Rvalue::ThreadLocalRef(item) => {
+            pretty.push_str("thread_local_ref");
+            pretty.push_str(format!("{:#?}", item).as_str());
+        }
+        Rvalue::NullaryOp(nul, ty) => {
+            pretty.push_str(format!("{:#?}", nul).as_str());
+            pretty.push_str(&&pretty_ty(ty.kind()));
+            pretty.push_str(" ");
+        }
+        Rvalue::UnaryOp(un, op) => {
+            pretty.push_str(&pretty_operand(op));
+            pretty.push_str(" ");
+            pretty.push_str(format!("{:#?}", un).as_str());
+        }
+        Rvalue::Use(op) => pretty.push_str(&pretty_operand(op)),
+    }
+    pretty
+}
+
+pub fn pretty_ty(ty: TyKind) -> String {
+    let mut pretty = String::new();
+    pretty.push_str("");
+    match ty {
+        TyKind::RigidTy(rigid_ty) => match rigid_ty {
+            RigidTy::Bool => "bool".to_string(),
+            RigidTy::Char => "char".to_string(),
+            RigidTy::Int(i) => match i {
+                IntTy::Isize => "isize".to_string(),
+                IntTy::I8 => "i8".to_string(),
+                IntTy::I16 => "i16".to_string(),
+                IntTy::I32 => "i32".to_string(),
+                IntTy::I64 => "i64".to_string(),
+                IntTy::I128 => "i128".to_string(),
+            },
+            RigidTy::Uint(u) => match u {
+                UintTy::Usize => "usize".to_string(),
+                UintTy::U8 => "u8".to_string(),
+                UintTy::U16 => "u16".to_string(),
+                UintTy::U32 => "u32".to_string(),
+                UintTy::U64 => "u64".to_string(),
+                UintTy::U128 => "u128".to_string(),
+            },
+            RigidTy::Float(f) => match f {
+                FloatTy::F32 => "f32".to_string(),
+                FloatTy::F64 => "f64".to_string(),
+            },
+            RigidTy::Adt(_, _) => {
+                // FIXME: Once https://github.com/rust-lang/rust/pull/117688 we will have ability to replace this
+                format!("{rigid_ty:#?}")
+            }
+            RigidTy::Str => "str".to_string(),
+            RigidTy::Array(ty, len) => {
+                // FIXME: Once https://github.com/rust-lang/rust/pull/117688 we will have ability to replace this
+                format!("[{}; {:#?}]", pretty_ty(ty.kind()), len)
+            }
+            RigidTy::Slice(ty) => {
+                format!("[{}]", pretty_ty(ty.kind()))
+            }
+            RigidTy::RawPtr(ty, mutability) => {
+                pretty.push_str("*");
+                match mutability {
+                    Mutability::Not => pretty.push_str("const "),
+                    Mutability::Mut => pretty.push_str("mut "),
+                }
+                pretty.push_str(&pretty_ty(ty.kind()));
+                pretty
+            }
+            RigidTy::Ref(_, ty, _) => pretty_ty(ty.kind()),
+            RigidTy::FnDef(_, _) => format!("{:#?}", rigid_ty),
+            RigidTy::FnPtr(_) => format!("{:#?}", rigid_ty),
+            RigidTy::Closure(_, _) => format!("{:#?}", rigid_ty),
+            RigidTy::Coroutine(_, _, _) => format!("{:#?}", rigid_ty),
+            RigidTy::Dynamic(data, region, repr) => {
+                // FIXME: Fix binder printing, it looks ugly now
+                pretty.push_str("(");
+                match repr {
+                    DynKind::Dyn => pretty.push_str("dyn "),
+                    DynKind::DynStar => pretty.push_str("dyn* "),
+                }
+                pretty.push_str(format!("{:#?}", data).as_str());
+                pretty.push_str(format!(" +  {:#?} )", region).as_str());
+                pretty
+            }
+            RigidTy::Never => "!".to_string(),
+            RigidTy::Tuple(tuple) => {
+                if tuple.is_empty() {
+                    "()".to_string()
+                } else {
+                    let mut tuple_str = String::new();
+                    tuple_str.push_str("(");
+                    tuple.iter().enumerate().for_each(|(i, ty)| {
+                        tuple_str.push_str(&pretty_ty(ty.kind()));
+                        if i != tuple.len() - 1 {
+                            tuple_str.push_str(", ");
+                        }
+                    });
+                    tuple_str.push_str(")");
+                    tuple_str
+                }
+            }
+            _ => format!("{:#?}", rigid_ty),
+        },
+        TyKind::Alias(_, _) => format!("{:#?}", ty),
+        TyKind::Param(param_ty) => {
+            format!("{:#?}", param_ty.name)
+        }
+        TyKind::Bound(_, _) => format!("{:#?}", ty),
+    }
+}

From 3b0e1d23b7fff6b57a634f529ee19d0d173a95f7 Mon Sep 17 00:00:00 2001
From: lcnr <rust@lcnr.de>
Date: Fri, 17 Nov 2023 11:03:40 +0000
Subject: [PATCH 32/34] only free lifetimes may get erased

---
 library/core/src/mem/mod.rs | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/library/core/src/mem/mod.rs b/library/core/src/mem/mod.rs
index b810318fe7d3d..bf10ada0176c2 100644
--- a/library/core/src/mem/mod.rs
+++ b/library/core/src/mem/mod.rs
@@ -1132,10 +1132,12 @@ impl<T> fmt::Debug for Discriminant<T> {
 ///
 /// [Reference]: ../../reference/items/enumerations.html#custom-discriminant-values-for-fieldless-enumerations
 ///
-/// The value of a [`Discriminant<T>`] is independent of any *lifetimes* in `T`. As such, reading
-/// or writing a `Discriminant<Foo<'a>>` as a `Discriminant<Foo<'b>>` (whether via [`transmute`] or
-/// otherwise) is always sound. Note that this is **not** true for other kinds of generic
-/// parameters; `Discriminant<Foo<A>>` and `Discriminant<Foo<B>>` might be incompatible.
+/// The value of a [`Discriminant<T>`] is independent of any *free lifetimes* in `T`. As such,
+/// reading or writing a `Discriminant<Foo<'a>>` as a `Discriminant<Foo<'b>>` (whether via
+/// [`transmute`] or otherwise) is always sound. Note that this is **not** true for other kinds
+/// of generic parameters and for higher-ranked lifetimes; `Discriminant<Foo<A>>` and
+/// `Discriminant<Foo<B>>` as well as `Discriminant<Bar<dyn for<'a> Trait<'a>>>` and
+/// `Discriminant<Bar<dyn Trait<'static>>>` may be incompatible.
 ///
 /// # Examples
 ///

From 99371ce7e02d8760c255458b93c9696af9f0976c Mon Sep 17 00:00:00 2001
From: "Celina G. Val" <celinval@amazon.com>
Date: Fri, 17 Nov 2023 11:46:39 -0800
Subject: [PATCH 33/34] Add stable mir members to triagebot config

---
 triagebot.toml | 9 +++++++++
 1 file changed, 9 insertions(+)

diff --git a/triagebot.toml b/triagebot.toml
index 4c8c1c59beba4..a72338d19505a 100644
--- a/triagebot.toml
+++ b/triagebot.toml
@@ -713,6 +713,13 @@ style-team = [
     "@yaahc",
 ]
 
+project-stable-mir = [
+    "@celinval",
+    "@oli-obk",
+    "@spastorino",
+    "@ouz-a",
+]
+
 [assign.owners]
 "/.github/workflows" =                       ["infra-ci"]
 "/Cargo.lock" =                              ["@Mark-Simulacrum"]
@@ -729,6 +736,7 @@ style-team = [
 "/compiler/rustc_const_eval/src/interpret" = ["compiler", "mir"]
 "/compiler/rustc_const_eval/src/transform" = ["compiler", "mir-opt"]
 "/compiler/rustc_mir_build/src/build" =      ["compiler", "mir"]
+"/compiler/rustc_smir" =                     ["project-stable-mir"]
 "/compiler/rustc_parse" =                    ["compiler", "parser"]
 "/compiler/rustc_parse/src/lexer" =          ["compiler", "lexer"]
 "/compiler/rustc_query_impl" =               ["compiler", "query-system"]
@@ -736,6 +744,7 @@ style-team = [
 "/compiler/rustc_trait_selection" =          ["compiler", "types"]
 "/compiler/rustc_traits" =                   ["compiler", "types"]
 "/compiler/rustc_type_ir" =                  ["compiler", "types"]
+"/compiler/stable_mir" =                     ["project-stable-mir"]
 "/library/alloc" =                           ["libs"]
 "/library/core" =                            ["libs"]
 "/library/panic_abort" =                     ["libs"]

From 92657f163ac3c30af2652c8c7ba5ee7edb14ba01 Mon Sep 17 00:00:00 2001
From: ouz-a <ouz.agz@gmail.com>
Date: Fri, 17 Nov 2023 14:03:54 +0300
Subject: [PATCH 34/34] use new apis and add new function

---
 compiler/rustc_smir/src/rustc_internal/pretty.rs |  2 +-
 compiler/rustc_smir/src/rustc_smir/mod.rs        |  6 +++++-
 compiler/stable_mir/src/lib.rs                   |  9 ++++++---
 compiler/stable_mir/src/mir/body.rs              |  5 ++---
 compiler/stable_mir/src/mir/pretty.rs            | 15 ++++++---------
 5 files changed, 20 insertions(+), 17 deletions(-)

diff --git a/compiler/rustc_smir/src/rustc_internal/pretty.rs b/compiler/rustc_smir/src/rustc_internal/pretty.rs
index 19baf490a5d29..3ef2d28ea4734 100644
--- a/compiler/rustc_smir/src/rustc_internal/pretty.rs
+++ b/compiler/rustc_smir/src/rustc_internal/pretty.rs
@@ -12,7 +12,7 @@ pub fn write_smir_pretty<'tcx, W: io::Write>(tcx: TyCtxt<'tcx>, w: &mut W) -> io
         w,
         "// If you find a bug or want to improve the output open a issue at https://github.com/rust-lang/project-stable-mir."
     )?;
-    run(tcx, || {
+    let _ = run(tcx, || {
         let items = stable_mir::all_local_items();
         let _ = items.iter().map(|item| -> io::Result<()> { item.dump(w) }).collect::<Vec<_>>();
     });
diff --git a/compiler/rustc_smir/src/rustc_smir/mod.rs b/compiler/rustc_smir/src/rustc_smir/mod.rs
index 69e556ff3ec5a..89dbf40c7b4d0 100644
--- a/compiler/rustc_smir/src/rustc_smir/mod.rs
+++ b/compiler/rustc_smir/src/rustc_smir/mod.rs
@@ -7,7 +7,7 @@
 //!
 //! For now, we are developing everything inside `rustc`, thus, we keep this module private.
 
-use crate::rustc_internal::{IndexMap, RustcInternal};
+use crate::rustc_internal::{internal, IndexMap, RustcInternal};
 use crate::rustc_smir::stable_mir::ty::{BoundRegion, Region};
 use rustc_hir as hir;
 use rustc_hir::def::DefKind;
@@ -105,6 +105,10 @@ impl<'tcx> Context for TablesWrapper<'tcx> {
         tables.tcx.type_of(item.internal(&mut *tables)).instantiate_identity().stable(&mut *tables)
     }
 
+    fn const_literal(&self, cnst: &stable_mir::ty::Const) -> String {
+        internal(cnst).to_string()
+    }
+
     fn span_of_an_item(&self, def_id: stable_mir::DefId) -> Span {
         let mut tables = self.0.borrow_mut();
         tables.tcx.def_span(tables[def_id]).stable(&mut *tables)
diff --git a/compiler/stable_mir/src/lib.rs b/compiler/stable_mir/src/lib.rs
index dca43a2c090d7..79102dcce3585 100644
--- a/compiler/stable_mir/src/lib.rs
+++ b/compiler/stable_mir/src/lib.rs
@@ -36,12 +36,12 @@ pub mod mir;
 pub mod ty;
 pub mod visitor;
 
-use crate::ty::{AdtDef, AdtKind, ClosureDef, ClosureKind};
 use crate::mir::pretty::function_name;
 use crate::mir::Mutability;
+use crate::ty::{AdtDef, AdtKind, ClosureDef, ClosureKind};
 pub use error::*;
 use mir::mono::Instance;
-use ty::{FnDef, GenericArgs};
+use ty::{Const, FnDef, GenericArgs};
 
 /// Use String for now but we should replace it.
 pub type Symbol = String;
@@ -139,7 +139,7 @@ impl CrateItem {
     pub fn ty(&self) -> Ty {
         with(|cx| cx.def_ty(self.0))
     }
-    
+
     pub fn dump<W: io::Write>(&self, w: &mut W) -> io::Result<()> {
         writeln!(w, "{}", function_name(*self))?;
         self.body().dump(w)
@@ -230,6 +230,9 @@ pub trait Context {
     /// Returns the type of given crate item.
     fn def_ty(&self, item: DefId) -> Ty;
 
+    /// Returns literal value of a const as a string.
+    fn const_literal(&self, cnst: &Const) -> String;
+
     /// `Span` of an item
     fn span_of_an_item(&self, def_id: DefId) -> Span;
 
diff --git a/compiler/stable_mir/src/mir/body.rs b/compiler/stable_mir/src/mir/body.rs
index b1ba8b97418e7..fa58a7ffe1554 100644
--- a/compiler/stable_mir/src/mir/body.rs
+++ b/compiler/stable_mir/src/mir/body.rs
@@ -60,8 +60,7 @@ impl Body {
 
     pub fn dump<W: io::Write>(&self, w: &mut W) -> io::Result<()> {
         writeln!(w, "{}", function_body(self))?;
-        let _ = self
-            .blocks
+        self.blocks
             .iter()
             .enumerate()
             .map(|(index, block)| -> io::Result<()> {
@@ -77,7 +76,7 @@ impl Body {
                 writeln!(w, "    }}").unwrap();
                 Ok(())
             })
-            .collect::<Vec<_>>();
+            .collect::<Result<Vec<_>, _>>()?;
         Ok(())
     }
 }
diff --git a/compiler/stable_mir/src/mir/pretty.rs b/compiler/stable_mir/src/mir/pretty.rs
index 2bdcabb1bf522..e52c3360ce425 100644
--- a/compiler/stable_mir/src/mir/pretty.rs
+++ b/compiler/stable_mir/src/mir/pretty.rs
@@ -1,6 +1,6 @@
 use crate::mir::{Operand, Rvalue, StatementKind};
 use crate::ty::{DynKind, FloatTy, IntTy, RigidTy, TyKind, UintTy};
-use crate::{Body, CrateItem, Mutability};
+use crate::{with, Body, CrateItem, Mutability};
 
 pub fn function_name(item: CrateItem) -> String {
     let mut pretty_name = String::new();
@@ -80,10 +80,9 @@ pub fn pretty_operand(operand: &Operand) -> String {
             pretty.push_str("move ");
             pretty.push_str(format!("_{}", mv.local).as_str());
         }
-        Operand::Constant(_) => {
-            // FIXME: Once https://github.com/rust-lang/rust/pull/117688 we will have ability to replace this
+        Operand::Constant(cnst) => {
             pretty.push_str("const ");
-            //pretty.push_str(internal(&cnst.literal).to_string().as_str());
+            pretty.push_str(with(|cx| cx.const_literal(&cnst.literal)).as_str());
         }
     }
     pretty
@@ -196,14 +195,12 @@ pub fn pretty_ty(ty: TyKind) -> String {
                 FloatTy::F32 => "f32".to_string(),
                 FloatTy::F64 => "f64".to_string(),
             },
-            RigidTy::Adt(_, _) => {
-                // FIXME: Once https://github.com/rust-lang/rust/pull/117688 we will have ability to replace this
-                format!("{rigid_ty:#?}")
+            RigidTy::Adt(def, _) => {
+                format!("{:#?}", with(|cx| cx.def_ty(def.0)))
             }
             RigidTy::Str => "str".to_string(),
             RigidTy::Array(ty, len) => {
-                // FIXME: Once https://github.com/rust-lang/rust/pull/117688 we will have ability to replace this
-                format!("[{}; {:#?}]", pretty_ty(ty.kind()), len)
+                format!("[{}; {}]", pretty_ty(ty.kind()), with(|cx| cx.const_literal(&len)))
             }
             RigidTy::Slice(ty) => {
                 format!("[{}]", pretty_ty(ty.kind()))