|
| 1 | +package decaf.backend.asm |
| 2 | + |
| 3 | +import java.io.PrintWriter |
| 4 | +import java.util.logging.Level |
| 5 | + |
| 6 | +import decaf.backend.dataflow.{CFG, LivenessAnalyzer} |
| 7 | +import decaf.backend.reg.RegAlloc |
| 8 | +import decaf.driver.{Config, Phase} |
| 9 | +import decaf.lowlevel.instr.PseudoInstr |
| 10 | +import decaf.lowlevel.log.Log |
| 11 | +import decaf.lowlevel.tac.TacProg |
| 12 | +import decaf.printing.PrettyCFG |
| 13 | +import decaf.util.Conversions._ |
| 14 | + |
| 15 | +/** |
| 16 | + * The assembly code generation phase: translate a TAC program to assembly code. |
| 17 | + * |
| 18 | + * @param emitter helper assembly code emitter |
| 19 | + * @param regAlloc register allocator |
| 20 | + */ |
| 21 | +class Asm(val emitter: AsmEmitter, val regAlloc: RegAlloc) extends Phase[TacProg, String]("asm: " + emitter) { |
| 22 | + |
| 23 | + override def transform(prog: TacProg): String = { |
| 24 | + Log.info("phase: asm") |
| 25 | + val analyzer = new LivenessAnalyzer[PseudoInstr] |
| 26 | + |
| 27 | + for (vtbl <- prog.vtables) { |
| 28 | + Log.info("emit vtable for %s", vtbl.className) |
| 29 | + emitter.emitVTable(vtbl) |
| 30 | + } |
| 31 | + |
| 32 | + emitter.emitSubroutineBegin() |
| 33 | + for (func <- prog.funcs) { |
| 34 | + Log.info("emit func for %s", func.entry.prettyString) |
| 35 | + val (instrSeq, info) = emitter.selectInstr(func) |
| 36 | + val cfg = CFG.buildFrom(instrSeq) |
| 37 | + analyzer(cfg) |
| 38 | + Log.ifLoggable(Level.FINE, printer => new PrettyCFG[PseudoInstr](printer).pretty(cfg)) |
| 39 | + regAlloc(cfg, info) |
| 40 | + } |
| 41 | + |
| 42 | + emitter.emitEnd() |
| 43 | + } |
| 44 | + |
| 45 | + override def post(code: String)(implicit config: Config): Unit = { |
| 46 | + if (config.target.equals(Config.Target.PA5)) { |
| 47 | + val path = config.dstDir / config.sourceBaseName + ".s" |
| 48 | + val printer = new PrintWriter(path) |
| 49 | + printer.print(code) |
| 50 | + printer.close() |
| 51 | + } |
| 52 | + } |
| 53 | +} |
0 commit comments