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
//! IR instructions.
use crate::compiler::ir::types::{IrBinaryOp, IrConstant, IrLabel, IrUnaryOp, IrVar};
/// Where a run of values goes once it has been produced. The register VM keeps
/// such a run on the stack rather than in named registers, so the producer and
/// the consumer are lowered together as one instruction.
#[derive(Clone, Debug, PartialEq)]
pub enum SpreadSink {
/// Passed as the trailing arguments of another call.
Call {
dsts: Vec<IrVar>,
callee: IrVar,
fixed_args: Vec<IrVar>,
retc: u8,
},
/// Appended to a table constructor's array part.
List { table: IrVar },
/// Returned from the enclosing function.
Return,
}
/// What produces a run of values: a call keeping all its results, or `...`.
#[derive(Clone, Debug, PartialEq)]
pub enum SpreadSource {
Call {
callee: IrVar,
args: Vec<IrVar>,
/// A producer for this call's own trailing arguments, as in
/// `f(g(h()))`, where each call passes on everything the next yields.
trailing: Option<Box<SpreadSource>>,
},
Vararg,
}
impl SpreadSource {
/// The variables read while producing the run.
pub fn use_vars(&self) -> Vec<IrVar> {
match self {
Self::Call {
callee,
args,
trailing,
} => {
let mut uses = vec![*callee];
uses.extend(args.iter().copied());
if let Some(inner) = trailing {
uses.extend(inner.use_vars());
}
uses
}
Self::Vararg => Vec::new(),
}
}
/// How many consecutive registers laying this producer out needs.
pub fn slots(&self) -> u8 {
match self {
Self::Call { args, trailing, .. } => {
let nested = trailing.as_ref().map(|t| t.slots()).unwrap_or(0);
1u8.saturating_add(args.len() as u8).saturating_add(nested)
}
Self::Vararg => 1,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum IrInst {
LoadConst {
dst: IrVar,
val: IrConstant,
},
LoadNil {
dst: IrVar,
},
Move {
dst: IrVar,
src: IrVar,
},
BinOp {
dst: IrVar,
op: IrBinaryOp,
lhs: IrVar,
rhs: IrVar,
},
UnOp {
dst: IrVar,
op: IrUnaryOp,
src: IrVar,
},
NewTable {
dst: IrVar,
array_cap: u8,
fields_cap: u8,
},
GetTable {
dst: IrVar,
table: IrVar,
key: IrVar,
},
GetImport {
dst: IrVar,
module: String,
field: String,
},
SetTable {
table: IrVar,
key: IrVar,
val: IrVar,
},
AppendArray {
table: IrVar,
src: IrVar,
},
GetGlobal {
dst: IrVar,
name: String,
},
SetGlobal {
name: String,
src: IrVar,
},
GetUpval {
dst: IrVar,
index: u8,
},
SetUpval {
index: u8,
src: IrVar,
},
Call {
/// Where the call's results go, one variable per result. A call used
/// as a statement has none; `local a, b = f()` has two.
dsts: Vec<IrVar>,
callee: IrVar,
args: Vec<IrVar>,
retc: u8,
},
Return(Vec<IrVar>),
Closure {
dst: IrVar,
proto_idx: u16,
/// Parallel to the nested prototype's upvalues: the parent variable
/// each one captures, or `None` when it comes from the parent's own
/// upvalues. Listing them here keeps the optimizer from dropping or
/// renaming a variable that only a nested function reads.
captures: Vec<Option<IrVar>>,
},
Vararg {
dst: IrVar,
count: u8,
},
ForPrep {
base: IrVar,
limit: IrVar,
step: IrVar,
loop_var: IrVar,
jump: IrLabel,
},
ForLoop {
base: IrVar,
jump: IrLabel,
},
TForCall {
base: IrVar,
state: IrVar,
ctrl: IrVar,
vars: Vec<IrVar>,
},
TForLoop {
base: IrVar,
jump: IrLabel,
},
/// Detaches these captured variables from any closure made so far, so the
/// next closure capturing one gets a fresh variable. Emitted where each
/// loop iteration starts for the loop's own locals.
CloseUpvals {
vars: Vec<IrVar>,
},
Jump(IrLabel),
JumpIfFalse {
cond: IrVar,
target: IrLabel,
},
/// Every value from `source` handed straight to `sink`, e.g. `f(g())`,
/// `{...}` or `return f()`.
Spread {
source: SpreadSource,
sink: SpreadSink,
},
Label(IrLabel),
/// The source line of the instructions that follow. Emits no code.
Line(u32),
/// From here on the local variable `name` lives in `var`. Debug info only.
DebugLocal {
name: String,
var: IrVar,
},
/// The locals declared since the matching scope began go out of scope.
/// With `keep_alive` the variables count as used here, so a debugger can
/// read them until the end of their scope.
DebugScopeEnd {
vars: Vec<IrVar>,
keep_alive: bool,
},
// SSA Phi node: chooses incoming variable based on predecessor block label
Phi {
dst: IrVar,
incoming: Vec<(IrLabel, IrVar)>,
},
}
impl IrInst {
pub fn def_var(&self) -> Option<IrVar> {
match self {
Self::LoadConst { dst, .. }
| Self::LoadNil { dst }
| Self::Move { dst, .. }
| Self::BinOp { dst, .. }
| Self::UnOp { dst, .. }
| Self::NewTable { dst, .. }
| Self::GetTable { dst, .. }
| Self::GetImport { dst, .. }
| Self::GetGlobal { dst, .. }
| Self::GetUpval { dst, .. }
| Self::Closure { dst, .. }
| Self::Vararg { dst, .. }
| Self::Phi { dst, .. } => Some(*dst),
Self::Call { dsts, .. } => dsts.first().copied(),
_ => None,
}
}
/// Every variable this instruction writes. `def_var` names only the single
/// value an expression produces; a `for` loop also writes its control and
/// loop variables on each iteration, and an analysis that cannot see those
/// will treat a use of the loop variable as loop-invariant.
pub fn def_vars(&self) -> Vec<IrVar> {
match self {
Self::ForPrep {
base,
limit,
step,
loop_var,
..
} => vec![*base, *limit, *step, *loop_var],
Self::ForLoop { base, .. } | Self::TForLoop { base, .. } => vec![*base],
Self::TForCall {
base,
state,
ctrl,
vars,
} => {
let mut defs = vec![*base, *state, *ctrl];
defs.extend(vars.iter().copied());
defs
}
Self::Call { dsts, .. } => dsts.clone(),
Self::Spread {
sink: SpreadSink::Call { dsts, .. },
..
} => dsts.clone(),
_ => self.def_var().into_iter().collect(),
}
}
pub fn use_vars(&self) -> Vec<IrVar> {
match self {
Self::Move { src, .. } | Self::UnOp { src, .. } => vec![*src],
Self::AppendArray { table, src } => vec![*table, *src],
Self::BinOp { lhs, rhs, .. } => vec![*lhs, *rhs],
Self::GetTable { table, key, .. } => vec![*table, *key],
Self::SetTable { table, key, val } => vec![*table, *key, *val],
Self::SetGlobal { src, .. } | Self::SetUpval { src, .. } => vec![*src],
Self::Call { callee, args, .. } => {
let mut uses = vec![*callee];
uses.extend(args.iter().copied());
uses
}
Self::Return(vars) => vars.clone(),
Self::JumpIfFalse { cond, .. } => vec![*cond],
Self::ForPrep {
base, limit, step, ..
} => vec![*base, *limit, *step],
Self::ForLoop { base, .. } | Self::TForLoop { base, .. } => vec![*base],
Self::TForCall {
base, state, ctrl, ..
} => vec![*base, *state, *ctrl],
Self::Closure { captures, .. } => captures.iter().flatten().copied().collect(),
// Reading them keeps each variable in its register up to here,
// so nothing else can occupy it while a closure still holds it.
Self::CloseUpvals { vars } => vars.clone(),
Self::Spread { source, sink } => {
let mut uses = source.use_vars();
match sink {
SpreadSink::Call {
callee, fixed_args, ..
} => {
uses.push(*callee);
uses.extend(fixed_args.iter().copied());
}
SpreadSink::List { table } => uses.push(*table),
SpreadSink::Return => {}
}
uses
}
Self::Phi { incoming, .. } => incoming.iter().map(|(_, v)| *v).collect(),
Self::DebugScopeEnd {
vars,
keep_alive: true,
} => vars.clone(),
_ => Vec::new(),
}
}
/// Line and local-variable markers, which produce no code.
pub fn is_debug_marker(&self) -> bool {
matches!(
self,
Self::Line(_) | Self::DebugLocal { .. } | Self::DebugScopeEnd { .. }
)
}
pub fn is_terminator(&self) -> bool {
matches!(
self,
Self::Return(_)
| Self::Spread {
sink: SpreadSink::Return,
..
}
| Self::Jump(_)
| Self::JumpIfFalse { .. }
| Self::ForPrep { .. }
| Self::ForLoop { .. }
| Self::TForLoop { .. }
)
}
pub fn jump_targets(&self) -> Vec<IrLabel> {
match self {
Self::Jump(lbl) => vec![*lbl],
Self::JumpIfFalse { target, .. } => vec![*target],
Self::ForPrep { jump, .. }
| Self::ForLoop { jump, .. }
| Self::TForLoop { jump, .. } => {
vec![*jump]
}
_ => Vec::new(),
}
}
}