Repository navigation
Expand file tree
/
Copy pathabi.rs
More file actions
2731 lines (2490 loc) · 108 KB
/
Copy pathabi.rs
File metadata and controls
2731 lines (2490 loc) · 108 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
//! Implementation of a vanilla ABI, shared between several machines. The
//! implementation here assumes that arguments will be passed in registers
//! first, then additional args on the stack; that the stack grows downward,
//! contains a standard frame (return address and frame pointer), and the
//! compiler is otherwise free to allocate space below that with its choice of
//! layout; and that the machine has some notion of caller- and callee-save
//! registers. Most modern machines, e.g. x86-64 and AArch64, should fit this
//! mold and thus both of these backends use this shared implementation.
//!
//! See the documentation in specific machine backends for the "instantiation"
//! of this generic ABI, i.e., which registers are caller/callee-save, arguments
//! and return values, and any other special requirements.
//!
//! For now the implementation here assumes a 64-bit machine, but we intend to
//! make this 32/64-bit-generic shortly.
//!
//! # Vanilla ABI
//!
//! First, arguments and return values are passed in registers up to a certain
//! fixed count, after which they overflow onto the stack. Multiple return
//! values either fit in registers, or are returned in a separate return-value
//! area on the stack, given by a hidden extra parameter.
//!
//! Note that the exact stack layout is up to us. We settled on the
//! below design based on several requirements. In particular, we need
//! to be able to generate instructions (or instruction sequences) to
//! access arguments, stack slots, and spill slots before we know how
//! many spill slots or clobber-saves there will be, because of our
//! pass structure. We also prefer positive offsets to negative
//! offsets because of an asymmetry in some machines' addressing modes
//! (e.g., on AArch64, positive offsets have a larger possible range
//! without a long-form sequence to synthesize an arbitrary
//! offset). We also need clobber-save registers to be "near" the
//! frame pointer: Windows unwind information requires it to be within
//! 240 bytes of RBP. Finally, it is not allowed to access memory
//! below the current SP value.
//!
//! We assume that a prologue first pushes the frame pointer (and
//! return address above that, if the machine does not do that in
//! hardware). We set FP to point to this two-word frame record. We
//! store all other frame slots below this two-word frame record, as
//! well as enough space for arguments to the largest possible
//! function call. The stack pointer then remains at this position
//! for the duration of the function, allowing us to address all
//! frame storage at positive offsets from SP.
//!
//! Note that if we ever support dynamic stack-space allocation (for
//! `alloca`), we will need a way to reference spill slots and stack
//! slots relative to a dynamic SP, because we will no longer be able
//! to know a static offset from SP to the slots at any particular
//! program point. Probably the best solution at that point will be to
//! revert to using the frame pointer as the reference for all slots,
//! to allow generating spill/reload and stackslot accesses before we
//! know how large the clobber-saves will be.
//!
//! # Stack Layout
//!
//! The stack looks like:
//!
//! ```plain
//! (high address)
//! | ... |
//! | caller frames |
//! | ... |
//! +===========================+
//! | ... |
//! | stack args |
//! Canonical Frame Address --> | (accessed via FP) |
//! +---------------------------+
//! SP at function entry -----> | return address |
//! +---------------------------+
//! FP after prologue --------> | FP (pushed by prologue) |
//! +---------------------------+ -----
//! | ... | |
//! | clobbered callee-saves | |
//! unwind-frame base --------> | (pushed by prologue) | |
//! +---------------------------+ ----- |
//! | ... | | |
//! | spill slots | | |
//! | (accessed via SP) | fixed active
//! | ... | frame size
//! | stack slots | storage |
//! | (accessed via SP) | size |
//! | (alloc'd by prologue) | | |
//! +---------------------------+ ----- |
//! | [alignment as needed] | |
//! | ... | |
//! | args for largest call | |
//! SP -----------------------> | (alloc'd by prologue) | |
//! +===========================+ -----
//!
//! (low address)
//! ```
//!
//! # Multi-value Returns
//!
//! We support multi-value returns by using multiple return-value
//! registers. In some cases this is an extension of the base system
//! ABI. See each platform's `abi.rs` implementation for details.
use crate::CodegenError;
use crate::FxHashMap;
use crate::HashMap;
use crate::entity::SecondaryMap;
use crate::ir::{ArgumentExtension, ArgumentPurpose, ExceptionTag, Signature};
use crate::ir::{StackSlotKey, types::*};
use crate::isa::TargetIsa;
use crate::settings::ProbestackStrategy;
use crate::{ir, isa};
use crate::{machinst::*, trace};
use alloc::boxed::Box;
use core::marker::PhantomData;
use regalloc2::{MachineEnv, PReg, PRegSet};
use smallvec::smallvec;
/// A small vector of instructions (with some reasonable size); appropriate for
/// a small fixed sequence implementing one operation.
pub type SmallInstVec<I> = SmallVec<[I; 4]>;
/// A type used by backends to track argument-binding info in the "args"
/// pseudoinst. The pseudoinst holds a boxed slice of `ArgPair` structs.
#[derive(Clone, Debug)]
pub struct ArgPair {
/// The vreg that is defined by this args pseudoinst.
pub vreg: Writable<Reg>,
/// The preg that the arg arrives in; this constrains the vreg's
/// placement at the pseudoinst.
pub preg: Reg,
}
/// A type used by backends to track return register binding info in the "ret"
/// pseudoinst. The pseudoinst holds a boxed slice of `RetPair` structs.
#[derive(Clone, Debug)]
pub struct RetPair {
/// The vreg that is returned by this pseudionst.
pub vreg: Reg,
/// The preg that the arg is returned through; this constrains the vreg's
/// placement at the pseudoinst.
pub preg: Reg,
}
/// A location for (part of) an argument or return value. These "storage slots"
/// are specified for each register-sized part of an argument.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ABIArgSlot {
/// In a real register.
Reg {
/// Register that holds this arg.
reg: RealReg,
/// Value type of this arg.
ty: ir::Type,
/// Should this arg be zero- or sign-extended?
extension: ir::ArgumentExtension,
},
/// Arguments only: on stack, at given offset from SP at entry.
Stack {
/// Offset of this arg relative to the base of stack args.
offset: i64,
/// Value type of this arg.
ty: ir::Type,
/// Should this arg be zero- or sign-extended?
extension: ir::ArgumentExtension,
},
}
impl ABIArgSlot {
/// The type of the value that will be stored in this slot.
pub fn get_type(&self) -> ir::Type {
match self {
ABIArgSlot::Reg { ty, .. } => *ty,
ABIArgSlot::Stack { ty, .. } => *ty,
}
}
}
/// A vector of `ABIArgSlot`s. Inline capacity for one element because basically
/// 100% of values use one slot. Only `i128`s need multiple slots, and they are
/// super rare (and never happen with Wasm).
pub type ABIArgSlotVec = SmallVec<[ABIArgSlot; 1]>;
/// An ABIArg is composed of one or more parts. This allows for a CLIF-level
/// Value to be passed with its parts in more than one location at the ABI
/// level. For example, a 128-bit integer may be passed in two 64-bit registers,
/// or even a 64-bit register and a 64-bit stack slot, on a 64-bit machine. The
/// number of "parts" should correspond to the number of registers used to store
/// this type according to the machine backend.
///
/// As an invariant, the `purpose` for every part must match. As a further
/// invariant, a `StructArg` part cannot appear with any other part.
#[derive(Clone, Debug)]
pub enum ABIArg {
/// Storage slots (registers or stack locations) for each part of the
/// argument value. The number of slots must equal the number of register
/// parts used to store a value of this type.
Slots {
/// Slots, one per register part.
slots: ABIArgSlotVec,
/// Purpose of this arg.
purpose: ir::ArgumentPurpose,
},
/// Structure argument. We reserve stack space for it, but the CLIF-level
/// semantics are a little weird: the value passed to the call instruction,
/// and received in the corresponding block param, is a *pointer*. On the
/// caller side, we memcpy the data from the passed-in pointer to the stack
/// area; on the callee side, we compute a pointer to this stack area and
/// provide that as the argument's value.
StructArg {
/// Offset of this arg relative to base of stack args.
offset: i64,
/// Size of this arg on the stack.
size: u64,
/// Purpose of this arg.
purpose: ir::ArgumentPurpose,
},
/// Implicit argument. Similar to a StructArg, except that we have the
/// target type, not a pointer type, at the CLIF-level. This argument is
/// still being passed via reference implicitly.
ImplicitPtrArg {
/// Register or stack slot holding a pointer to the buffer.
pointer: ABIArgSlot,
/// Offset of the argument buffer.
offset: i64,
/// Type of the implicit argument.
ty: Type,
/// Purpose of this arg.
purpose: ir::ArgumentPurpose,
},
}
impl ABIArg {
/// Create an ABIArg from one register.
pub fn reg(
reg: RealReg,
ty: ir::Type,
extension: ir::ArgumentExtension,
purpose: ir::ArgumentPurpose,
) -> ABIArg {
ABIArg::Slots {
slots: smallvec![ABIArgSlot::Reg { reg, ty, extension }],
purpose,
}
}
/// Create an ABIArg from one stack slot.
pub fn stack(
offset: i64,
ty: ir::Type,
extension: ir::ArgumentExtension,
purpose: ir::ArgumentPurpose,
) -> ABIArg {
ABIArg::Slots {
slots: smallvec![ABIArgSlot::Stack {
offset,
ty,
extension,
}],
purpose,
}
}
}
/// Are we computing information about arguments or return values? Much of the
/// handling is factored out into common routines; this enum allows us to
/// distinguish which case we're handling.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ArgsOrRets {
/// Arguments.
Args,
/// Return values.
Rets,
}
/// Whether an ABI argument slot lives in a register or on the stack.
/// Passed to `get_ext_mode` so backends can apply different extension
/// rules depending on the argument's location.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ABIArgLocation {
/// The argument is passed in a register.
Reg,
/// The argument is passed on the stack.
Stack,
}
/// Abstract location for a machine-specific ABI impl to translate into the
/// appropriate addressing mode.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StackAMode {
/// Offset into the current frame's argument area.
IncomingArg(i64, u32),
/// Offset within the stack slots in the current frame.
Slot(i64),
/// Offset into the callee frame's argument area.
OutgoingArg(i64),
}
impl StackAMode {
fn offset_by(&self, offset: u32) -> Self {
match self {
StackAMode::IncomingArg(off, size) => {
StackAMode::IncomingArg(off.checked_add(i64::from(offset)).unwrap(), *size)
}
StackAMode::Slot(off) => StackAMode::Slot(off.checked_add(i64::from(offset)).unwrap()),
StackAMode::OutgoingArg(off) => {
StackAMode::OutgoingArg(off.checked_add(i64::from(offset)).unwrap())
}
}
}
}
/// Trait implemented by machine-specific backend to represent ISA flags.
pub trait IsaFlags: Clone {
/// Get a flag indicating whether forward-edge CFI is enabled.
fn is_forward_edge_cfi_enabled(&self) -> bool {
false
}
}
/// Used as an out-parameter to accumulate a sequence of `ABIArg`s in
/// `ABIMachineSpec::compute_arg_locs`. Wraps the shared allocation for all
/// `ABIArg`s in `SigSet` and exposes just the args for the current
/// `compute_arg_locs` call.
pub struct ArgsAccumulator<'a> {
sig_set_abi_args: &'a mut Vec<ABIArg>,
start: usize,
non_formal_flag: bool,
}
impl<'a> ArgsAccumulator<'a> {
fn new(sig_set_abi_args: &'a mut Vec<ABIArg>) -> Self {
let start = sig_set_abi_args.len();
ArgsAccumulator {
sig_set_abi_args,
start,
non_formal_flag: false,
}
}
#[inline]
pub fn push(&mut self, arg: ABIArg) {
debug_assert!(!self.non_formal_flag);
self.sig_set_abi_args.push(arg)
}
#[inline]
pub fn push_non_formal(&mut self, arg: ABIArg) {
self.non_formal_flag = true;
self.sig_set_abi_args.push(arg)
}
#[inline]
pub fn args(&self) -> &[ABIArg] {
&self.sig_set_abi_args[self.start..]
}
#[inline]
pub fn args_mut(&mut self) -> &mut [ABIArg] {
&mut self.sig_set_abi_args[self.start..]
}
}
/// Trait implemented by machine-specific backend to provide information about
/// register assignments and to allow generating the specific instructions for
/// stack loads/saves, prologues/epilogues, etc.
pub trait ABIMachineSpec {
/// The instruction type.
type I: VCodeInst;
/// The ISA flags type.
type F: IsaFlags;
/// This is the limit for the size of argument and return-value areas on the
/// stack. We place a reasonable limit here to avoid integer overflow issues
/// with 32-bit arithmetic.
const STACK_ARG_RET_SIZE_LIMIT: u32;
/// Returns the number of bits in a word, that is 32/64 for 32/64-bit architecture.
fn word_bits() -> u32;
/// Returns the number of bytes in a word.
fn word_bytes() -> u32 {
return Self::word_bits() / 8;
}
/// Returns word-size integer type.
fn word_type() -> Type {
match Self::word_bits() {
32 => I32,
64 => I64,
_ => unreachable!(),
}
}
/// Returns word register class.
fn word_reg_class() -> RegClass {
RegClass::Int
}
/// Returns required stack alignment in bytes.
fn stack_align(call_conv: isa::CallConv) -> u32;
/// Process a list of parameters or return values and allocate them to registers
/// and stack slots.
///
/// The argument locations should be pushed onto the given `ArgsAccumulator`
/// in order. Any extra arguments added (such as return area pointers)
/// should come at the end of the list so that the first N lowered
/// parameters align with the N clif parameters.
///
/// Returns the stack-space used (rounded up to as alignment requires), and
/// if `add_ret_area_ptr` was passed, the index of the extra synthetic arg
/// that was added.
fn compute_arg_locs(
call_conv: isa::CallConv,
flags: &settings::Flags,
params: &[ir::AbiParam],
args_or_rets: ArgsOrRets,
add_ret_area_ptr: bool,
args: ArgsAccumulator,
) -> CodegenResult<(u32, Option<usize>)>;
/// Generate a load from the stack.
fn gen_load_stack(mem: StackAMode, into_reg: Writable<Reg>, ty: Type) -> Self::I;
/// Generate a store to the stack.
fn gen_store_stack(mem: StackAMode, from_reg: Reg, ty: Type) -> Self::I;
/// Generate a move.
fn gen_move(to_reg: Writable<Reg>, from_reg: Reg, ty: Type) -> Self::I;
/// Generate an integer-extend operation.
fn gen_extend(
to_reg: Writable<Reg>,
from_reg: Reg,
is_signed: bool,
from_bits: u8,
to_bits: u8,
) -> Self::I;
/// Generate an "args" pseudo-instruction to capture input args in
/// registers.
fn gen_args(args: Box<[ArgPair]>) -> Self::I;
/// Generate a "rets" pseudo-instruction that moves vregs to return
/// registers.
fn gen_rets(rets: Box<[RetPair]>) -> Self::I;
/// Generate an add-with-immediate. Note that even if this uses a scratch
/// register, it must satisfy two requirements:
///
/// - The add-imm sequence must only clobber caller-save registers that are
/// not used for arguments, because it will be placed in the prologue
/// before the clobbered callee-save registers are saved.
///
/// - The add-imm sequence must work correctly when `from_reg` and/or
/// `into_reg` are the register returned by `get_stacklimit_reg()`.
fn gen_add_imm(
call_conv: isa::CallConv,
into_reg: Writable<Reg>,
from_reg: Reg,
imm: u32,
) -> SmallInstVec<Self::I>;
/// Generate a sequence that traps with a `TrapCode::StackOverflow` code if
/// the stack pointer is less than the given limit register (assuming the
/// stack grows downward).
fn gen_stack_lower_bound_trap(limit_reg: Reg) -> SmallInstVec<Self::I>;
/// Generate an instruction to compute an address of a stack slot (FP- or
/// SP-based offset).
fn gen_get_stack_addr(mem: StackAMode, into_reg: Writable<Reg>) -> Self::I;
/// Get a fixed register to use to compute a stack limit. This is needed for
/// certain sequences generated after the register allocator has already
/// run. This must satisfy two requirements:
///
/// - It must be a caller-save register that is not used for arguments,
/// because it will be clobbered in the prologue before the clobbered
/// callee-save registers are saved.
///
/// - It must be safe to pass as an argument and/or destination to
/// `gen_add_imm()`. This is relevant when an addition with a large
/// immediate needs its own temporary; it cannot use the same fixed
/// temporary as this one.
fn get_stacklimit_reg(call_conv: isa::CallConv) -> Reg;
/// Generate a load to the given [base+offset] address.
fn gen_load_base_offset(into_reg: Writable<Reg>, base: Reg, offset: i32, ty: Type) -> Self::I;
/// Generate a store from the given [base+offset] address.
fn gen_store_base_offset(base: Reg, offset: i32, from_reg: Reg, ty: Type) -> Self::I;
/// Adjust the stack pointer up or down.
fn gen_sp_reg_adjust(amount: i32) -> SmallInstVec<Self::I>;
/// Compute a FrameLayout structure containing a sorted list of all clobbered
/// registers that are callee-saved according to the ABI, as well as the sizes
/// of all parts of the stack frame. The result is used to emit the prologue
/// and epilogue routines.
fn compute_frame_layout(
call_conv: isa::CallConv,
flags: &settings::Flags,
sig: &Signature,
regs: &[Writable<RealReg>],
function_calls: FunctionCalls,
incoming_args_size: u32,
tail_args_size: u32,
stackslots_size: u32,
fixed_frame_storage_size: u32,
outgoing_args_size: u32,
) -> FrameLayout;
/// Defaults to a conservative 1GiB
/// across all backends.
fn maximum_frame_size() -> u32 {
1 << 30 // 1 GiB
}
/// Generate the usual frame-setup sequence for this architecture: e.g.,
/// `push rbp / mov rbp, rsp` on x86-64, or `stp fp, lr, [sp, #-16]!` on
/// AArch64.
fn gen_prologue_frame_setup(
call_conv: isa::CallConv,
flags: &settings::Flags,
isa_flags: &Self::F,
frame_layout: &FrameLayout,
) -> SmallInstVec<Self::I>;
/// Generate the usual frame-restore sequence for this architecture.
fn gen_epilogue_frame_restore(
call_conv: isa::CallConv,
flags: &settings::Flags,
isa_flags: &Self::F,
frame_layout: &FrameLayout,
) -> SmallInstVec<Self::I>;
/// Generate a return instruction.
fn gen_return(
call_conv: isa::CallConv,
isa_flags: &Self::F,
frame_layout: &FrameLayout,
) -> SmallInstVec<Self::I>;
/// Generate a probestack call.
fn gen_probestack(insts: &mut SmallInstVec<Self::I>, frame_size: u32);
/// Generate a inline stack probe.
fn gen_inline_probestack(
insts: &mut SmallInstVec<Self::I>,
call_conv: isa::CallConv,
frame_size: u32,
guard_size: u32,
);
/// Generate a clobber-save sequence. The implementation here should return
/// a sequence of instructions that "push" or otherwise save to the stack all
/// registers written/modified by the function body that are callee-saved.
/// The sequence of instructions should adjust the stack pointer downward,
/// and should align as necessary according to ABI requirements.
fn gen_clobber_save(
call_conv: isa::CallConv,
flags: &settings::Flags,
frame_layout: &FrameLayout,
) -> SmallVec<[Self::I; 16]>;
/// Generate a clobber-restore sequence. This sequence should perform the
/// opposite of the clobber-save sequence generated above, assuming that SP
/// going into the sequence is at the same point that it was left when the
/// clobber-save sequence finished.
fn gen_clobber_restore(
call_conv: isa::CallConv,
flags: &settings::Flags,
frame_layout: &FrameLayout,
) -> SmallVec<[Self::I; 16]>;
/// Generate a memcpy invocation. Used to set up struct
/// args. Takes `src`, `dst` as read-only inputs and passes a temporary
/// allocator.
fn gen_memcpy<F: FnMut(Type) -> Writable<Reg>>(
call_conv: isa::CallConv,
dst: Reg,
src: Reg,
size: usize,
alloc_tmp: F,
) -> SmallVec<[Self::I; 8]>;
/// Get the number of spillslots required for the given register-class.
fn get_number_of_spillslots_for_value(
rc: RegClass,
target_vector_bytes: u32,
isa_flags: &Self::F,
) -> u32;
/// Get the ABI-dependent MachineEnv for managing register allocation.
fn get_machine_env(flags: &settings::Flags, call_conv: isa::CallConv) -> &MachineEnv;
/// Get all caller-save registers, that is, registers that we expect
/// not to be saved across a call to a callee with the given ABI.
fn get_regs_clobbered_by_call(
call_conv_of_callee: isa::CallConv,
is_exception: bool,
) -> PRegSet;
/// Get the needed extension mode, given the mode attached to the argument
/// in the signature and the calling convention. The input (the attribute in
/// the signature) specifies what extension type should be done *if* the ABI
/// requires extension to the full register; this method's return value
/// indicates whether the extension actually *will* be done.
/// The `location` parameter indicates whether the argument is in a register
/// or on the stack, allowing backends to apply different rules per location.
fn get_ext_mode(
call_conv: isa::CallConv,
specified: ir::ArgumentExtension,
location: ABIArgLocation,
) -> ir::ArgumentExtension;
/// Get a temporary register that is available to use after a call
/// completes and that does not interfere with register-carried
/// return values. This is used to move stack-carried return
/// values directly into spillslots if needed.
fn retval_temp_reg(call_conv_of_callee: isa::CallConv) -> Writable<Reg>;
/// Get the exception payload registers, if any, for a calling
/// convention.
///
/// Note that the argument here is the calling convention of the *callee*.
/// This might differ from the caller but the exceptional payloads that are
/// available are defined by the callee, not the caller.
fn exception_payload_regs(callee_conv: isa::CallConv) -> &'static [Reg] {
let _ = callee_conv;
&[]
}
}
/// Out-of-line data for calls, to keep the size of `Inst` down.
#[derive(Clone, Debug)]
pub struct CallInfo<T> {
/// Receiver of this call
pub dest: T,
/// Register uses of this call.
pub uses: CallArgList,
/// Register defs of this call.
pub defs: CallRetList,
/// Registers clobbered by this call, as per its calling convention.
pub clobbers: PRegSet,
/// The calling convention of the callee.
pub callee_conv: isa::CallConv,
/// The calling convention of the caller.
pub caller_conv: isa::CallConv,
/// The number of bytes that the callee will pop from the stack for the
/// caller, if any. (Used for popping stack arguments with the `tail`
/// calling convention.)
pub callee_pop_size: u32,
/// Information for a try-call, if this is one. We combine
/// handling of calls and try-calls as much as possible to share
/// argument/return logic; they mostly differ in the metadata that
/// they emit, which this information feeds into.
pub try_call_info: Option<TryCallInfo>,
/// Whether this call is patchable.
pub patchable: bool,
}
/// Out-of-line information present on `try_call` instructions only:
/// information that is used to generate exception-handling tables and
/// link up to destination blocks properly.
#[derive(Clone, Debug)]
pub struct TryCallInfo {
/// The target to jump to on a normal returhn.
pub continuation: MachLabel,
/// Exception tags to catch and corresponding destination labels.
pub exception_handlers: Box<[TryCallHandler]>,
}
/// Information about an individual handler at a try-call site.
#[derive(Clone, Debug)]
pub enum TryCallHandler {
/// If the tag matches (given the current context), recover at the
/// label.
Tag(ExceptionTag, MachLabel),
/// Recover at the label unconditionally.
Default(MachLabel),
/// Set the dynamic context for interpreting tags at this point in
/// the handler list.
Context(Reg),
}
impl<T> CallInfo<T> {
/// Creates an empty set of info with no clobbers/uses/etc with the
/// specified ABI
pub fn empty(dest: T, call_conv: isa::CallConv) -> CallInfo<T> {
CallInfo {
dest,
uses: smallvec![],
defs: smallvec![],
clobbers: PRegSet::empty(),
caller_conv: call_conv,
callee_conv: call_conv,
callee_pop_size: 0,
try_call_info: None,
patchable: false,
}
}
}
/// The id of an ABI signature within the `SigSet`.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Sig(u32);
cranelift_entity::entity_impl!(Sig);
impl Sig {
fn prev(self) -> Option<Sig> {
self.0.checked_sub(1).map(Sig)
}
}
/// ABI information shared between body (callee) and caller.
#[derive(Clone, Debug)]
pub struct SigData {
/// Currently both return values and arguments are stored in a continuous space vector
/// in `SigSet::abi_args`.
///
/// ```plain
/// +----------------------------------------------+
/// | return values |
/// | ... |
/// rets_end --> +----------------------------------------------+
/// | arguments |
/// | ... |
/// args_end --> +----------------------------------------------+
///
/// ```
///
/// Note we only store two offsets as rets_end == args_start, and rets_start == prev.args_end.
///
/// Argument location ending offset (regs or stack slots). Stack offsets are relative to
/// SP on entry to function.
///
/// This is a index into the `SigSet::abi_args`.
args_end: u32,
/// Return-value location ending offset. Stack offsets are relative to the return-area
/// pointer.
///
/// This is a index into the `SigSet::abi_args`.
rets_end: u32,
/// Space on stack used to store arguments. We're storing the size in u32 to
/// reduce the size of the struct.
sized_stack_arg_space: u32,
/// Space on stack used to store return values. We're storing the size in u32 to
/// reduce the size of the struct.
sized_stack_ret_space: u32,
/// Index in `args` of the stack-return-value-area argument.
stack_ret_arg: Option<u16>,
/// Calling convention used.
call_conv: isa::CallConv,
}
impl SigData {
/// Get total stack space required for arguments.
pub fn sized_stack_arg_space(&self) -> u32 {
self.sized_stack_arg_space
}
/// Get total stack space required for return values.
pub fn sized_stack_ret_space(&self) -> u32 {
self.sized_stack_ret_space
}
/// Get calling convention used.
pub fn call_conv(&self) -> isa::CallConv {
self.call_conv
}
/// The index of the stack-return-value-area argument, if any.
pub fn stack_ret_arg(&self) -> Option<u16> {
self.stack_ret_arg
}
}
/// A (mostly) deduplicated set of ABI signatures.
///
/// We say "mostly" because we do not dedupe between signatures interned via
/// `ir::SigRef` (direct and indirect calls; the vast majority of signatures in
/// this set) vs via `ir::Signature` (the callee itself and libcalls). Doing
/// this final bit of deduplication would require filling out the
/// `ir_signature_to_abi_sig`, which is a bunch of allocations (not just the
/// hash map itself but params and returns vecs in each signature) that we want
/// to avoid.
///
/// In general, prefer using the `ir::SigRef`-taking methods to the
/// `ir::Signature`-taking methods when you can get away with it, as they don't
/// require cloning non-copy types that will trigger heap allocations.
///
/// This type can be indexed by `Sig` to access its associated `SigData`.
pub struct SigSet {
/// Interned `ir::Signature`s that we already have an ABI signature for.
ir_signature_to_abi_sig: FxHashMap<ir::Signature, Sig>,
/// Interned `ir::SigRef`s that we already have an ABI signature for.
ir_sig_ref_to_abi_sig: SecondaryMap<ir::SigRef, Option<Sig>>,
/// A single, shared allocation for all `ABIArg`s used by all
/// `SigData`s. Each `SigData` references its args/rets via indices into
/// this allocation.
abi_args: Vec<ABIArg>,
/// The actual ABI signatures, keyed by `Sig`.
sigs: PrimaryMap<Sig, SigData>,
}
impl SigSet {
/// Construct a new `SigSet`, interning all of the signatures used by the
/// given function.
pub fn new<M>(func: &ir::Function, flags: &settings::Flags) -> CodegenResult<Self>
where
M: ABIMachineSpec,
{
let arg_estimate = func.dfg.signatures.len() * 6;
let mut sigs = SigSet {
ir_signature_to_abi_sig: FxHashMap::default(),
ir_sig_ref_to_abi_sig: SecondaryMap::with_capacity(func.dfg.signatures.len()),
abi_args: Vec::with_capacity(arg_estimate),
sigs: PrimaryMap::with_capacity(1 + func.dfg.signatures.len()),
};
sigs.make_abi_sig_from_ir_signature::<M>(func.signature.clone(), flags)?;
for sig_ref in func.dfg.signatures.keys() {
sigs.make_abi_sig_from_ir_sig_ref::<M>(sig_ref, &func.dfg, flags)?;
}
Ok(sigs)
}
/// Have we already interned an ABI signature for the given `ir::Signature`?
pub fn have_abi_sig_for_signature(&self, signature: &ir::Signature) -> bool {
self.ir_signature_to_abi_sig.contains_key(signature)
}
/// Construct and intern an ABI signature for the given `ir::Signature`.
pub fn make_abi_sig_from_ir_signature<M>(
&mut self,
signature: ir::Signature,
flags: &settings::Flags,
) -> CodegenResult<Sig>
where
M: ABIMachineSpec,
{
// Because the `HashMap` entry API requires taking ownership of the
// lookup key -- and we want to avoid unnecessary clones of
// `ir::Signature`s, even at the cost of duplicate lookups -- we can't
// have a single, get-or-create-style method for interning
// `ir::Signature`s into ABI signatures. So at least (debug) assert that
// we aren't creating duplicate ABI signatures for the same
// `ir::Signature`.
debug_assert!(!self.have_abi_sig_for_signature(&signature));
let sig_data = self.from_func_sig::<M>(&signature, flags)?;
let sig = self.sigs.push(sig_data);
self.ir_signature_to_abi_sig.insert(signature, sig);
Ok(sig)
}
fn make_abi_sig_from_ir_sig_ref<M>(
&mut self,
sig_ref: ir::SigRef,
dfg: &ir::DataFlowGraph,
flags: &settings::Flags,
) -> CodegenResult<Sig>
where
M: ABIMachineSpec,
{
if let Some(sig) = self.ir_sig_ref_to_abi_sig[sig_ref] {
return Ok(sig);
}
let signature = &dfg.signatures[sig_ref];
let sig_data = self.from_func_sig::<M>(signature, flags)?;
let sig = self.sigs.push(sig_data);
self.ir_sig_ref_to_abi_sig[sig_ref] = Some(sig);
Ok(sig)
}
/// Get the already-interned ABI signature id for the given `ir::SigRef`.
pub fn abi_sig_for_sig_ref(&self, sig_ref: ir::SigRef) -> Sig {
self.ir_sig_ref_to_abi_sig[sig_ref]
.expect("must call `make_abi_sig_from_ir_sig_ref` before `get_abi_sig_for_sig_ref`")
}
/// Get the already-interned ABI signature id for the given `ir::Signature`.
pub fn abi_sig_for_signature(&self, signature: &ir::Signature) -> Sig {
self.ir_signature_to_abi_sig
.get(signature)
.copied()
.expect("must call `make_abi_sig_from_ir_signature` before `get_abi_sig_for_signature`")
}
pub fn from_func_sig<M: ABIMachineSpec>(
&mut self,
sig: &ir::Signature,
flags: &settings::Flags,
) -> CodegenResult<SigData> {
// Keep in sync with ensure_struct_return_ptr_is_returned
if sig.uses_special_return(ArgumentPurpose::StructReturn) {
panic!("Explicit StructReturn return value not allowed: {sig:?}")
}
let tmp;
let returns = if let Some(struct_ret_index) =
sig.special_param_index(ArgumentPurpose::StructReturn)
{
if !sig.returns.is_empty() {
panic!("No return values are allowed when using StructReturn: {sig:?}");
}
tmp = [sig.params[struct_ret_index]];
&tmp
} else {
sig.returns.as_slice()
};
// Compute args and retvals from signature. Handle retvals first,
// because we may need to add a return-area arg to the args.
// NOTE: We rely on the order of the args (rets -> args) inserted to compute the offsets in
// `SigSet::args()` and `SigSet::rets()`. Therefore, we cannot change the two
// compute_arg_locs order.
let (sized_stack_ret_space, _) = M::compute_arg_locs(
sig.call_conv,
flags,
&returns,
ArgsOrRets::Rets,
/* extra ret-area ptr = */ false,
ArgsAccumulator::new(&mut self.abi_args),
)?;
if !flags.enable_multi_ret_implicit_sret() {
assert_eq!(sized_stack_ret_space, 0);
}
let rets_end = u32::try_from(self.abi_args.len()).unwrap();
// To avoid overflow issues, limit the return size to something reasonable.
if sized_stack_ret_space > M::STACK_ARG_RET_SIZE_LIMIT {
return Err(CodegenError::ImplLimitExceeded);
}
let need_stack_return_area = sized_stack_ret_space > 0;
if need_stack_return_area {
assert!(!sig.uses_special_param(ir::ArgumentPurpose::StructReturn));
}
let (sized_stack_arg_space, stack_ret_arg) = M::compute_arg_locs(
sig.call_conv,
flags,
&sig.params,
ArgsOrRets::Args,
need_stack_return_area,
ArgsAccumulator::new(&mut self.abi_args),
)?;
let args_end = u32::try_from(self.abi_args.len()).unwrap();
// To avoid overflow issues, limit the arg size to something reasonable.
if sized_stack_arg_space > M::STACK_ARG_RET_SIZE_LIMIT {
return Err(CodegenError::ImplLimitExceeded);
}
trace!(
"ABISig: sig {:?} => args end = {} rets end = {}
arg stack = {} ret stack = {} stack_ret_arg = {:?}",
sig,
args_end,
rets_end,
sized_stack_arg_space,
sized_stack_ret_space,
need_stack_return_area,
);
let stack_ret_arg = stack_ret_arg.map(|s| u16::try_from(s).unwrap());
Ok(SigData {
args_end,
rets_end,
sized_stack_arg_space,
sized_stack_ret_space,
stack_ret_arg,
call_conv: sig.call_conv,
})
}
/// Get this signature's ABI arguments.
pub fn args(&self, sig: Sig) -> &[ABIArg] {
let sig_data = &self.sigs[sig];
// Please see comments in `SigSet::from_func_sig` of how we store the offsets.
let start = usize::try_from(sig_data.rets_end).unwrap();
let end = usize::try_from(sig_data.args_end).unwrap();
&self.abi_args[start..end]
}
/// Get information specifying how to pass the implicit pointer
/// to the return-value area on the stack, if required.
pub fn get_ret_arg(&self, sig: Sig) -> Option<ABIArg> {
let sig_data = &self.sigs[sig];