@@ -129,6 +129,41 @@ impl<'tcx> ConstReader<'tcx> {
129129 interp_ok ( bytes)
130130 }
131131
132+ /// If the array `op` is made of two or more copies of one value, the number of copies. This
133+ /// compares raw bytes, so that large arrays aren't read element by element; arrays with
134+ /// uninitialized bytes or pointers are conservatively not repeats.
135+ fn repeat_count (
136+ & self ,
137+ ecx : & CompileTimeInterpCx < ' tcx > ,
138+ op : & OpTy < ' tcx > ,
139+ ) -> InterpResult < ' tcx , Option < u64 > > {
140+ let Some ( mplace) = op. as_mplace_or_imm ( ) . left ( ) else {
141+ return interp_ok ( None ) ;
142+ } ;
143+ let count = mplace. len ( ecx) ?;
144+ if count < 2 {
145+ return interp_ok ( None ) ;
146+ }
147+ let size = mplace. layout . size ;
148+ // Zero-sized values are all equal.
149+ if size. bytes ( ) == 0 {
150+ return interp_ok ( Some ( count) ) ;
151+ }
152+ let ( alloc_id, offset, _) = ecx. ptr_get_alloc_id ( mplace. ptr ( ) , size. bytes ( ) as i64 ) ?;
153+ let alloc = ecx. get_alloc_raw ( alloc_id) ?;
154+ let range = interpret:: alloc_range ( offset, size) ;
155+ if alloc. init_mask ( ) . is_range_initialized ( range) . is_err ( )
156+ || !alloc. provenance ( ) . range_empty ( range, ecx)
157+ {
158+ return interp_ok ( None ) ;
159+ }
160+ // The elements are all equal iff the bytes are equal to themselves shifted by one element.
161+ let elem_size = ( size. bytes ( ) / count) as usize ;
162+ let bytes = alloc. get_bytes_unchecked ( range) ;
163+ let is_repeat = bytes[ elem_size..] == bytes[ ..bytes. len ( ) - elem_size] ;
164+ interp_ok ( is_repeat. then_some ( count) )
165+ }
166+
132167 /// The sized type that `tail`, the unsized tail of `place`, was unsized from. This is found in
133168 /// the metadata of the place.
134169 pub ( crate ) fn sized_tail (
@@ -250,6 +285,13 @@ impl<'tcx> ConstReader<'tcx> {
250285 variant : None ,
251286 fields : read_fields ( op, args. len ( ) ) ?,
252287 } ,
288+ ty:: Array ( ..) if let Some ( count) = self . repeat_count ( ecx, & op) ? => {
289+ let value = self . read_op ( ecx, ecx. project_index ( & op, 0 ) ?) ?;
290+ ConstKind :: Repeat {
291+ value : Box :: new ( value) ,
292+ count,
293+ }
294+ }
253295 ty:: Array ( ..) | ty:: Slice ( ..) => {
254296 let mut elems = ecx. project_array_fields ( & op) ?;
255297 let mut fields = vec ! [ ] ;
0 commit comments