1 use crate::config::Config;
2 use crate::cranelift_arbitrary::CraneliftArbitrary;
3 use crate::target_isa_extras::TargetIsaExtras;
4 use anyhow::Result;
5 use arbitrary::{Arbitrary, Unstructured};
6 use cranelift::codegen::data_value::DataValue;
7 use cranelift::codegen::ir::immediates::Offset32;
8 use cranelift::codegen::ir::instructions::{InstructionFormat, ResolvedConstraint};
9 use cranelift::codegen::ir::stackslot::StackSize;
10 
11 use cranelift::codegen::ir::{
12     types::*, AtomicRmwOp, Block, ConstantData, Endianness, ExternalName, FuncRef, Function,
13     LibCall, Opcode, SigRef, Signature, StackSlot, Type, UserExternalName, UserFuncName, Value,
14 };
15 use cranelift::codegen::isa::CallConv;
16 use cranelift::frontend::{FunctionBuilder, FunctionBuilderContext, Switch, Variable};
17 use cranelift::prelude::isa::OwnedTargetIsa;
18 use cranelift::prelude::{
19     EntityRef, ExtFuncData, FloatCC, InstBuilder, IntCC, JumpTableData, MemFlags, StackSlotData,
20     StackSlotKind,
21 };
22 use once_cell::sync::Lazy;
23 use std::collections::HashMap;
24 use std::ops::RangeInclusive;
25 use std::str::FromStr;
26 use target_lexicon::{Architecture, Triple};
27 
28 type BlockSignature = Vec<Type>;
29 
30 fn insert_opcode(
31     fgen: &mut FunctionGenerator,
32     builder: &mut FunctionBuilder,
33     opcode: Opcode,
34     args: &[Type],
35     rets: &[Type],
36 ) -> Result<()> {
37     let mut vals = Vec::with_capacity(args.len());
38     for &arg in args.into_iter() {
39         let var = fgen.get_variable_of_type(arg)?;
40         let val = builder.use_var(var);
41         vals.push(val);
42     }
43 
44     // Some opcodes require us to look at their input arguments to determine the
45     // controlling type. This is not the general case, but we can neatly check this
46     // using `requires_typevar_operand`.
47     let ctrl_type = if opcode.constraints().requires_typevar_operand() {
48         args.first()
49     } else {
50         rets.first()
51     }
52     .copied()
53     .unwrap_or(INVALID);
54 
55     // Choose the appropriate instruction format for this opcode
56     let (inst, dfg) = match opcode.format() {
57         InstructionFormat::NullAry => builder.ins().NullAry(opcode, ctrl_type),
58         InstructionFormat::Unary => builder.ins().Unary(opcode, ctrl_type, vals[0]),
59         InstructionFormat::Binary => builder.ins().Binary(opcode, ctrl_type, vals[0], vals[1]),
60         InstructionFormat::Ternary => builder
61             .ins()
62             .Ternary(opcode, ctrl_type, vals[0], vals[1], vals[2]),
63         _ => unimplemented!(),
64     };
65     let results = dfg.inst_results(inst).to_vec();
66 
67     for (val, &ty) in results.into_iter().zip(rets) {
68         let var = fgen.get_variable_of_type(ty)?;
69         builder.def_var(var, val);
70     }
71     Ok(())
72 }
73 
74 fn insert_call_to_function(
75     fgen: &mut FunctionGenerator,
76     builder: &mut FunctionBuilder,
77     call_opcode: Opcode,
78     sig: &Signature,
79     sig_ref: SigRef,
80     func_ref: FuncRef,
81 ) -> Result<()> {
82     let actuals = fgen.generate_values_for_signature(
83         builder,
84         sig.params.iter().map(|abi_param| abi_param.value_type),
85     )?;
86 
87     let addr_ty = fgen.isa.pointer_type();
88     let call = match call_opcode {
89         Opcode::Call => builder.ins().call(func_ref, &actuals),
90         Opcode::ReturnCall => builder.ins().return_call(func_ref, &actuals),
91         Opcode::CallIndirect => {
92             let addr = builder.ins().func_addr(addr_ty, func_ref);
93             builder.ins().call_indirect(sig_ref, addr, &actuals)
94         }
95         Opcode::ReturnCallIndirect => {
96             let addr = builder.ins().func_addr(addr_ty, func_ref);
97             builder.ins().return_call_indirect(sig_ref, addr, &actuals)
98         }
99         _ => unreachable!(),
100     };
101 
102     // Assign the return values to random variables
103     let ret_values = builder.inst_results(call).to_vec();
104     let ret_types = sig.returns.iter().map(|p| p.value_type);
105     for (ty, val) in ret_types.zip(ret_values) {
106         let var = fgen.get_variable_of_type(ty)?;
107         builder.def_var(var, val);
108     }
109 
110     Ok(())
111 }
112 
113 fn insert_call(
114     fgen: &mut FunctionGenerator,
115     builder: &mut FunctionBuilder,
116     opcode: Opcode,
117     _args: &[Type],
118     _rets: &[Type],
119 ) -> Result<()> {
120     assert!(matches!(opcode, Opcode::Call | Opcode::CallIndirect));
121     let (sig, sig_ref, func_ref) = fgen.u.choose(&fgen.resources.func_refs)?.clone();
122 
123     insert_call_to_function(fgen, builder, opcode, &sig, sig_ref, func_ref)
124 }
125 
126 fn insert_stack_load(
127     fgen: &mut FunctionGenerator,
128     builder: &mut FunctionBuilder,
129     _opcode: Opcode,
130     _args: &[Type],
131     rets: &[Type],
132 ) -> Result<()> {
133     let typevar = rets[0];
134     let type_size = typevar.bytes();
135     let (slot, slot_size, category) = fgen.stack_slot_with_size(type_size)?;
136 
137     // `stack_load` doesen't support setting MemFlags, and it does not set any
138     // alias analysis bits, so we can only emit it for `Other` slots.
139     if category != AACategory::Other {
140         return Err(arbitrary::Error::IncorrectFormat.into());
141     }
142 
143     let offset = fgen.u.int_in_range(0..=(slot_size - type_size))? as i32;
144 
145     let val = builder.ins().stack_load(typevar, slot, offset);
146     let var = fgen.get_variable_of_type(typevar)?;
147     builder.def_var(var, val);
148 
149     Ok(())
150 }
151 
152 fn insert_stack_store(
153     fgen: &mut FunctionGenerator,
154     builder: &mut FunctionBuilder,
155     _opcode: Opcode,
156     args: &[Type],
157     _rets: &[Type],
158 ) -> Result<()> {
159     let typevar = args[0];
160     let type_size = typevar.bytes();
161 
162     let (slot, slot_size, category) = fgen.stack_slot_with_size(type_size)?;
163 
164     // `stack_store` doesen't support setting MemFlags, and it does not set any
165     // alias analysis bits, so we can only emit it for `Other` slots.
166     if category != AACategory::Other {
167         return Err(arbitrary::Error::IncorrectFormat.into());
168     }
169 
170     let offset = fgen.u.int_in_range(0..=(slot_size - type_size))? as i32;
171 
172     let arg0 = fgen.get_variable_of_type(typevar)?;
173     let arg0 = builder.use_var(arg0);
174 
175     builder.ins().stack_store(arg0, slot, offset);
176     Ok(())
177 }
178 
179 fn insert_cmp(
180     fgen: &mut FunctionGenerator,
181     builder: &mut FunctionBuilder,
182     opcode: Opcode,
183     args: &[Type],
184     rets: &[Type],
185 ) -> Result<()> {
186     let lhs = fgen.get_variable_of_type(args[0])?;
187     let lhs = builder.use_var(lhs);
188 
189     let rhs = fgen.get_variable_of_type(args[1])?;
190     let rhs = builder.use_var(rhs);
191 
192     let res = if opcode == Opcode::Fcmp {
193         let cc = *fgen.u.choose(FloatCC::all())?;
194 
195         // We filter out condition codes that aren't supported by the target at
196         // this point after randomly choosing one, instead of randomly choosing a
197         // supported one, to avoid invalidating the corpus when these get implemented.
198         let unimplemented_cc = match (fgen.isa.triple().architecture, cc) {
199             // Some FloatCC's are not implemented on AArch64, see:
200             // https://github.com/bytecodealliance/wasmtime/issues/4850
201             (Architecture::Aarch64(_), FloatCC::OrderedNotEqual) => true,
202             (Architecture::Aarch64(_), FloatCC::UnorderedOrEqual) => true,
203             (Architecture::Aarch64(_), FloatCC::UnorderedOrLessThan) => true,
204             (Architecture::Aarch64(_), FloatCC::UnorderedOrLessThanOrEqual) => true,
205             (Architecture::Aarch64(_), FloatCC::UnorderedOrGreaterThan) => true,
206             (Architecture::Aarch64(_), FloatCC::UnorderedOrGreaterThanOrEqual) => true,
207 
208             // These are not implemented on x86_64, for vectors.
209             (Architecture::X86_64, FloatCC::UnorderedOrEqual | FloatCC::OrderedNotEqual) => {
210                 args[0].is_vector()
211             }
212             _ => false,
213         };
214         if unimplemented_cc {
215             return Err(arbitrary::Error::IncorrectFormat.into());
216         }
217 
218         builder.ins().fcmp(cc, lhs, rhs)
219     } else {
220         let cc = *fgen.u.choose(IntCC::all())?;
221         builder.ins().icmp(cc, lhs, rhs)
222     };
223 
224     let var = fgen.get_variable_of_type(rets[0])?;
225     builder.def_var(var, res);
226 
227     Ok(())
228 }
229 
230 fn insert_const(
231     fgen: &mut FunctionGenerator,
232     builder: &mut FunctionBuilder,
233     _opcode: Opcode,
234     _args: &[Type],
235     rets: &[Type],
236 ) -> Result<()> {
237     let typevar = rets[0];
238     let var = fgen.get_variable_of_type(typevar)?;
239     let val = fgen.generate_const(builder, typevar)?;
240     builder.def_var(var, val);
241     Ok(())
242 }
243 
244 fn insert_bitcast(
245     fgen: &mut FunctionGenerator,
246     builder: &mut FunctionBuilder,
247     args: &[Type],
248     rets: &[Type],
249 ) -> Result<()> {
250     let from_var = fgen.get_variable_of_type(args[0])?;
251     let from_val = builder.use_var(from_var);
252 
253     let to_var = fgen.get_variable_of_type(rets[0])?;
254 
255     // TODO: We can generate little/big endian flags here.
256     let mut memflags = MemFlags::new();
257 
258     // When bitcasting between vectors of different lane counts, we need to
259     // specify the endianness.
260     if args[0].lane_count() != rets[0].lane_count() {
261         memflags.set_endianness(Endianness::Little);
262     }
263 
264     let res = builder.ins().bitcast(rets[0], memflags, from_val);
265     builder.def_var(to_var, res);
266     Ok(())
267 }
268 
269 fn insert_load_store(
270     fgen: &mut FunctionGenerator,
271     builder: &mut FunctionBuilder,
272     opcode: Opcode,
273     args: &[Type],
274     rets: &[Type],
275 ) -> Result<()> {
276     if opcode == Opcode::Bitcast {
277         return insert_bitcast(fgen, builder, args, rets);
278     }
279 
280     let ctrl_type = *rets.first().or(args.first()).unwrap();
281     let type_size = ctrl_type.bytes();
282 
283     let is_atomic = [Opcode::AtomicLoad, Opcode::AtomicStore].contains(&opcode);
284     let (address, flags, offset) =
285         fgen.generate_address_and_memflags(builder, type_size, is_atomic)?;
286 
287     // The variable being loaded or stored into
288     let var = fgen.get_variable_of_type(ctrl_type)?;
289 
290     match opcode.format() {
291         InstructionFormat::LoadNoOffset => {
292             let (inst, dfg) = builder
293                 .ins()
294                 .LoadNoOffset(opcode, ctrl_type, flags, address);
295 
296             let new_val = dfg.first_result(inst);
297             builder.def_var(var, new_val);
298         }
299         InstructionFormat::StoreNoOffset => {
300             let val = builder.use_var(var);
301 
302             builder
303                 .ins()
304                 .StoreNoOffset(opcode, ctrl_type, flags, val, address);
305         }
306         InstructionFormat::Store => {
307             let val = builder.use_var(var);
308 
309             builder
310                 .ins()
311                 .Store(opcode, ctrl_type, flags, offset, val, address);
312         }
313         InstructionFormat::Load => {
314             let (inst, dfg) = builder
315                 .ins()
316                 .Load(opcode, ctrl_type, flags, offset, address);
317 
318             let new_val = dfg.first_result(inst);
319             builder.def_var(var, new_val);
320         }
321         _ => unimplemented!(),
322     }
323 
324     Ok(())
325 }
326 
327 fn insert_atomic_rmw(
328     fgen: &mut FunctionGenerator,
329     builder: &mut FunctionBuilder,
330     _: Opcode,
331     _: &[Type],
332     rets: &[Type],
333 ) -> Result<()> {
334     let ctrl_type = *rets.first().unwrap();
335     let type_size = ctrl_type.bytes();
336 
337     let rmw_op = *fgen.u.choose(AtomicRmwOp::all())?;
338 
339     let (address, flags, offset) = fgen.generate_address_and_memflags(builder, type_size, true)?;
340 
341     // AtomicRMW does not directly support offsets, so add the offset to the address separately.
342     let address = builder.ins().iadd_imm(address, i64::from(offset));
343 
344     // Load and store target variables
345     let source_var = fgen.get_variable_of_type(ctrl_type)?;
346     let target_var = fgen.get_variable_of_type(ctrl_type)?;
347 
348     let source_val = builder.use_var(source_var);
349     let new_val = builder
350         .ins()
351         .atomic_rmw(ctrl_type, flags, rmw_op, address, source_val);
352 
353     builder.def_var(target_var, new_val);
354     Ok(())
355 }
356 
357 fn insert_atomic_cas(
358     fgen: &mut FunctionGenerator,
359     builder: &mut FunctionBuilder,
360     _: Opcode,
361     _: &[Type],
362     rets: &[Type],
363 ) -> Result<()> {
364     let ctrl_type = *rets.first().unwrap();
365     let type_size = ctrl_type.bytes();
366 
367     let (address, flags, offset) = fgen.generate_address_and_memflags(builder, type_size, true)?;
368 
369     // AtomicCas does not directly support offsets, so add the offset to the address separately.
370     let address = builder.ins().iadd_imm(address, i64::from(offset));
371 
372     // Source and Target variables
373     let expected_var = fgen.get_variable_of_type(ctrl_type)?;
374     let store_var = fgen.get_variable_of_type(ctrl_type)?;
375     let loaded_var = fgen.get_variable_of_type(ctrl_type)?;
376 
377     let expected_val = builder.use_var(expected_var);
378     let store_val = builder.use_var(store_var);
379     let new_val = builder
380         .ins()
381         .atomic_cas(flags, address, expected_val, store_val);
382 
383     builder.def_var(loaded_var, new_val);
384     Ok(())
385 }
386 
387 fn insert_shuffle(
388     fgen: &mut FunctionGenerator,
389     builder: &mut FunctionBuilder,
390     opcode: Opcode,
391     _: &[Type],
392     rets: &[Type],
393 ) -> Result<()> {
394     let ctrl_type = *rets.first().unwrap();
395 
396     let lhs = builder.use_var(fgen.get_variable_of_type(ctrl_type)?);
397     let rhs = builder.use_var(fgen.get_variable_of_type(ctrl_type)?);
398 
399     let mask = {
400         let mut lanes = [0u8; 16];
401         for lane in lanes.iter_mut() {
402             *lane = fgen.u.int_in_range(0..=31)?;
403         }
404         let lanes = ConstantData::from(lanes.as_ref());
405         builder.func.dfg.immediates.push(lanes)
406     };
407 
408     // This function is called for any `InstructionFormat::Shuffle`. Which today is just
409     // `shuffle`, but lets assert that, just to be sure we don't accidentally insert
410     // something else.
411     assert_eq!(opcode, Opcode::Shuffle);
412     let res = builder.ins().shuffle(lhs, rhs, mask);
413 
414     let target_var = fgen.get_variable_of_type(ctrl_type)?;
415     builder.def_var(target_var, res);
416 
417     Ok(())
418 }
419 
420 fn insert_ins_ext_lane(
421     fgen: &mut FunctionGenerator,
422     builder: &mut FunctionBuilder,
423     opcode: Opcode,
424     args: &[Type],
425     rets: &[Type],
426 ) -> Result<()> {
427     let vector_type = *args.first().unwrap();
428     let ret_type = *rets.first().unwrap();
429 
430     let lhs = builder.use_var(fgen.get_variable_of_type(vector_type)?);
431     let max_lane = (vector_type.lane_count() as u8) - 1;
432     let lane = fgen.u.int_in_range(0..=max_lane)?;
433 
434     let res = match opcode {
435         Opcode::Insertlane => {
436             let rhs = builder.use_var(fgen.get_variable_of_type(args[1])?);
437             builder.ins().insertlane(lhs, rhs, lane)
438         }
439         Opcode::Extractlane => builder.ins().extractlane(lhs, lane),
440         _ => todo!(),
441     };
442 
443     let target_var = fgen.get_variable_of_type(ret_type)?;
444     builder.def_var(target_var, res);
445 
446     Ok(())
447 }
448 
449 type OpcodeInserter = fn(
450     fgen: &mut FunctionGenerator,
451     builder: &mut FunctionBuilder,
452     Opcode,
453     &[Type],
454     &[Type],
455 ) -> Result<()>;
456 
457 macro_rules! exceptions {
458     ($op:expr, $args:expr, $rets:expr, $(($($cases:pat),*)),* $(,)?) => {
459         match ($op, $args, $rets) {
460             $( ($($cases,)* ..) => return false, )*
461             _ => true,
462         }
463     }
464 }
465 
466 /// Returns true if we believe this `OpcodeSignature` should compile correctly
467 /// for the given target triple. We currently have a range of known issues
468 /// with specific lowerings on specific backends, and we don't want to get
469 /// fuzz bug reports for those. Over time our goal is to eliminate all of these
470 /// exceptions.
471 fn valid_for_target(triple: &Triple, op: Opcode, args: &[Type], rets: &[Type]) -> bool {
472     // Rule out invalid combinations that we don't yet have a good way of rejecting with the
473     // instruction DSL type constraints.
474     match op {
475         Opcode::FcvtToUintSat | Opcode::FcvtToSintSat => {
476             assert_eq!(args.len(), 1);
477             assert_eq!(rets.len(), 1);
478 
479             let arg = args[0];
480             let ret = rets[0];
481 
482             // Vector arguments must produce vector results, and scalar arguments must produce
483             // scalar results.
484             if arg.is_vector() != ret.is_vector() {
485                 return false;
486             }
487 
488             if arg.is_vector() && ret.is_vector() {
489                 // Vector conversions must have the same number of lanes, and the lanes must be the
490                 // same bit-width.
491                 if arg.lane_count() != ret.lane_count() {
492                     return false;
493                 }
494 
495                 if arg.lane_of().bits() != ret.lane_of().bits() {
496                     return false;
497                 }
498             }
499         }
500 
501         Opcode::Bitcast => {
502             assert_eq!(args.len(), 1);
503             assert_eq!(rets.len(), 1);
504 
505             let arg = args[0];
506             let ret = rets[0];
507 
508             // The opcode generator still allows bitcasts between different sized types, but these
509             // are rejected in the verifier.
510             if arg.bits() != ret.bits() {
511                 return false;
512             }
513         }
514 
515         _ => {}
516     }
517 
518     match triple.architecture {
519         Architecture::X86_64 => {
520             exceptions!(
521                 op,
522                 args,
523                 rets,
524                 (Opcode::UmulOverflow | Opcode::SmulOverflow, &[I128, I128]),
525                 (Opcode::Imul, &[I8X16, I8X16]),
526                 // https://github.com/bytecodealliance/wasmtime/issues/5468
527                 (Opcode::Smulhi | Opcode::Umulhi, &[I8, I8]),
528                 // https://github.com/bytecodealliance/wasmtime/issues/4756
529                 (Opcode::Udiv | Opcode::Sdiv, &[I128, I128]),
530                 // https://github.com/bytecodealliance/wasmtime/issues/5474
531                 (Opcode::Urem | Opcode::Srem, &[I128, I128]),
532                 // https://github.com/bytecodealliance/wasmtime/issues/3370
533                 (
534                     Opcode::Smin | Opcode::Umin | Opcode::Smax | Opcode::Umax,
535                     &[I128, I128]
536                 ),
537                 // https://github.com/bytecodealliance/wasmtime/issues/5107
538                 (Opcode::Cls, &[I8], &[I8]),
539                 (Opcode::Cls, &[I16], &[I16]),
540                 (Opcode::Cls, &[I32], &[I32]),
541                 (Opcode::Cls, &[I64], &[I64]),
542                 (Opcode::Cls, &[I128], &[I128]),
543                 // TODO
544                 (Opcode::Bitselect, &[_, _, _], &[F32 | F64]),
545                 // https://github.com/bytecodealliance/wasmtime/issues/4897
546                 // https://github.com/bytecodealliance/wasmtime/issues/4899
547                 (
548                     Opcode::FcvtToUint
549                         | Opcode::FcvtToUintSat
550                         | Opcode::FcvtToSint
551                         | Opcode::FcvtToSintSat,
552                     &[F32 | F64],
553                     &[I8 | I16 | I128]
554                 ),
555                 (Opcode::FcvtToUint | Opcode::FcvtToSint, &[F32X4], &[I32X4]),
556                 (
557                     Opcode::FcvtToUint
558                         | Opcode::FcvtToUintSat
559                         | Opcode::FcvtToSint
560                         | Opcode::FcvtToSintSat,
561                     &[F64X2],
562                     &[I64X2]
563                 ),
564                 // https://github.com/bytecodealliance/wasmtime/issues/4900
565                 (Opcode::FcvtFromUint, &[I128], &[F32 | F64]),
566                 // This has a lowering, but only when preceded by `uwiden_low`.
567                 (Opcode::FcvtFromUint, &[I64X2], &[F64X2]),
568                 // https://github.com/bytecodealliance/wasmtime/issues/4900
569                 (Opcode::FcvtFromSint, &[I128], &[F32 | F64]),
570                 (Opcode::FcvtFromSint, &[I64X2], &[F64X2]),
571                 (
572                     Opcode::Umulhi | Opcode::Smulhi,
573                     &([I8X16, I8X16] | [I16X8, I16X8] | [I32X4, I32X4] | [I64X2, I64X2])
574                 ),
575                 (
576                     Opcode::UaddSat | Opcode::SaddSat | Opcode::UsubSat | Opcode::SsubSat,
577                     &([I32X4, I32X4] | [I64X2, I64X2])
578                 ),
579                 (Opcode::Fcopysign, &([F32X4, F32X4] | [F64X2, F64X2])),
580                 (Opcode::Popcnt, &([I8X16] | [I16X8] | [I32X4] | [I64X2])),
581                 (
582                     Opcode::Umax | Opcode::Smax | Opcode::Umin | Opcode::Smin,
583                     &[I64X2, I64X2]
584                 ),
585                 // https://github.com/bytecodealliance/wasmtime/issues/6104
586                 (Opcode::Bitcast, &[I128], &[_]),
587                 (Opcode::Bitcast, &[_], &[I128]),
588                 (Opcode::Uunarrow),
589                 (Opcode::Snarrow | Opcode::Unarrow, &[I64X2, I64X2]),
590                 (Opcode::SqmulRoundSat, &[I32X4, I32X4]),
591                 // This Icmp is not implemented: #5529
592                 (Opcode::Icmp, &[I64X2, I64X2]),
593                 // IaddPairwise is implemented, but only for some types, and with some preceding ops.
594                 (Opcode::IaddPairwise),
595                 // Nothing wrong with this select. But we have an isle rule that can optimize it
596                 // into a `min`/`max` instructions, which we don't have implemented yet.
597                 (Opcode::Select, &[_, I128, I128]),
598                 // These stack accesses can cause segfaults if they are merged into an SSE instruction.
599                 // See: #5922
600                 (
601                     Opcode::StackStore,
602                     &[I8X16 | I16X8 | I32X4 | I64X2 | F32X4 | F64X2]
603                 ),
604                 (
605                     Opcode::StackLoad,
606                     &[],
607                     &[I8X16 | I16X8 | I32X4 | I64X2 | F32X4 | F64X2]
608                 ),
609                 // TODO
610                 (
611                     Opcode::Sshr | Opcode::Ushr | Opcode::Ishl,
612                     &[I8X16 | I16X8 | I32X4 | I64X2, I128]
613                 ),
614                 (
615                     Opcode::Rotr | Opcode::Rotl,
616                     &[I8X16 | I16X8 | I32X4 | I64X2, _]
617                 ),
618             )
619         }
620 
621         Architecture::Aarch64(_) => {
622             exceptions!(
623                 op,
624                 args,
625                 rets,
626                 (Opcode::UmulOverflow | Opcode::SmulOverflow, &[I128, I128]),
627                 // https://github.com/bytecodealliance/wasmtime/issues/4864
628                 (Opcode::Udiv | Opcode::Sdiv, &[I128, I128]),
629                 // https://github.com/bytecodealliance/wasmtime/issues/5472
630                 (Opcode::Urem | Opcode::Srem, &[I128, I128]),
631                 // https://github.com/bytecodealliance/wasmtime/issues/4313
632                 (
633                     Opcode::Smin | Opcode::Umin | Opcode::Smax | Opcode::Umax,
634                     &[I128, I128]
635                 ),
636                 // https://github.com/bytecodealliance/wasmtime/issues/4870
637                 (Opcode::Bnot, &[F32 | F64]),
638                 (
639                     Opcode::Band
640                         | Opcode::Bor
641                         | Opcode::Bxor
642                         | Opcode::BandNot
643                         | Opcode::BorNot
644                         | Opcode::BxorNot,
645                     &([F32, F32] | [F64, F64])
646                 ),
647                 // https://github.com/bytecodealliance/wasmtime/issues/5198
648                 (Opcode::Bitselect, &[I128, I128, I128]),
649                 // https://github.com/bytecodealliance/wasmtime/issues/4934
650                 (
651                     Opcode::FcvtToUint
652                         | Opcode::FcvtToUintSat
653                         | Opcode::FcvtToSint
654                         | Opcode::FcvtToSintSat,
655                     &[F32 | F64],
656                     &[I128]
657                 ),
658                 // https://github.com/bytecodealliance/wasmtime/issues/4933
659                 (
660                     Opcode::FcvtFromUint | Opcode::FcvtFromSint,
661                     &[I128],
662                     &[F32 | F64]
663                 ),
664                 (
665                     Opcode::Umulhi | Opcode::Smulhi,
666                     &([I8X16, I8X16] | [I16X8, I16X8] | [I32X4, I32X4] | [I64X2, I64X2])
667                 ),
668                 (Opcode::Popcnt, &[I16X8 | I32X4 | I64X2]),
669                 // Nothing wrong with this select. But we have an isle rule that can optimize it
670                 // into a `min`/`max` instructions, which we don't have implemented yet.
671                 (Opcode::Select, &[I8, I128, I128]),
672                 // https://github.com/bytecodealliance/wasmtime/issues/6104
673                 (Opcode::Bitcast, &[I128], &[_]),
674                 (Opcode::Bitcast, &[_], &[I128]),
675                 // TODO
676                 (
677                     Opcode::Sshr | Opcode::Ushr | Opcode::Ishl,
678                     &[I8X16 | I16X8 | I32X4 | I64X2, I128]
679                 ),
680                 (
681                     Opcode::Rotr | Opcode::Rotl,
682                     &[I8X16 | I16X8 | I32X4 | I64X2, _]
683                 ),
684                 // TODO
685                 (Opcode::Bitselect, &[_, _, _], &[F32 | F64]),
686                 (Opcode::VhighBits, &[F32X4 | F64X2]),
687             )
688         }
689 
690         Architecture::S390x => {
691             exceptions!(
692                 op,
693                 args,
694                 rets,
695                 (Opcode::UaddOverflow | Opcode::SaddOverflow),
696                 (Opcode::UsubOverflow | Opcode::SsubOverflow),
697                 (Opcode::UmulOverflow | Opcode::SmulOverflow),
698                 (
699                     Opcode::Udiv | Opcode::Sdiv | Opcode::Urem | Opcode::Srem,
700                     &[I128, I128]
701                 ),
702                 (Opcode::Bnot, &[F32 | F64]),
703                 (
704                     Opcode::Band
705                         | Opcode::Bor
706                         | Opcode::Bxor
707                         | Opcode::BandNot
708                         | Opcode::BorNot
709                         | Opcode::BxorNot,
710                     &([F32, F32] | [F64, F64])
711                 ),
712                 (
713                     Opcode::FcvtToUint
714                         | Opcode::FcvtToUintSat
715                         | Opcode::FcvtToSint
716                         | Opcode::FcvtToSintSat,
717                     &[F32 | F64],
718                     &[I128]
719                 ),
720                 (
721                     Opcode::FcvtFromUint | Opcode::FcvtFromSint,
722                     &[I128],
723                     &[F32 | F64]
724                 ),
725                 (Opcode::SsubSat | Opcode::SaddSat, &[I64X2, I64X2]),
726                 // https://github.com/bytecodealliance/wasmtime/issues/6104
727                 (Opcode::Bitcast, &[I128], &[_]),
728                 (Opcode::Bitcast, &[_], &[I128]),
729                 // TODO
730                 (Opcode::Bitselect, &[_, _, _], &[F32 | F64]),
731             )
732         }
733 
734         Architecture::Riscv64(_) => {
735             exceptions!(
736                 op,
737                 args,
738                 rets,
739                 // TODO
740                 (Opcode::UaddOverflow | Opcode::SaddOverflow),
741                 (Opcode::UsubOverflow | Opcode::SsubOverflow),
742                 (Opcode::UmulOverflow | Opcode::SmulOverflow),
743                 // TODO
744                 (
745                     Opcode::Udiv | Opcode::Sdiv | Opcode::Urem | Opcode::Srem,
746                     &[I128, I128]
747                 ),
748                 // TODO
749                 (Opcode::Iabs, &[I128]),
750                 // TODO
751                 (Opcode::Bitselect, &[I128, I128, I128]),
752                 // https://github.com/bytecodealliance/wasmtime/issues/5528
753                 (
754                     Opcode::FcvtToUint | Opcode::FcvtToSint,
755                     [F32 | F64],
756                     &[I128]
757                 ),
758                 (
759                     Opcode::FcvtToUintSat | Opcode::FcvtToSintSat,
760                     &[F32 | F64],
761                     &[I128]
762                 ),
763                 // https://github.com/bytecodealliance/wasmtime/issues/5528
764                 (
765                     Opcode::FcvtFromUint | Opcode::FcvtFromSint,
766                     &[I128],
767                     &[F32 | F64]
768                 ),
769                 // https://github.com/bytecodealliance/wasmtime/issues/6104
770                 (Opcode::Bitcast, &[I128], &[_]),
771                 (Opcode::Bitcast, &[_], &[I128]),
772                 // TODO
773                 (
774                     Opcode::SelectSpectreGuard,
775                     &[_, _, _],
776                     &[F32 | F64 | I8X16 | I16X8 | I32X4 | I64X2 | F64X2 | F32X4]
777                 ),
778                 // TODO
779                 (Opcode::Bitselect, &[_, _, _], &[F32 | F64]),
780                 (
781                     Opcode::Rotr | Opcode::Rotl,
782                     &[I8X16 | I16X8 | I32X4 | I64X2, _]
783                 ),
784             )
785         }
786 
787         _ => true,
788     }
789 }
790 
791 type OpcodeSignature = (Opcode, Vec<Type>, Vec<Type>);
792 
793 static OPCODE_SIGNATURES: Lazy<Vec<OpcodeSignature>> = Lazy::new(|| {
794     let types = &[
795         I8, I16, I32, I64, I128, // Scalar Integers
796         F32, F64, // Scalar Floats
797         I8X16, I16X8, I32X4, I64X2, // SIMD Integers
798         F32X4, F64X2, // SIMD Floats
799     ];
800 
801     // When this env variable is passed, we only generate instructions for the opcodes listed in
802     // the comma-separated list. This is useful for debugging, as it allows us to focus on a few
803     // specific opcodes.
804     let allowed_opcodes = std::env::var("FUZZGEN_ALLOWED_OPS").ok().map(|s| {
805         s.split(',')
806             .map(|s| s.trim())
807             .filter(|s| !s.is_empty())
808             .map(|s| Opcode::from_str(s).expect("Unrecoginzed opcode"))
809             .collect::<Vec<_>>()
810     });
811 
812     Opcode::all()
813         .iter()
814         .filter(|op| {
815             match op {
816                 // Control flow opcodes should not be generated through `generate_instructions`.
817                 Opcode::BrTable
818                 | Opcode::Brif
819                 | Opcode::Jump
820                 | Opcode::Return
821                 | Opcode::ReturnCall
822                 | Opcode::ReturnCallIndirect => false,
823 
824                 // Constants are generated outside of `generate_instructions`
825                 Opcode::Iconst => false,
826 
827                 // TODO: extract_vector raises exceptions during return type generation becuase it
828                 // uses dynamic vectors.
829                 Opcode::ExtractVector => false,
830 
831                 _ => true,
832             }
833         })
834         .flat_map(|op| {
835             let constraints = op.constraints();
836 
837             let ctrl_types = if let Some(ctrls) = constraints.ctrl_typeset() {
838                 Vec::from_iter(types.iter().copied().filter(|ty| ctrls.contains(*ty)))
839             } else {
840                 vec![INVALID]
841             };
842 
843             ctrl_types.into_iter().flat_map(move |ctrl_type| {
844                 let rets = Vec::from_iter(
845                     (0..constraints.num_fixed_results())
846                         .map(|i| constraints.result_type(i, ctrl_type)),
847                 );
848 
849                 // Cols is a vector whose length will match `num_fixed_value_arguments`, and whose
850                 // elements will be vectors of types that are valid for that fixed argument
851                 // position.
852                 let mut cols = vec![];
853 
854                 for i in 0..constraints.num_fixed_value_arguments() {
855                     match constraints.value_argument_constraint(i, ctrl_type) {
856                         ResolvedConstraint::Bound(ty) => cols.push(Vec::from([ty])),
857                         ResolvedConstraint::Free(tys) => cols.push(Vec::from_iter(
858                             types.iter().copied().filter(|ty| tys.contains(*ty)),
859                         )),
860                     }
861                 }
862 
863                 // Generate the cartesian product of cols to produce a vector of argument lists,
864                 // argss. The argss vector is seeded with the empty argument list, so there's an
865                 // initial value to be extended in the loop below.
866                 let mut argss = vec![vec![]];
867                 let mut cols = cols.as_slice();
868                 while let Some((col, rest)) = cols.split_last() {
869                     cols = rest;
870 
871                     let mut next = vec![];
872                     for current in argss.iter() {
873                         // Extend the front of each argument candidate with every type in `col`.
874                         for ty in col {
875                             let mut args = vec![*ty];
876                             args.extend_from_slice(&current);
877                             next.push(args);
878                         }
879                     }
880 
881                     let _ = std::mem::replace(&mut argss, next);
882                 }
883 
884                 argss.into_iter().map(move |args| (*op, args, rets.clone()))
885             })
886         })
887         .filter(|(op, args, rets)| {
888             // These op/signature combinations need to be vetted
889             exceptions!(
890                 op,
891                 args.as_slice(),
892                 rets.as_slice(),
893                 (Opcode::Debugtrap),
894                 (Opcode::Trap),
895                 (Opcode::Trapz),
896                 (Opcode::ResumableTrap),
897                 (Opcode::Trapnz),
898                 (Opcode::ResumableTrapnz),
899                 (Opcode::CallIndirect, &[I32]),
900                 (Opcode::FuncAddr),
901                 (Opcode::X86Pshufb),
902                 (Opcode::AvgRound),
903                 (Opcode::Uload8x8),
904                 (Opcode::Sload8x8),
905                 (Opcode::Uload16x4),
906                 (Opcode::Sload16x4),
907                 (Opcode::Uload32x2),
908                 (Opcode::Sload32x2),
909                 (Opcode::StackAddr),
910                 (Opcode::DynamicStackLoad),
911                 (Opcode::DynamicStackStore),
912                 (Opcode::DynamicStackAddr),
913                 (Opcode::GlobalValue),
914                 (Opcode::SymbolValue),
915                 (Opcode::TlsValue),
916                 (Opcode::GetPinnedReg),
917                 (Opcode::SetPinnedReg),
918                 (Opcode::GetFramePointer),
919                 (Opcode::GetStackPointer),
920                 (Opcode::GetReturnAddress),
921                 (Opcode::TableAddr),
922                 (Opcode::Null),
923                 (Opcode::X86Blendv),
924                 (Opcode::IcmpImm),
925                 (Opcode::X86Pmulhrsw),
926                 (Opcode::IaddImm),
927                 (Opcode::ImulImm),
928                 (Opcode::UdivImm),
929                 (Opcode::SdivImm),
930                 (Opcode::UremImm),
931                 (Opcode::SremImm),
932                 (Opcode::IrsubImm),
933                 (Opcode::IaddCin),
934                 (Opcode::IaddCarry),
935                 (Opcode::UaddOverflowTrap),
936                 (Opcode::IsubBin),
937                 (Opcode::IsubBorrow),
938                 (Opcode::BandImm),
939                 (Opcode::BorImm),
940                 (Opcode::BxorImm),
941                 (Opcode::RotlImm),
942                 (Opcode::RotrImm),
943                 (Opcode::IshlImm),
944                 (Opcode::UshrImm),
945                 (Opcode::SshrImm),
946                 (Opcode::IsNull),
947                 (Opcode::IsInvalid),
948                 (Opcode::ScalarToVector),
949                 (Opcode::X86Pmaddubsw),
950                 (Opcode::X86Cvtt2dq),
951                 (Opcode::Umulhi, &[I128, I128], &[I128]),
952                 (Opcode::Smulhi, &[I128, I128], &[I128]),
953                 // https://github.com/bytecodealliance/wasmtime/issues/6073
954                 (Opcode::Iconcat, &[I32, I32], &[I64]),
955                 (Opcode::Iconcat, &[I16, I16], &[I32]),
956                 (Opcode::Iconcat, &[I8, I8], &[I16]),
957                 // https://github.com/bytecodealliance/wasmtime/issues/6073
958                 (Opcode::Isplit, &[I64], &[I32, I32]),
959                 (Opcode::Isplit, &[I32], &[I16, I16]),
960                 (Opcode::Isplit, &[I16], &[I8, I8]),
961                 (Opcode::Fmin, &[F32X4, F32X4], &[F32X4]),
962                 (Opcode::Fmin, &[F64X2, F64X2], &[F64X2]),
963                 (Opcode::Fmax, &[F32X4, F32X4], &[F32X4]),
964                 (Opcode::Fmax, &[F64X2, F64X2], &[F64X2]),
965                 (Opcode::FcvtToUintSat, &[F32X4], &[I8]),
966                 (Opcode::FcvtToUintSat, &[F64X2], &[I8]),
967                 (Opcode::FcvtToUintSat, &[F32X4], &[I16]),
968                 (Opcode::FcvtToUintSat, &[F64X2], &[I16]),
969                 (Opcode::FcvtToUintSat, &[F32X4], &[I32]),
970                 (Opcode::FcvtToUintSat, &[F64X2], &[I32]),
971                 (Opcode::FcvtToUintSat, &[F32X4], &[I64]),
972                 (Opcode::FcvtToUintSat, &[F64X2], &[I64]),
973                 (Opcode::FcvtToUintSat, &[F32X4], &[I128]),
974                 (Opcode::FcvtToUintSat, &[F64X2], &[I128]),
975                 (Opcode::FcvtToUintSat, &[F32], &[I8X16]),
976                 (Opcode::FcvtToUintSat, &[F64], &[I8X16]),
977                 (Opcode::FcvtToUintSat, &[F32X4], &[I8X16]),
978                 (Opcode::FcvtToUintSat, &[F64X2], &[I8X16]),
979                 (Opcode::FcvtToUintSat, &[F32], &[I16X8]),
980                 (Opcode::FcvtToUintSat, &[F64], &[I16X8]),
981                 (Opcode::FcvtToUintSat, &[F32X4], &[I16X8]),
982                 (Opcode::FcvtToUintSat, &[F64X2], &[I16X8]),
983                 (Opcode::FcvtToUintSat, &[F32], &[I32X4]),
984                 (Opcode::FcvtToUintSat, &[F64], &[I32X4]),
985                 (Opcode::FcvtToUintSat, &[F64X2], &[I32X4]),
986                 (Opcode::FcvtToUintSat, &[F32], &[I64X2]),
987                 (Opcode::FcvtToUintSat, &[F64], &[I64X2]),
988                 (Opcode::FcvtToUintSat, &[F32X4], &[I64X2]),
989                 (Opcode::FcvtToSintSat, &[F32X4], &[I8]),
990                 (Opcode::FcvtToSintSat, &[F64X2], &[I8]),
991                 (Opcode::FcvtToSintSat, &[F32X4], &[I16]),
992                 (Opcode::FcvtToSintSat, &[F64X2], &[I16]),
993                 (Opcode::FcvtToSintSat, &[F32X4], &[I32]),
994                 (Opcode::FcvtToSintSat, &[F64X2], &[I32]),
995                 (Opcode::FcvtToSintSat, &[F32X4], &[I64]),
996                 (Opcode::FcvtToSintSat, &[F64X2], &[I64]),
997                 (Opcode::FcvtToSintSat, &[F32X4], &[I128]),
998                 (Opcode::FcvtToSintSat, &[F64X2], &[I128]),
999                 (Opcode::FcvtToSintSat, &[F32], &[I8X16]),
1000                 (Opcode::FcvtToSintSat, &[F64], &[I8X16]),
1001                 (Opcode::FcvtToSintSat, &[F32X4], &[I8X16]),
1002                 (Opcode::FcvtToSintSat, &[F64X2], &[I8X16]),
1003                 (Opcode::FcvtToSintSat, &[F32], &[I16X8]),
1004                 (Opcode::FcvtToSintSat, &[F64], &[I16X8]),
1005                 (Opcode::FcvtToSintSat, &[F32X4], &[I16X8]),
1006                 (Opcode::FcvtToSintSat, &[F64X2], &[I16X8]),
1007                 (Opcode::FcvtToSintSat, &[F32], &[I32X4]),
1008                 (Opcode::FcvtToSintSat, &[F64], &[I32X4]),
1009                 (Opcode::FcvtToSintSat, &[F64X2], &[I32X4]),
1010                 (Opcode::FcvtToSintSat, &[F32], &[I64X2]),
1011                 (Opcode::FcvtToSintSat, &[F64], &[I64X2]),
1012                 (Opcode::FcvtToSintSat, &[F32X4], &[I64X2]),
1013                 (Opcode::FcvtFromUint, &[I8X16], &[F32]),
1014                 (Opcode::FcvtFromUint, &[I16X8], &[F32]),
1015                 (Opcode::FcvtFromUint, &[I32X4], &[F32]),
1016                 (Opcode::FcvtFromUint, &[I64X2], &[F32]),
1017                 (Opcode::FcvtFromUint, &[I8X16], &[F64]),
1018                 (Opcode::FcvtFromUint, &[I16X8], &[F64]),
1019                 (Opcode::FcvtFromUint, &[I32X4], &[F64]),
1020                 (Opcode::FcvtFromUint, &[I64X2], &[F64]),
1021                 (Opcode::FcvtFromUint, &[I8], &[F32X4]),
1022                 (Opcode::FcvtFromUint, &[I16], &[F32X4]),
1023                 (Opcode::FcvtFromUint, &[I32], &[F32X4]),
1024                 (Opcode::FcvtFromUint, &[I64], &[F32X4]),
1025                 (Opcode::FcvtFromUint, &[I128], &[F32X4]),
1026                 (Opcode::FcvtFromUint, &[I8X16], &[F32X4]),
1027                 (Opcode::FcvtFromUint, &[I16X8], &[F32X4]),
1028                 (Opcode::FcvtFromUint, &[I64X2], &[F32X4]),
1029                 (Opcode::FcvtFromUint, &[I8], &[F64X2]),
1030                 (Opcode::FcvtFromUint, &[I16], &[F64X2]),
1031                 (Opcode::FcvtFromUint, &[I32], &[F64X2]),
1032                 (Opcode::FcvtFromUint, &[I64], &[F64X2]),
1033                 (Opcode::FcvtFromUint, &[I128], &[F64X2]),
1034                 (Opcode::FcvtFromUint, &[I8X16], &[F64X2]),
1035                 (Opcode::FcvtFromUint, &[I16X8], &[F64X2]),
1036                 (Opcode::FcvtFromUint, &[I32X4], &[F64X2]),
1037                 (Opcode::FcvtFromSint, &[I8X16], &[F32]),
1038                 (Opcode::FcvtFromSint, &[I16X8], &[F32]),
1039                 (Opcode::FcvtFromSint, &[I32X4], &[F32]),
1040                 (Opcode::FcvtFromSint, &[I64X2], &[F32]),
1041                 (Opcode::FcvtFromSint, &[I8X16], &[F64]),
1042                 (Opcode::FcvtFromSint, &[I16X8], &[F64]),
1043                 (Opcode::FcvtFromSint, &[I32X4], &[F64]),
1044                 (Opcode::FcvtFromSint, &[I64X2], &[F64]),
1045                 (Opcode::FcvtFromSint, &[I8], &[F32X4]),
1046                 (Opcode::FcvtFromSint, &[I16], &[F32X4]),
1047                 (Opcode::FcvtFromSint, &[I32], &[F32X4]),
1048                 (Opcode::FcvtFromSint, &[I64], &[F32X4]),
1049                 (Opcode::FcvtFromSint, &[I128], &[F32X4]),
1050                 (Opcode::FcvtFromSint, &[I8X16], &[F32X4]),
1051                 (Opcode::FcvtFromSint, &[I16X8], &[F32X4]),
1052                 (Opcode::FcvtFromSint, &[I64X2], &[F32X4]),
1053                 (Opcode::FcvtFromSint, &[I8], &[F64X2]),
1054                 (Opcode::FcvtFromSint, &[I16], &[F64X2]),
1055                 (Opcode::FcvtFromSint, &[I32], &[F64X2]),
1056                 (Opcode::FcvtFromSint, &[I64], &[F64X2]),
1057                 (Opcode::FcvtFromSint, &[I128], &[F64X2]),
1058                 (Opcode::FcvtFromSint, &[I8X16], &[F64X2]),
1059                 (Opcode::FcvtFromSint, &[I16X8], &[F64X2]),
1060                 (Opcode::FcvtFromSint, &[I32X4], &[F64X2]),
1061             )
1062         })
1063         .filter(|(op, ..)| {
1064             allowed_opcodes
1065                 .as_ref()
1066                 .map_or(true, |opcodes| opcodes.contains(op))
1067         })
1068         .collect()
1069 });
1070 
1071 fn inserter_for_format(fmt: InstructionFormat) -> OpcodeInserter {
1072     match fmt {
1073         InstructionFormat::AtomicCas => insert_atomic_cas,
1074         InstructionFormat::AtomicRmw => insert_atomic_rmw,
1075         InstructionFormat::Binary => insert_opcode,
1076         InstructionFormat::BinaryImm64 => todo!(),
1077         InstructionFormat::BinaryImm8 => insert_ins_ext_lane,
1078         InstructionFormat::Call => insert_call,
1079         InstructionFormat::CallIndirect => insert_call,
1080         InstructionFormat::CondTrap => todo!(),
1081         InstructionFormat::DynamicStackLoad => todo!(),
1082         InstructionFormat::DynamicStackStore => todo!(),
1083         InstructionFormat::FloatCompare => insert_cmp,
1084         InstructionFormat::FuncAddr => todo!(),
1085         InstructionFormat::IntAddTrap => todo!(),
1086         InstructionFormat::IntCompare => insert_cmp,
1087         InstructionFormat::IntCompareImm => todo!(),
1088         InstructionFormat::Load => insert_load_store,
1089         InstructionFormat::LoadNoOffset => insert_load_store,
1090         InstructionFormat::NullAry => insert_opcode,
1091         InstructionFormat::Shuffle => insert_shuffle,
1092         InstructionFormat::StackLoad => insert_stack_load,
1093         InstructionFormat::StackStore => insert_stack_store,
1094         InstructionFormat::Store => insert_load_store,
1095         InstructionFormat::StoreNoOffset => insert_load_store,
1096         InstructionFormat::TableAddr => todo!(),
1097         InstructionFormat::Ternary => insert_opcode,
1098         InstructionFormat::TernaryImm8 => insert_ins_ext_lane,
1099         InstructionFormat::Trap => todo!(),
1100         InstructionFormat::Unary => insert_opcode,
1101         InstructionFormat::UnaryConst => insert_const,
1102         InstructionFormat::UnaryGlobalValue => todo!(),
1103         InstructionFormat::UnaryIeee32 => insert_const,
1104         InstructionFormat::UnaryIeee64 => insert_const,
1105         InstructionFormat::UnaryImm => insert_const,
1106 
1107         InstructionFormat::BranchTable
1108         | InstructionFormat::Brif
1109         | InstructionFormat::Jump
1110         | InstructionFormat::MultiAry => {
1111             panic!(
1112                 "Control-flow instructions should be handled by 'insert_terminator': {:?}",
1113                 fmt
1114             )
1115         }
1116     }
1117 }
1118 
1119 pub struct FunctionGenerator<'r, 'data>
1120 where
1121     'data: 'r,
1122 {
1123     u: &'r mut Unstructured<'data>,
1124     config: &'r Config,
1125     resources: Resources,
1126     isa: OwnedTargetIsa,
1127     name: UserFuncName,
1128     signature: Signature,
1129 }
1130 
1131 #[derive(Debug, Clone)]
1132 enum BlockTerminator {
1133     Return,
1134     Jump(Block),
1135     Br(Block, Block),
1136     BrTable(Block, Vec<Block>),
1137     Switch(Type, Block, HashMap<u128, Block>),
1138     TailCall(FuncRef),
1139     TailCallIndirect(FuncRef),
1140 }
1141 
1142 #[derive(Debug, Clone)]
1143 enum BlockTerminatorKind {
1144     Return,
1145     Jump,
1146     Br,
1147     BrTable,
1148     Switch,
1149     TailCall,
1150     TailCallIndirect,
1151 }
1152 
1153 /// Alias Analysis Category
1154 ///
1155 /// Our alias analysis pass supports 4 categories of accesses to distinguish
1156 /// different regions. The "Other" region is the general case, and is the default
1157 /// Although they have highly suggestive names there is no difference between any
1158 /// of the categories.
1159 ///
1160 /// We assign each stack slot a category when we first generate them, and then
1161 /// ensure that all accesses to that stack slot are correctly tagged. We already
1162 /// ensure that memory accesses never cross stack slots, so there is no risk
1163 /// of a memory access being tagged with the wrong category.
1164 #[derive(Debug, PartialEq, Clone, Copy)]
1165 enum AACategory {
1166     Other,
1167     Heap,
1168     Table,
1169     VmCtx,
1170 }
1171 
1172 impl AACategory {
1173     pub fn all() -> &'static [Self] {
1174         &[
1175             AACategory::Other,
1176             AACategory::Heap,
1177             AACategory::Table,
1178             AACategory::VmCtx,
1179         ]
1180     }
1181 
1182     pub fn update_memflags(&self, flags: &mut MemFlags) {
1183         match self {
1184             AACategory::Other => {}
1185             AACategory::Heap => flags.set_heap(),
1186             AACategory::Table => flags.set_table(),
1187             AACategory::VmCtx => flags.set_vmctx(),
1188         }
1189     }
1190 }
1191 
1192 #[derive(Default)]
1193 struct Resources {
1194     vars: HashMap<Type, Vec<Variable>>,
1195     blocks: Vec<(Block, BlockSignature)>,
1196     blocks_without_params: Vec<Block>,
1197     block_terminators: Vec<BlockTerminator>,
1198     func_refs: Vec<(Signature, SigRef, FuncRef)>,
1199     /// This field is required to be sorted by stack slot size at all times.
1200     /// We use this invariant when searching for stack slots with a given size.
1201     /// See [FunctionGenerator::stack_slot_with_size]
1202     stack_slots: Vec<(StackSlot, StackSize, AACategory)>,
1203     usercalls: Vec<(UserExternalName, Signature)>,
1204     libcalls: Vec<LibCall>,
1205 }
1206 
1207 impl Resources {
1208     /// Partitions blocks at `block`. Only blocks that can be targeted by branches are considered.
1209     ///
1210     /// The first slice includes all blocks up to and including `block`.
1211     /// The second slice includes all remaining blocks.
1212     fn partition_target_blocks(
1213         &self,
1214         block: Block,
1215     ) -> (&[(Block, BlockSignature)], &[(Block, BlockSignature)]) {
1216         // Blocks are stored in-order and have no gaps, this means that we can simply index them by
1217         // their number. We also need to exclude the entry block since it isn't a valid target.
1218         let target_blocks = &self.blocks[1..];
1219         target_blocks.split_at(block.as_u32() as usize)
1220     }
1221 
1222     /// Returns blocks forward of `block`. Only blocks that can be targeted by branches are considered.
1223     fn forward_blocks(&self, block: Block) -> &[(Block, BlockSignature)] {
1224         let (_, forward_blocks) = self.partition_target_blocks(block);
1225         forward_blocks
1226     }
1227 
1228     /// Generates a slice of `blocks_without_params` ahead of `block`
1229     fn forward_blocks_without_params(&self, block: Block) -> &[Block] {
1230         let partition_point = self.blocks_without_params.partition_point(|b| *b <= block);
1231         &self.blocks_without_params[partition_point..]
1232     }
1233 
1234     /// Generates an iterator of all valid tail call targets. This includes all functions with both
1235     ///  the `tail` calling convention and the same return values as the caller.
1236     fn tail_call_targets<'a>(
1237         &'a self,
1238         caller_sig: &'a Signature,
1239     ) -> impl Iterator<Item = &'a (Signature, SigRef, FuncRef)> {
1240         self.func_refs.iter().filter(|(sig, _, _)| {
1241             sig.call_conv == CallConv::Tail && sig.returns == caller_sig.returns
1242         })
1243     }
1244 }
1245 
1246 impl<'r, 'data> FunctionGenerator<'r, 'data>
1247 where
1248     'data: 'r,
1249 {
1250     pub fn new(
1251         u: &'r mut Unstructured<'data>,
1252         config: &'r Config,
1253         isa: OwnedTargetIsa,
1254         name: UserFuncName,
1255         signature: Signature,
1256         usercalls: Vec<(UserExternalName, Signature)>,
1257         libcalls: Vec<LibCall>,
1258     ) -> Self {
1259         Self {
1260             u,
1261             config,
1262             resources: Resources {
1263                 usercalls,
1264                 libcalls,
1265                 ..Resources::default()
1266             },
1267             isa,
1268             name,
1269             signature,
1270         }
1271     }
1272 
1273     /// Generates a random value for config `param`
1274     fn param(&mut self, param: &RangeInclusive<usize>) -> Result<usize> {
1275         Ok(self.u.int_in_range(param.clone())?)
1276     }
1277 
1278     fn system_callconv(&mut self) -> CallConv {
1279         // TODO: This currently only runs on linux, so this is the only choice
1280         // We should improve this once we generate flags and targets
1281         CallConv::SystemV
1282     }
1283 
1284     /// Finds a stack slot with size of at least n bytes
1285     fn stack_slot_with_size(&mut self, n: u32) -> Result<(StackSlot, StackSize, AACategory)> {
1286         let first = self
1287             .resources
1288             .stack_slots
1289             .partition_point(|&(_slot, size, _category)| size < n);
1290         Ok(*self.u.choose(&self.resources.stack_slots[first..])?)
1291     }
1292 
1293     /// Generates an address that should allow for a store or a load.
1294     ///
1295     /// Addresses aren't generated like other values. They are never stored in variables so that
1296     /// we don't run the risk of returning them from a function, which would make the fuzzer
1297     /// complain since they are different from the interpreter to the backend.
1298     ///
1299     /// `min_size`: Controls the amount of space that the address should have.
1300     ///
1301     /// `aligned`: When passed as true, the resulting address is guaranteed to be aligned
1302     /// on an 8 byte boundary.
1303     ///
1304     /// Returns a valid address and the maximum possible offset that still respects `min_size`.
1305     fn generate_load_store_address(
1306         &mut self,
1307         builder: &mut FunctionBuilder,
1308         min_size: u32,
1309         aligned: bool,
1310     ) -> Result<(Value, u32, AACategory)> {
1311         // TODO: Currently our only source of addresses is stack_addr, but we
1312         // should add global_value, symbol_value eventually
1313         let (addr, available_size, category) = {
1314             let (ss, slot_size, category) = self.stack_slot_with_size(min_size)?;
1315 
1316             // stack_slot_with_size guarantees that slot_size >= min_size
1317             let max_offset = slot_size - min_size;
1318             let offset = if aligned {
1319                 self.u.int_in_range(0..=max_offset / min_size)? * min_size
1320             } else {
1321                 self.u.int_in_range(0..=max_offset)?
1322             };
1323 
1324             let base_addr = builder.ins().stack_addr(I64, ss, offset as i32);
1325             let available_size = slot_size.saturating_sub(offset);
1326             (base_addr, available_size, category)
1327         };
1328 
1329         // TODO: Insert a bunch of amode opcodes here to modify the address!
1330 
1331         // Now that we have an address and a size, we just choose a random offset to return to the
1332         // caller. Preserving min_size bytes.
1333         let max_offset = available_size.saturating_sub(min_size);
1334         Ok((addr, max_offset, category))
1335     }
1336 
1337     // Generates an address and memflags for a load or store.
1338     fn generate_address_and_memflags(
1339         &mut self,
1340         builder: &mut FunctionBuilder,
1341         min_size: u32,
1342         is_atomic: bool,
1343     ) -> Result<(Value, MemFlags, Offset32)> {
1344         // Should we generate an aligned address
1345         // Some backends have issues with unaligned atomics.
1346         // AArch64: https://github.com/bytecodealliance/wasmtime/issues/5483
1347         // RISCV: https://github.com/bytecodealliance/wasmtime/issues/5882
1348         let requires_aligned_atomics = matches!(
1349             self.isa.triple().architecture,
1350             Architecture::Aarch64(_) | Architecture::Riscv64(_)
1351         );
1352         let aligned = if is_atomic && requires_aligned_atomics {
1353             true
1354         } else if min_size > 8 {
1355             // TODO: We currently can't guarantee that a stack_slot will be aligned on a 16 byte
1356             // boundary. We don't have a way to specify alignment when creating stack slots, and
1357             // cranelift only guarantees 8 byte alignment between stack slots.
1358             // See: https://github.com/bytecodealliance/wasmtime/issues/5922#issuecomment-1457926624
1359             false
1360         } else {
1361             bool::arbitrary(self.u)?
1362         };
1363 
1364         let mut flags = MemFlags::new();
1365         // Even if we picked an aligned address, we can always generate unaligned memflags
1366         if aligned && bool::arbitrary(self.u)? {
1367             flags.set_aligned();
1368         }
1369         // If the address is aligned, then we know it won't trap
1370         if aligned && bool::arbitrary(self.u)? {
1371             flags.set_notrap();
1372         }
1373 
1374         let (address, max_offset, category) =
1375             self.generate_load_store_address(builder, min_size, aligned)?;
1376 
1377         // Set the Alias Analysis bits on the memflags
1378         category.update_memflags(&mut flags);
1379 
1380         // Pick an offset to pass into the load/store.
1381         let offset = if aligned {
1382             0
1383         } else {
1384             self.u.int_in_range(0..=max_offset)? as i32
1385         }
1386         .into();
1387 
1388         Ok((address, flags, offset))
1389     }
1390 
1391     /// Get a variable of type `ty` from the current function
1392     fn get_variable_of_type(&mut self, ty: Type) -> Result<Variable> {
1393         let opts = self.resources.vars.get(&ty).map_or(&[][..], Vec::as_slice);
1394         let var = self.u.choose(opts)?;
1395         Ok(*var)
1396     }
1397 
1398     /// Generates an instruction(`iconst`/`fconst`/etc...) to introduce a constant value
1399     fn generate_const(&mut self, builder: &mut FunctionBuilder, ty: Type) -> Result<Value> {
1400         Ok(match self.u.datavalue(ty)? {
1401             DataValue::I8(i) => builder.ins().iconst(ty, i as u8 as i64),
1402             DataValue::I16(i) => builder.ins().iconst(ty, i as u16 as i64),
1403             DataValue::I32(i) => builder.ins().iconst(ty, i as u32 as i64),
1404             DataValue::I64(i) => builder.ins().iconst(ty, i),
1405             DataValue::I128(i) => {
1406                 let hi = builder.ins().iconst(I64, (i >> 64) as i64);
1407                 let lo = builder.ins().iconst(I64, i as i64);
1408                 builder.ins().iconcat(lo, hi)
1409             }
1410             DataValue::F32(f) => builder.ins().f32const(f),
1411             DataValue::F64(f) => builder.ins().f64const(f),
1412             DataValue::V128(bytes) => {
1413                 let data = bytes.to_vec().into();
1414                 let handle = builder.func.dfg.constants.insert(data);
1415                 builder.ins().vconst(ty, handle)
1416             }
1417             _ => unimplemented!(),
1418         })
1419     }
1420 
1421     /// Chooses a random block which can be targeted by a jump / branch.
1422     /// This means any block that is not the first block.
1423     fn generate_target_block(&mut self, source_block: Block) -> Result<Block> {
1424         // We try to mostly generate forward branches to avoid generating an excessive amount of
1425         // infinite loops. But they are still important, so give them a small chance of existing.
1426         let (backwards_blocks, forward_blocks) =
1427             self.resources.partition_target_blocks(source_block);
1428         let ratio = self.config.backwards_branch_ratio;
1429         let block_targets = if !backwards_blocks.is_empty() && self.u.ratio(ratio.0, ratio.1)? {
1430             backwards_blocks
1431         } else {
1432             forward_blocks
1433         };
1434         assert!(!block_targets.is_empty());
1435 
1436         let (block, _) = self.u.choose(block_targets)?.clone();
1437         Ok(block)
1438     }
1439 
1440     fn generate_values_for_block(
1441         &mut self,
1442         builder: &mut FunctionBuilder,
1443         block: Block,
1444     ) -> Result<Vec<Value>> {
1445         let (_, sig) = self.resources.blocks[block.as_u32() as usize].clone();
1446         self.generate_values_for_signature(builder, sig.iter().copied())
1447     }
1448 
1449     fn generate_values_for_signature<I: Iterator<Item = Type>>(
1450         &mut self,
1451         builder: &mut FunctionBuilder,
1452         signature: I,
1453     ) -> Result<Vec<Value>> {
1454         signature
1455             .map(|ty| {
1456                 let var = self.get_variable_of_type(ty)?;
1457                 let val = builder.use_var(var);
1458                 Ok(val)
1459             })
1460             .collect()
1461     }
1462 
1463     /// The terminator that we need to insert has already been picked ahead of time
1464     /// we just need to build the instructions for it
1465     fn insert_terminator(
1466         &mut self,
1467         builder: &mut FunctionBuilder,
1468         source_block: Block,
1469     ) -> Result<()> {
1470         let terminator = self.resources.block_terminators[source_block.as_u32() as usize].clone();
1471 
1472         match terminator {
1473             BlockTerminator::Return => {
1474                 let types: Vec<Type> = {
1475                     let rets = &builder.func.signature.returns;
1476                     rets.iter().map(|p| p.value_type).collect()
1477                 };
1478                 let vals = self.generate_values_for_signature(builder, types.into_iter())?;
1479 
1480                 builder.ins().return_(&vals[..]);
1481             }
1482             BlockTerminator::Jump(target) => {
1483                 let args = self.generate_values_for_block(builder, target)?;
1484                 builder.ins().jump(target, &args[..]);
1485             }
1486             BlockTerminator::Br(left, right) => {
1487                 let left_args = self.generate_values_for_block(builder, left)?;
1488                 let right_args = self.generate_values_for_block(builder, right)?;
1489 
1490                 let condbr_types = [I8, I16, I32, I64, I128];
1491                 let _type = *self.u.choose(&condbr_types[..])?;
1492                 let val = builder.use_var(self.get_variable_of_type(_type)?);
1493                 builder
1494                     .ins()
1495                     .brif(val, left, &left_args[..], right, &right_args[..]);
1496             }
1497             BlockTerminator::BrTable(default, targets) => {
1498                 // Create jump tables on demand
1499                 let mut jt = Vec::with_capacity(targets.len());
1500                 for block in targets {
1501                     let args = self.generate_values_for_block(builder, block)?;
1502                     jt.push(builder.func.dfg.block_call(block, &args))
1503                 }
1504 
1505                 let args = self.generate_values_for_block(builder, default)?;
1506                 let jt_data = JumpTableData::new(builder.func.dfg.block_call(default, &args), &jt);
1507                 let jt = builder.create_jump_table(jt_data);
1508 
1509                 // br_table only supports I32
1510                 let val = builder.use_var(self.get_variable_of_type(I32)?);
1511 
1512                 builder.ins().br_table(val, jt);
1513             }
1514             BlockTerminator::Switch(_type, default, entries) => {
1515                 let mut switch = Switch::new();
1516                 for (&entry, &block) in entries.iter() {
1517                     switch.set_entry(entry, block);
1518                 }
1519 
1520                 let switch_val = builder.use_var(self.get_variable_of_type(_type)?);
1521 
1522                 switch.emit(builder, switch_val, default);
1523             }
1524             BlockTerminator::TailCall(target) | BlockTerminator::TailCallIndirect(target) => {
1525                 let (sig, sig_ref, func_ref) = self
1526                     .resources
1527                     .func_refs
1528                     .iter()
1529                     .find(|(_, _, f)| *f == target)
1530                     .expect("Failed to find previously selected function")
1531                     .clone();
1532 
1533                 let opcode = match terminator {
1534                     BlockTerminator::TailCall(_) => Opcode::ReturnCall,
1535                     BlockTerminator::TailCallIndirect(_) => Opcode::ReturnCallIndirect,
1536                     _ => unreachable!(),
1537                 };
1538 
1539                 insert_call_to_function(self, builder, opcode, &sig, sig_ref, func_ref)?;
1540             }
1541         }
1542 
1543         Ok(())
1544     }
1545 
1546     /// Fills the current block with random instructions
1547     fn generate_instructions(&mut self, builder: &mut FunctionBuilder) -> Result<()> {
1548         for _ in 0..self.param(&self.config.instructions_per_block)? {
1549             let (op, args, rets) = self.u.choose(&OPCODE_SIGNATURES)?;
1550 
1551             // We filter out instructions that aren't supported by the target at this point instead
1552             // of building a single vector of valid instructions at the beginning of function
1553             // generation, to avoid invalidating the corpus when instructions are enabled/disabled.
1554             if !valid_for_target(&self.isa.triple(), *op, &args, &rets) {
1555                 return Err(arbitrary::Error::IncorrectFormat.into());
1556             }
1557 
1558             let inserter = inserter_for_format(op.format());
1559             inserter(self, builder, *op, &args, &rets)?;
1560         }
1561 
1562         Ok(())
1563     }
1564 
1565     fn generate_funcrefs(&mut self, builder: &mut FunctionBuilder) -> Result<()> {
1566         let usercalls: Vec<(ExternalName, Signature)> = self
1567             .resources
1568             .usercalls
1569             .iter()
1570             .map(|(name, signature)| {
1571                 let user_func_ref = builder.func.declare_imported_user_function(name.clone());
1572                 let name = ExternalName::User(user_func_ref);
1573                 (name, signature.clone())
1574             })
1575             .collect();
1576 
1577         let lib_callconv = self.system_callconv();
1578         let libcalls: Vec<(ExternalName, Signature)> = self
1579             .resources
1580             .libcalls
1581             .iter()
1582             .map(|libcall| {
1583                 let pointer_type = Type::int_with_byte_size(
1584                     self.isa.triple().pointer_width().unwrap().bytes().into(),
1585                 )
1586                 .unwrap();
1587                 let signature = libcall.signature(lib_callconv, pointer_type);
1588                 let name = ExternalName::LibCall(*libcall);
1589                 (name, signature)
1590             })
1591             .collect();
1592 
1593         for (name, signature) in usercalls.into_iter().chain(libcalls) {
1594             let sig_ref = builder.import_signature(signature.clone());
1595             let func_ref = builder.import_function(ExtFuncData {
1596                 name,
1597                 signature: sig_ref,
1598                 colocated: self.u.arbitrary()?,
1599             });
1600 
1601             self.resources
1602                 .func_refs
1603                 .push((signature, sig_ref, func_ref));
1604         }
1605 
1606         Ok(())
1607     }
1608 
1609     fn generate_stack_slots(&mut self, builder: &mut FunctionBuilder) -> Result<()> {
1610         for _ in 0..self.param(&self.config.static_stack_slots_per_function)? {
1611             let bytes = self.param(&self.config.static_stack_slot_size)? as u32;
1612             let ss_data = StackSlotData::new(StackSlotKind::ExplicitSlot, bytes);
1613             let slot = builder.create_sized_stack_slot(ss_data);
1614 
1615             // Generate one Alias Analysis Category for each slot
1616             let category = *self.u.choose(AACategory::all())?;
1617 
1618             self.resources.stack_slots.push((slot, bytes, category));
1619         }
1620 
1621         self.resources
1622             .stack_slots
1623             .sort_unstable_by_key(|&(_slot, bytes, _category)| bytes);
1624 
1625         Ok(())
1626     }
1627 
1628     /// Zero initializes the stack slot by inserting `stack_store`'s.
1629     fn initialize_stack_slots(&mut self, builder: &mut FunctionBuilder) -> Result<()> {
1630         let i8_zero = builder.ins().iconst(I8, 0);
1631         let i16_zero = builder.ins().iconst(I16, 0);
1632         let i32_zero = builder.ins().iconst(I32, 0);
1633         let i64_zero = builder.ins().iconst(I64, 0);
1634         let i128_zero = builder.ins().uextend(I128, i64_zero);
1635 
1636         for &(slot, init_size, category) in self.resources.stack_slots.iter() {
1637             let mut size = init_size;
1638 
1639             // Insert the largest available store for the remaining size.
1640             while size != 0 {
1641                 let offset = (init_size - size) as i32;
1642                 let (val, filled) = match size {
1643                     sz if sz / 16 > 0 => (i128_zero, 16),
1644                     sz if sz / 8 > 0 => (i64_zero, 8),
1645                     sz if sz / 4 > 0 => (i32_zero, 4),
1646                     sz if sz / 2 > 0 => (i16_zero, 2),
1647                     _ => (i8_zero, 1),
1648                 };
1649                 let addr = builder.ins().stack_addr(I64, slot, offset);
1650 
1651                 // Each stack slot has an associated category, that means we have to set the
1652                 // correct memflags for it. So we can't use `stack_store` directly.
1653                 let mut flags = MemFlags::new();
1654                 flags.set_notrap();
1655                 category.update_memflags(&mut flags);
1656 
1657                 builder.ins().store(flags, val, addr, 0);
1658 
1659                 size -= filled;
1660             }
1661         }
1662         Ok(())
1663     }
1664 
1665     /// Creates a random amount of blocks in this function
1666     fn generate_blocks(&mut self, builder: &mut FunctionBuilder) -> Result<()> {
1667         let extra_block_count = self.param(&self.config.blocks_per_function)?;
1668 
1669         // We must always have at least one block, so we generate the "extra" blocks and add 1 for
1670         // the entry block.
1671         let block_count = 1 + extra_block_count;
1672 
1673         // Blocks need to be sorted in ascending order
1674         self.resources.blocks = (0..block_count)
1675             .map(|i| {
1676                 let is_entry = i == 0;
1677                 let block = builder.create_block();
1678 
1679                 // Optionally mark blocks that are not the entry block as cold
1680                 if !is_entry {
1681                     if bool::arbitrary(self.u)? {
1682                         builder.set_cold_block(block);
1683                     }
1684                 }
1685 
1686                 // The first block has to have the function signature, but for the rest of them we generate
1687                 // a random signature;
1688                 if is_entry {
1689                     builder.append_block_params_for_function_params(block);
1690                     Ok((
1691                         block,
1692                         self.signature.params.iter().map(|a| a.value_type).collect(),
1693                     ))
1694                 } else {
1695                     let sig = self.generate_block_signature()?;
1696                     sig.iter().for_each(|ty| {
1697                         builder.append_block_param(block, *ty);
1698                     });
1699                     Ok((block, sig))
1700                 }
1701             })
1702             .collect::<Result<Vec<_>>>()?;
1703 
1704         // Valid blocks for jump tables have to have no parameters in the signature, and must also
1705         // not be the first block.
1706         self.resources.blocks_without_params = self.resources.blocks[1..]
1707             .iter()
1708             .filter(|(_, sig)| sig.len() == 0)
1709             .map(|(b, _)| *b)
1710             .collect();
1711 
1712         // Compute the block CFG
1713         //
1714         // cranelift-frontend requires us to never generate unreachable blocks
1715         // To ensure this property we start by constructing a main "spine" of blocks. So block1 can
1716         // always jump to block2, and block2 can always jump to block3, etc...
1717         //
1718         // That is not a very interesting CFG, so we introduce variations on that, but always
1719         // ensuring that the property of pointing to the next block is maintained whatever the
1720         // branching mechanism we use.
1721         let blocks = self.resources.blocks.clone();
1722         self.resources.block_terminators = blocks
1723             .iter()
1724             .map(|&(block, _)| {
1725                 let next_block = Block::with_number(block.as_u32() + 1).unwrap();
1726                 let forward_blocks = self.resources.forward_blocks(block);
1727                 let paramless_targets = self.resources.forward_blocks_without_params(block);
1728                 let has_paramless_targets = !paramless_targets.is_empty();
1729                 let next_block_is_paramless = paramless_targets.contains(&next_block);
1730 
1731                 let mut valid_terminators = vec![];
1732 
1733                 if forward_blocks.is_empty() {
1734                     // Return is only valid on the last block.
1735                     valid_terminators.push(BlockTerminatorKind::Return);
1736                 } else {
1737                     // If we have more than one block we can allow terminators that target blocks.
1738                     // TODO: We could add some kind of BrReturn here, to explore edges where we
1739                     // exit in the middle of the function
1740                     valid_terminators.extend_from_slice(&[
1741                         BlockTerminatorKind::Jump,
1742                         BlockTerminatorKind::Br,
1743                         BlockTerminatorKind::BrTable,
1744                     ]);
1745                 }
1746 
1747                 // As the Switch interface only allows targeting blocks without params we need
1748                 // to ensure that the next block has no params, since that one is guaranteed to be
1749                 // picked in either case.
1750                 if has_paramless_targets && next_block_is_paramless {
1751                     valid_terminators.push(BlockTerminatorKind::Switch);
1752                 }
1753 
1754                 // Tail Calls are a block terminator, so we should insert them as any other block
1755                 // terminator. We should ensure that we can select at least one target before considering
1756                 // them as candidate instructions.
1757                 let has_tail_callees = self
1758                     .resources
1759                     .tail_call_targets(&self.signature)
1760                     .next()
1761                     .is_some();
1762                 let is_tail_caller = self.signature.call_conv == CallConv::Tail;
1763 
1764                 let supports_tail_calls = match self.isa.triple().architecture {
1765                     Architecture::Aarch64(_) | Architecture::Riscv64(_) => true,
1766                     // TODO: x64 currently requires frame pointers for tail calls.
1767                     Architecture::X86_64 => self.isa.flags().preserve_frame_pointers(),
1768                     // TODO: Other platforms do not support tail calls yet.
1769                     _ => false,
1770                 };
1771 
1772                 if is_tail_caller && has_tail_callees && supports_tail_calls {
1773                     valid_terminators.extend([
1774                         BlockTerminatorKind::TailCall,
1775                         BlockTerminatorKind::TailCallIndirect,
1776                     ]);
1777                 }
1778 
1779                 let terminator = self.u.choose(&valid_terminators)?;
1780 
1781                 // Choose block targets for the terminators that we picked above
1782                 Ok(match terminator {
1783                     BlockTerminatorKind::Return => BlockTerminator::Return,
1784                     BlockTerminatorKind::Jump => BlockTerminator::Jump(next_block),
1785                     BlockTerminatorKind::Br => {
1786                         BlockTerminator::Br(next_block, self.generate_target_block(block)?)
1787                     }
1788                     // TODO: Allow generating backwards branches here
1789                     BlockTerminatorKind::BrTable => {
1790                         // Make the default the next block, and then we don't have to worry
1791                         // that we can reach it via the targets
1792                         let default = next_block;
1793 
1794                         let target_count = self.param(&self.config.jump_table_entries)?;
1795                         let targets = Result::from_iter(
1796                             (0..target_count).map(|_| self.generate_target_block(block)),
1797                         )?;
1798 
1799                         BlockTerminator::BrTable(default, targets)
1800                     }
1801                     BlockTerminatorKind::Switch => {
1802                         // Make the default the next block, and then we don't have to worry
1803                         // that we can reach it via the entries below
1804                         let default_block = next_block;
1805 
1806                         let _type = *self.u.choose(&[I8, I16, I32, I64, I128][..])?;
1807 
1808                         // Build this into a HashMap since we cannot have duplicate entries.
1809                         let mut entries = HashMap::new();
1810                         for _ in 0..self.param(&self.config.switch_cases)? {
1811                             // The Switch API only allows for entries that are addressable by the index type
1812                             // so we need to limit the range of values that we generate.
1813                             let (ty_min, ty_max) = _type.bounds(false);
1814                             let range_start = self.u.int_in_range(ty_min..=ty_max)?;
1815 
1816                             // We can either insert a contiguous range of blocks or a individual block
1817                             // This is done because the Switch API specializes contiguous ranges.
1818                             let range_size = if bool::arbitrary(self.u)? {
1819                                 1
1820                             } else {
1821                                 self.param(&self.config.switch_max_range_size)?
1822                             } as u128;
1823 
1824                             // Build the switch entries
1825                             for i in 0..range_size {
1826                                 let index = range_start.wrapping_add(i) % ty_max;
1827                                 let block = *self
1828                                     .u
1829                                     .choose(self.resources.forward_blocks_without_params(block))?;
1830 
1831                                 entries.insert(index, block);
1832                             }
1833                         }
1834 
1835                         BlockTerminator::Switch(_type, default_block, entries)
1836                     }
1837                     BlockTerminatorKind::TailCall => {
1838                         let targets = self
1839                             .resources
1840                             .tail_call_targets(&self.signature)
1841                             .collect::<Vec<_>>();
1842                         let (_, _, funcref) = *self.u.choose(&targets[..])?;
1843                         BlockTerminator::TailCall(*funcref)
1844                     }
1845                     BlockTerminatorKind::TailCallIndirect => {
1846                         let targets = self
1847                             .resources
1848                             .tail_call_targets(&self.signature)
1849                             .collect::<Vec<_>>();
1850                         let (_, _, funcref) = *self.u.choose(&targets[..])?;
1851                         BlockTerminator::TailCallIndirect(*funcref)
1852                     }
1853                 })
1854             })
1855             .collect::<Result<_>>()?;
1856 
1857         Ok(())
1858     }
1859 
1860     fn generate_block_signature(&mut self) -> Result<BlockSignature> {
1861         let param_count = self.param(&self.config.block_signature_params)?;
1862 
1863         let mut params = Vec::with_capacity(param_count);
1864         for _ in 0..param_count {
1865             params.push(self.u._type((&*self.isa).supports_simd())?);
1866         }
1867         Ok(params)
1868     }
1869 
1870     fn build_variable_pool(&mut self, builder: &mut FunctionBuilder) -> Result<()> {
1871         let block = builder.current_block().unwrap();
1872 
1873         // Define variables for the function signature
1874         let mut vars: Vec<_> = builder
1875             .func
1876             .signature
1877             .params
1878             .iter()
1879             .map(|param| param.value_type)
1880             .zip(builder.block_params(block).iter().copied())
1881             .collect();
1882 
1883         // Create a pool of vars that are going to be used in this function
1884         for _ in 0..self.param(&self.config.vars_per_function)? {
1885             let ty = self.u._type((&*self.isa).supports_simd())?;
1886             let value = self.generate_const(builder, ty)?;
1887             vars.push((ty, value));
1888         }
1889 
1890         for (id, (ty, value)) in vars.into_iter().enumerate() {
1891             let var = Variable::new(id);
1892             builder.declare_var(var, ty);
1893             builder.def_var(var, value);
1894             self.resources
1895                 .vars
1896                 .entry(ty)
1897                 .or_insert_with(Vec::new)
1898                 .push(var);
1899         }
1900 
1901         Ok(())
1902     }
1903 
1904     /// We generate a function in multiple stages:
1905     ///
1906     /// * First we generate a random number of empty blocks
1907     /// * Then we generate a random pool of variables to be used throughout the function
1908     /// * We then visit each block and generate random instructions
1909     ///
1910     /// Because we generate all blocks and variables up front we already know everything that
1911     /// we need when generating instructions (i.e. jump targets / variables)
1912     pub fn generate(mut self) -> Result<Function> {
1913         let mut fn_builder_ctx = FunctionBuilderContext::new();
1914         let mut func = Function::with_name_signature(self.name.clone(), self.signature.clone());
1915 
1916         let mut builder = FunctionBuilder::new(&mut func, &mut fn_builder_ctx);
1917 
1918         // Build the function references before generating the block CFG since we store
1919         // function references in the CFG.
1920         self.generate_funcrefs(&mut builder)?;
1921         self.generate_blocks(&mut builder)?;
1922 
1923         // Function preamble
1924         self.generate_stack_slots(&mut builder)?;
1925 
1926         // Main instruction generation loop
1927         for (block, block_sig) in self.resources.blocks.clone().into_iter() {
1928             let is_block0 = block.as_u32() == 0;
1929             builder.switch_to_block(block);
1930 
1931             if is_block0 {
1932                 // The first block is special because we must create variables both for the
1933                 // block signature and for the variable pool. Additionally, we must also define
1934                 // initial values for all variables that are not the function signature.
1935                 self.build_variable_pool(&mut builder)?;
1936 
1937                 // Stack slots have random bytes at the beginning of the function
1938                 // initialize them to a constant value so that execution stays predictable.
1939                 self.initialize_stack_slots(&mut builder)?;
1940             } else {
1941                 // Define variables for the block params
1942                 for (i, ty) in block_sig.iter().enumerate() {
1943                     let var = self.get_variable_of_type(*ty)?;
1944                     let block_param = builder.block_params(block)[i];
1945                     builder.def_var(var, block_param);
1946                 }
1947             }
1948 
1949             // Generate block instructions
1950             self.generate_instructions(&mut builder)?;
1951 
1952             // Insert a terminator to safely exit the block
1953             self.insert_terminator(&mut builder, block)?;
1954         }
1955 
1956         builder.seal_all_blocks();
1957         builder.finalize();
1958 
1959         Ok(func)
1960     }
1961 }
1962