@@ -106,6 +106,51 @@ pub const unsafe fn unreachable_unchecked() -> ! {
106
106
}
107
107
}
108
108
109
+ /// Makes a *soundness* promise to the compiler that `cond` holds.
110
+ ///
111
+ /// This may allow the optimizer to simplify things,
112
+ /// but it might also make the generated code slower.
113
+ /// Either way, calling it will most likely make compilation take longer.
114
+ ///
115
+ /// This is a situational tool for micro-optimization, and is allowed to do nothing.
116
+ /// Any use should come with a repeatable benchmark to show the value
117
+ /// and allow removing it later should the optimizer get smarter and no longer need it.
118
+ ///
119
+ /// The more complicated the condition the less likely this is to be fruitful.
120
+ /// For example, `assert_unchecked(foo.is_sorted())` is a complex enough value
121
+ /// that the compiler is unlikely to be able to take advantage of it.
122
+ ///
123
+ /// There's also no need to `assert_unchecked` basic properties of things. For
124
+ /// example, the compiler already knows the range of `count_ones`, so there's no
125
+ /// benefit to `let n = u32::count_ones(x); assert_unchecked(n <= u32::BITS);`.
126
+ ///
127
+ /// You may know this from other places
128
+ /// as [`llvm.assume`](https://llvm.org/docs/LangRef.html#llvm-assume-intrinsic)
129
+ /// or [`__builtin_assume`](https://clang.llvm.org/docs/LanguageExtensions.html#builtin-assume).
130
+ ///
131
+ /// This promotes a correctness requirement to a soundness requirement.
132
+ /// Don't do that without very good reason.
133
+ ///
134
+ /// # Safety
135
+ ///
136
+ /// `cond` must be `true`. It's immediate UB to call this with `false`.
137
+ ///
138
+ #[ inline( always) ]
139
+ #[ doc( alias = "assume" ) ]
140
+ #[ track_caller]
141
+ #[ unstable( feature = "hint_assert_unchecked" , issue = "119131" ) ]
142
+ #[ rustc_const_unstable( feature = "const_hint_assert_unchecked" , issue = "119131" ) ]
143
+ pub const unsafe fn assert_unchecked ( cond : bool ) {
144
+ // SAFETY: The caller promised `cond` is true.
145
+ unsafe {
146
+ intrinsics:: assert_unsafe_precondition!(
147
+ "hint::assert_unchecked must never be called when the condition is false" ,
148
+ ( cond: bool ) => cond,
149
+ ) ;
150
+ crate :: intrinsics:: assume ( cond) ;
151
+ }
152
+ }
153
+
109
154
/// Emits a machine instruction to signal the processor that it is running in
110
155
/// a busy-wait spin-loop ("spin lock").
111
156
///
0 commit comments