19using namespace std::string_literals;
25using Names = std::array<std::string_view, 4>;
28constexpr std::array<Names, 16> names = {{
29 {
"%al",
"%ax",
"%eax",
"%rax"}, {
"%cl",
"%cx",
"%ecx",
"%rcx"},
30 {
"%dl",
"%dx",
"%edx",
"%rdx"}, {
"%bl",
"%bx",
"%ebx",
"%rbx"},
31 {
"%spl",
"%sp",
"%esp",
"%rsp"}, {
"%bpl",
"%bp",
"%ebp",
"%rbp"},
32 {
"%sil",
"%si",
"%esi",
"%rsi"}, {
"%dil",
"%di",
"%edi",
"%rdi"},
33 {
"%r8b",
"%r8w",
"%r8d",
"%r8" }, {
"%r9b",
"%r9w",
"%r9d",
"%r9" },
34 {
"%r10b",
"%r10w",
"%r10d",
"%r10"}, {
"%r11b",
"%r11w",
"%r11d",
"%r11"},
35 {
"%r12b",
"%r12w",
"%r12d",
"%r12"}, {
"%r13b",
"%r13w",
"%r13d",
"%r13"},
36 {
"%r14b",
"%r14w",
"%r14d",
"%r14"}, {
"%r15b",
"%r15w",
"%r15d",
"%r15"},
40constexpr std::array<std::string_view, 16> ccs
41 = {
"o",
"no",
"b",
"ae",
"e",
"ne",
"be",
"a",
"s",
"ns",
"p",
"np",
"l",
"ge",
"le",
"g"};
45constexpr std::array<std::pair<std::string_view, std::optional<bool>>, 16> fccs = {{
47 {
"", {}}, {
"e",
false}, {
"b",
false}, {
"be",
false}, {
"a", {}}, {
"ae", {}}, {
"ne", {}}, {
"np", {}},
48 {
"p", {}}, {
"e", {}}, {
"b", {}}, {
"be", {}}, {
"a",
true}, {
"ae",
true}, {
"ne",
true}, {
"", {}},
51constexpr size_t Fcmp_T = 15;
53size_t log_bytes(
nat_t w) {
return std::countr_zero(w / 8); }
54std::string_view name(
size_t r,
nat_t w) {
return names[
r][log_bytes(w)]; }
55char suffix(
nat_t w) {
return "bwlq"[log_bytes(w)]; }
57nat_t wide(
nat_t w) {
return std::max<nat_t>(w, 32); }
58std::string
xmm(
size_t r) {
return std::format(
"%xmm{}", r); }
60std::string_view fsz(
nat_t w) {
return w == 64 ?
"sd" :
"ss"; }
63std::string_view farith(
flags_t id) {
84nat_t width(
const Def* type) {
91class Emitter :
public mach::Emitter {
93 Emitter(std::ostream& os, Emit&
emit, Lam* fun)
94 : mach::Emitter(
emit.target(), os,
emit, fun)
98 std::string
slot(
size_t i,
size_t off = 0)
const {
99 return std::format(
"{}(%rbp)", int64_t(off) - int64_t(8 * (saved(
Target::Gpr).
size() + i + 1)));
102 std::string src(
const Def* def,
nat_t w)
const;
104 std::string wide_src(
const Def* def,
nat_t w)
const {
105 return Lit::isa(def) ?
imm(def, w) : std::string(name(use_reg(def), wide(
w)));
107 std::string
imm(
const Def* lit,
nat_t w)
const;
108 std::string
addr(
const Def*)
const;
112 std::string abs_mask(
nat_t w) {
113 return w == 64 ?
pool(0x7fff'ffff'ffff'ffff, 0x7fff'ffff'ffff'ffff)
114 :
pool(0x7fff'ffff'7fff'ffff, 0x7fff'ffff'7fff'ffff);
117 std::string two32() {
return pool(std::bit_cast<u64>(4294967296.0), 0); }
119 std::string local(std::string_view what) {
120 return std::format(
"{}{}.{}{}", target().local_prefix(), fun()->unique_name(), what, sel_++);
123 void ucomi(
size_t sub,
nat_t w, std::string_view src,
size_t a,
size_t dst);
126 void insn(
const Def* res,
const Def* f,
const Def* x);
128 void step(
const App*)
final;
129 void move(Reg dst, Reg src)
final;
131 void swap(Reg a, Reg b)
final;
132 void mov_imm(Reg dst,
const Def* lit)
final;
133 void push_slot(
size_t i)
final { line(
"pushq {}",
slot(i)); }
134 void pop_slot(
size_t i)
final { line(
"popq {}",
slot(i)); }
135 void spill(Src src,
const Def* type,
size_t i)
final;
136 void reload(Reg dst,
const Def* type,
size_t i)
final;
137 void load_arg(Reg dst,
const Def* type,
size_t i)
final;
138 void load_from(Reg dst,
const Def* type, std::string_view src);
140 void slot_addr(
size_t dst,
size_t first,
size_t n)
final {
141 line(
"leaq {}, {}",
slot(first + n - 1), name(dst, 64));
143 void jmp(std::string_view label)
final { line(
"jmp {}", label); }
144 void branch_cc(
size_t cc, std::string_view label)
final { line(
"j{} {}", ccs[
cc], label); }
145 void branch_if(
size_t r, std::string_view label,
bool unless)
final {
147 line(
"testb {}, {}", n, n);
148 line(
"{} {}", unless ?
"je" :
"jne", label);
150 void call_insn(std::string_view sym, std::optional<std::array<size_t, Target::Num_Classes>> num_args)
final {
152 if (num_args) line(
"movl ${}, %eax", (*num_args)[
Target::Fpr]);
153 line(
"call {}", sym);
155 void prologue(std::ostream& os)
final;
162std::
string Emitter::imm(const Def* lit,
nat_t w)
const {
164 auto s = std::bit_cast<int64_t>(l << (64 - w)) >> (64 -
w);
165 if (s < INT32_MIN || s > INT32_MAX)
166 lit->blame(
"{} backend: literal `{}` does not fit an immediate", backend(), lit).bail();
167 return std::format(
"${}", s);
170std::string Emitter::src(
const Def* def,
nat_t w)
const {
172 return std::string(name(use_reg(def), w));
175std::string Emitter::addr(
const Def* a)
const {
178 auto d = std::bit_cast<int32_t>(
u32(
nat(disp)));
179 if (
auto l =
Lit::isa(base);
l && *
l != 0)
base->blame(
"{} backend: literal base `{}`", backend(), base).bail();
181 if (!has_base && !ix)
return std::to_string(d);
183 auto res =
d != 0 ? std::to_string(d) :
""s;
185 if (has_base) res += name(use_reg(base), 64);
188 res += std::format(
",{},{}", name(use_reg(
index), 64), 1 <<
nat(scale));
193std::string Emitter::pool(
u64 lo,
u64 hi) {
194 return std::format(
"{}pool{}(%rip)", target().local_prefix(), emit_.pool(lo, hi));
197void Emitter::move(Reg dst, Reg src) {
201 line(
"movq {}, {}", name(src.
num, 64), name(dst.
num, 64));
205void Emitter::swap(Reg a, Reg b) {
206 if (
a.cls ==
Target::Gpr)
return line(
"xchgq {}, {}", name(
a.num, 64), name(
b.num, 64));
207 line(
"xorps {}, {}",
xmm(
a.num),
xmm(
b.num));
208 line(
"xorps {}, {}",
xmm(
b.num),
xmm(
a.num));
209 line(
"xorps {}, {}",
xmm(
a.num),
xmm(
b.num));
212void Emitter::mov_imm(Reg dst,
const Def* lit) {
213 auto w = width(
lit->type());
216 if (w != 32 && w != 64)
lit->blame(
"{} backend: `math.F` of {} bits is not supported", backend(), w).bail();
217 return line(
"mov{} {}, {}", fsz(w),
pool(l, w == 64 ? 0 : l),
xmm(dst.
num));
220 if (l == 0 && flags_clobbered())
return line(
"xorl {}, {}", name(dst.
num, 32), name(dst.
num, 32));
221 if (w < 64)
return line(
"movl ${}, {}", l, name(dst.
num, 32));
222 auto s = std::bit_cast<int64_t>(l);
223 if (s < INT32_MIN || s > INT32_MAX)
224 line(
"movabsq ${}, {}", s, name(dst.
num, 64));
226 line(
"movq ${}, {}", s, name(dst.
num, 64));
229void Emitter::insn(
const Def* res,
const Def* f,
const Def* x) {
230 auto axm = std::get<0>(
Axm::get(f));
231 auto id = axm->base();
238 if (!keep) clobber_flags();
240 auto binary = [&](std::string_view mnemonic) {
241 auto [
a,
b] = x->projs<2>();
242 auto w = width(res->type());
243 auto dst = def_reg(res);
244 assert(use_reg(a) == dst);
245 line(
"{}{} {}, {}", mnemonic, suffix(wide(w)), wide_src(b, w), name(dst, wide(w)));
247 auto shift = [&](std::string_view mnemonic) {
248 auto [
a,
b] = x->projs<2>();
249 auto w = width(res->type());
250 auto dst = def_reg(res);
251 assert(use_reg(a) == dst);
253 auto wd = mnemonic ==
"shl" ? wide(w) :
w;
255 line(
"{}{} ${}, {}", mnemonic, suffix(wd), *l % w, name(dst, wd));
257 line(
"{}{} %cl, {}", mnemonic, suffix(wd), name(dst, wd));
259 auto divide = [&](
bool sign) {
260 auto [
a,
b] = x->projs<2>();
261 auto w = width(
a->type());
264 line(
"xorl %edx, %edx");
266 line(
"{}", w == 64 ?
"cqto" : w == 32 ?
"cltd" :
"cwtd");
267 line(
"{}div{} {}", sign ?
"i" :
"", suffix(w), name(use_reg(b), w));
269 auto extend = [&](
char kind) {
270 auto ws = width(x->type());
271 auto wd = width(res->type());
272 auto rs = use_reg(x);
273 auto rd = def_reg(res);
274 if (ws < wd && !(kind ==
'z' && ws == 32))
275 line(
"mov{}{}{} {}, {}", kind, suffix(ws), suffix(wd), name(rs, ws), name(rd, wd));
277 line(
"movl {}, {}", name(rs, 32), name(rd, 32));
279 line(
"movq {}, {}", name(rs, 64), name(rd, 64));
283 if (
auto mn =
alu(
id); !mn.empty())
binary(mn);
293 if (!
Lit::isa(x)) x->blame(
"{} backend: `x86.mov` of `{}`, which is no literal", backend(), x).bail();
296 auto w = width(x->type());
297 auto rs = use_reg(x);
298 auto rd = def_reg(res);
300 line(
"movz{}l {}, {}", suffix(w), name(rs, w), name(rd, 32));
302 line(
"movl {}, {}", name(rs, 32), name(rd, 32));
304 line(
"movq {}, {}", name(rs, 64), name(rd, 64));
306 line(
"leaq {}, {}",
addr(x), name(def_reg(res), 64));
308 auto [
a,
b] = x->projs<2>();
309 auto w = width(res->type());
310 line(
"imul{} {}, {}, {}", suffix(wide(w)),
imm(b, w), name(use_reg(a), wide(w)), name(def_reg(res), wide(w)));
312 auto [
a,
b] = x->projs<2>();
313 auto w = width(res->type());
314 auto dst = def_reg(res);
315 assert(use_reg(b) == dst);
316 line(
"neg{} {}", suffix(wide(w)), name(dst, wide(w)));
317 line(
"add{} {}, {}", suffix(wide(w)), wide_src(a, w), name(dst, wide(w)));
319 auto [
a,
b] = x->projs<2>();
320 auto w = width(res->type());
322 auto ra = name(use_reg(a), 64);
324 line(
"lea{} {}({}), {}", suffix(wd),
imm(b, w).substr(1), ra, name(def_reg(res), wd));
326 line(
"lea{} ({},{}), {}", suffix(wd), ra, name(use_reg(b), 64), name(def_reg(res), wd));
328 auto w = width(res->type());
329 auto rs = use_reg(x);
330 auto rd = def_reg(res);
332 auto full =
w == 64 ? 0 : 1_n <<
w;
333 if (n != 0 && !std::has_single_bit(n)) {
335 auto save = fe::Vector<size_t>();
337 if (r != rd) save.emplace_back(r);
339 line(
"pushq {}", name(r, 64));
340 auto wx = width(x->type());
341 auto ws = std::max<nat_t>(wx, 32);
343 line(
"movz{}l {}, %eax", suffix(wx), name(rs, wx));
345 line(
"mov{} {}, {}", suffix(ws), name(rs, ws), name(
encoding(
reg::rax), ws));
346 line(
"xorl %edx, %edx");
350 for (
auto r : save | std::views::reverse)
351 line(
"popq {}", name(r, 64));
353 if (rs != rd) line(
"movq {}, {}", name(rs, 64), name(rd, 64));
354 if (std::has_single_bit(n) && n != full) line(
"and{} ${}, {}", suffix(wide(w)), n - 1, name(rd, wide(w)));
357 auto [
a,
b] = x->projs<2>();
358 auto w = width(
a->type());
359 line(
"{}{} {}, {}",
id ==
Annex::Base<cmp> ?
"cmp" :
"test", suffix(w), src(b, w), name(use_reg(a), w));
364 if (
auto r = isa_reg(res)) line(
"set{} {}", ccs[axm->sub()], name(*r, 8));
366 auto [fl,
a,
b] = x->projs<3>();
367 auto w = width(res->type());
368 auto dst = def_reg(res);
369 assert(use_reg(a) == dst);
371 line(
"cmov{} {}, {}", ccs[axm->sub()], name(use_reg(b), wide(w)), name(dst, wide(w)));
374 auto [
a,
b] = x->projs<2>();
375 auto w = width(res->type());
376 auto dst = def_reg(res);
377 assert(use_reg(a) == dst);
378 line(
"{}{} {}, {}", farith(
id), fsz(w),
xmm(use_reg(b)),
xmm(dst));
381 auto ws = width(x->type());
385 auto w = width(res->type());
386 auto dst = def_reg(res);
387 assert(use_reg(x) == dst);
388 line(
"and{} {}, {}", w == 64 ?
"pd" :
"ps", abs_mask(w),
xmm(dst));
390 if (!
Lit::isa(x)) x->blame(
"{} backend: `x86.fmov` of `{}`, which is no literal", backend(), x).bail();
393 auto [
a,
b] = x->projs<2>();
394 ucomi(axm->sub(), width(
a->type()),
xmm(use_reg(b)), use_reg(a), def_reg(res));
396 auto [
c,
a,
b] = x->projs<3>();
397 auto dst = def_reg(res);
398 assert(use_reg(a) == dst);
399 auto l = local(
"fsel");
400 line(
"testb {}, {}", name(use_reg(c), 8), name(use_reg(c), 8));
402 line(
"movaps {}, {}",
xmm(use_reg(b)),
xmm(dst));
405 auto ws = width(x->type());
406 auto wr = width(res->type());
407 if (ws == 64)
f->blame(
"{} backend: `x86.u2f` from `i64` is not supported yet", backend()).bail();
408 auto src = name(use_reg(x), 32);
409 auto dst =
xmm(def_reg(res));
410 auto l = local(
"u2f");
412 line(
"cvtsi2sdl {}, {}", src, dst);
413 line(
"testl {}, {}", src, src);
415 line(
"addsd {}, {}", two32(), dst);
417 if (wr == 32) line(
"cvtsd2ss {}, {}", dst, dst);
419 f->blame(
"{} backend: cannot emit `{}`", backend(), axm).bail();
423void Emitter::ucomi(
size_t sub,
nat_t w, std::string_view src,
size_t a,
size_t dst) {
424 auto [
cc, unordered] = fccs[
sub];
425 if (
cc.empty())
return line(
"movl ${}, {}",
sub == Fcmp_T ? 1 : 0, name(dst, 32));
426 line(
"ucomi{} {}, {}", fsz(w), src,
xmm(a));
427 line(
"set{} {}",
cc, name(dst, 8));
428 if (!unordered)
return;
429 auto l = local(
"fcmp");
431 line(
"movl ${}, {}", *unordered ? 1 : 0, name(dst, 32));
435void Emitter::unary(
flags_t id, std::string_view src,
nat_t ws,
const Def* res) {
436 auto wr = width(res->type());
437 auto dst = def_reg(res);
439 return line(
"movs{}{} {}, {}", suffix(ws), suffix(wide(wr)), src, name(dst, wide(wr)));
441 if (
id ==
Annex::Base<i2f>)
return line(
"cvtsi2{}{} {}, {}", fsz(wr), ws == 64 ?
"q" :
"l", src,
xmm(dst));
442 if (
id ==
Annex::Base<f2i>)
return line(
"cvtt{}2si{} {}, {}", fsz(ws), wr == 64 ?
"q" :
"l", src, name(dst, wr));
443 if (
id ==
Annex::Base<f2f>)
return line(
"cvt{}2{} {}, {}", fsz(ws), fsz(wr), src,
xmm(dst));
444 if (wr == 64) res->blame(
"{} backend: `x86.f2u` to `i64` is not supported yet", backend()).bail();
445 line(
"cvtt{}2siq {}, {}", fsz(ws), src, name(dst, 64));
446 line(
"movl {}, {}", name(dst, 32), name(dst, 32));
449void Emitter::step(
const App* app) {
457 auto [_,
a,
p] = app->args<3>();
458 auto w = width(
a->type());
459 auto dst = def_reg(app->proj(2, 1));
460 auto insn =
op->decurry()->arg()->as<
App>()->axm();
462 assert(use_reg(a) == dst);
464 line(
"{}{} {}, {}", farith(insn->base()), fsz(w),
addr(p),
xmm(dst));
466 line(
"{}{} {}, {}",
alu(insn->flags()), suffix(w),
addr(p), name(dst, w));
471 auto [_,
p] = app->args<2>();
472 auto f = app->callee()->as<
App>()->arg();
473 return unary(
insn::op(app),
addr(p), width(
f->type()->as<Pi>()->dom()), app->proj(2, 1));
477 auto [_,
p,
b] = app->args<3>();
478 auto w = width(
b->type());
479 line(
"{}{} {}, {}",
alu(
op->decurry()->arg()->as<App>()->axm()->flags()), suffix(w), src(b, w),
addr(p));
484 auto [_,
p] = app->args<2>();
485 auto res = app->proj(2, 1);
486 auto w = width(res->type());
489 line(
"movz{}l {}, {}", suffix(w),
addr(p), name(def_reg(res), 32));
491 line(
"mov{} {}, {}", suffix(w),
addr(p), name(def_reg(res), w));
496 auto [_,
p] = app->args<2>();
497 auto res = app->proj(2, 1);
498 auto w = width(res->type());
499 line(
"mov{} {}, {}", fsz(w),
addr(p),
xmm(def_reg(res)));
504 auto [_,
p, v] = app->args<3>();
505 auto w = width(v->type());
506 line(
"mov{} {}, {}", fsz(w),
xmm(use_reg(v)),
addr(p));
510 auto [_,
p, v] = app->args<3>();
511 auto w = width(v->type());
512 line(
"mov{} {}, {}", suffix(w), src(v, w),
addr(p));
515void Emitter::spill(Src src,
const Def* type,
size_t i) {
517 auto s = src.
imm ?
imm(src.
imm, 64) : std::string(name(src.
reg.num, 64));
518 return line(
"movq {}, {}", s,
slot(i));
520 auto w = width(type);
523 line(
"movl ${}, {}",
u32(l),
slot(i));
524 if (w == 64) line(
"movl ${}, {}",
u32(l >> 32),
slot(i, 4));
530void Emitter::load_from(Reg dst,
const Def* type, std::string_view src) {
532 line(
"mov{} {}, {}", fsz(width(type)), src,
xmm(dst.
num));
534 line(
"movq {}, {}", src, name(dst.
num, 64));
537void Emitter::reload(Reg dst,
const Def* type,
size_t i) { load_from(dst, type,
slot(i)); }
540void Emitter::load_arg(Reg dst,
const Def* type,
size_t i) {
541 load_from(dst, type, std::format(
"{}(%rbp)", 16 + 8 * i));
544void Emitter::leave() {
549 for (
auto r : saved(
Target::Gpr) | std::views::reverse)
550 line(
"popq {}", name(r, 64));
555void Emitter::prologue(std::ostream& os) {
556 auto frame = frame_size() - 8 * saved(
Target::Gpr).size();
557 std::println(os,
"\tpushq %rbp");
558 std::println(os,
"\tmovq %rsp, %rbp");
560 std::println(os,
"\tpushq {}", name(r, 64));
561 if (frame != 0) std::println(os,
"\tsubq ${}, %rsp", frame);
566void Emit::emit(std::ostream& os,
Lam* fun,
bool global) { Emitter(os, *
this, fun).emit(global); }
569 if (pool_.empty())
return;
570 auto constants = fe::Vector<std::pair<u64, u64>>(pool_.size());
571 for (
auto& [c, i] : pool_)
573 std::println(os,
"\t{}",
Target::is_elf() ?
".section .rodata" :
".section __TEXT,__const");
574 std::println(os,
"\t.p2align 4");
575 for (
size_t i = 0; i != constants.size(); ++i) {
577 std::println(os,
"\t.quad 0x{:016x}", constants[i].first);
578 std::println(os,
"\t.quad 0x{:016x}", constants[i].second);
static auto isa(const Def *def)
static auto as(const Def *def)
static std::tuple< const Axm *, u8, u8 > get(const Def *def)
Yields currying counter of def.
static std::optional< nat_t > isa_lit(const Def *def)
static nat_t expect_bitwidth(const Def *type, fe::cite_string< Args... > fmt, Args &&... args)
Yields the bit width of the Idx type or bails if type is not an Idx; see Def::expect.
static std::optional< T > isa(const Def *def)
static const Def * sched_insn(const App *app)
static constexpr std::string_view local_prefix()
The prefix of an assembler-local label.
static constexpr bool is_elf()
void finish(std::ostream &os) final
Writes what all functions together need after them, e.g. a constant pool.
void emit(std::ostream &os, Lam *fun, bool global) final
std::optional< nat_t > isa_f(const Def *def)
flags_t op(const App *app)
The operation f of the memory form x86.rm f, x86.rm1 f, or x86.mr f app.
constexpr size_t encoding(Reg r)
The hardware encoding of the register r of a backend's module reg, whose subtags are in encoding orde...
static constexpr flags_t Base