-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbfcc.rs
More file actions
3155 lines (2764 loc) · 78.1 KB
/
bfcc.rs
File metadata and controls
3155 lines (2764 loc) · 78.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
extern crate llvm_ir;
use std::fmt;
use std::cell::RefCell;
use std::fmt::Write;
use std::ops::Deref;
use std::path::Path;
use std::rc::Rc;
use std::convert::TryFrom;
use std::convert::TryInto;
// Split all blocks at calls. This should result in all calls treated sorta like
// terminator instructions being the last instruction of their block before a
// unconditional branch.
//
// This makes it way easier to generate brainfuck control flow as calls
// use the same control flow mechanism as blocks. A call/branch combo sets
// up the current and next frames then switches to the next frame. Since it
// always makes up the end of a block we'll re-enter the main loop and
// continue into the next frame. Upon returning the branch will have setup
// frame to resume right into the right block.
// what a deal!
fn calls_terminate_blocks(module: &mut llvm_ir::Module) {
for func in module.functions.iter_mut() {
let mut block = 0;
while block < func.basic_blocks.len() {
let mut instr = 0;
while instr < func.basic_blocks[block].instrs.len() {
if let llvm_ir::Instruction::Call(_) =
func.basic_blocks[block].instrs[instr]
{
} else {
instr += 1;
continue;
}
// so when we get to a call
let nextn = llvm_ir::Name::Name(Box::new(format!(
"call_term_for_{}",
block
)));
let last_instr =
instr == func.basic_blocks[block].instrs.len() - 1;
// even if it's the last instr that's a call we still split the
// block and sprinkle in an uncond br to make things ez
if last_instr {
let splitn = llvm_ir::BasicBlock {
name: nextn.clone(),
instrs: vec![],
term: func.basic_blocks[block].term.clone(),
};
func.basic_blocks.insert(block + 1, splitn);
func.basic_blocks[block].term =
llvm_ir::Terminator::Br(llvm_ir::terminator::Br {
debugloc: None,
dest: nextn.clone(),
});
} else {
let splitn = llvm_ir::BasicBlock {
name: nextn.clone(),
instrs: func.basic_blocks[block]
.instrs
.split_off(instr + 1),
term: func.basic_blocks[block].term.clone(),
};
func.basic_blocks.insert(block + 1, splitn);
func.basic_blocks[block].term =
llvm_ir::Terminator::Br(llvm_ir::terminator::Br {
debugloc: None,
dest: nextn.clone(),
});
}
// update all the phi nodes too. Since our block now has a
// unconditional succ we'll need to rename any phis naming this
// block to instead name the succ.
//
// man... maybe i shoulda done this in cpp cause like... man
// llvm has all this stufffff
let orig_block = func.basic_blocks[block].name.clone();
for bblock in &mut func.basic_blocks {
for instr in &mut bblock.instrs {
match instr {
llvm_ir::Instruction::Phi(phi) => {
for inval in &mut phi.incoming_values {
if inval.1 == orig_block {
inval.1 = nextn.clone();
}
}
}
_ => {}
}
}
}
instr += 1;
}
block += 1;
}
}
}
// TODO: this isn't really the move tbh
// function calls always call into block 0. Thing is, if we're making a call
// from block 0 into another block 0 we could end up end up setting everything
// up for the callee but then then re-entering block 0 in the caller instead of
// the target. This is really just a quirk of control flow using one massive
// loop with masks for functions and blocks. Moving control flow between
// blocks/functions involes reentering the block or function level loop with the
// proper mask set. Since functions share the same space for block control flow
// mask space the transition between functions temporarily involves executing
// in the calling function with the callee's mask set.
fn calls_never_in_first_block(module: &mut llvm_ir::Module) {
for func in module.functions.iter_mut() {
let hascall = func.basic_blocks[0].instrs.iter().any(|i| match i {
llvm_ir::Instruction::Call(_) => true,
_ => false,
});
if !hascall {
continue;
}
let nextn = llvm_ir::Name::Name(Box::new(format!(
"no_block0_call_for_{}",
func.name
)));
func.basic_blocks.insert(
0,
llvm_ir::BasicBlock {
name: nextn,
instrs: vec![],
term: llvm_ir::Terminator::Br(llvm_ir::terminator::Br {
debugloc: None,
dest: func.basic_blocks[0].name.clone(),
}),
},
);
}
}
#[derive(Debug, Clone)]
struct Addr {
v: Rc<RefCell<Addrt>>,
}
impl fmt::Display for Addr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, ".{:?}", self.v.borrow())
}
}
#[derive(Debug, Clone)]
enum Addrt {
Fixed(usize),
Offset(Addr, i64),
Named(llvm_ir::Name),
}
// type Addr = Rc<RefCell<Addrt>>;
fn offset(s: Addr, i: i64) -> Addr {
Addr {
v: Rc::new(RefCell::new(Addrt::Offset(s, i))),
}
}
fn resaddr(s: Addr) -> usize {
match s.v.deref().borrow().clone() {
Addrt::Fixed(u) => u,
Addrt::Offset(a, o) => (resaddr(a) as i64 + o) as usize,
Addrt::Named(_) => panic!("named address cant be resolved"),
}
}
fn fixed_addr(a: usize) -> Addr {
Addr {
v: Rc::new(RefCell::new(Addrt::Fixed(a))),
}
}
#[derive(Debug, Clone)]
enum BfOp {
// kinda actual brainfuck, these do fucky stuff to the instr pointer
// future passes can't understand
Right(usize),
Left(usize),
// extra spooky! loop enters and exits on different addresses. so like the
// instr pointer is now split between both addrs after this op, statically
// we'll assume it enters on the former address and exists on the later
// addr so uh... glhf
//
// If the addr is truthy the PC will be at the latter addr on exit
// If the addr is falsey the PC will be at the former addr on exit
Loop2(Addr, Addr, Vec<BfOp>),
AddI(Addr, u8), // *a + n -> *a : a must be less than 255
SubI(Addr, u8), // *a - n -> *a : a msut be greater than 0
Dup(Addr, Addr, Addr), /* *a -> *b, *c : a will be zeroed, b and c must
* be zero */
//DupThru(Addr, Addr, Addr), /* *a -> *b (c is a tmp) : a will be zeroed,
// * b and c must be zero */
// the only architecture with a real mov instruction
Mov(Addr, Addr), // *a -> *b : a will be zeroed, b must be zero
Putch(Addr),
Zero(Addr),
Loop(Addr, Vec<BfOp>),
// debug
Tag(Addr, String), // tag address with name in debugger
Comment(String), // if you see something say something
Nop,
}
// have to promise to give registers before you take them otherwise
// you could end up giving a register you've just taken.
fn give_reg<'a>(
ctx: &'a mut Ctx,
name: &llvm_ir::Name,
multi_use: bool,
) -> Addr {
assert!(
!ctx.layout.iter().any(|c| match c {
Cell::Reg { n, .. } => n == name,
Cell::Alloc(n) => n == name,
_ => false,
}),
"wtf man, we already have that"
);
ctx.layout.push(Cell::Reg {
n: name.clone(),
multi_use: multi_use,
});
Addr {
v: Rc::new(RefCell::new(Addrt::Fixed(ctx.layout.len() - 1))),
}
}
fn op_unwrap_ptr_all(op: &llvm_ir::Operand) -> llvm_ir::Operand {
let mut op = op.clone();
while match &op {
llvm_ir::Operand::LocalOperand { ty, .. } => match ty.deref() {
llvm_ir::Type::PointerType { .. } => true,
_ => false,
},
_ => false,
} {
op = op_unwrap_ptr(&op);
}
return op.clone();
}
fn op_unwrap_ptr(op: &llvm_ir::Operand) -> llvm_ir::Operand {
match op {
llvm_ir::Operand::LocalOperand { name, ty } => match ty.deref() {
llvm_ir::Type::PointerType {
pointee_type: pty,
addr_space: _,
} => llvm_ir::Operand::LocalOperand {
name: name.clone(),
ty: pty.clone(),
},
_ => panic!("no more pointers to unwrap"),
},
_ => panic!("no more pointers to unwrap"),
}
}
// available names is a combination of all the living registers:
// onstack + allocs
fn take_reg(ctx: &Ctx, name: &llvm_ir::Name) -> Addr {
Addr {
v: Rc::new(RefCell::new(Addrt::Fixed(
ctx.layout
.iter()
.position(|c| match c {
Cell::Alloc(n) => n == name,
Cell::Reg { n, .. } => n == name,
_ => false,
})
.unwrap(),
))),
}
}
// get addr of function mask
fn fn_mask(ctx: &mut Ctx, name: &String) -> Addr {
fixed_addr(
ctx.layout
.iter()
.position(|c| match c {
Cell::FuncMask(n) => n == name,
_ => false,
})
.unwrap(),
)
}
// generate the ops to zero all the allocs and fixed regs in a function
fn zero_frame(ctx: &mut Ctx) -> Vec<BfOp> {
let mut ops = vec![BfOp::Comment(format!("zero all function allocs"))];
ops.append(
&mut ctx
.layout
.clone()
.iter()
.enumerate()
.filter_map(|(i, c)| match c {
Cell::Alloc(c) => Some(c),
Cell::Reg { multi_use: true, n } => Some(n),
_ => None,
})
.map(|a| BfOp::Zero(take_reg(ctx, a)))
.collect(),
);
ops
}
// so like take an instruction operand and do the right thing
// - constant registers (allocas) return said register
// - constants will reserve a temp register and store the value there
// - pointers will reserve a temp and store the pointer's int value
// the returned reg MUST be consumed if it is one of the latter two. the former
// depends on what the producing function expects.
fn op_to_reg<'a>(ctx: &'a mut Ctx, op: &llvm_ir::Operand) -> (Addr, Vec<BfOp>) {
match op {
llvm_ir::Operand::LocalOperand { name, ty } => match ty.deref() {
llvm_ir::Type::IntegerType { .. } => (take_reg(ctx, name), vec![]),
llvm_ir::Type::PointerType {
pointee_type: _,
addr_space: _,
} => {
let from_alloc = ctx.layout.iter().position(|c| match c {
Cell::Alloc(n) => n == name,
_ => false,
});
if from_alloc.is_some() {
let from_alloc = from_alloc.unwrap();
let pasi = borrow_reg(ctx, 1);
let tmp = borrow_reg(ctx, 1);
(
pasi.clone(),
vec![
// basically reach back to the stack pointer and
// add it to our destination int. This way the
// initified pointer be basically be:
// the address of the stack register position
// +
// the current stack's position
BfOp::Comment(format!(
"op_to_reg storing pointer value in temp address"
)),
BfOp::Tag(
pasi.clone(),
format!("tmp_allocptr_{}", name),
),
BfOp::Tag(
tmp.clone(),
format!("tmp_allocptr_tru_{}", name),
),
BfOp::Left(1),
BfOp::Dup(
fixed_addr(0),
offset(pasi.clone(), 1),
offset(tmp.clone(), 1),
),
BfOp::Mov(offset(tmp.clone(), 1), fixed_addr(0)),
BfOp::Right(1),
BfOp::AddI(pasi, from_alloc as u8 + 1),
],
)
} else {
let found =
ctx.addrs.iter().find(|a| match a.v.borrow().clone() {
Addrt::Named(n) => &n == name,
_ => false,
});
if found.is_some() {
return (found.unwrap().clone(), vec![]);
}
(
fixed_addr(
ctx.layout
.iter()
.position(|c| match c {
Cell::Reg { n, .. } => n == name,
_ => false,
})
.unwrap(),
),
vec![],
)
}
}
_ => unimplemented!("meta?"),
},
llvm_ir::Operand::ConstantOperand(_) => {
let tmp = borrow_reg(ctx, 1);
let v = uncop(ctx, op);
(
tmp.clone(),
vec![
BfOp::Comment(format!(
"op_to_reg storing const value in temp address"
)),
BfOp::Tag(tmp.clone(), format!("constop_{}", v)),
BfOp::AddI(tmp.clone(), v as u8),
],
)
}
_ => unimplemented!("lol cucked"),
}
}
// borrow a register for scratch space.you just have to really
// really really promise to not leave any junk beyond the lifetime
// of the instruction. Otherwise absolute chaos ensues since
// this potentially borrows control flow regs.
//
// TODO(turbio): also also this needs to be used after all gives/takes
fn borrow_reg(ctx: &mut Ctx, contig: usize) -> Addr {
for i in 0..(ctx.layout.len() - contig) {
for j in 0..contig {
let c = &ctx.layout[i + j];
if !match c {
Cell::Free => true,
_ => false,
} {
break;
}
if j == contig - 1 {
for c in 0..contig {
let prev =
std::mem::replace(&mut ctx.layout[i + c], Cell::Free);
ctx.layout[i + c] = Cell::Borrowed(Box::new(prev));
}
return fixed_addr(i);
}
}
}
let slot = ctx.layout.len();
for _ in 0..contig {
ctx.layout.push(Cell::Borrowed(Box::new(Cell::Free)));
}
fixed_addr(slot)
}
// these are all based around sub w/o underflow:
// a | ... | u flag | ... | b | 0 | 1res
//
// a[- b [->] | > | [<] | < | a]
// | | | |
// b or 0 | 0 b
// 0 or 1
//
// Both minuend and subtrahend will be zeroed by this algorithm. The
// returned usize will be the difference.
//
// theres an optinal underflow address if a subtraction to the minuend would
// cause the cell to go negative then this address will be the difference.
fn subnu<'a>(
ctx: &'a mut Ctx,
minuend: Addr,
subtractend: Addr,
underflow: Option<Addr>,
) -> (Vec<BfOp>, Addr) {
let tmps = borrow_reg(ctx, 3);
let tmpb = tmps.clone();
let tmp0 = offset(tmps.clone(), 1);
let tmp1 = offset(tmps.clone(), 2);
(
vec![
BfOp::Tag(tmpb.clone(), format!("subnu_tmpb")),
BfOp::Tag(tmp0, format!("subnu_tmp0")),
BfOp::Tag(tmp1.clone(), format!("subnu_tmp1")),
BfOp::Mov(minuend, tmpb.clone()),
BfOp::AddI(tmp1.clone(), 1),
BfOp::Loop(
subtractend.clone(),
vec![
BfOp::SubI(subtractend.clone(), 1),
if underflow.is_some() {
BfOp::AddI(underflow.clone().unwrap(), 1)
} else {
BfOp::Nop
},
BfOp::Loop(
tmpb.clone(),
vec![
BfOp::SubI(tmpb.clone(), 1),
if underflow.is_some() {
BfOp::SubI(underflow.clone().unwrap(), 1)
} else {
BfOp::Nop
},
BfOp::Right(1),
],
),
BfOp::Right(1),
BfOp::Loop(tmpb.clone(), vec![BfOp::Left(1)]),
BfOp::Left(1),
],
),
BfOp::SubI(tmp1.clone(), 1),
],
tmpb.clone(),
)
}
// all the u8 icmp ops built from underflowing subtract.
fn build_icmp<'a>(
ctx: &'a mut Ctx,
pred: llvm_ir::IntPredicate,
op0: Addr,
op1: Addr,
dest: Addr,
) -> Vec<BfOp> {
let mut icmp_out = Vec::<BfOp>::new();
// So like all the int comparisons are done by subtracting w the underflow
// flag. So like equality is checked by subnu, if the result is 0 and the
// underflow is 0 the operands must be equal. From there it's just a matter
// of setting the dest address to 1 or 0.
match pred {
llvm_ir::IntPredicate::SLT | llvm_ir::IntPredicate::ULT => {
let (mut ops, diff) = subnu(ctx, op1, op0, None);
icmp_out.append(&mut ops);
icmp_out.push(BfOp::Loop(
diff.clone(),
vec![BfOp::Zero(diff.clone()), BfOp::AddI(dest.clone(), 1)],
));
}
llvm_ir::IntPredicate::NE => {
let underflow = borrow_reg(ctx, 1);
let (mut ops, diff) = subnu(ctx, op0, op1, Some(underflow.clone()));
icmp_out.append(&mut ops);
// don't need to worry about casting to i1 since it'll either
// underflow xor have a remainter
icmp_out.push(BfOp::Loop(
diff.clone(),
vec![BfOp::Zero(diff.clone()), BfOp::AddI(dest.clone(), 1)],
));
icmp_out.push(BfOp::Loop(
underflow.clone(),
vec![
BfOp::Zero(underflow.clone()),
BfOp::AddI(dest.clone(), 1),
],
));
}
llvm_ir::IntPredicate::SLE | llvm_ir::IntPredicate::ULE => {
let (mut ops, diff) = subnu(ctx, op0, op1, None);
icmp_out.append(&mut ops);
icmp_out.push(BfOp::AddI(dest.clone(), 1));
icmp_out.push(BfOp::Loop(
diff.clone(),
vec![BfOp::Zero(diff.clone()), BfOp::Zero(dest.clone())],
));
}
llvm_ir::IntPredicate::SGE | llvm_ir::IntPredicate::UGE => {
let (mut ops, diff) = subnu(ctx, op1, op0, None);
icmp_out.append(&mut ops);
icmp_out.push(BfOp::AddI(dest.clone(), 1));
icmp_out.push(BfOp::Loop(
diff.clone(),
vec![BfOp::Zero(diff.clone()), BfOp::Zero(dest.clone())],
));
}
llvm_ir::IntPredicate::EQ => {
let underflow = borrow_reg(ctx, 1);
let (mut ops, diff) = subnu(ctx, op1, op0, Some(underflow.clone()));
icmp_out.append(&mut ops);
icmp_out.push(BfOp::AddI(dest.clone(), 1));
icmp_out.push(BfOp::Loop(
diff.clone(),
vec![BfOp::Zero(diff.clone()), BfOp::Zero(dest.clone())],
));
icmp_out.push(BfOp::Loop(
underflow.clone(),
vec![BfOp::Zero(underflow.clone()), BfOp::Zero(dest.clone())],
));
}
llvm_ir::IntPredicate::SGT | llvm_ir::IntPredicate::UGT => {
let (mut ops, diff) = subnu(ctx, op0, op1, None);
icmp_out.append(&mut ops);
icmp_out.push(BfOp::Loop(
diff.clone(),
vec![BfOp::Zero(diff.clone()), BfOp::AddI(dest.clone(), 1)],
));
}
}
icmp_out
}
#[derive(Debug, Clone)]
enum Cell {
//Args,
//StackPtr,
MainLoop,
FuncMask(String),
BlockMask(llvm_ir::Name),
Borrowed(Box<Cell>),
Alloc(llvm_ir::Name),
Reg { n: llvm_ir::Name, multi_use: bool },
Free,
}
type Layout = Vec<Cell>;
const STACK_PTR_W: usize = 1;
// How do you deref an address when you're lost in a sea of tape?
fn build_ptr_train(
ctx: &mut Ctx,
addr: Addr, // the actual address to visit
store: Option<Addr>, /* if set the value at `store` is taken and stored
* at `addr` */
load: Option<Addr>, // if set the value at `addr` is copied put in `load`
) -> Vec<BfOp> {
let mut routine = Vec::<BfOp>::new();
// The engines don't move the ship at all. The ship stays where it is and
// the engines move the universe around it
// this is pretty hairy. The general idea is to copy the pointer value into
// a region which is then moved as a unit until it reaches the address
// pointed to.
//
// for example: say we have the tape:
//
// | tmp | ret | ptr | ? | ? | value | ptr | ? |
// ^ |
// | |
// +------+
//
// Where we want to deref `ptr`, which points to `value`. `ptr` is at a
// known offset from the current tape address. In this example the `ptr`
// would have value 5.
//
// copying `ptr` to the train would load 2 in the ptr cell since the trains
// own location in memory must be accounted for.
//
// | 0 | 0 | 2 | ? | ? | value | ptr | ? |
//
// and then just repeatedly move one cell forward... ptr copy is
// decremented and a return counter is incremented.
//
// | ? | 0 | 1 | 1 | ? | value | ptr | ? |
//
// until ptr is zero.
//
// | ? | ? | 0 | 2 | 0 | value | ptr | ? |
//
// then the cell right after the train aka `value` is loaded in and we drive
// back using ret.
//
// | ? | ? | 0 | 2 | value | value | ptr | ? |
//
// | ? | 0 | 1 | value | ? | value | ptr | ? |
//
// | 0 | 0 | value | ? | ? | value | ptr | ? |
//
// it's like a train! choo choo
// layout of a train is:
// to store: <before> | tmp | ret | ptr | cargo | <behind>
// from store: <before> | tmp | ret | 0 | 0 | <behind>
// to load: <before> | tmp | ret | ptr | <behind>
// from load: <before> | tmp | ret | cargo | <behind>
let is_store = store.is_some();
let train_len = if is_store { 4 } else { 3 };
let train = borrow_reg(ctx, train_len);
let train_tmp = offset(train.clone(), 0);
let train_ret = offset(train.clone(), 1);
let train_ptr = offset(train.clone(), 2);
let train_cargo = offset(train.clone(), 3); // this is only valid when storing
let before_train = offset(train.clone(), -1);
let behind_train = offset(train.clone(), train_len as i64); // train_cargo + 1;
// while driving forward train is layed out like:
// <before> | tmp | ret | ptr | cargo | <behind>
routine.append(&mut vec![
BfOp::Tag(train_tmp.clone(), format!("train_tmp")),
BfOp::Tag(train_ret.clone(), format!("train_ret")),
BfOp::Tag(train_ptr.clone(), format!("train_ptr")),
if is_store {
BfOp::Tag(train_cargo.clone(), format!("train_cargo"))
} else {
BfOp::Nop
},
]);
// this is all just concerned with getting the right value into the train's
// ptr
{
// so when moving left really we want to calculate the equivalent of:
// stack_pointer - addr + train_address
//
// first we sub addr from stackpointer, a negative result indicating the
// address is to the left of the current stack frame
//
// moving &train to train_ptr
// routine.push(BfOp::AddI(train_ptr, train as u8));
let stackptr_tmp = borrow_reg(ctx, 1);
let stackptr = borrow_reg(ctx, 1);
routine.push(BfOp::Tag(stackptr.clone(), format!("stackptr")));
routine.push(BfOp::Tag(stackptr_tmp.clone(), format!("stackptr_tmp")));
// grab the stackptr
routine.append(&mut vec![
BfOp::Left(1),
BfOp::Dup(
fixed_addr(0),
offset(stackptr_tmp.clone(), 1),
offset(stackptr.clone(), 1),
),
BfOp::Mov(offset(stackptr_tmp.clone(), 1), fixed_addr(0)),
BfOp::Right(1),
]);
let neg = borrow_reg(ctx, 1);
routine.push(BfOp::Tag(neg.clone(), format!("ptr_underflow")));
let (mut ops, to) =
subnu(ctx, stackptr.clone(), addr, Some(neg.clone()));
routine.append(&mut ops);
routine.push(BfOp::Tag(to.clone(), format!("subnu_to")));
routine.append(&mut vec![
// if pos
// train_ptr = &train + abs(stackptr - addr)
BfOp::Loop(
to.clone(),
vec![
BfOp::Comment(format!("if pos")),
BfOp::Mov(to.clone(), train_ptr.clone()),
// TODO: would be cool do defer resolution here so we're
// carrying around resolvable values
BfOp::AddI(train_ptr.clone(), resaddr(train.clone()) as u8),
],
),
// if neg
// train_ptr = &train + abs(stackptr - addr)
BfOp::Loop(
neg.clone(),
vec![
BfOp::Comment(format!("if neg")),
BfOp::AddI(train_ptr.clone(), resaddr(train.clone()) as u8),
BfOp::Loop(
neg.clone(),
vec![
BfOp::SubI(neg.clone(), 1),
BfOp::SubI(train_ptr.clone(), 1),
],
),
],
),
]);
}
if is_store {
// load in the cargo hehe
routine.push(BfOp::Mov(store.clone().unwrap(), train_cargo.clone()));
}
routine.push(BfOp::Comment(format!("drive left! choo choo")));
// time to drive! choo choo!
routine.append(&mut vec![BfOp::Loop(
train_ptr.clone(),
vec![
BfOp::Mov(train_ret.clone(), train_tmp.clone()),
BfOp::Mov(train_ptr.clone(), train_ret.clone()),
if is_store {
BfOp::Mov(train_cargo.clone(), train_ptr.clone())
} else {
BfOp::Nop
},
BfOp::Mov(before_train.clone(), offset(behind_train.clone(), -1)),
BfOp::Left(1),
BfOp::SubI(train_ptr.clone(), 1),
BfOp::AddI(train_ret.clone(), 1),
],
)]);
if is_store {
// unload the cargo
routine.push(BfOp::Zero(before_train.clone()));
routine.push(BfOp::Mov(train_cargo.clone(), before_train.clone()));
} else if load.is_some() {
routine.push(BfOp::Comment(format!("get our bag")));
routine.push(BfOp::Dup(
before_train.clone(),
train_tmp.clone(),
train_ptr.clone(),
));
routine.push(BfOp::Mov(train_tmp.clone(), before_train.clone()));
}
// reverse outta there dude
routine.append(&mut vec![BfOp::Loop(
train_ret.clone(),
vec![
BfOp::Mov(behind_train.clone(), train_tmp.clone()),
if load.is_some() {
BfOp::Mov(train_ptr.clone(), behind_train.clone())
} else {
BfOp::Nop
},
BfOp::Mov(train_ret.clone(), train_ptr.clone()),
BfOp::Right(1),
BfOp::SubI(train_ret.clone(), 1),
],
)]);
if load.is_some() {
routine.push(BfOp::Mov(train_ptr.clone(), load.unwrap()));
}
routine
}
#[derive(Debug, Clone)]
struct GlobalMap {
name: llvm_ir::Name,
addr: u8,
}
#[derive(Debug)]
struct Ctx {
layout: Layout,
addrs: Vec<Addr>,
ret_pad_width: Option<usize>,
stack_width: Option<usize>,
entry_block_addr: Option<usize>,
retpad_addr: Option<Addr>,
ownfid: Option<usize>,
globals: Vec<GlobalMap>,
}
enum RetMeta {
Addr,
InPlace,
None,
}
#[derive(Debug)]
enum BuilderArgs {
ConsumedReg(Addr),
PreservedReg(Addr),
Alloc(Addr),
Const(usize),
}
struct InstrMeta<'a> {
builders: &'a [(
RetMeta,
fn(
&mut Ctx,
&llvm_ir::Instruction,
&llvm_ir::BasicBlock,
&[BuilderArgs],
Option<Addr>,
) -> Vec<BfOp>,
)],
}
fn build_getelemptr(
ctx: &mut Ctx,
i: &llvm_ir::Instruction,
block: &llvm_ir::BasicBlock,
args: &[BuilderArgs],
ret: Option<Addr>,
) -> Vec<BfOp> {
let dest = ret.unwrap();
let (op0, o0) = builder_args_to_consumable_reg(ctx, &args[0]);
let (op1, o1) = builder_args_to_consumable_reg(ctx, &args[1]);
vec![]
.into_iter()
.chain(o0)
.chain(o1)
.chain(vec![
BfOp::Mov(op0.clone(), dest.clone()),
BfOp::Loop(
op1.clone(),
vec![BfOp::SubI(op1.clone(), 1), BfOp::AddI(dest.clone(), 1)],
),
])
.collect()
}
fn build_sub(
ctx: &mut Ctx,
i: &llvm_ir::Instruction,
block: &llvm_ir::BasicBlock,
args: &[BuilderArgs],
ret: Option<Addr>,
) -> Vec<BfOp> {
let (op0, o0) = builder_args_to_consumable_reg(ctx, &args[0]);
let (op1, o1) = builder_args_to_consumable_reg(ctx, &args[1]);
let dest = ret.unwrap();
vec![]
.into_iter()
.chain(o0)
.chain(o1)
.chain(vec![
BfOp::Mov(op0.clone(), dest.clone()),
BfOp::Loop(
op1.clone(),
vec![BfOp::SubI(op1.clone(), 1), BfOp::SubI(dest.clone(), 1)],
),
])
.collect()
}
// whole idea behind all the bitwise ops is to repeatedly split a value in half
// into two cells. Equality of the cells determines the lsb. This process can be
// repeated until the lower half is 0. e.g. w/ 5:
// .---.---.---.
// | 5 | 0 | 0 | initial
// '---'---'---'
// .---.---.---.
// | 0 | 3 | 2 | half
// '---'---'---'
// '---^---^
// .---.---.---.
// | 2 | 3 | 2 | dup
// '---'---'---'
// ^-------'
// .---.---.---.
// | 2 | 1 | 0 | sub
// '---'---'---'
// ^ lsb: 1
// .---.---.---.
// | 2 | 0 | 0 | reset
// '---'---'---'
// ^0