Ahm*_*mud 2 compiler-construction assembly compiler-optimization rust peephole-optimization
所以我试图实现窥视孔优化,我从 a 开始Vec<LLStackInstruction> -> Vec<LLStackInstruction>,返回的列表被优化。(LL对于低级)我们的编译器被建模为抽象堆栈机,对于 init/assign,我们将 RHS 压入堆栈,将 LHS 的 addr 压入堆栈,然后弹出和 STR,但尝试将其减少为压入 RHS,然后存储到直接通过地址说明符来寻址,但我得到了一个非常丑陋的匹配,如下所示:(并且具有可变性)
pub fn peephole_optimiser(instrs: Vec<LLStackInstruction>) -> Vec<LLStackInstruction> {
let mut optimized_instructions: Vec<LLStackInstruction> = Vec::new();
let mut iter = instrs.iter().peekable();
while let Some(instruction) = iter.next() {
let window_iter = iter.clone();
let window: Vec<_> = [vec![instruction], window_iter.take(10).collect()].concat();
if let Some(LLStackInstruction::Push(Register::FP)) = window.get(0) {
if let Some(LLStackInstruction::Mov(Condition::None, r1, ArgType::Imm(n))) = window.get(1) {
if let Some(LLStackInstruction::Push(r2)) = window.get(2) {
if let Some(LLStackInstruction::Pop(_)) = window.get(3) {
if let Some(LLStackInstruction::Pop(_)) = window.get(4) {
if let Some(LLStackInstruction::Sub(..)) = window.get(5) {
if let Some(LLStackInstruction::Branch(..)) = window.get(6) {
if let Some(LLStackInstruction::Push(_)) = window.get(7) {
if let Some(LLStackInstruction::Pop(_)) = window.get(8) {
if let Some(LLStackInstruction::Pop(_)) = window.get(9) {
if let Some(LLStackInstruction::Str(..)) = window.get(10) {
if r1 == r2 {
optimized_instructions.push(LLStackInstruction::Pop(Register::R4));
optimized_instructions.push(LLStackInstruction::Str(Register::R4, AddressSpecifier::ImmediateOffset(Register::FP, -n)));
iter.nth(9);
continue;
}
}
}
}
}
}
}
}
}
}
}
}
optimized_instructions.push(instruction.clone());
}
optimized_instructions
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能让这个变得更好
此优化的作用示例
// Compact init/assign statements
// push {fp}
// mov r1, #88
// push {r1}
// pop {r0}
// pop {r1}
// subs r0, r1, r0
// bvs _overflow_err
// push {r0}
// pop {r3}
// pop {r4}
// str r4, [r3]
// INTO
// pop {r4}
// str r4, [fp, #-88]
Run Code Online (Sandbox Code Playgroud)
我唯一能想到的是,如果我可以将其表达为较小窗口的多个步骤并执行多个优化过程(或者在优化窗口之后,从结果开始重新运行,直到其不变)
您可以直接匹配窗口而不是嵌套if let语句。Rust 支持切片的模式解构:
match window[..11] {
[
LLStackInstruction::Push(Register::FP),
LLStackInstruction::Push(r2),
LLStackInstruction::Pop(_),
LLStackInstruction::Pop(_),
LLStackInstruction::Sub(..),
LLStackInstruction::Branch(..),
LLStackInstruction::Push(_),
LLStackInstruction::Pop(_),
LLStackInstruction::Pop(_),
LLStackInstruction::Str(..)
] if r1 == r2 => {
optimized_instructions.push(LLStackInstruction::Pop(Register::R4));
optimized_instructions.push(LLStackInstruction::Str(
Register::R4,
AddressSpecifier::ImmediateOffset(Register::FP, -n),
));
iter.nth(9);
continue;
}
_ => {}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
93 次 |
| 最近记录: |