1use std::ops::{Index, IndexMut};
30
31use rucc_base::{Idx, Symbol};
32use rucc_diag::Span;
33use rucc_target::Slot;
34
35use crate::inst::{
36 Abi, AbiList, AsmInfo, Block, BlockCall, BlockCallList, BlockData, CallInfo, Def, Extra, Imm,
37 ImmList, Inst, InstData, InstLayout, MemInfo, Sig, Signature, SlotList, SwitchInfo, VaInfo,
38 Value, ValueData, ValueList,
39};
40use crate::module::{Linkage, Visibility};
41use crate::{Attrs, Facts, Flags, FloatPred, IntPred, MemOrder, Opcode, PrefetchHint, RmwOp, Type};
42
43#[derive(Debug)]
45pub struct Func {
46 pub name: Symbol,
48 pub linkage: Linkage,
50 pub visibility: Visibility,
52 pub section: Option<Symbol>,
55 pub align: Option<u32>,
62 pub attrs: Attrs,
65
66 values: Vec<ValueData>,
67 insts: Vec<InstData>,
68 inst_layout: Vec<InstLayout>,
69 inst_spans: Vec<Span>,
70 blocks: Vec<BlockData>,
71
72 value_pool: Vec<Value>,
73 block_calls: Vec<BlockCall>,
74 imms: Vec<Imm>,
75 mem: Vec<MemInfo>,
76 calls: Vec<CallInfo>,
77 abis: Vec<Abi>,
78 switches: Vec<SwitchInfo>,
79 asms: Vec<AsmInfo>,
80 slots: Vec<Slot>,
81 va_objects: Vec<VaInfo>,
82 signatures: Vec<Signature>,
83 facts: Vec<(Value, Facts)>,
84 labels: Vec<(Block, Symbol)>,
85
86 first_block: Option<Block>,
87 last_block: Option<Block>,
88}
89
90impl Func {
91 #[must_use]
98 pub fn new(name: Symbol, signature: Signature) -> Self {
99 Self {
100 name,
101 linkage: Linkage::External,
102 visibility: Visibility::Default,
103 section: None,
104 align: None,
105 attrs: Attrs::NONE,
106 values: Vec::new(),
107 insts: Vec::new(),
108 inst_layout: Vec::new(),
109 inst_spans: Vec::new(),
110 blocks: Vec::new(),
111 value_pool: Vec::new(),
112 block_calls: Vec::new(),
113 imms: Vec::new(),
114 mem: Vec::new(),
115 calls: Vec::new(),
116 abis: Vec::new(),
117 switches: Vec::new(),
118 asms: Vec::new(),
119 slots: Vec::new(),
120 va_objects: Vec::new(),
121 signatures: vec![signature],
122 facts: Vec::new(),
123 labels: Vec::new(),
124 first_block: None,
125 last_block: None,
126 }
127 }
128
129 #[must_use]
131 pub fn signature(&self) -> &Signature {
132 &self.signatures[0]
133 }
134
135 pub fn set_signature(&mut self, signature: Signature) {
145 self.signatures[0] = signature;
146 }
147
148 pub fn signatures(&self) -> impl Iterator<Item = &Signature> {
150 self.signatures.iter()
151 }
152
153 pub fn add_signature(&mut self, signature: Signature) -> Sig {
155 self.signatures.push(signature);
156 Idx::from_usize(self.signatures.len() - 1)
157 }
158
159 #[must_use]
164 pub fn entry(&self) -> Option<Block> {
165 self.first_block
166 }
167
168 #[must_use]
175 pub fn is_declaration(&self) -> bool {
176 self.first_block.is_none()
177 }
178
179 pub fn create_block(&mut self) -> Block {
183 let block = Idx::from_usize(self.blocks.len());
184 self.blocks.push(BlockData { prev: self.last_block, ..BlockData::default() });
185 match self.last_block {
186 Some(last) => self.blocks[last.index()].next = Some(block),
187 None => self.first_block = Some(block),
188 }
189 self.last_block = Some(block);
190 block
191 }
192
193 pub fn remove_block(&mut self, block: Block) {
206 assert!(self.first_block != Some(block), "the entry block is not removable");
207 let (prev, next) = (self.blocks[block.index()].prev, self.blocks[block.index()].next);
208 match prev {
209 Some(prev) => self.blocks[prev.index()].next = next,
210 None => self.first_block = next,
211 }
212 match next {
213 Some(next) => self.blocks[next.index()].prev = prev,
214 None => self.last_block = prev,
215 }
216 let insts: Vec<Inst> = self.insts(block).collect();
220 for inst in insts {
221 self.inst_layout[inst.index()] = InstLayout::default();
222 }
223 self.blocks[block.index()] = BlockData::default();
224 }
225
226 pub fn append_param(&mut self, block: Block, ty: Type) -> Value {
235 let index = u32::try_from(self.blocks[block.index()].params.len())
236 .expect("a block with four billion parameters");
237 let value = self.add_value(ValueData { ty, def: Def::Param { block, index } });
238 self.blocks[block.index()].params.push(value);
239 value
240 }
241
242 pub fn retain_params(&mut self, block: Block, mut keep: impl FnMut(Value) -> bool) {
254 let mut params = std::mem::take(&mut self.blocks[block.index()].params);
255 params.retain(|&value| keep(value));
256 for (index, &value) in params.iter().enumerate() {
257 let index = u32::try_from(index).expect("a block with four billion parameters");
258 self.values[value.index()].def = Def::Param { block, index };
259 }
260 self.blocks[block.index()].params = params;
261 }
262
263 pub fn retype(&mut self, value: Value, ty: Type) {
275 self.values[value.index()].ty = ty;
276 }
277
278 pub fn values(&self) -> impl Iterator<Item = Value> + use<'_> {
283 (0..self.values.len()).map(Idx::from_usize)
284 }
285
286 pub fn blocks(&self) -> impl Iterator<Item = Block> + use<'_> {
288 std::iter::successors(self.first_block, move |&block| self.blocks[block.index()].next)
289 }
290
291 pub fn insts(&self, block: Block) -> impl Iterator<Item = Inst> + use<'_> {
293 std::iter::successors(self.blocks[block.index()].first, move |&inst| {
294 self.inst_layout[inst.index()].next
295 })
296 }
297
298 pub fn insts_backwards(&self, block: Block) -> impl Iterator<Item = Inst> + use<'_> {
304 std::iter::successors(self.blocks[block.index()].last, move |&inst| {
305 self.inst_layout[inst.index()].prev
306 })
307 }
308
309 #[must_use]
311 pub fn terminator(&self, block: Block) -> Option<Inst> {
312 self.blocks[block.index()].last.filter(|&inst| self.is_terminator(inst))
313 }
314
315 #[must_use]
321 pub fn is_terminator(&self, inst: Inst) -> bool {
322 let data = &self[inst];
323 match data.extra {
324 Extra::Asm(info) => {
325 data.opcode.is_terminator() || !self.asms[info.index()].targets.is_empty()
326 }
327 _ => data.opcode.is_terminator(),
328 }
329 }
330
331 pub fn create_inst(&mut self, mut data: InstData, results: &[Type], span: Span) -> Inst {
342 let inst = Idx::from_usize(self.insts.len());
343 data.results = u8::try_from(results.len()).expect("an instruction with too many results");
344 data.first_result = results.first().map(|_| Idx::from_usize(self.values.len()));
345 for (index, &ty) in results.iter().enumerate() {
346 let index = u8::try_from(index).expect("checked just above");
347 self.add_value(ValueData { ty, def: Def::Result { inst, index } });
348 }
349 self.insts.push(data);
350 self.inst_layout.push(InstLayout::default());
351 self.inst_spans.push(span);
352 inst
353 }
354
355 pub fn append_inst(&mut self, block: Block, inst: Inst) {
362 assert!(self.inst_layout[inst.index()].block.is_none(), "the instruction is in a block");
363 let last = self.blocks[block.index()].last;
364 self.inst_layout[inst.index()] = InstLayout { block: Some(block), prev: last, next: None };
365 match last {
366 Some(last) => self.inst_layout[last.index()].next = Some(inst),
367 None => self.blocks[block.index()].first = Some(inst),
368 }
369 self.blocks[block.index()].last = Some(inst);
370 }
371
372 pub fn insert_before(&mut self, inst: Inst, before: Inst) {
378 assert!(self.inst_layout[inst.index()].block.is_none(), "the instruction is in a block");
379 let at = self.inst_layout[before.index()];
380 let block = at.block.expect("the instruction to insert before is not in a block");
381 self.inst_layout[inst.index()] =
382 InstLayout { block: Some(block), prev: at.prev, next: Some(before) };
383 self.inst_layout[before.index()].prev = Some(inst);
384 match at.prev {
385 Some(prev) => self.inst_layout[prev.index()].next = Some(inst),
386 None => self.blocks[block.index()].first = Some(inst),
387 }
388 }
389
390 pub fn insert_after(&mut self, inst: Inst, after: Inst) {
402 assert!(self.inst_layout[inst.index()].block.is_none(), "the instruction is in a block");
403 let at = self.inst_layout[after.index()];
404 let block = at.block.expect("the instruction to insert after is not in a block");
405 assert!(at.next.is_some(), "nothing goes after a terminator");
406 self.inst_layout[inst.index()] =
407 InstLayout { block: Some(block), prev: Some(after), next: at.next };
408 self.inst_layout[after.index()].next = Some(inst);
409 if let Some(next) = at.next {
410 self.inst_layout[next.index()].prev = Some(inst);
411 }
412 }
413
414 pub fn remove_inst(&mut self, inst: Inst) {
424 let at = self.inst_layout[inst.index()];
425 let block = at.block.expect("the instruction is not in a block");
426 match at.prev {
427 Some(prev) => self.inst_layout[prev.index()].next = at.next,
428 None => self.blocks[block.index()].first = at.next,
429 }
430 match at.next {
431 Some(next) => self.inst_layout[next.index()].prev = at.prev,
432 None => self.blocks[block.index()].last = at.prev,
433 }
434 self.inst_layout[inst.index()] = InstLayout::default();
435 }
436
437 #[must_use]
439 pub fn block_of(&self, inst: Inst) -> Option<Block> {
440 self.inst_layout[inst.index()].block
441 }
442
443 #[must_use]
455 pub fn mem_in(&self, inst: Inst) -> Option<Value> {
456 let args = &self[self[inst].args];
457 args.last().copied().filter(|&arg| self[arg].ty.is_mem())
458 }
459
460 #[must_use]
470 pub fn mem_out(&self, inst: Inst) -> Option<Value> {
471 self[inst].results().last().filter(|&result| self[result].ty.is_mem())
472 }
473
474 #[must_use]
476 pub fn carries_mem(&self, inst: Inst) -> bool {
477 self.mem_in(inst).is_some() || self.mem_out(inst).is_some()
478 }
479
480 pub fn with_mem(&mut self, inst: Inst, incoming: Value) -> Inst {
496 assert!(self[incoming].ty.is_mem(), "the incoming version of memory is not memory");
497 assert!(self[inst].opcode.touches_memory(), "this does not touch memory");
498 assert!(self.mem_in(inst).is_none(), "this is already on the memory chain");
499 let data = self[inst];
500 let mut args = self[data.args].to_vec();
501 args.push(incoming);
502 let mut results: Vec<Type> = data.results().map(|result| self[result].ty).collect();
503 if data.opcode.writes_memory() {
504 results.push(Type::MEM);
505 }
506 let span = self.span(inst);
507 let args = self.push_values(&args);
508 self.create_inst(InstData { args, ..data }, &results, span)
509 }
510
511 #[must_use]
513 pub fn span(&self, inst: Inst) -> Span {
514 self.inst_spans[inst.index()]
515 }
516
517 pub fn successors(&self, inst: Inst) -> impl Iterator<Item = BlockCall> + use<'_> {
522 self.block_calls[self.target_list(inst).as_usize_range()].iter().copied()
523 }
524
525 #[must_use]
532 pub fn target_list(&self, inst: Inst) -> BlockCallList {
533 match self[inst].extra {
534 Extra::Targets(targets) => targets,
535 Extra::Switch(info) => self.switches[info.index()].targets,
536 Extra::Asm(info) => self.asms[info.index()].targets,
537 _ => BlockCallList::EMPTY,
538 }
539 }
540
541 pub fn push_values(&mut self, values: &[Value]) -> ValueList {
545 let start = Idx::from_usize(self.value_pool.len());
546 self.value_pool.extend_from_slice(values);
547 ValueList::new(start, Idx::from_usize(self.value_pool.len()))
548 }
549
550 pub fn append_arg(&mut self, list: ValueList, value: Value) -> ValueList {
557 let range = list.as_usize_range();
558 if range.end == self.value_pool.len() {
559 self.value_pool.push(value);
560 return ValueList::new(Idx::from_usize(range.start), Idx::from_usize(range.end + 1));
561 }
562 let start = self.value_pool.len();
563 self.value_pool.extend_from_within(range);
564 self.value_pool.push(value);
565 ValueList::new(Idx::from_usize(start), Idx::from_usize(self.value_pool.len()))
566 }
567
568 pub fn rewrite(&mut self, list: ValueList, mut with: impl FnMut(Value) -> Value) {
573 for value in &mut self.value_pool[list.as_usize_range()] {
574 *value = with(*value);
575 }
576 }
577
578 pub fn push_block_calls(&mut self, calls: &[BlockCall]) -> BlockCallList {
580 let start = Idx::from_usize(self.block_calls.len());
581 self.block_calls.extend_from_slice(calls);
582 BlockCallList::new(start, Idx::from_usize(self.block_calls.len()))
583 }
584
585 pub fn set_block_call(&mut self, at: Idx<BlockCall>, call: BlockCall) {
587 self.block_calls[at.index()] = call;
588 }
589
590 pub fn push_imms(&mut self, imms: &[Imm]) -> ImmList {
592 let start = Idx::from_usize(self.imms.len());
593 self.imms.extend_from_slice(imms);
594 ImmList::new(start, Idx::from_usize(self.imms.len()))
595 }
596
597 pub fn add_imm(&mut self, imm: Imm) -> Idx<Imm> {
599 self.imms.push(imm);
600 Idx::from_usize(self.imms.len() - 1)
601 }
602
603 pub fn push_slots(&mut self, slots: &[Slot]) -> SlotList {
605 let start = Idx::from_usize(self.slots.len());
606 self.slots.extend_from_slice(slots);
607 SlotList::new(start, Idx::from_usize(self.slots.len()))
608 }
609
610 pub fn add_va_object(&mut self, info: VaInfo) -> Idx<VaInfo> {
612 self.va_objects.push(info);
613 Idx::from_usize(self.va_objects.len() - 1)
614 }
615
616 pub fn add_mem(&mut self, info: MemInfo) -> Idx<MemInfo> {
618 self.mem.push(info);
619 Idx::from_usize(self.mem.len() - 1)
620 }
621
622 pub fn push_abis(&mut self, abis: &[Abi]) -> AbiList {
624 let start = Idx::from_usize(self.abis.len());
625 self.abis.extend_from_slice(abis);
626 AbiList::new(start, Idx::from_usize(self.abis.len()))
627 }
628
629 pub fn add_call(&mut self, info: CallInfo) -> Idx<CallInfo> {
631 self.calls.push(info);
632 Idx::from_usize(self.calls.len() - 1)
633 }
634
635 pub fn add_switch(&mut self, info: SwitchInfo) -> Idx<SwitchInfo> {
637 self.switches.push(info);
638 Idx::from_usize(self.switches.len() - 1)
639 }
640
641 pub fn add_asm(&mut self, info: AsmInfo) -> Idx<AsmInfo> {
643 self.asms.push(info);
644 Idx::from_usize(self.asms.len() - 1)
645 }
646
647 #[must_use]
650 pub fn counts(&self) -> Counts {
651 Counts { values: self.values.len(), insts: self.insts.len(), blocks: self.blocks.len() }
652 }
653
654 #[must_use]
660 pub fn facts(&self, value: Value) -> Facts {
661 match self.facts.binary_search_by_key(&value.raw(), |&(at, _)| at.raw()) {
662 Ok(at) => self.facts[at].1,
663 Err(_) => Facts::NONE,
664 }
665 }
666
667 pub fn set_facts(&mut self, value: Value, facts: Facts) {
672 let found = self.facts.binary_search_by_key(&value.raw(), |&(at, _)| at.raw());
673 match (found, facts.is_empty()) {
674 (Ok(at), true) => drop(self.facts.remove(at)),
675 (Ok(at), false) => self.facts[at].1 = facts,
676 (Err(_), true) => {}
677 (Err(at), false) => self.facts.insert(at, (value, facts)),
678 }
679 }
680
681 pub fn known(&self) -> impl Iterator<Item = (Value, Facts)> + '_ {
683 self.facts.iter().copied()
684 }
685
686 pub fn name_block(&mut self, block: Block, name: Symbol) {
700 let found = self.labels.binary_search_by_key(&block.raw(), |&(at, _)| at.raw());
701 if let Err(at) = found {
702 self.labels.insert(at, (block, name));
703 }
704 }
705
706 #[must_use]
708 pub fn block_name(&self, block: Block) -> Option<Symbol> {
709 match self.labels.binary_search_by_key(&block.raw(), |&(at, _)| at.raw()) {
710 Ok(at) => Some(self.labels[at].1),
711 Err(_) => None,
712 }
713 }
714
715 pub fn named_blocks(&self) -> impl Iterator<Item = (Block, Symbol)> + '_ {
717 self.labels.iter().copied()
718 }
719
720 fn add_value(&mut self, data: ValueData) -> Value {
721 self.values.push(data);
722 Idx::from_usize(self.values.len() - 1)
723 }
724}
725
726#[derive(Clone, Copy, Debug, PartialEq, Eq)]
728pub struct Counts {
729 pub values: usize,
731 pub insts: usize,
733 pub blocks: usize,
735}
736
737impl Index<Value> for Func {
740 type Output = ValueData;
741
742 fn index(&self, value: Value) -> &ValueData {
743 &self.values[value.index()]
744 }
745}
746
747impl Index<Inst> for Func {
748 type Output = InstData;
749
750 fn index(&self, inst: Inst) -> &InstData {
751 &self.insts[inst.index()]
752 }
753}
754
755impl IndexMut<Inst> for Func {
756 fn index_mut(&mut self, inst: Inst) -> &mut InstData {
757 &mut self.insts[inst.index()]
758 }
759}
760
761impl Index<Block> for Func {
762 type Output = BlockData;
763
764 fn index(&self, block: Block) -> &BlockData {
765 &self.blocks[block.index()]
766 }
767}
768
769impl Index<Sig> for Func {
770 type Output = Signature;
771
772 fn index(&self, sig: Sig) -> &Signature {
773 &self.signatures[sig.index()]
774 }
775}
776
777impl Index<ValueList> for Func {
778 type Output = [Value];
779
780 fn index(&self, list: ValueList) -> &[Value] {
781 &self.value_pool[list.as_usize_range()]
782 }
783}
784
785impl Index<BlockCallList> for Func {
786 type Output = [BlockCall];
787
788 fn index(&self, list: BlockCallList) -> &[BlockCall] {
789 &self.block_calls[list.as_usize_range()]
790 }
791}
792
793impl Index<Idx<BlockCall>> for Func {
794 type Output = BlockCall;
795
796 fn index(&self, at: Idx<BlockCall>) -> &BlockCall {
797 &self.block_calls[at.index()]
798 }
799}
800
801impl Index<ImmList> for Func {
802 type Output = [Imm];
803
804 fn index(&self, list: ImmList) -> &[Imm] {
805 &self.imms[list.as_usize_range()]
806 }
807}
808
809impl Index<Idx<Imm>> for Func {
810 type Output = Imm;
811
812 fn index(&self, at: Idx<Imm>) -> &Imm {
813 &self.imms[at.index()]
814 }
815}
816
817impl Index<Idx<MemInfo>> for Func {
818 type Output = MemInfo;
819
820 fn index(&self, at: Idx<MemInfo>) -> &MemInfo {
821 &self.mem[at.index()]
822 }
823}
824
825impl Index<AbiList> for Func {
826 type Output = [Abi];
827
828 fn index(&self, list: AbiList) -> &[Abi] {
829 &self.abis[list.as_usize_range()]
830 }
831}
832
833impl Index<SlotList> for Func {
834 type Output = [Slot];
835
836 fn index(&self, list: SlotList) -> &[Slot] {
837 &self.slots[list.as_usize_range()]
838 }
839}
840
841impl Index<Idx<VaInfo>> for Func {
842 type Output = VaInfo;
843
844 fn index(&self, at: Idx<VaInfo>) -> &VaInfo {
845 &self.va_objects[at.index()]
846 }
847}
848
849impl Index<Idx<CallInfo>> for Func {
850 type Output = CallInfo;
851
852 fn index(&self, at: Idx<CallInfo>) -> &CallInfo {
853 &self.calls[at.index()]
854 }
855}
856
857impl Index<Idx<SwitchInfo>> for Func {
858 type Output = SwitchInfo;
859
860 fn index(&self, at: Idx<SwitchInfo>) -> &SwitchInfo {
861 &self.switches[at.index()]
862 }
863}
864
865impl Index<Idx<AsmInfo>> for Func {
866 type Output = AsmInfo;
867
868 fn index(&self, at: Idx<AsmInfo>) -> &AsmInfo {
869 &self.asms[at.index()]
870 }
871}
872
873#[derive(Debug)]
880pub struct Builder<'a> {
881 func: &'a mut Func,
882 block: Block,
883 span: Span,
884}
885
886impl<'a> Builder<'a> {
887 pub fn new(func: &'a mut Func, block: Block) -> Self {
889 Self { func, block, span: Span::DUMMY }
890 }
891
892 #[must_use]
894 pub fn at(mut self, span: Span) -> Self {
895 self.span = span;
896 self
897 }
898
899 pub fn set_span(&mut self, span: Span) {
901 self.span = span;
902 }
903
904 pub fn func(&mut self) -> &mut Func {
906 self.func
907 }
908
909 #[must_use]
911 pub fn block(&self) -> Block {
912 self.block
913 }
914
915 pub fn inst(&mut self, data: InstData, results: &[Type]) -> Inst {
917 let inst = self.func.create_inst(data, results, self.span);
918 self.func.append_inst(self.block, inst);
919 inst
920 }
921
922 pub fn value(&mut self, data: InstData, ty: Type) -> Value {
928 let inst = self.inst(data, &[ty]);
929 self.func[inst].first_result.expect("one result was asked for")
930 }
931
932 pub fn iconst(&mut self, ty: Type, value: i128) -> Value {
938 let imm = self.func.add_imm(Imm::int(value, ty.lane()));
939 self.value(InstData { extra: Extra::Imm(imm), ..InstData::new(Opcode::IConst) }, ty)
940 }
941
942 pub fn fconst(&mut self, ty: Type, bits: u128) -> Value {
944 let imm = self.func.add_imm(Imm::from_bits(bits));
945 self.value(InstData { extra: Extra::Imm(imm), ..InstData::new(Opcode::FConst) }, ty)
946 }
947
948 pub fn binary(&mut self, opcode: Opcode, lhs: Value, rhs: Value, flags: Flags) -> Value {
950 let ty = self.func[lhs].ty;
951 let args = self.func.push_values(&[lhs, rhs]);
952 self.value(InstData { args, flags, ..InstData::new(opcode) }, ty)
953 }
954
955 pub fn checked(&mut self, opcode: Opcode, lhs: Value, rhs: Value) -> (Value, Value) {
968 let ty = self.func[lhs].ty;
969 let args = self.func.push_values(&[lhs, rhs]);
970 let results = [ty, ty.with_lane(Type::I1)];
971 let inst = self.inst(InstData { args, ..InstData::new(opcode) }, &results);
972 let mut answers = self.func[inst].results();
973 let value = answers.next().expect("two results were asked for");
974 let wrapped = answers.next().expect("two results were asked for");
975 (value, wrapped)
976 }
977
978 pub fn unary(&mut self, opcode: Opcode, arg: Value, ty: Type) -> Value {
980 let args = self.func.push_values(&[arg]);
981 self.value(InstData { args, ..InstData::new(opcode) }, ty)
982 }
983
984 pub fn icmp(&mut self, pred: IntPred, lhs: Value, rhs: Value) -> Value {
986 let ty = self.func[lhs].ty.with_lane(Type::I1);
987 let args = self.func.push_values(&[lhs, rhs]);
988 self.value(
989 InstData { args, extra: Extra::IntPred(pred), ..InstData::new(Opcode::ICmp) },
990 ty,
991 )
992 }
993
994 pub fn select(&mut self, cond: Value, then: Value, other: Value) -> Value {
1000 let ty = self.func[then].ty;
1001 let args = self.func.push_values(&[cond, then, other]);
1002 self.value(InstData { args, ..InstData::new(Opcode::Select) }, ty)
1003 }
1004
1005 pub fn fcmp(&mut self, pred: FloatPred, lhs: Value, rhs: Value, flags: Flags) -> Value {
1007 let ty = self.func[lhs].ty.with_lane(Type::I1);
1008 let args = self.func.push_values(&[lhs, rhs]);
1009 self.value(
1010 InstData { args, flags, extra: Extra::FloatPred(pred), ..InstData::new(Opcode::FCmp) },
1011 ty,
1012 )
1013 }
1014
1015 pub fn mem_entry(&mut self) -> Value {
1019 self.value(InstData::new(Opcode::MemEntry), Type::MEM)
1020 }
1021
1022 pub fn load(&mut self, ty: Type, addr: Value, info: MemInfo, flags: Flags) -> Value {
1024 let mem = self.func.add_mem(info);
1025 let args = self.func.push_values(&[addr]);
1026 self.value(
1027 InstData { args, flags, extra: Extra::Mem(mem), ..InstData::new(Opcode::Load) },
1028 ty,
1029 )
1030 }
1031
1032 pub fn store(&mut self, value: Value, addr: Value, info: MemInfo, flags: Flags) -> Inst {
1034 let mem = self.func.add_mem(info);
1035 let args = self.func.push_values(&[value, addr]);
1036 self.inst(
1037 InstData { args, flags, extra: Extra::Mem(mem), ..InstData::new(Opcode::Store) },
1038 &[],
1039 )
1040 }
1041
1042 pub fn atomic_load(&mut self, ty: Type, addr: Value, info: MemInfo, flags: Flags) -> Value {
1050 let mem = self.func.add_mem(info);
1051 let args = self.func.push_values(&[addr]);
1052 self.value(
1053 InstData { args, flags, extra: Extra::Mem(mem), ..InstData::new(Opcode::AtomicLoad) },
1054 ty,
1055 )
1056 }
1057
1058 pub fn atomic_store(&mut self, value: Value, addr: Value, info: MemInfo, flags: Flags) -> Inst {
1060 let mem = self.func.add_mem(info);
1061 let args = self.func.push_values(&[value, addr]);
1062 self.inst(
1063 InstData { args, flags, extra: Extra::Mem(mem), ..InstData::new(Opcode::AtomicStore) },
1064 &[],
1065 )
1066 }
1067
1068 pub fn cmpxchg(
1075 &mut self,
1076 addr: Value,
1077 expected: Value,
1078 desired: Value,
1079 info: MemInfo,
1080 flags: Flags,
1081 ) -> (Value, Value) {
1082 let ty = self.func[expected].ty;
1083 let mem = self.func.add_mem(info);
1084 let args = self.func.push_values(&[addr, expected, desired]);
1085 let inst = self.inst(
1086 InstData { args, flags, extra: Extra::Mem(mem), ..InstData::new(Opcode::Cmpxchg) },
1087 &[ty, Type::I1],
1088 );
1089 let results: Vec<Value> = self.func[inst].results().collect();
1090 let [old, exchanged] = results[..] else { unreachable!("two results were asked for") };
1091 (old, exchanged)
1092 }
1093
1094 pub fn atomic_rmw(
1102 &mut self,
1103 op: RmwOp,
1104 addr: Value,
1105 operand: Value,
1106 info: MemInfo,
1107 flags: Flags,
1108 ) -> Value {
1109 let ty = self.func[operand].ty;
1110 let mem = self.func.add_mem(info);
1111 let args = self.func.push_values(&[addr, operand]);
1112 self.value(
1113 InstData {
1114 args,
1115 flags,
1116 extra: Extra::Rmw(op, mem),
1117 ..InstData::new(Opcode::AtomicRmw)
1118 },
1119 ty,
1120 )
1121 }
1122
1123 pub fn fence(&mut self, order: MemOrder) -> Inst {
1125 self.inst(InstData { extra: Extra::Order(order), ..InstData::new(Opcode::Fence) }, &[])
1126 }
1127
1128 pub fn prefetch(&mut self, address: Value, hint: PrefetchHint) -> Inst {
1135 let args = self.func.push_values(&[address]);
1136 self.inst(
1137 InstData { args, extra: Extra::Prefetch(hint), ..InstData::new(Opcode::Prefetch) },
1138 &[],
1139 )
1140 }
1141
1142 pub fn jump(&mut self, target: Block, args: &[Value]) -> Inst {
1144 let call = self.block_call(target, args);
1145 let targets = self.func.push_block_calls(&[call]);
1146 self.inst(InstData { extra: Extra::Targets(targets), ..InstData::new(Opcode::Jump) }, &[])
1147 }
1148
1149 pub fn block_addr(&mut self, target: Block) -> Value {
1155 let call = self.block_call(target, &[]);
1156 let targets = self.func.push_block_calls(&[call]);
1157 self.value(
1158 InstData { extra: Extra::Targets(targets), ..InstData::new(Opcode::BlockAddr) },
1159 Type::PTR,
1160 )
1161 }
1162
1163 pub fn indirect_br(&mut self, addr: Value, targets: &[Block]) -> Inst {
1169 let calls: Vec<BlockCall> =
1170 targets.iter().map(|&target| self.block_call(target, &[])).collect();
1171 let targets = self.func.push_block_calls(&calls);
1172 let args = self.func.push_values(&[addr]);
1173 self.inst(
1174 InstData { args, extra: Extra::Targets(targets), ..InstData::new(Opcode::IndirectBr) },
1175 &[],
1176 )
1177 }
1178
1179 pub fn br_if(
1181 &mut self,
1182 cond: Value,
1183 then_block: Block,
1184 then_args: &[Value],
1185 else_block: Block,
1186 else_args: &[Value],
1187 ) -> Inst {
1188 let then_call = self.block_call(then_block, then_args);
1189 let else_call = self.block_call(else_block, else_args);
1190 let targets = self.func.push_block_calls(&[then_call, else_call]);
1191 let args = self.func.push_values(&[cond]);
1192 self.inst(
1193 InstData { args, extra: Extra::Targets(targets), ..InstData::new(Opcode::BrIf) },
1194 &[],
1195 )
1196 }
1197
1198 pub fn switch(&mut self, value: Value, default: Block, cases: &[(i128, Block)]) -> Inst {
1205 let ty = self.func[value].ty.lane();
1206 let mut calls = vec![self.block_call(default, &[])];
1207 let mut values = Vec::with_capacity(cases.len());
1208 for &(value, block) in cases {
1209 calls.push(self.block_call(block, &[]));
1210 values.push(Imm::int(value, ty));
1211 }
1212 let targets = self.func.push_block_calls(&calls);
1213 let cases = self.func.push_imms(&values);
1214 let info = self.func.add_switch(SwitchInfo { targets, cases });
1215 let args = self.func.push_values(&[value]);
1216 self.inst(
1217 InstData { args, extra: Extra::Switch(info), ..InstData::new(Opcode::Switch) },
1218 &[],
1219 )
1220 }
1221
1222 pub fn ret(&mut self, values: &[Value]) -> Inst {
1224 let args = self.func.push_values(values);
1225 self.inst(InstData { args, ..InstData::new(Opcode::Return) }, &[])
1226 }
1227
1228 pub fn unreachable(&mut self) -> Inst {
1230 self.inst(InstData::new(Opcode::Unreachable), &[])
1231 }
1232
1233 pub fn call(&mut self, callee: Symbol, signature: Sig, args: &[Value]) -> Inst {
1235 self.call_varargs(callee, signature, args, &[])
1236 }
1237
1238 pub fn call_varargs(
1244 &mut self,
1245 callee: Symbol,
1246 signature: Sig,
1247 args: &[Value],
1248 varargs: &[Abi],
1249 ) -> Inst {
1250 let varargs = self.func.push_abis(varargs);
1251 let info = self.func.add_call(CallInfo { callee: Some(callee), signature, varargs });
1252 let returns: Vec<Type> = self.func[signature].return_types().collect();
1253 let args = self.func.push_values(args);
1254 self.inst(
1255 InstData { args, extra: Extra::Call(info), ..InstData::new(Opcode::Call) },
1256 &returns,
1257 )
1258 }
1259
1260 pub fn inline_asm(
1266 &mut self,
1267 info: AsmInfo,
1268 args: &[Value],
1269 results: &[Type],
1270 flags: Flags,
1271 ) -> Inst {
1272 let info = self.func.add_asm(info);
1273 let args = self.func.push_values(args);
1274 self.inst(
1275 InstData { args, flags, extra: Extra::Asm(info), ..InstData::new(Opcode::InlineAsm) },
1276 results,
1277 )
1278 }
1279
1280 fn block_call(&mut self, block: Block, args: &[Value]) -> BlockCall {
1281 BlockCall::new(block, self.func.push_values(args))
1282 }
1283}
1284
1285#[cfg(test)]
1286mod tests {
1287 use rucc_base::Interner;
1288
1289 use super::*;
1290 use crate::inst::BlockCallList;
1291 use crate::{MemOrder, Restrict};
1292
1293 fn sum() -> (Func, Block, Block, Block) {
1295 let mut names = Interner::new();
1296 let i32_ = Type::int(32);
1297 let mut func = Func::new(
1298 names.intern("sum"),
1299 Signature::new().with_params(&[i32_]).with_returns(&[i32_]),
1300 );
1301
1302 let entry = func.create_block();
1303 let n = func.append_param(entry, i32_);
1304 let header = func.create_block();
1305 let acc = func.append_param(header, i32_);
1306 let i = func.append_param(header, i32_);
1307 let exit = func.create_block();
1308 let result = func.append_param(exit, i32_);
1309
1310 let mut b = Builder::new(&mut func, entry);
1311 let zero = b.iconst(i32_, 0);
1312 let cmp = b.icmp(IntPred::Sle, n, zero);
1313 b.br_if(cmp, exit, &[zero], header, &[zero, zero]);
1314
1315 let mut b = Builder::new(&mut func, header);
1316 let one = b.iconst(i32_, 1);
1317 let next = b.binary(Opcode::Add, i, one, Flags::NSW);
1318 let total = b.binary(Opcode::Add, acc, next, Flags::NSW);
1319 let done = b.icmp(IntPred::Sge, next, n);
1320 b.br_if(done, exit, &[total], header, &[total, next]);
1321
1322 let mut b = Builder::new(&mut func, exit);
1323 b.ret(&[result]);
1324
1325 (func, entry, header, exit)
1326 }
1327
1328 #[test]
1329 fn the_blocks_come_back_in_the_order_they_were_made() {
1330 let (func, entry, header, exit) = sum();
1331 assert_eq!(func.blocks().collect::<Vec<_>>(), [entry, header, exit]);
1332 assert_eq!(func.entry(), Some(entry));
1333 }
1334
1335 #[test]
1336 fn a_removed_block_is_gone_from_the_layout_and_so_is_what_was_in_it() {
1337 let (mut func, entry, header, exit) = sum();
1338 let inside: Vec<Inst> = func.insts(header).collect();
1339 func.remove_block(header);
1340 assert_eq!(func.blocks().collect::<Vec<_>>(), [entry, exit]);
1341 assert_eq!(func.entry(), Some(entry));
1342 assert_eq!(func[entry].next, Some(exit));
1343 assert_eq!(func[exit].prev, Some(entry));
1344 assert!(inside.iter().all(|&inst| func.block_of(inst).is_none()));
1346 assert!(func.insts(header).next().is_none());
1347 }
1348
1349 #[test]
1350 fn each_block_holds_what_was_appended_to_it() {
1351 let (func, entry, header, exit) = sum();
1352 let opcodes =
1353 |block| func.insts(block).map(|inst| func[inst].opcode.name()).collect::<Vec<_>>();
1354 assert_eq!(opcodes(entry), ["iconst", "icmp", "br_if"]);
1355 assert_eq!(opcodes(header), ["iconst", "add", "add", "icmp", "br_if"]);
1356 assert_eq!(opcodes(exit), ["return"]);
1357 }
1358
1359 #[test]
1360 fn asm_ends_a_block_when_it_has_labels_and_not_otherwise() {
1361 let mut func = Func::new(Symbol::from_raw(0), Signature::new());
1364 let block = func.create_block();
1365 let plain = func.add_asm(AsmInfo {
1366 template: Symbol::from_raw(0),
1367 constraints: Symbol::from_raw(0),
1368 clobbers: Symbol::from_raw(0),
1369 targets: BlockCallList::EMPTY,
1370 });
1371 let call = BlockCall::to(block);
1372 let targets = func.push_block_calls(&[call]);
1373 let labelled = func.add_asm(AsmInfo {
1374 template: Symbol::from_raw(0),
1375 constraints: Symbol::from_raw(0),
1376 clobbers: Symbol::from_raw(0),
1377 targets,
1378 });
1379
1380 let mut make = |extra| {
1381 let data = InstData { extra, ..InstData::new(Opcode::InlineAsm) };
1382 func.create_inst(data, &[], Span::DUMMY)
1383 };
1384 let plain = make(Extra::Asm(plain));
1385 let labelled = make(Extra::Asm(labelled));
1386 assert!(!func.is_terminator(plain));
1387 assert!(func.is_terminator(labelled));
1388 }
1389
1390 #[test]
1391 fn every_block_ends_in_its_terminator() {
1392 let (func, entry, header, exit) = sum();
1393 for block in [entry, header, exit] {
1394 let last = func.terminator(block).expect("a terminator");
1395 assert_eq!(Some(last), func.insts(block).last());
1396 }
1397 }
1398
1399 #[test]
1400 fn a_branch_carries_the_arguments_the_block_takes() {
1401 let (func, entry, header, _) = sum();
1402 let br = func.terminator(entry).expect("a terminator");
1403 let calls: Vec<BlockCall> = func.successors(br).collect();
1404 assert_eq!(calls.len(), 2);
1405 assert_eq!(calls[1].block, header);
1407 assert_eq!(func[calls[1].args].len(), 2);
1408 assert_eq!(func[header].params.len(), 2);
1409 assert_eq!(func[calls[0].args].len(), 1);
1410 }
1411
1412 #[test]
1413 fn a_value_knows_what_defined_it() {
1414 let (func, entry, _, _) = sum();
1415 let first = func.insts(entry).next().expect("an instruction");
1416 let value = func[first].first_result.expect("a result");
1417 assert_eq!(func[value].def, Def::Result { inst: first, index: 0 });
1418 assert_eq!(func[value].ty, Type::int(32));
1419
1420 let param = func[entry].params[0];
1421 assert_eq!(func[param].def, Def::Param { block: entry, index: 0 });
1422 }
1423
1424 #[test]
1425 fn a_comparison_produces_one_bit() {
1426 let (func, entry, _, _) = sum();
1427 let cmp = func.insts(entry).nth(1).expect("the comparison");
1428 let value = func[cmp].first_result.expect("a result");
1429 assert_eq!(func[value].ty, Type::I1);
1430 assert_eq!(func[cmp].extra, Extra::IntPred(IntPred::Sle));
1431 }
1432
1433 #[test]
1434 fn flags_ride_along_on_the_instruction_that_was_given_them() {
1435 let (func, _, header, _) = sum();
1436 let add = func.insts(header).nth(1).expect("the addition");
1437 assert_eq!(func[add].flags, Flags::NSW);
1438 let cmp = func.insts(header).nth(3).expect("the comparison");
1439 assert_eq!(func[cmp].flags, Flags::NONE);
1440 }
1441
1442 #[test]
1443 fn removing_an_instruction_takes_it_out_of_the_middle() {
1444 let (mut func, _, header, _) = sum();
1445 let add = func.insts(header).nth(1).expect("the addition");
1446 func.remove_inst(add);
1447 let opcodes: Vec<&str> = func.insts(header).map(|inst| func[inst].opcode.name()).collect();
1448 assert_eq!(opcodes, ["iconst", "add", "icmp", "br_if"]);
1449 assert_eq!(func.block_of(add), None);
1450 }
1451
1452 #[test]
1453 fn removing_the_first_and_the_last_keeps_the_ends_right() {
1454 let (mut func, entry, _, _) = sum();
1455 let first = func.insts(entry).next().expect("an instruction");
1456 let last = func.terminator(entry).expect("a terminator");
1457 func.remove_inst(first);
1458 func.remove_inst(last);
1459 let opcodes: Vec<&str> = func.insts(entry).map(|inst| func[inst].opcode.name()).collect();
1460 assert_eq!(opcodes, ["icmp"]);
1461 assert_eq!(func[entry].first, func[entry].last);
1462 }
1463
1464 #[test]
1465 fn removing_the_only_instruction_empties_the_block() {
1466 let (mut func, _, _, exit) = sum();
1467 let only = func.insts(exit).next().expect("an instruction");
1468 func.remove_inst(only);
1469 assert_eq!(func.insts(exit).count(), 0);
1470 assert_eq!(func[exit].first, None);
1471 assert_eq!(func[exit].last, None);
1472 }
1473
1474 #[test]
1475 fn inserting_before_puts_it_in_the_right_place() {
1476 let (mut func, entry, _, _) = sum();
1477 let cmp = func.insts(entry).nth(1).expect("the comparison");
1478 let made = func.create_inst(InstData::new(Opcode::Unreachable), &[], Span::DUMMY);
1479 func.insert_before(made, cmp);
1480 let opcodes: Vec<&str> = func.insts(entry).map(|inst| func[inst].opcode.name()).collect();
1481 assert_eq!(opcodes, ["iconst", "unreachable", "icmp", "br_if"]);
1482 }
1483
1484 #[test]
1485 fn inserting_before_the_first_makes_it_the_first() {
1486 let (mut func, entry, _, _) = sum();
1487 let first = func.insts(entry).next().expect("an instruction");
1488 let made = func.create_inst(InstData::new(Opcode::Unreachable), &[], Span::DUMMY);
1489 func.insert_before(made, first);
1490 assert_eq!(func.insts(entry).next(), Some(made));
1491 assert_eq!(func[entry].first, Some(made));
1492 }
1493
1494 #[test]
1495 fn inserting_after_puts_it_in_the_right_place() {
1496 let (mut func, entry, _, _) = sum();
1497 let first = func.insts(entry).next().expect("an instruction");
1498 let made = func.create_inst(InstData::new(Opcode::Unreachable), &[], Span::DUMMY);
1499 func.insert_after(made, first);
1500 let opcodes: Vec<&str> = func.insts(entry).map(|inst| func[inst].opcode.name()).collect();
1501 assert_eq!(opcodes, ["iconst", "unreachable", "icmp", "br_if"]);
1502 assert_eq!(func[entry].first, Some(first));
1503 }
1504
1505 #[test]
1506 #[should_panic(expected = "nothing goes after a terminator")]
1507 fn inserting_after_the_terminator_is_refused() {
1508 let (mut func, entry, _, _) = sum();
1511 let last = func.insts(entry).last().expect("a terminator");
1512 let made = func.create_inst(InstData::new(Opcode::Unreachable), &[], Span::DUMMY);
1513 func.insert_after(made, last);
1514 }
1515
1516 #[test]
1517 fn a_list_grows_in_place_while_it_is_the_last_thing_in_the_pool() {
1518 let mut func = Func::new(Symbol::from_raw(0), Signature::new());
1519 let block = func.create_block();
1520 let a = func.append_param(block, Type::int(32));
1521 let b = func.append_param(block, Type::int(32));
1522 let list = func.push_values(&[a]);
1523 let grown = func.append_arg(list, b);
1524 assert_eq!(func[grown], [a, b]);
1525 assert_eq!(grown.as_usize_range().start, list.as_usize_range().start);
1526 }
1527
1528 #[test]
1529 fn a_list_is_copied_when_something_is_behind_it() {
1530 let mut func = Func::new(Symbol::from_raw(0), Signature::new());
1531 let block = func.create_block();
1532 let a = func.append_param(block, Type::int(32));
1533 let b = func.append_param(block, Type::int(32));
1534 let list = func.push_values(&[a, a]);
1535 let behind = func.push_values(&[b]);
1536 let grown = func.append_arg(list, b);
1537 assert_eq!(func[grown], [a, a, b]);
1538 assert_eq!(func[list], [a, a], "the old run is still readable");
1539 assert_eq!(func[behind], [b], "and so is what was behind it");
1540 assert_ne!(grown.as_usize_range().start, list.as_usize_range().start);
1541 }
1542
1543 #[test]
1544 fn a_parameter_added_late_is_the_next_one_along() {
1545 let (mut func, entry, header, _) = sum();
1549 let extra = func.append_param(header, Type::int(32));
1550 assert_eq!(func[header].params.len(), 3);
1551 assert_eq!(func[extra].def, Def::Param { block: header, index: 2 });
1552
1553 let br = func.terminator(entry).expect("a terminator");
1554 let call = func.successors(br).nth(1).expect("the branch to the header");
1555 let grown = func.append_arg(call.args, extra);
1556 assert_eq!(func[grown].len(), 3);
1557 }
1558
1559 #[test]
1560 fn a_span_rides_along_with_the_instruction() {
1561 let mut func = Func::new(Symbol::from_raw(0), Signature::new());
1562 let block = func.create_block();
1563 let span = Span::new(10, 20);
1564 let mut b = Builder::new(&mut func, block).at(span);
1565 let value = b.iconst(Type::int(32), 7);
1566 let inst = match func[value].def {
1567 Def::Result { inst, .. } => inst,
1568 Def::Param { .. } => unreachable!("a constant is not a parameter"),
1569 };
1570 assert_eq!(func.span(inst), span);
1571 }
1572
1573 #[test]
1574 fn a_store_produces_nothing_and_a_load_produces_one_value() {
1575 let mut func = Func::new(Symbol::from_raw(0), Signature::new());
1576 let block = func.create_block();
1577 let addr = func.append_param(block, Type::PTR);
1578 let info = MemInfo {
1579 size: 4,
1580 align: 4,
1581 order: MemOrder::NotAtomic,
1582 tbaa: None,
1583 owns: 0,
1584 restrict: Restrict::NONE,
1585 };
1586 let mut b = Builder::new(&mut func, block);
1587 let value = b.load(Type::int(32), addr, info, Flags::NONE);
1588 let store = b.store(value, addr, info, Flags::VOLATILE);
1589 assert_eq!(func[store].results, 0);
1590 assert_eq!(func[store].flags, Flags::VOLATILE);
1591 assert_eq!(func[value].ty, Type::int(32));
1592 }
1593
1594 #[test]
1595 fn a_call_produces_what_its_signature_returns() {
1596 let mut names = Interner::new();
1597 let mut func = Func::new(names.intern("caller"), Signature::new());
1598 let sig = func.add_signature(
1599 Signature::new().with_params(&[Type::int(32)]).with_returns(&[Type::int(64)]),
1600 );
1601 let block = func.create_block();
1602 let arg = func.append_param(block, Type::int(32));
1603 let callee = names.intern("callee");
1604 let mut b = Builder::new(&mut func, block);
1605 let call = b.call(callee, sig, &[arg]);
1606 assert_eq!(func[call].results, 1);
1607 let value = func[call].first_result.expect("a result");
1608 assert_eq!(func[value].ty, Type::int(64));
1609 assert_eq!(func[call].extra, Extra::Call(Idx::new(0)));
1610 }
1611
1612 #[test]
1613 fn the_counts_are_what_was_made() {
1614 let (func, _, _, _) = sum();
1615 let counts = func.counts();
1616 assert_eq!(counts.blocks, 3);
1617 assert_eq!(counts.insts, 9);
1618 assert_eq!(counts.values, 4 + 6);
1621 }
1622
1623 #[test]
1624 #[should_panic(expected = "the instruction is in a block")]
1625 fn appending_an_instruction_twice_is_refused() {
1626 let (mut func, entry, _, _) = sum();
1627 let first = func.insts(entry).next().expect("an instruction");
1628 func.append_inst(entry, first);
1629 }
1630
1631 #[test]
1632 #[should_panic(expected = "the instruction is not in a block")]
1633 fn removing_an_instruction_twice_is_refused() {
1634 let (mut func, entry, _, _) = sum();
1635 let first = func.insts(entry).next().expect("an instruction");
1636 func.remove_inst(first);
1637 func.remove_inst(first);
1638 }
1639
1640 fn threaded() -> (Func, Inst, Inst) {
1642 let mut names = Interner::new();
1643 let i32_ = Type::int(32);
1644 let mut func = Func::new(
1645 names.intern("thread"),
1646 Signature::new().with_params(&[Type::PTR]).with_returns(&[i32_]),
1647 );
1648 let entry = func.create_block();
1649 let addr = func.append_param(entry, Type::PTR);
1650 let info = MemInfo {
1651 size: 4,
1652 align: 4,
1653 order: MemOrder::NotAtomic,
1654 tbaa: None,
1655 owns: 0,
1656 restrict: Restrict::NONE,
1657 };
1658
1659 let mut b = Builder::new(&mut func, entry);
1660 let start = b.mem_entry();
1661 let seven = b.iconst(i32_, 7);
1662 let store = b.store(seven, addr, info, Flags::NONE);
1663 let value = b.load(i32_, addr, info, Flags::NONE);
1664 let Def::Result { inst: load, .. } = func[value].def else {
1665 panic!("the load produced it");
1666 };
1667
1668 let store = func.with_mem(store, start);
1669 let after = func.mem_out(store).expect("a store makes a new version");
1670 let load = func.with_mem(load, after);
1671 (func, store, load)
1672 }
1673
1674 #[test]
1675 fn threading_memory_puts_it_last_and_leaves_everything_else_where_it_was() {
1676 let (func, store, load) = threaded();
1677 assert_eq!(func.mem_in(store), func.mem_out(store).map(|_| func[func[store].args][2]));
1678 assert_eq!(func[func[store].args].len(), 3);
1679 assert!(func.carries_mem(store));
1680 assert!(func.carries_mem(load));
1681
1682 assert_eq!(func[func[load].args][0], func[func.entry().expect("an entry")].params[0]);
1685 assert_eq!(func.mem_in(load), func.mem_out(store));
1686 assert_eq!(func.mem_out(load), None);
1687 }
1688
1689 #[test]
1690 #[should_panic(expected = "this is already on the memory chain")]
1691 fn threading_memory_through_the_same_instruction_twice_is_refused() {
1692 let (mut func, store, _) = threaded();
1693 let start = func.mem_in(store).expect("it was threaded");
1694 func.with_mem(store, start);
1695 }
1696}