TPDE
Loading...
Searching...
No Matches
CompilerA64.hpp
1// SPDX-FileCopyrightText: 2025 Contributors to TPDE <https://tpde.org>
2//
3// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
4#pragma once
5
6#include "AssemblerElfA64.hpp"
7#include "tpde/CompilerBase.hpp"
8#include "tpde/base.hpp"
9#include "tpde/util/SmallVector.hpp"
10#include "tpde/util/misc.hpp"
11
12#include <bit>
13#include <disarm64.h>
14#include <elf.h>
15
16// Helper macros for assembling in the compiler
17#if defined(ASM) || defined(ASMNC) || defined(ASMC)
18 #error Got definition for ASM macros from somewhere else. Maybe you included compilers for multiple architectures?
19#endif
20
21/// Encode an instruction with an explicit compiler pointer
22#define ASMC(compiler, op, ...) \
23 ((compiler)->text_writer.write_inst(de64_##op(__VA_ARGS__)))
24/// Encode an instruction into this
25#define ASM(...) ASMC(this, __VA_ARGS__)
26/// Encode an instruction without checking that enough space is available
27#define ASMNC(op, ...) \
28 (this->text_writer.write_inst_unchecked(de64_##op(__VA_ARGS__)))
29/// Encode an instruction if the encoding is successful (returns true)
30#define ASMIFC(compiler, op, ...) \
31 ((compiler)->text_writer.try_write_inst(de64_##op(__VA_ARGS__)))
32/// Encode an instruction if the encoding is successful (returns true)
33#define ASMIF(...) ASMIFC(this, __VA_ARGS__)
34
35namespace tpde::a64 {
36
37struct AsmReg : Reg {
38 enum REG : u8 {
39 R0 = 0,
40 R1,
41 R2,
42 R3,
43 R4,
44 R5,
45 R6,
46 R7,
47 R8,
48 R9,
49 R10,
50 R11,
51 R12,
52 R13,
53 R14,
54 R15,
55 R16,
56 R17,
57 R18,
58 R19,
59 R20,
60 R21,
61 R22,
62 R23,
63 R24,
64 R25,
65 R26,
66 R27,
67 R28,
68 R29,
69 FP = 29,
70 R30,
71 LR = 30,
72 SP = 31,
73
74 V0 = 32,
75 V1,
76 V2,
77 V3,
78 V4,
79 V5,
80 V6,
81 V7,
82 V8,
83 V9,
84 V10,
85 V11,
86 V12,
87 V13,
88 V14,
89 V15,
90 V16,
91 V17,
92 V18,
93 V19,
94 V20,
95 V21,
96 V22,
97 V23,
98 V24,
99 V25,
100 V26,
101 V27,
102 V28,
103 V29,
104 V30,
105 V31
106 };
107
108 constexpr explicit AsmReg() noexcept : Reg((u8)0xFF) {}
109
110 constexpr AsmReg(const REG id) noexcept : Reg((u8)id) {}
111
112 constexpr AsmReg(const Reg base) noexcept : Reg(base) {}
113
114 constexpr explicit AsmReg(const u8 id) noexcept : Reg(id) {
115 assert(id <= SP || (id >= V0 && id <= V31));
116 }
117
118 constexpr explicit AsmReg(const u64 id) noexcept : Reg(id) {
119 assert(id <= SP || (id >= V0 && id <= V31));
120 }
121
122 operator DA_GReg() const noexcept {
123 assert(reg_id < V0);
124 return DA_GReg{reg_id};
125 }
126
127 operator DA_GRegZR() const noexcept {
128 assert(reg_id < V0);
129 assert(reg_id != SP); // 31 means SP in our enums
130 return DA_GRegZR{reg_id};
131 }
132
133 operator DA_GRegSP() const noexcept {
134 assert(reg_id <= SP);
135 return DA_GRegSP{reg_id};
136 }
137
138 operator DA_VReg() const noexcept {
139 assert(reg_id >= V0 && reg_id <= V31);
140 return DA_VReg{static_cast<u8>(reg_id - V0)};
141 }
142};
143
144constexpr static u64
145 create_bitmask(const std::initializer_list<AsmReg::REG> regs) {
146 u64 set = 0;
147 for (const auto reg : regs) {
148 set |= 1ull << reg;
149 }
150 return set;
151}
152
153template <size_t N>
154constexpr static u64 create_bitmask(const std::array<AsmReg, N> regs) {
155 u64 set = 0;
156 for (const auto reg : regs) {
157 set |= 1ull << reg.id();
158 }
159 return set;
160}
161
162class CCAssignerAAPCS : public CCAssigner {
163 static constexpr CCInfo Info{
164 // we reserve SP,FP,R16 and R17 for our special use cases
165 .allocatable_regs =
166 0xFFFF'FFFF'FFFF'FFFF &
167 ~create_bitmask({AsmReg::SP, AsmReg::FP, AsmReg::R16, AsmReg::R17}),
168 // callee-saved registers
169 .callee_saved_regs = create_bitmask({
170 AsmReg::R19,
171 AsmReg::R20,
172 AsmReg::R21,
173 AsmReg::R22,
174 AsmReg::R23,
175 AsmReg::R24,
176 AsmReg::R25,
177 AsmReg::R26,
178 AsmReg::R27,
179 AsmReg::R28,
180 AsmReg::V8,
181 AsmReg::V9,
182 AsmReg::V10,
183 AsmReg::V11,
184 AsmReg::V12,
185 AsmReg::V13,
186 AsmReg::V14,
187 AsmReg::V15,
188 }),
189 .arg_regs = create_bitmask({
190 AsmReg::R0,
191 AsmReg::R1,
192 AsmReg::R2,
193 AsmReg::R3,
194 AsmReg::R4,
195 AsmReg::R5,
196 AsmReg::R6,
197 AsmReg::R7,
198 AsmReg::R8, // sret register
199 AsmReg::V0,
200 AsmReg::V1,
201 AsmReg::V2,
202 AsmReg::V3,
203 AsmReg::V4,
204 AsmReg::V5,
205 AsmReg::V6,
206 AsmReg::V7,
207 }),
208 };
209
210 // NGRN = Next General-purpose Register Number
211 // NSRN = Next SIMD/FP Register Number
212 // NSAA = Next Stack Argument Address
213 u32 ngrn = 0, nsrn = 0, nsaa = 0;
214 u32 ret_ngrn = 0, ret_nsrn = 0;
215
216public:
217 CCAssignerAAPCS() noexcept : CCAssigner(Info) {}
218
219 void reset() noexcept override {
220 ngrn = nsrn = nsaa = ret_ngrn = ret_nsrn = 0;
221 }
222
223 void assign_arg(CCAssignment &arg) noexcept override {
224 if (arg.byval) [[unlikely]] {
225 nsaa = util::align_up(nsaa, arg.byval_align < 8 ? 8 : arg.byval_align);
226 arg.stack_off = nsaa;
227 nsaa += arg.byval_size;
228 return;
229 }
230
231 if (arg.sret) [[unlikely]] {
232 arg.reg = AsmReg{AsmReg::R8};
233 return;
234 }
235
236 if (arg.bank == RegBank{0}) {
237 if (arg.align > 8) {
238 ngrn = util::align_up(ngrn, 2);
239 }
240 if (ngrn + arg.consecutive < 8) {
241 arg.reg = Reg{AsmReg::R0 + ngrn};
242 ngrn += 1;
243 } else {
244 ngrn = 8;
245 nsaa = util::align_up(nsaa, arg.align < 8 ? 8 : arg.align);
246 arg.stack_off = nsaa;
247 nsaa += 8;
248 }
249 } else {
250 if (nsrn + arg.consecutive < 8) {
251 arg.reg = Reg{AsmReg::V0 + nsrn};
252 nsrn += 1;
253 } else {
254 nsrn = 8;
255 u32 size = util::align_up(arg.size, 8);
256 nsaa = util::align_up(nsaa, size);
257 arg.stack_off = nsaa;
258 nsaa += size;
259 }
260 }
261 }
262
263 u32 get_stack_size() noexcept override { return nsaa; }
264
265 void assign_ret(CCAssignment &arg) noexcept override {
266 assert(!arg.byval && !arg.sret);
267 if (arg.bank == RegBank{0}) {
268 if (arg.align > 8) {
269 ret_ngrn = util::align_up(ret_ngrn, 2);
270 }
271 if (ret_ngrn + arg.consecutive < 8) {
272 arg.reg = Reg{AsmReg::R0 + ret_ngrn};
273 ret_ngrn += 1;
274 } else {
275 assert(false);
276 }
277 } else {
278 if (ret_nsrn + arg.consecutive < 8) {
279 arg.reg = Reg{AsmReg::V0 + ret_nsrn};
280 ret_nsrn += 1;
281 } else {
282 assert(false);
283 }
284 }
285 }
286};
287
288struct PlatformConfig : CompilerConfigDefault {
289 using Assembler = AssemblerElfA64;
290 using AsmReg = tpde::a64::AsmReg;
291 using DefaultCCAssigner = CCAssignerAAPCS;
292
293 static constexpr RegBank GP_BANK{0};
294 static constexpr RegBank FP_BANK{1};
295 static constexpr bool FRAME_INDEXING_NEGATIVE = false;
296 static constexpr u32 PLATFORM_POINTER_SIZE = 8;
297 static constexpr u32 NUM_BANKS = 2;
298};
299
300namespace concepts {
301template <typename T, typename Config>
302concept Compiler = tpde::Compiler<T, Config> && requires(T a) {
303 {
304 a.arg_is_int128(std::declval<typename T::IRValueRef>())
305 } -> std::convertible_to<bool>;
306
307 {
308 a.arg_allow_split_reg_stack_passing(std::declval<typename T::IRValueRef>())
309 } -> std::convertible_to<bool>;
310};
311} // namespace concepts
312
313template <IRAdaptor Adaptor,
314 typename Derived,
315 template <typename, typename, typename> typename BaseTy =
316 CompilerBase,
317 typename Config = PlatformConfig>
318struct CompilerA64 : BaseTy<Adaptor, Derived, Config> {
319 using Base = BaseTy<Adaptor, Derived, Config>;
320
321 using IRValueRef = typename Base::IRValueRef;
322 using IRBlockRef = typename Base::IRBlockRef;
323 using IRFuncRef = typename Base::IRFuncRef;
324
325 using ScratchReg = typename Base::ScratchReg;
326 using ValuePartRef = typename Base::ValuePartRef;
327 using ValuePart = typename Base::ValuePart;
328 using GenericValuePart = typename Base::GenericValuePart;
329
330 using Assembler = typename PlatformConfig::Assembler;
331 using RegisterFile = typename Base::RegisterFile;
332
333 using CallArg = typename Base::CallArg;
334
335 using Base::derived;
336
337
338 // TODO(ts): make this dependent on the number of callee-saved regs of the
339 // current function or if there is a call in the function?
340 static constexpr u32 NUM_FIXED_ASSIGNMENTS[PlatformConfig::NUM_BANKS] = {5,
341 6};
342
343 enum CPU_FEATURES : u32 {
344 CPU_BASELINE = 0, // ARMV8.0
345 };
346
347 CPU_FEATURES cpu_feats = CPU_BASELINE;
348
349 // When handling function arguments, we need to prevent argument registers
350 // from being handed out as fixed registers
351 //
352 // Additionally, we prevent R0 and R1 from being fixed assignments to
353 // prevent issues with exception handling
354 u64 fixed_assignment_nonallocatable_mask =
355 create_bitmask({AsmReg::R0, AsmReg::R1});
356 u32 func_start_off = 0u, func_prologue_alloc = 0u, func_epilogue_alloc = 0u;
357 /// Offset to the `add sp, sp, XXX` instruction that the argument handling
358 /// uses to access stack arguments if needed
359 u32 func_arg_stack_add_off = ~0u;
360 AsmReg func_arg_stack_add_reg = AsmReg::make_invalid();
361
362 /// Permanent scratch register, e.g. to materialize constants/offsets. This is
363 /// used by materialize_constant, load_from_stack, spill_reg.
364 AsmReg permanent_scratch_reg = AsmReg::R16;
365
366 u32 scalar_arg_count = 0xFFFF'FFFF, vec_arg_count = 0xFFFF'FFFF;
367 u32 reg_save_frame_off = 0;
368 util::SmallVector<u32, 8> func_ret_offs = {};
369
370 class CallBuilder : public Base::template CallBuilderBase<CallBuilder> {
371 u32 stack_adjust_off = 0;
372 u32 stack_size = 0;
373 u32 stack_sub = 0;
374
375 void set_stack_used() noexcept;
376
377 public:
378 CallBuilder(Derived &compiler, CCAssigner &assigner) noexcept
379 : Base::template CallBuilderBase<CallBuilder>(compiler, assigner) {}
380
381 void add_arg_byval(ValuePart &vp, CCAssignment &cca) noexcept;
382 void add_arg_stack(ValuePart &vp, CCAssignment &cca) noexcept;
383 void call_impl(
384 std::variant<typename Assembler::SymRef, ValuePart> &&) noexcept;
385 void reset_stack() noexcept;
386 };
387
388 // for now, always generate an object
389 explicit CompilerA64(Adaptor *adaptor,
390 const CPU_FEATURES cpu_features = CPU_BASELINE)
391 : Base{adaptor}, cpu_feats(cpu_features) {
392 static_assert(std::is_base_of_v<CompilerA64, Derived>);
393 static_assert(concepts::Compiler<Derived, PlatformConfig>);
394 }
395
396 void start_func(u32 func_idx) noexcept;
397
398 void gen_func_prolog_and_args(CCAssigner *cc_assigner) noexcept;
399
400 // note: this has to call assembler->end_func
401 void finish_func(u32 func_idx) noexcept;
402
403 void reset() noexcept;
404
405 // helpers
406
407 void gen_func_epilog() noexcept;
408
409 void
410 spill_reg(const AsmReg reg, const u32 frame_off, const u32 size) noexcept;
411
412 void load_from_stack(AsmReg dst,
413 i32 frame_off,
414 u32 size,
415 bool sign_extend = false) noexcept;
416
417 void load_address_of_stack_var(AsmReg dst, AssignmentPartRef ap) noexcept;
418
419 void mov(AsmReg dst, AsmReg src, u32 size) noexcept;
420
421 GenericValuePart val_spill_slot(ValuePart &val_ref) noexcept {
422 const auto ap = val_ref.assignment();
423 assert(ap.stack_valid() && !ap.variable_ref());
424 return typename GenericValuePart::Expr(AsmReg::R29, ap.frame_off());
425 }
426
427 AsmReg gval_expr_as_reg(GenericValuePart &gv) noexcept;
428
429 void materialize_constant(const u64 *data,
430 RegBank bank,
431 u32 size,
432 AsmReg dst) noexcept;
433 void materialize_constant(u64 const_u64,
434 RegBank bank,
435 u32 size,
436 AsmReg dst) noexcept {
437 assert(size <= sizeof(const_u64));
438 materialize_constant(&const_u64, bank, size, dst);
439 }
440
441 AsmReg select_fixed_assignment_reg(RegBank bank, IRValueRef) noexcept;
442
443 struct Jump {
444 enum Kind : uint8_t {
445 Jeq,
446 Jne,
447 Jcs,
448 Jhs = Jcs,
449 Jcc,
450 Jlo = Jcc,
451 Jmi,
452 Jpl,
453 Jvs,
454 Jvc,
455 Jhi,
456 Jls,
457 Jge,
458 Jlt,
459 Jgt,
460 Jle,
461 // TDOO: consistency
462 jmp,
463 Cbz,
464 Cbnz,
465 Tbz,
466 Tbnz
467 };
468
469 Kind kind;
470 AsmReg cmp_reg;
471 bool cmp_is_32;
472 u8 test_bit;
473
474 constexpr Jump() : kind(Kind::jmp) {}
475
476 constexpr Jump(Kind kind) : kind(kind), cmp_is_32(false), test_bit(0) {
477 assert(kind != Cbz && kind != Cbnz && kind != Tbz && kind != Tbnz);
478 }
479
480 constexpr Jump(Kind kind, AsmReg cmp_reg, bool cmp_is_32)
481 : kind(kind), cmp_reg(cmp_reg), cmp_is_32(cmp_is_32), test_bit(0) {
482 assert(kind == Cbz || kind == Cbnz);
483 }
484
485 constexpr Jump(Kind kind, AsmReg cmp_reg, u8 test_bit)
486 : kind(kind), cmp_reg(cmp_reg), cmp_is_32(false), test_bit(test_bit) {
487 assert(kind == Tbz || kind == Tbnz);
488 }
489
490 constexpr Jump change_kind(Kind new_kind) const {
491 auto cpy = *this;
492 cpy.kind = new_kind;
493 return cpy;
494 }
495 };
496
497 Jump invert_jump(Jump jmp) noexcept;
498 Jump swap_jump(Jump jmp) noexcept;
499
500 void generate_branch_to_block(Jump jmp,
501 IRBlockRef target,
502 bool needs_split,
503 bool last_inst) noexcept;
504
505 void generate_raw_jump(Jump jmp, Assembler::Label target) noexcept;
506
507 /// Convert jump condition to disarms Da64Cond.
508 /// \warning Cbz,Cbnz,Tbz and Tbnz are not supported
509 Da64Cond jump_to_cond(Jump jmp) noexcept;
510 /// Set dst to 1 if cc is true, otherwise set it to zero
511 void generate_raw_set(Jump cc, AsmReg dst) noexcept;
512 /// Set all bits of dst to 1 if cc is true, otherwise set dst to zero
513 void generate_raw_mask(Jump cc, AsmReg dst) noexcept;
514
515 /// Moves true_select into dst if cc is true,
516 /// otherwise move false_select into dst
517 void generate_raw_select(Jump cc,
518 AsmReg dst,
519 AsmReg true_select,
520 AsmReg false_select,
521 bool is_64) noexcept;
522
523 void generate_raw_intext(
524 AsmReg dst, AsmReg src, bool sign, u32 from, u32 to) noexcept;
525
526 /// Generate a function call
527 ///
528 /// This will get the arguments into the correct registers according to the
529 /// calling convention, clear non-callee-saved registers from the register
530 /// file (make sure you do not have any fixed assignments left over) and
531 /// fill the result registers (the u8 in the ScratchReg pair indicates the
532 /// register bank)
533 ///
534 /// Targets can be a symbol (call to PLT with relocation), or an indirect
535 /// call to a ValuePart. Result is an optional reference.
536 void generate_call(std::variant<Assembler::SymRef, ValuePart> &&target,
537 std::span<CallArg> arguments,
538 typename Base::ValueRef *result,
539 bool variable_args = false);
540
541 /// Generate code sequence to load address of sym into a register. This will
542 /// generate a function call for dynamic TLS access models.
543 ScratchReg tls_get_addr(Assembler::SymRef sym, TLSModel model) noexcept;
544
545 bool has_cpu_feats(CPU_FEATURES feats) const noexcept {
546 return ((cpu_feats & feats) == feats);
547 }
548};
549
550template <IRAdaptor Adaptor,
551 typename Derived,
552 template <typename, typename, typename> class BaseTy,
553 typename Config>
554void CompilerA64<Adaptor, Derived, BaseTy, Config>::CallBuilder::
555 set_stack_used() noexcept {
556 if (stack_adjust_off == 0) {
557 this->compiler.text_writer.ensure_space(16);
558 stack_adjust_off = this->compiler.text_writer.offset();
559 this->compiler.text_writer.cur_ptr() += 4;
560 }
561}
562
563template <IRAdaptor Adaptor,
564 typename Derived,
565 template <typename, typename, typename> class BaseTy,
566 typename Config>
567void CompilerA64<Adaptor, Derived, BaseTy, Config>::CallBuilder::add_arg_byval(
568 ValuePart &vp, CCAssignment &cca) noexcept {
569 AsmReg ptr_reg = vp.load_to_reg(&this->compiler);
570 AsmReg tmp_reg = AsmReg::R16;
571
572 auto size = cca.byval_size;
573 set_stack_used();
574 for (u32 off = 0; off < size;) {
575 if (size - off >= 8) {
576 ASMC(&this->compiler, LDRxu, tmp_reg, ptr_reg, off);
577 ASMC(&this->compiler, STRxu, tmp_reg, DA_SP, cca.stack_off + off);
578 off += 8;
579 } else if (size - off >= 4) {
580 ASMC(&this->compiler, LDRwu, tmp_reg, ptr_reg, off);
581 ASMC(&this->compiler, STRwu, tmp_reg, DA_SP, cca.stack_off + off);
582 off += 4;
583 } else if (size - off >= 2) {
584 ASMC(&this->compiler, LDRHu, tmp_reg, ptr_reg, off);
585 ASMC(&this->compiler, STRHu, tmp_reg, DA_SP, cca.stack_off + off);
586 off += 2;
587 } else {
588 ASMC(&this->compiler, LDRBu, tmp_reg, ptr_reg, off);
589 ASMC(&this->compiler, STRBu, tmp_reg, DA_SP, cca.stack_off + off);
590 off += 1;
591 }
592 }
593}
594
595template <IRAdaptor Adaptor,
596 typename Derived,
597 template <typename, typename, typename> class BaseTy,
598 typename Config>
599void CompilerA64<Adaptor, Derived, BaseTy, Config>::CallBuilder::add_arg_stack(
600 ValuePart &vp, CCAssignment &cca) noexcept {
601 set_stack_used();
602
603 auto reg = vp.load_to_reg(&this->compiler);
604 if (this->compiler.register_file.reg_bank(reg) == Config::GP_BANK) {
605 switch (cca.size) {
606 case 1: ASMC(&this->compiler, STRBu, reg, DA_SP, cca.stack_off); break;
607 case 2: ASMC(&this->compiler, STRHu, reg, DA_SP, cca.stack_off); break;
608 case 4: ASMC(&this->compiler, STRwu, reg, DA_SP, cca.stack_off); break;
609 case 8: ASMC(&this->compiler, STRxu, reg, DA_SP, cca.stack_off); break;
610 default: TPDE_UNREACHABLE("invalid GP reg size");
611 }
612 } else {
613 assert(this->compiler.register_file.reg_bank(reg) == Config::FP_BANK);
614 switch (cca.size) {
615 case 1: ASMC(&this->compiler, STRbu, reg, DA_SP, cca.stack_off); break;
616 case 2: ASMC(&this->compiler, STRhu, reg, DA_SP, cca.stack_off); break;
617 case 4: ASMC(&this->compiler, STRsu, reg, DA_SP, cca.stack_off); break;
618 case 8: ASMC(&this->compiler, STRdu, reg, DA_SP, cca.stack_off); break;
619 case 16: ASMC(&this->compiler, STRqu, reg, DA_SP, cca.stack_off); break;
620 default: TPDE_UNREACHABLE("invalid FP reg size");
621 }
622 }
623}
624
625template <IRAdaptor Adaptor,
626 typename Derived,
627 template <typename, typename, typename> class BaseTy,
628 typename Config>
629void CompilerA64<Adaptor, Derived, BaseTy, Config>::CallBuilder::call_impl(
630 std::variant<typename Assembler::SymRef, ValuePart> &&target) noexcept {
631 u32 sub = 0;
632 if (stack_adjust_off != 0) {
633 auto *text_data = this->compiler.text_writer.begin_ptr();
634 u32 *write_ptr = reinterpret_cast<u32 *>(text_data + stack_adjust_off);
635 u32 stack_size = this->assigner.get_stack_size();
636 sub = util::align_up(stack_size, stack_size < 0x1000 ? 0x10 : 0x1000);
637 *write_ptr = de64_SUBxi(DA_SP, DA_SP, sub);
638 } else {
639 assert(this->assigner.get_stack_size() == 0);
640 }
641
642
643 if (auto *sym = std::get_if<typename Assembler::SymRef>(&target)) {
644 ASMC(&this->compiler, BL, 0);
645 this->compiler.reloc_text(
646 *sym, R_AARCH64_CALL26, this->compiler.text_writer.offset() - 4);
647 } else {
648 ValuePart &tvp = std::get<ValuePart>(target);
649 AsmReg reg = tvp.cur_reg_unlocked();
650 if (!reg.valid()) {
651 reg = tvp.reload_into_specific_fixed(&this->compiler, AsmReg::R16);
652 }
653 ASMC(&this->compiler, BLR, reg);
654 tvp.reset(&this->compiler);
655 }
656
657 if (stack_adjust_off != 0) {
658 ASMC(&this->compiler, ADDxi, DA_SP, DA_SP, sub);
659 }
660}
661
662template <IRAdaptor Adaptor,
663 typename Derived,
664 template <typename, typename, typename> class BaseTy,
665 typename Config>
666void CompilerA64<Adaptor, Derived, BaseTy, Config>::start_func(
667 const u32 /*func_idx*/) noexcept {
668 this->assembler.except_begin_func();
669 this->text_writer.align(16);
670}
671
672template <IRAdaptor Adaptor,
673 typename Derived,
674 template <typename, typename, typename> typename BaseTy,
675 typename Config>
676void CompilerA64<Adaptor, Derived, BaseTy, Config>::gen_func_prolog_and_args(
677 CCAssigner *cc_assigner) noexcept {
678 // prologue:
679 // sub sp, sp, #<frame_size>
680 // stp x29, x30, [sp]
681 // mov x29, sp
682 // optionally create vararg save-area
683 // reserve space for callee-saved regs
684 // 4 byte per callee-saved reg pair since for each we do
685 // stp r1, r2, [sp + XX]
686
687 // TODO(ts): for smaller functions we could enable an optimization
688 // to store the saved regs after the local variables
689 // which we could then use to not allocate space for unsaved regs
690 // which could help in the common case.
691 // However, we need to commit to this at the beginning of the function
692 // as otherwise stack accesses need to skip the reg-save area
693
694 func_ret_offs.clear();
695 func_start_off = this->text_writer.offset();
696
697 const CCInfo &cc_info = cc_assigner->get_ccinfo();
698
699 // We don't actually generate the prologue here and merely allocate space
700 // for it. Right now, we don't know which callee-saved registers will be
701 // used. While we could pad with nops, we later move the beginning of the
702 // function so that small functions don't have to execute 9 nops.
703 // See finish_func.
704 this->stack.frame_size = 16; // FP, LR
705 {
706 auto csr = cc_info.callee_saved_regs;
707 auto csr_gp = csr & this->register_file.bank_regs(Config::GP_BANK);
708 auto csr_fp = csr & this->register_file.bank_regs(Config::FP_BANK);
709 u32 gp_saves = std::popcount(csr_gp);
710 u32 fp_saves = std::popcount(csr_fp);
711 // LDP/STP can handle two registers of the same bank.
712 u32 reg_save_size = 4 * ((gp_saves + 1) / 2 + (fp_saves + 1) / 2);
713 // TODO: support CSR of Qx/Vx registers, not just Dx
714 this->stack.frame_size += util::align_up(gp_saves * 8 + fp_saves * 8, 16);
715
716 // Reserve space for sub sp, stp x29/x30, and mov x29, sp.
717 func_prologue_alloc = reg_save_size + 12;
718 this->text_writer.ensure_space(func_prologue_alloc);
719 this->text_writer.cur_ptr() += func_prologue_alloc;
720 // ldp needs the same number of instructions as stp
721 // additionally, there's an add sp, ldp x29/x30, ret (+12)
722 func_epilogue_alloc = reg_save_size + 12;
723 // extra mov sp, fp
724 func_epilogue_alloc += this->adaptor->cur_has_dynamic_alloca() ? 4 : 0;
725 }
726
727 // TODO(ts): support larger stack alignments?
728
729 if (this->adaptor->cur_is_vararg()) [[unlikely]] {
730 reg_save_frame_off = this->stack.frame_size;
731 // We additionally store a pointer to the stack area, which we can't compute
732 // with a constant offset from the frame pointer. Add 16 bytes to maintain
733 // alignment.
734 this->stack.frame_size += 8 * 8 + 8 * 16 + 16;
735 this->text_writer.ensure_space(4 * 8);
736 ASMNC(STPx, DA_GP(0), DA_GP(1), DA_SP, reg_save_frame_off);
737 ASMNC(STPx, DA_GP(2), DA_GP(3), DA_SP, reg_save_frame_off + 16);
738 ASMNC(STPx, DA_GP(4), DA_GP(5), DA_SP, reg_save_frame_off + 32);
739 ASMNC(STPx, DA_GP(6), DA_GP(7), DA_SP, reg_save_frame_off + 48);
740 ASMNC(STPq, DA_V(0), DA_V(1), DA_SP, reg_save_frame_off + 64);
741 ASMNC(STPq, DA_V(2), DA_V(3), DA_SP, reg_save_frame_off + 96);
742 ASMNC(STPq, DA_V(4), DA_V(5), DA_SP, reg_save_frame_off + 128);
743 ASMNC(STPq, DA_V(6), DA_V(7), DA_SP, reg_save_frame_off + 160);
744 }
745
746 // Temporarily prevent argument registers from being assigned.
747 assert((cc_info.allocatable_regs & cc_info.arg_regs) == cc_info.arg_regs &&
748 "argument registers must also be allocatable");
749 this->register_file.allocatable &= ~cc_info.arg_regs;
750
751 this->func_arg_stack_add_off = ~0u;
752
753 u32 arg_idx = 0;
754 for (const IRValueRef arg : this->adaptor->cur_args()) {
755 derived()->handle_func_arg(
756 arg_idx,
757 arg,
758 [&](ValuePart &&vp, CCAssignment cca) -> std::optional<i32> {
759 cca.bank = vp.bank();
760 cca.size = vp.part_size();
761
762 cc_assigner->assign_arg(cca);
763
764 if (cca.reg.valid()) [[likely]] {
765 vp.set_value_reg(this, cca.reg);
766 // Mark register as allocatable as soon as it is assigned. If the
767 // argument is unused, the register will be freed immediately and
768 // can be used for later stack arguments.
769 this->register_file.allocatable |= u64{1} << cca.reg.id();
770 return {};
771 }
772
773 this->text_writer.ensure_space(8);
774 AsmReg stack_reg = AsmReg::R17;
775 // TODO: allocate an actual scratch register for this.
776 assert(
777 !(this->register_file.allocatable & (u64{1} << stack_reg.id())) &&
778 "x17 must not be allocatable");
779 if (this->func_arg_stack_add_off == ~0u) {
780 this->func_arg_stack_add_off = this->text_writer.offset();
781 this->func_arg_stack_add_reg = stack_reg;
782 // Fixed in finish_func when frame size is known
783 ASMNC(ADDxi, stack_reg, DA_SP, 0);
784 }
785
786 AsmReg dst = vp.alloc_reg(this);
787 if (cca.byval) {
788 ASM(ADDxi, dst, stack_reg, cca.stack_off);
789 } else if (cca.bank == Config::GP_BANK) {
790 switch (cca.size) {
791 case 1: ASMNC(LDRBu, dst, stack_reg, cca.stack_off); break;
792 case 2: ASMNC(LDRHu, dst, stack_reg, cca.stack_off); break;
793 case 4: ASMNC(LDRwu, dst, stack_reg, cca.stack_off); break;
794 case 8: ASMNC(LDRxu, dst, stack_reg, cca.stack_off); break;
795 default: TPDE_UNREACHABLE("invalid GP reg size");
796 }
797 } else {
798 assert(cca.bank == Config::FP_BANK);
799 switch (cca.size) {
800 case 1: ASMNC(LDRbu, dst, stack_reg, cca.stack_off); break;
801 case 2: ASMNC(LDRhu, dst, stack_reg, cca.stack_off); break;
802 case 4: ASMNC(LDRsu, dst, stack_reg, cca.stack_off); break;
803 case 8: ASMNC(LDRdu, dst, stack_reg, cca.stack_off); break;
804 case 16: ASMNC(LDRqu, dst, stack_reg, cca.stack_off); break;
805 default: TPDE_UNREACHABLE("invalid FP reg size");
806 }
807 }
808 return {};
809 });
810
811 arg_idx += 1;
812 }
813
814 // Hack: we don't know the frame size, so for a va_start(), we cannot easily
815 // compute the offset from the frame pointer. But we have a stack_reg here,
816 // so use it for var args.
817 if (this->adaptor->cur_is_vararg()) [[unlikely]] {
818 AsmReg stack_reg = AsmReg::R17;
819 // TODO: allocate an actual scratch register for this.
820 assert(!(this->register_file.allocatable & (u64{1} << stack_reg.id())) &&
821 "x17 must not be allocatable");
822 if (this->func_arg_stack_add_off == ~0u) {
823 this->func_arg_stack_add_off = this->text_writer.offset();
824 this->func_arg_stack_add_reg = stack_reg;
825 // Fixed in finish_func when frame size is known
826 ASMC(this, ADDxi, stack_reg, DA_SP, 0);
827 }
828 ASM(ADDxi, stack_reg, stack_reg, cc_assigner->get_stack_size());
829 ASM(STRxu, stack_reg, DA_GP(29), this->reg_save_frame_off + 192);
830
831 // TODO: extract ngrn/nsrn from CCAssigner
832 // TODO: this isn't quite accurate, e.g. for (i128, i128, i128, i64, i128),
833 // this should be 8 but will end up with 7.
834 auto arg_regs = this->register_file.allocatable & cc_info.arg_regs;
835 u32 ngrn = 8 - util::cnt_lz<u16>((arg_regs & 0xff) << 8 | 0x80);
836 u32 nsrn = 8 - util::cnt_lz<u16>(((arg_regs >> 32) & 0xff) << 8 | 0x80);
837 this->scalar_arg_count = ngrn;
838 this->vec_arg_count = nsrn;
839 }
840
841 this->register_file.allocatable |= cc_info.arg_regs;
842}
843
844template <IRAdaptor Adaptor,
845 typename Derived,
846 template <typename, typename, typename> typename BaseTy,
847 typename Config>
848void CompilerA64<Adaptor, Derived, BaseTy, Config>::finish_func(
849 u32 func_idx) noexcept {
850 auto csr = derived()->cur_cc_assigner()->get_ccinfo().callee_saved_regs;
851 u64 saved_regs = this->register_file.clobbered & csr;
852
853 const auto dyn_alloca = this->adaptor->cur_has_dynamic_alloca();
854 auto stack_reg = DA_SP;
855 if (dyn_alloca) {
856 stack_reg = DA_GP(29);
857 }
858
859 auto final_frame_size = util::align_up(this->stack.frame_size, 16);
860 if (final_frame_size > 4095) {
861 // round up to 4k since SUB cannot encode immediates greater than 4095
862 final_frame_size = util::align_up(final_frame_size, 4096);
863 assert(final_frame_size < 16 * 1024 * 1024);
864 }
865
866 auto fde_off = this->assembler.eh_begin_fde(this->get_personality_sym());
867
868 {
869 // NB: code alignment factor 4, data alignment factor -8.
870 util::SmallVector<u32, 16> prologue;
871 prologue.push_back(de64_SUBxi(DA_SP, DA_SP, final_frame_size));
872 this->assembler.eh_write_inst(dwarf::DW_CFA_advance_loc, 1);
873 this->assembler.eh_write_inst(dwarf::DW_CFA_def_cfa_offset,
874 final_frame_size);
875 prologue.push_back(de64_STPx(DA_GP(29), DA_GP(30), DA_SP, 0));
876 prologue.push_back(de64_MOV_SPx(DA_GP(29), DA_SP));
877 this->assembler.eh_write_inst(dwarf::DW_CFA_advance_loc, 2);
878 this->assembler.eh_write_inst(dwarf::DW_CFA_def_cfa_register,
879 dwarf::a64::DW_reg_fp);
880 this->assembler.eh_write_inst(
881 dwarf::DW_CFA_offset, dwarf::a64::DW_reg_fp, final_frame_size / 8);
882 this->assembler.eh_write_inst(
883 dwarf::DW_CFA_offset, dwarf::a64::DW_reg_lr, final_frame_size / 8 - 1);
884
885 // Patched below
886 auto fde_prologue_adv_off = this->assembler.eh_writer.size();
887 this->assembler.eh_write_inst(dwarf::DW_CFA_advance_loc, 0);
888
889 AsmReg last_reg = AsmReg::make_invalid();
890 u32 frame_off = 16;
891 for (auto reg : util::BitSetIterator{saved_regs}) {
892 if (last_reg.valid()) {
893 const auto reg_bank = this->register_file.reg_bank(AsmReg{reg});
894 const auto last_bank = this->register_file.reg_bank(last_reg);
895 if (reg_bank == last_bank) {
896 if (reg_bank == Config::GP_BANK) {
897 prologue.push_back(
898 de64_STPx(last_reg, AsmReg{reg}, stack_reg, frame_off));
899 } else {
900 prologue.push_back(
901 de64_STPd(last_reg, AsmReg{reg}, stack_reg, frame_off));
902 }
903 frame_off += 16;
904 last_reg = AsmReg::make_invalid();
905 } else {
906 assert(last_bank == Config::GP_BANK && reg_bank == Config::FP_BANK);
907 prologue.push_back(de64_STRxu(last_reg, stack_reg, frame_off));
908 frame_off += 8;
909 last_reg = AsmReg{reg};
910 }
911 continue;
912 }
913
914 u8 dwarf_base = reg < 32 ? dwarf::a64::DW_reg_v0 : dwarf::a64::DW_reg_x0;
915 u8 dwarf_reg = dwarf_base + reg % 32;
916 u32 cfa_off = (final_frame_size - frame_off) / 8;
917 if ((dwarf_reg & dwarf::DWARF_CFI_PRIMARY_OPCODE_MASK) == 0) {
918 this->assembler.eh_write_inst(dwarf::DW_CFA_offset, dwarf_reg, cfa_off);
919 } else {
920 this->assembler.eh_write_inst(
921 dwarf::DW_CFA_offset_extended, dwarf_reg, cfa_off);
922 }
923
924 last_reg = AsmReg{reg};
925 }
926
927 if (last_reg.valid()) {
928 if (this->register_file.reg_bank(last_reg) == Config::GP_BANK) {
929 prologue.push_back(de64_STRxu(last_reg, stack_reg, frame_off));
930 } else {
931 assert(this->register_file.reg_bank(last_reg) == Config::FP_BANK);
932 prologue.push_back(de64_STRdu(last_reg, stack_reg, frame_off));
933 }
934 }
935
936 assert(prologue.size() * sizeof(u32) <= func_prologue_alloc);
937
938 assert(prologue.size() < 0x4c);
939 this->assembler.eh_writer.data()[fde_prologue_adv_off] =
940 dwarf::DW_CFA_advance_loc | (prologue.size() - 3);
941
942 // Pad with NOPs so that func_prologue_alloc - prologue.size() is a
943 // multiple if 16 (the function alignment).
944 const auto nop_count = (func_prologue_alloc / 4 - prologue.size()) % 4;
945 const auto nop = de64_NOP();
946 for (auto i = 0u; i < nop_count; ++i) {
947 prologue.push_back(nop);
948 }
949
950 // Shrink function at the beginning
951 u32 skip = util::align_down(func_prologue_alloc - prologue.size() * 4, 16);
952 std::memset(this->text_writer.begin_ptr() + func_start_off, 0, skip);
953 func_start_off += skip;
954 this->assembler.sym_set_value(this->func_syms[func_idx], func_start_off);
955 std::memcpy(this->text_writer.begin_ptr() + func_start_off,
956 prologue.data(),
957 prologue.size() * sizeof(u32));
958 }
959
960 if (func_arg_stack_add_off != ~0u) {
961 auto *inst_ptr = this->text_writer.begin_ptr() + func_arg_stack_add_off;
962 *reinterpret_cast<u32 *>(inst_ptr) =
963 de64_ADDxi(func_arg_stack_add_reg, DA_SP, final_frame_size);
964 }
965
966 // TODO(ts): honor cur_needs_unwind_info
967 auto func_sym = this->func_syms[func_idx];
968 auto func_sec = this->text_writer.get_sec_ref();
969
970 if (func_ret_offs.empty()) {
971 auto func_size = this->text_writer.offset() - func_start_off;
972 this->assembler.sym_def(func_sym, func_sec, func_start_off, func_size);
973 this->assembler.eh_end_fde(fde_off, func_sym);
974 this->assembler.except_encode_func(func_sym);
975 return;
976 }
977
978 auto *text_data = this->text_writer.begin_ptr();
979 u32 first_ret_off = func_ret_offs[0];
980 u32 ret_size = 0;
981 {
982 u32 *write_ptr = reinterpret_cast<u32 *>(text_data + first_ret_off);
983 const auto ret_start = write_ptr;
984 if (dyn_alloca) {
985 *write_ptr++ = de64_MOV_SPx(DA_SP, DA_GP(29));
986 } else {
987 *write_ptr++ = de64_LDPx(DA_GP(29), DA_GP(30), DA_SP, 0);
988 }
989
990 AsmReg last_reg = AsmReg::make_invalid();
991 u32 frame_off = 16;
992 for (auto reg : util::BitSetIterator{saved_regs}) {
993 if (last_reg.valid()) {
994 const auto reg_bank = this->register_file.reg_bank(AsmReg{reg});
995 const auto last_bank = this->register_file.reg_bank(last_reg);
996 if (reg_bank == last_bank) {
997 if (reg_bank == Config::GP_BANK) {
998 *write_ptr++ =
999 de64_LDPx(last_reg, AsmReg{reg}, stack_reg, frame_off);
1000 } else {
1001 *write_ptr++ =
1002 de64_LDPd(last_reg, AsmReg{reg}, stack_reg, frame_off);
1003 }
1004 frame_off += 16;
1005 last_reg = AsmReg::make_invalid();
1006 } else {
1007 assert(last_bank == Config::GP_BANK && reg_bank == Config::FP_BANK);
1008 *write_ptr++ = de64_LDRxu(last_reg, stack_reg, frame_off);
1009 frame_off += 8;
1010 last_reg = AsmReg{reg};
1011 }
1012 continue;
1013 }
1014
1015 last_reg = AsmReg{reg};
1016 }
1017
1018 if (last_reg.valid()) {
1019 if (this->register_file.reg_bank(last_reg) == Config::GP_BANK) {
1020 *write_ptr++ = de64_LDRxu(last_reg, stack_reg, frame_off);
1021 } else {
1022 *write_ptr++ = de64_LDRdu(last_reg, stack_reg, frame_off);
1023 }
1024 }
1025
1026 if (dyn_alloca) {
1027 *write_ptr++ = de64_LDPx(DA_GP(29), DA_GP(30), DA_SP, 0);
1028 }
1029
1030 *write_ptr++ = de64_ADDxi(DA_SP, DA_SP, final_frame_size);
1031 *write_ptr++ = de64_RET(DA_GP(30));
1032
1033 ret_size = (write_ptr - ret_start) * 4;
1034 assert(ret_size <= func_epilogue_alloc);
1035 std::memset(write_ptr, 0, func_epilogue_alloc - ret_size);
1036 }
1037
1038 for (u32 i = 1; i < func_ret_offs.size(); ++i) {
1039 std::memcpy(text_data + func_ret_offs[i],
1040 text_data + first_ret_off,
1041 func_epilogue_alloc);
1042 }
1043
1044 u32 func_end_ret_off = this->text_writer.offset() - func_epilogue_alloc;
1045 if (func_ret_offs.back() == func_end_ret_off) {
1046 this->text_writer.cur_ptr() -= func_epilogue_alloc - ret_size;
1047 }
1048
1049 auto func_size = this->text_writer.offset() - func_start_off;
1050 this->assembler.sym_def(func_sym, func_sec, func_start_off, func_size);
1051 this->assembler.eh_end_fde(fde_off, func_sym);
1052 this->assembler.except_encode_func(func_sym);
1053}
1054
1055template <IRAdaptor Adaptor,
1056 typename Derived,
1057 template <typename, typename, typename> typename BaseTy,
1058 typename Config>
1059void CompilerA64<Adaptor, Derived, BaseTy, Config>::reset() noexcept {
1060 func_ret_offs.clear();
1061 Base::reset();
1062}
1063
1064template <IRAdaptor Adaptor,
1065 typename Derived,
1066 template <typename, typename, typename> typename BaseTy,
1067 typename Config>
1068void CompilerA64<Adaptor, Derived, BaseTy, Config>::gen_func_epilog() noexcept {
1069 // epilogue:
1070 // if !func_has_dynamic_alloca:
1071 // ldp x29, x30, [sp]
1072 // else:
1073 // mov sp, fp
1074 // for each saved reg pair:
1075 // if func_has_dynamic_alloca:
1076 // ldp r1, r2, [fp, #<off>]
1077 // else:
1078 // ldp r1, r2, [sp, #<off>]
1079 // if func_has_dynamic_alloca:
1080 // ldp x29, x30, [sp]
1081 // add sp, sp, #<frame_size>
1082 // ret
1083 //
1084 // however, since we will later patch this, we only
1085 // reserve the space for now
1086
1087 func_ret_offs.push_back(this->text_writer.offset());
1088 this->text_writer.ensure_space(func_epilogue_alloc);
1089 this->text_writer.cur_ptr() += func_epilogue_alloc;
1090}
1091
1092template <IRAdaptor Adaptor,
1093 typename Derived,
1094 template <typename, typename, typename> typename BaseTy,
1095 typename Config>
1096void CompilerA64<Adaptor, Derived, BaseTy, Config>::spill_reg(
1097 const AsmReg reg, const u32 frame_off, const u32 size) noexcept {
1098 assert((size & (size - 1)) == 0);
1099 assert(util::align_up(frame_off, size) == frame_off);
1100 // We don't support stack frames that aren't encodeable with add/sub.
1101 assert(frame_off < 0x1'000'000);
1102
1103 u32 off = frame_off;
1104 auto addr_base = AsmReg{AsmReg::FP};
1105 if (off >= 0x1000 * size) [[unlikely]] {
1106 // We cannot encode the offset in the store instruction.
1107 ASM(ADDxi, permanent_scratch_reg, DA_GP(29), off & ~0xfff);
1108 off &= 0xfff;
1109 addr_base = permanent_scratch_reg;
1110 }
1111
1112 this->text_writer.ensure_space(4);
1113 assert(-static_cast<i32>(frame_off) < 0);
1114 if (reg.id() <= AsmReg::R30) {
1115 switch (size) {
1116 case 1: ASMNC(STRBu, reg, addr_base, off); break;
1117 case 2: ASMNC(STRHu, reg, addr_base, off); break;
1118 case 4: ASMNC(STRwu, reg, addr_base, off); break;
1119 case 8: ASMNC(STRxu, reg, addr_base, off); break;
1120 default: TPDE_UNREACHABLE("invalid register spill size");
1121 }
1122 } else {
1123 switch (size) {
1124 case 1: ASMNC(STRbu, reg, addr_base, off); break;
1125 case 2: ASMNC(STRhu, reg, addr_base, off); break;
1126 case 4: ASMNC(STRsu, reg, addr_base, off); break;
1127 case 8: ASMNC(STRdu, reg, addr_base, off); break;
1128 case 16: ASMNC(STRqu, reg, addr_base, off); break;
1129 default: TPDE_UNREACHABLE("invalid register spill size");
1130 }
1131 }
1132}
1133
1134template <IRAdaptor Adaptor,
1135 typename Derived,
1136 template <typename, typename, typename> typename BaseTy,
1137 typename Config>
1138void CompilerA64<Adaptor, Derived, BaseTy, Config>::load_from_stack(
1139 const AsmReg dst,
1140 const i32 frame_off,
1141 const u32 size,
1142 const bool sign_extend) noexcept {
1143 assert((size & (size - 1)) == 0);
1144 assert(util::align_up(frame_off, size) == frame_off);
1145 // We don't support stack frames that aren't encodeable with add/sub.
1146 assert(frame_off >= 0 && frame_off < 0x1'000'000);
1147
1148 u32 off = frame_off;
1149 auto addr_base = AsmReg{AsmReg::FP};
1150 if (off >= 0x1000 * size) [[unlikely]] {
1151 // need to calculate this explicitly
1152 addr_base = dst.id() <= AsmReg::R30 ? dst : permanent_scratch_reg;
1153 ASM(ADDxi, addr_base, DA_GP(29), off & ~0xfff);
1154 off &= 0xfff;
1155 }
1156
1157 this->text_writer.ensure_space(4);
1158 if (dst.id() <= AsmReg::R30) {
1159 if (!sign_extend) {
1160 switch (size) {
1161 case 1: ASMNC(LDRBu, dst, addr_base, off); break;
1162 case 2: ASMNC(LDRHu, dst, addr_base, off); break;
1163 case 4: ASMNC(LDRwu, dst, addr_base, off); break;
1164 case 8: ASMNC(LDRxu, dst, addr_base, off); break;
1165 default: TPDE_UNREACHABLE("invalid register spill size");
1166 }
1167 } else {
1168 switch (size) {
1169 case 1: ASMNC(LDRSBwu, dst, addr_base, off); break;
1170 case 2: ASMNC(LDRSHwu, dst, addr_base, off); break;
1171 case 4: ASMNC(LDRSWxu, dst, addr_base, off); break;
1172 case 8: ASMNC(LDRxu, dst, addr_base, off); break;
1173 default: TPDE_UNREACHABLE("invalid register spill size");
1174 }
1175 }
1176 return;
1177 }
1178
1179 assert(!sign_extend);
1180
1181 switch (size) {
1182 case 1: ASMNC(LDRbu, dst, addr_base, off); break;
1183 case 2: ASMNC(LDRhu, dst, addr_base, off); break;
1184 case 4: ASMNC(LDRsu, dst, addr_base, off); break;
1185 case 8: ASMNC(LDRdu, dst, addr_base, off); break;
1186 case 16: ASMNC(LDRqu, dst, addr_base, off); break;
1187 default: TPDE_UNREACHABLE("invalid register spill size");
1188 }
1189}
1190
1191template <IRAdaptor Adaptor,
1192 typename Derived,
1193 template <typename, typename, typename> typename BaseTy,
1194 typename Config>
1195void CompilerA64<Adaptor, Derived, BaseTy, Config>::load_address_of_stack_var(
1196 const AsmReg dst, const AssignmentPartRef ap) noexcept {
1197 auto frame_off = ap.variable_stack_off();
1198 assert(frame_off >= 0);
1199 if (!ASMIF(ADDxi, dst, DA_GP(29), frame_off)) {
1200 materialize_constant(frame_off, Config::GP_BANK, 4, dst);
1201 ASM(ADDx_uxtw, dst, DA_GP(29), dst, 0);
1202 }
1203}
1204
1205template <IRAdaptor Adaptor,
1206 typename Derived,
1207 template <typename, typename, typename> typename BaseTy,
1208 typename Config>
1209void CompilerA64<Adaptor, Derived, BaseTy, Config>::mov(
1210 const AsmReg dst, const AsmReg src, const u32 size) noexcept {
1211 assert(dst.valid());
1212 assert(src.valid());
1213 if (dst.id() <= AsmReg::SP && src.id() <= AsmReg::SP) {
1214 assert(dst.id() != AsmReg::SP && src.id() != AsmReg::SP);
1215 if (size > 4) {
1216 ASM(MOVx, dst, src);
1217 } else {
1218 ASM(MOVw, dst, src);
1219 }
1220 } else if (dst.id() >= AsmReg::V0 && src.id() >= AsmReg::V0) {
1221 ASM(ORR16b, dst, src, src);
1222 } else if (dst.id() <= AsmReg::SP) {
1223 assert(dst.id() != AsmReg::SP);
1224 // gp<-vector
1225 assert(src.id() >= AsmReg::V0);
1226 assert(size <= 8);
1227 if (size <= 4) {
1228 ASM(FMOVws, dst, src);
1229 } else {
1230 ASM(FMOVxd, dst, src);
1231 }
1232 } else {
1233 // vector<-gp
1234 assert(src.id() <= AsmReg::R30);
1235 assert(dst.id() >= AsmReg::V0);
1236 assert(size <= 8);
1237 if (size <= 4) {
1238 ASM(FMOVsw, dst, src);
1239 } else {
1240 ASM(FMOVdx, dst, src);
1241 }
1242 }
1243}
1244
1245template <IRAdaptor Adaptor,
1246 typename Derived,
1247 template <typename, typename, typename> typename BaseTy,
1248 typename Config>
1249AsmReg CompilerA64<Adaptor, Derived, BaseTy, Config>::gval_expr_as_reg(
1250 GenericValuePart &gv) noexcept {
1251 auto &expr = std::get<typename GenericValuePart::Expr>(gv.state);
1252
1253 ScratchReg scratch{derived()};
1254 if (!expr.has_base() && !expr.has_index()) {
1255 AsmReg dst = scratch.alloc_gp();
1256 derived()->materialize_constant(expr.disp, Config::GP_BANK, 8, dst);
1257 expr.disp = 0;
1258 } else if (!expr.has_base() && expr.has_index()) {
1259 AsmReg index_reg = expr.index_reg();
1260 if (std::holds_alternative<ScratchReg>(expr.index)) {
1261 scratch = std::move(std::get<ScratchReg>(expr.index));
1262 } else {
1263 (void)scratch.alloc_gp();
1264 }
1265 AsmReg dst = scratch.cur_reg();
1266 if ((expr.scale & (expr.scale - 1)) == 0) {
1267 const auto shift = util::cnt_tz<u64>(expr.scale);
1268 ASM(LSLxi, dst, index_reg, shift);
1269 } else {
1270 AsmReg tmp2 = permanent_scratch_reg;
1271 derived()->materialize_constant(expr.scale, Config::GP_BANK, 8, tmp2);
1272 ASM(MULx, dst, index_reg, tmp2);
1273 }
1274 } else if (expr.has_base() && expr.has_index()) {
1275 AsmReg base_reg = expr.base_reg();
1276 AsmReg index_reg = expr.index_reg();
1277 if (std::holds_alternative<ScratchReg>(expr.base)) {
1278 scratch = std::move(std::get<ScratchReg>(expr.base));
1279 } else if (std::holds_alternative<ScratchReg>(expr.index)) {
1280 scratch = std::move(std::get<ScratchReg>(expr.index));
1281 } else {
1282 (void)scratch.alloc_gp();
1283 }
1284 AsmReg dst = scratch.cur_reg();
1285 if ((expr.scale & (expr.scale - 1)) == 0) {
1286 const auto shift = util::cnt_tz<u64>(expr.scale);
1287 ASM(ADDx_lsl, dst, base_reg, index_reg, shift);
1288 } else {
1289 AsmReg tmp2 = permanent_scratch_reg;
1290 derived()->materialize_constant(expr.scale, Config::GP_BANK, 8, tmp2);
1291 ASM(MADDx, dst, index_reg, tmp2, base_reg);
1292 }
1293 } else if (expr.has_base() && !expr.has_index()) {
1294 AsmReg base_reg = expr.base_reg();
1295 if (std::holds_alternative<ScratchReg>(expr.base)) {
1296 scratch = std::move(std::get<ScratchReg>(expr.base));
1297 } else {
1298 (void)scratch.alloc_gp();
1299 }
1300 AsmReg dst = scratch.cur_reg();
1301 if (expr.disp != 0 && ASMIF(ADDxi, dst, base_reg, expr.disp)) {
1302 expr.disp = 0;
1303 } else if (dst != base_reg) {
1304 ASM(MOVx, dst, base_reg);
1305 }
1306 } else {
1307 TPDE_UNREACHABLE("inconsistent GenericValuePart::Expr");
1308 }
1309
1310 AsmReg dst = scratch.cur_reg();
1311 if (expr.disp != 0) {
1312 if (!ASMIF(ADDxi, dst, dst, expr.disp)) {
1313 AsmReg tmp2 = permanent_scratch_reg;
1314 derived()->materialize_constant(expr.disp, Config::GP_BANK, 8, tmp2);
1315 ASM(ADDx, dst, dst, tmp2);
1316 }
1317 }
1318
1319 gv.state = std::move(scratch);
1320 return dst;
1321}
1322
1323template <IRAdaptor Adaptor,
1324 typename Derived,
1325 template <typename, typename, typename> typename BaseTy,
1326 typename Config>
1327void CompilerA64<Adaptor, Derived, BaseTy, Config>::materialize_constant(
1328 const u64 *data, const RegBank bank, const u32 size, AsmReg dst) noexcept {
1329 const auto const_u64 = data[0];
1330 if (bank == Config::GP_BANK) {
1331 assert(size <= 8);
1332 if (const_u64 == 0) {
1333 ASM(MOVZw, dst, 0);
1334 return;
1335 }
1336
1337 this->text_writer.ensure_space(5 * 4);
1338 this->text_writer.cur_ptr() +=
1339 sizeof(u32) *
1340 de64_MOVconst(reinterpret_cast<u32 *>(this->text_writer.cur_ptr()),
1341 dst,
1342 const_u64);
1343 return;
1344 }
1345
1346 assert(bank == Config::FP_BANK);
1347 // Try instructions that take an immediate
1348 if (size == 4) {
1349 if (ASMIF(FMOVsi, dst, std::bit_cast<float>((u32)const_u64))) {
1350 return;
1351 } else if (ASMIF(MOVId, dst, static_cast<u32>(const_u64))) {
1352 return;
1353 }
1354 } else if (size == 8) {
1355 if (ASMIF(FMOVdi, dst, std::bit_cast<double>(const_u64))) {
1356 return;
1357 } else if (ASMIF(MOVId, dst, const_u64)) {
1358 return;
1359 }
1360 } else if (size == 16) {
1361 const auto high_u64 = data[1];
1362 if (const_u64 == high_u64 && ASMIF(MOVI2d, dst, const_u64)) {
1363 return;
1364 } else if (high_u64 == 0 && ASMIF(MOVId, dst, const_u64)) {
1365 return;
1366 }
1367 }
1368
1369 // We must either load through a GP register of from memory. Both cases need a
1370 // GP register in the common case. We reserve x16/x17 for cases like this.
1371 if (size <= 16) {
1372 this->register_file.mark_clobbered(permanent_scratch_reg);
1373 // Copy from a GP register
1374 // TODO: always load from memory?
1375 if (size <= 8) {
1376 materialize_constant(data, Config::GP_BANK, size, permanent_scratch_reg);
1377 if (size <= 4) {
1378 ASMNC(FMOVsw, dst, permanent_scratch_reg);
1379 } else {
1380 ASMNC(FMOVdx, dst, permanent_scratch_reg);
1381 }
1382 return;
1383 }
1384
1385 auto rodata = this->assembler.get_data_section(true, false);
1386 std::span<const u8> raw_data{reinterpret_cast<const u8 *>(data), size};
1387 auto sym = this->assembler.sym_def_data(
1388 rodata, "", raw_data, 16, Assembler::SymBinding::LOCAL);
1389 this->text_writer.ensure_space(8); // ensure contiguous instructions
1390 this->reloc_text(
1391 sym, R_AARCH64_ADR_PREL_PG_HI21, this->text_writer.offset(), 0);
1392 ASMNC(ADRP, permanent_scratch_reg, 0, 0);
1393 this->reloc_text(
1394 sym, R_AARCH64_LDST128_ABS_LO12_NC, this->text_writer.offset(), 0);
1395 ASMNC(LDRqu, dst, permanent_scratch_reg, 0);
1396 return;
1397 }
1398
1399 TPDE_FATAL("unable to materialize constant");
1400}
1401
1402template <IRAdaptor Adaptor,
1403 typename Derived,
1404 template <typename, typename, typename> typename BaseTy,
1405 typename Config>
1406AsmReg
1407 CompilerA64<Adaptor, Derived, BaseTy, Config>::select_fixed_assignment_reg(
1408 const RegBank bank, IRValueRef) noexcept {
1409 // TODO(ts): why is this in here?
1410 assert(bank.id() <= Config::NUM_BANKS);
1411 auto reg_mask = this->register_file.bank_regs(bank);
1412 reg_mask &= ~fixed_assignment_nonallocatable_mask;
1413
1414 const auto find_possible_regs = [this,
1415 reg_mask](const u64 preferred_regs) -> u64 {
1416 // try to first get an unused reg, otherwise an unfixed reg
1417 u64 free_regs = this->register_file.allocatable & ~this->register_file.used;
1418 u64 possible_regs = free_regs & preferred_regs & reg_mask;
1419 if (possible_regs == 0) {
1420 possible_regs = (this->register_file.used & ~this->register_file.fixed) &
1421 preferred_regs & reg_mask;
1422 }
1423 return possible_regs;
1424 };
1425
1426 u64 possible_regs;
1427 auto csr = derived()->cur_cc_assigner()->get_ccinfo().callee_saved_regs;
1428 if (derived()->cur_func_may_emit_calls()) {
1429 // we can only allocated fixed assignments from the callee-saved regs
1430 possible_regs = find_possible_regs(csr);
1431 } else {
1432 // try allocating any non-callee saved register first, except the result
1433 // registers
1434 possible_regs = find_possible_regs(~csr);
1435 if (possible_regs == 0) {
1436 // otherwise fallback to callee-saved regs
1437 possible_regs = find_possible_regs(csr);
1438 }
1439 }
1440
1441 if (possible_regs == 0) {
1442 return AsmReg::make_invalid();
1443 }
1444
1445 // try to first get an unused reg, otherwise an unfixed reg
1446 if ((possible_regs & ~this->register_file.used) != 0) {
1447 return AsmReg{util::cnt_tz(possible_regs & ~this->register_file.used)};
1448 }
1449
1450 for (const auto reg_id : util::BitSetIterator<>{possible_regs}) {
1451 const auto reg = AsmReg{reg_id};
1452
1453 assert(!this->register_file.is_fixed(reg));
1454
1455 const auto local_idx = this->register_file.reg_local_idx(reg);
1456 const auto part = this->register_file.reg_part(reg);
1457 assert(local_idx != Base::INVALID_VAL_LOCAL_IDX);
1458
1459 auto *assignment = this->val_assignment(local_idx);
1460 auto ap = AssignmentPartRef{assignment, part};
1461 if (ap.modified()) {
1462 continue;
1463 }
1464
1465 return reg;
1466 }
1467
1468 return AsmReg::make_invalid();
1469}
1470
1471template <IRAdaptor Adaptor,
1472 typename Derived,
1473 template <typename, typename, typename> class BaseTy,
1474 typename Config>
1475typename CompilerA64<Adaptor, Derived, BaseTy, Config>::Jump
1476 CompilerA64<Adaptor, Derived, BaseTy, Config>::invert_jump(
1477 Jump jmp) noexcept {
1478 switch (jmp.kind) {
1479 case Jump::Jeq: return jmp.change_kind(Jump::Jne);
1480 case Jump::Jne: return jmp.change_kind(Jump::Jeq);
1481 case Jump::Jcs: return jmp.change_kind(Jump::Jcc);
1482 case Jump::Jcc: return jmp.change_kind(Jump::Jcs);
1483 case Jump::Jmi: return jmp.change_kind(Jump::Jpl);
1484 case Jump::Jpl: return jmp.change_kind(Jump::Jmi);
1485 case Jump::Jvs: return jmp.change_kind(Jump::Jvc);
1486 case Jump::Jvc: return jmp.change_kind(Jump::Jvs);
1487 case Jump::Jhi: return jmp.change_kind(Jump::Jls);
1488 case Jump::Jls: return jmp.change_kind(Jump::Jhi);
1489 case Jump::Jge: return jmp.change_kind(Jump::Jlt);
1490 case Jump::Jlt: return jmp.change_kind(Jump::Jge);
1491 case Jump::Jgt: return jmp.change_kind(Jump::Jle);
1492 case Jump::Jle: return jmp.change_kind(Jump::Jgt);
1493 case Jump::jmp: return jmp;
1494 case Jump::Cbz: return jmp.change_kind(Jump::Cbnz);
1495 case Jump::Cbnz: return jmp.change_kind(Jump::Cbz);
1496 case Jump::Tbz: return jmp.change_kind(Jump::Tbnz);
1497 case Jump::Tbnz: return jmp.change_kind(Jump::Tbz);
1498 default: TPDE_UNREACHABLE("invalid jump kind");
1499 }
1500}
1501
1502template <IRAdaptor Adaptor,
1503 typename Derived,
1504 template <typename, typename, typename> typename BaseTy,
1505 typename Config>
1506typename CompilerA64<Adaptor, Derived, BaseTy, Config>::Jump
1507 CompilerA64<Adaptor, Derived, BaseTy, Config>::swap_jump(
1508 Jump jmp) noexcept {
1509 switch (jmp.kind) {
1510 case Jump::Jeq: return jmp.change_kind(Jump::Jeq);
1511 case Jump::Jne: return jmp.change_kind(Jump::Jne);
1512 case Jump::Jcc: return jmp.change_kind(Jump::Jhi);
1513 case Jump::Jcs: return jmp.change_kind(Jump::Jls);
1514 case Jump::Jhi: return jmp.change_kind(Jump::Jcc);
1515 case Jump::Jls: return jmp.change_kind(Jump::Jcs);
1516 case Jump::Jge: return jmp.change_kind(Jump::Jle);
1517 case Jump::Jlt: return jmp.change_kind(Jump::Jgt);
1518 case Jump::Jgt: return jmp.change_kind(Jump::Jlt);
1519 case Jump::Jle: return jmp.change_kind(Jump::Jge);
1520 case Jump::jmp: return jmp;
1521 case Jump::Jmi:
1522 case Jump::Jpl:
1523 case Jump::Jvs:
1524 case Jump::Jvc:
1525 case Jump::Cbz:
1526 case Jump::Cbnz:
1527 case Jump::Tbz:
1528 case Jump::Tbnz:
1529 default: TPDE_UNREACHABLE("invalid jump kind for swap_jump");
1530 }
1531}
1532
1533template <IRAdaptor Adaptor,
1534 typename Derived,
1535 template <typename, typename, typename> typename BaseTy,
1536 typename Config>
1537void CompilerA64<Adaptor, Derived, BaseTy, Config>::generate_branch_to_block(
1538 const Jump jmp,
1539 IRBlockRef target,
1540 const bool needs_split,
1541 const bool last_inst) noexcept {
1542 const auto target_idx = this->analyzer.block_idx(target);
1543 if (!needs_split || jmp.kind == Jump::jmp) {
1544 this->derived()->move_to_phi_nodes(target_idx);
1545
1546 if (!last_inst || this->analyzer.block_idx(target) != this->next_block()) {
1547 generate_raw_jump(jmp, this->block_labels[(u32)target_idx]);
1548 }
1549 } else {
1550 auto tmp_label = this->assembler.label_create();
1551 generate_raw_jump(invert_jump(jmp), tmp_label);
1552
1553 this->derived()->move_to_phi_nodes(target_idx);
1554
1555 generate_raw_jump(Jump::jmp, this->block_labels[(u32)target_idx]);
1556
1557 this->label_place(tmp_label);
1558 }
1559}
1560
1561template <IRAdaptor Adaptor,
1562 typename Derived,
1563 template <typename, typename, typename> typename BaseTy,
1564 typename Config>
1565void CompilerA64<Adaptor, Derived, BaseTy, Config>::generate_raw_jump(
1566 Jump jmp, Assembler::Label target_label) noexcept {
1567 const auto is_pending = this->assembler.label_is_pending(target_label);
1568 this->text_writer.ensure_space(4);
1569 if (jmp.kind == Jump::jmp) {
1570 if (is_pending) {
1571 ASMNC(B, 0);
1572 this->assembler.add_unresolved_entry(target_label,
1573 this->text_writer.get_sec_ref(),
1574 this->text_writer.offset() - 4,
1575 Assembler::UnresolvedEntryKind::BR);
1576 } else {
1577 const auto label_off = this->assembler.label_offset(target_label);
1578 const auto cur_off = this->text_writer.offset();
1579 assert(cur_off >= label_off);
1580 const auto diff = cur_off - label_off;
1581 assert((diff & 0b11) == 0);
1582 assert(diff < 128 * 1024 * 1024);
1583
1584 ASMNC(B, -static_cast<ptrdiff_t>(diff) / 4);
1585 }
1586 return;
1587 }
1588
1589 if (jmp.kind == Jump::Cbz || jmp.kind == Jump::Cbnz) {
1590 u32 off = 0;
1591 if (!is_pending) {
1592 const auto label_off = this->assembler.label_offset(target_label);
1593 const auto cur_off = this->text_writer.offset();
1594 assert(cur_off >= label_off);
1595 off = cur_off - label_off;
1596 assert((off & 0b11) == 0);
1597 assert(off < 128 * 1024 * 1024);
1598 }
1599
1600 if (off <= 1024 * 1024) {
1601 auto imm19 = -static_cast<ptrdiff_t>(off) / 4;
1602 if (jmp.kind == Jump::Cbz) {
1603 if (jmp.cmp_is_32) {
1604 ASMNC(CBZw, jmp.cmp_reg, imm19);
1605 } else {
1606 ASMNC(CBZx, jmp.cmp_reg, imm19);
1607 }
1608 } else {
1609 if (jmp.cmp_is_32) {
1610 ASMNC(CBNZw, jmp.cmp_reg, imm19);
1611 } else {
1612 ASMNC(CBNZx, jmp.cmp_reg, imm19);
1613 }
1614 }
1615
1616 if (is_pending) {
1617 this->assembler.add_unresolved_entry(
1618 target_label,
1619 this->text_writer.get_sec_ref(),
1620 this->text_writer.offset() - 4,
1621 Assembler::UnresolvedEntryKind::COND_BR);
1622 }
1623 } else {
1624 assert(!is_pending);
1625 this->text_writer.ensure_space(2 * 4);
1626
1627 if (jmp.kind == Jump::Cbz) {
1628 if (jmp.cmp_is_32) { // need to jump over 2 instructions
1629 ASMNC(CBNZw, jmp.cmp_reg, 2);
1630 } else {
1631 ASMNC(CBNZx, jmp.cmp_reg, 2);
1632 }
1633 } else {
1634 if (jmp.cmp_is_32) {
1635 ASMNC(CBZw, jmp.cmp_reg, 2);
1636 } else {
1637 ASMNC(CBZx, jmp.cmp_reg, 2);
1638 }
1639 }
1640 // + 4 since we already wrote the cb(n)z instruction
1641 ASMNC(B, -static_cast<ptrdiff_t>(off + 4) / 4);
1642 }
1643 return;
1644 }
1645
1646 if (jmp.kind == Jump::Tbz || jmp.kind == Jump::Tbnz) {
1647 u32 off = 0;
1648 if (!is_pending) {
1649 const auto label_off = this->assembler.label_offset(target_label);
1650 const auto cur_off = this->text_writer.offset();
1651 assert(cur_off >= label_off);
1652 off = cur_off - label_off;
1653 assert((off & 0b11) == 0);
1654 assert(off < 128 * 1024 * 1024);
1655 }
1656
1657 if (off <= 32 * 1024) {
1658 auto imm14 = -static_cast<ptrdiff_t>(off) / 4;
1659 if (jmp.kind == Jump::Tbz) {
1660 ASMNC(TBZ, jmp.cmp_reg, jmp.test_bit, imm14);
1661 } else {
1662 ASMNC(TBNZ, jmp.cmp_reg, jmp.test_bit, imm14);
1663 }
1664
1665 if (is_pending) {
1666 this->assembler.add_unresolved_entry(
1667 target_label,
1668 this->text_writer.get_sec_ref(),
1669 this->text_writer.offset() - 4,
1670 Assembler::UnresolvedEntryKind::TEST_BR);
1671 }
1672 } else {
1673 assert(!is_pending);
1674 this->text_writer.ensure_space(2 * 4);
1675
1676 if (jmp.kind == Jump::Tbz) {
1677 // need to jump over 2 instructions
1678 ASMNC(TBNZ, jmp.cmp_reg, jmp.test_bit, 2);
1679 } else {
1680 ASMNC(TBZ, jmp.cmp_reg, jmp.test_bit, 2);
1681 }
1682 // + 4 since we already wrote the tb(n)z instruction
1683 ASMNC(B, -static_cast<ptrdiff_t>(off + 4) / 4);
1684 }
1685 return;
1686 }
1687
1688 Da64Cond cond, cond_compl;
1689 switch (jmp.kind) {
1690 case Jump::Jeq:
1691 cond = DA_EQ;
1692 cond_compl = DA_NE;
1693 break;
1694 case Jump::Jne:
1695 cond = DA_NE;
1696 cond_compl = DA_EQ;
1697 break;
1698 case Jump::Jcs:
1699 cond = DA_CS;
1700 cond_compl = DA_CC;
1701 break;
1702 case Jump::Jcc:
1703 cond = DA_CC;
1704 cond_compl = DA_CS;
1705 break;
1706 case Jump::Jmi:
1707 cond = DA_MI;
1708 cond_compl = DA_PL;
1709 break;
1710 case Jump::Jpl:
1711 cond = DA_PL;
1712 cond_compl = DA_MI;
1713 break;
1714 case Jump::Jvs:
1715 cond = DA_VS;
1716 cond_compl = DA_VC;
1717 break;
1718 case Jump::Jvc:
1719 cond = DA_VC;
1720 cond_compl = DA_VS;
1721 break;
1722 case Jump::Jhi:
1723 cond = DA_HI;
1724 cond_compl = DA_LS;
1725 break;
1726 case Jump::Jls:
1727 cond = DA_LS;
1728 cond_compl = DA_HI;
1729 break;
1730 case Jump::Jge:
1731 cond = DA_GE;
1732 cond_compl = DA_LT;
1733 break;
1734 case Jump::Jlt:
1735 cond = DA_LT;
1736 cond_compl = DA_GE;
1737 break;
1738 case Jump::Jgt:
1739 cond = DA_GT;
1740 cond_compl = DA_LE;
1741 break;
1742 case Jump::Jle:
1743 cond = DA_LE;
1744 cond_compl = DA_GT;
1745 break;
1746 default: TPDE_UNREACHABLE("invalid jump kind");
1747 }
1748
1749
1750 u32 off = 0;
1751 if (!is_pending) {
1752 const auto label_off = this->assembler.label_offset(target_label);
1753 const auto cur_off = this->text_writer.offset();
1754 assert(cur_off >= label_off);
1755 off = cur_off - label_off;
1756 assert((off & 0b11) == 0);
1757 assert(off < 128 * 1024 * 1024);
1758 }
1759
1760 if (off <= 1024 * 1024) {
1761 ASMNC(BCOND, cond, -static_cast<ptrdiff_t>(off) / 4);
1762
1763 if (is_pending) {
1764 this->assembler.add_unresolved_entry(
1765 target_label,
1766 this->text_writer.get_sec_ref(),
1767 this->text_writer.offset() - 4,
1768 Assembler::UnresolvedEntryKind::COND_BR);
1769 }
1770 } else {
1771 assert(!is_pending);
1772 this->text_writer.ensure_space(2 * 4);
1773
1774 // 2 to skip over the branch following
1775 ASMNC(BCOND, cond_compl, 2);
1776 // + 4 since we already wrote the branch instruction
1777 ASMNC(B, -static_cast<ptrdiff_t>(off + 4) / 4);
1778 }
1779}
1780template <IRAdaptor Adaptor,
1781 typename Derived,
1782 template <typename, typename, typename> class BaseTy,
1783 typename Config>
1784Da64Cond CompilerA64<Adaptor, Derived, BaseTy, Config>::jump_to_cond(
1785 Jump jmp) noexcept {
1786 switch (jmp.kind) {
1787 case Jump::Jeq: return DA_EQ;
1788 case Jump::Jne: return DA_NE;
1789 case Jump::Jcs: return DA_CS;
1790 case Jump::Jcc: return DA_CC;
1791 case Jump::Jmi: return DA_MI;
1792 case Jump::Jpl: return DA_PL;
1793 case Jump::Jvs: return DA_VS;
1794 case Jump::Jvc: return DA_VC;
1795 case Jump::Jhi: return DA_HI;
1796 case Jump::Jls: return DA_LS;
1797 case Jump::Jge: return DA_GE;
1798 case Jump::Jlt: return DA_LT;
1799 case Jump::Jgt: return DA_GT;
1800 case Jump::Jle: return DA_LE;
1801 case Jump::jmp: return DA_AL;
1802 default: TPDE_UNREACHABLE("invalid jump kind for conversion to Da64Cond");
1803 }
1804}
1805
1806template <IRAdaptor Adaptor,
1807 typename Derived,
1808 template <typename, typename, typename> class BaseTy,
1809 typename Config>
1810void CompilerA64<Adaptor, Derived, BaseTy, Config>::generate_raw_set(
1811 Jump cc, AsmReg dst) noexcept {
1812 ASM(CSETw, dst, jump_to_cond(cc));
1813}
1814
1815template <IRAdaptor Adaptor,
1816 typename Derived,
1817 template <typename, typename, typename> class BaseTy,
1818 typename Config>
1819void CompilerA64<Adaptor, Derived, BaseTy, Config>::generate_raw_mask(
1820 Jump cc, AsmReg dst) noexcept {
1821 ASM(CSETMx, dst, jump_to_cond(cc));
1822}
1823template <IRAdaptor Adaptor,
1824 typename Derived,
1825 template <typename, typename, typename> class BaseTy,
1826 typename Config>
1827void CompilerA64<Adaptor, Derived, BaseTy, Config>::generate_raw_select(
1828 Jump cc,
1829 AsmReg dst,
1830 AsmReg true_select,
1831 AsmReg false_select,
1832 bool is_64) noexcept {
1833 this->text_writer.ensure_space(4);
1834 Da64Cond cond = jump_to_cond(cc);
1835 if (is_64) {
1836 ASMNC(CSELx, dst, true_select, false_select, cond);
1837 } else {
1838 ASMNC(CSELw, dst, true_select, false_select, cond);
1839 }
1840}
1841
1842template <IRAdaptor Adaptor,
1843 typename Derived,
1844 template <typename, typename, typename> class BaseTy,
1845 typename Config>
1846void CompilerA64<Adaptor, Derived, BaseTy, Config>::generate_raw_intext(
1847 AsmReg dst, AsmReg src, bool sign, u32 from, u32 to) noexcept {
1848 assert(from < to && to <= 64);
1849 (void)to;
1850 if (sign) {
1851 if (to <= 32) {
1852 ASM(SBFXw, dst, src, 0, from);
1853 } else {
1854 ASM(SBFXx, dst, src, 0, from);
1855 }
1856 } else {
1857 if (to <= 32) {
1858 ASM(UBFXw, dst, src, 0, from);
1859 } else {
1860 ASM(UBFXx, dst, src, 0, from);
1861 }
1862 }
1863}
1864
1865template <IRAdaptor Adaptor,
1866 typename Derived,
1867 template <typename, typename, typename> typename BaseTy,
1868 typename Config>
1869void CompilerA64<Adaptor, Derived, BaseTy, Config>::generate_call(
1870 std::variant<Assembler::SymRef, ValuePart> &&target,
1871 std::span<CallArg> arguments,
1872 typename Base::ValueRef *result,
1873 bool) {
1874 CCAssignerAAPCS assigner;
1875 CallBuilder cb{*derived(), assigner};
1876 for (auto &arg : arguments) {
1877 cb.add_arg(std::move(arg));
1878 }
1879 cb.call(std::move(target));
1880 if (result) {
1881 cb.add_ret(*result);
1882 }
1883}
1884
1885template <IRAdaptor Adaptor,
1886 typename Derived,
1887 template <typename, typename, typename> typename BaseTy,
1888 typename Config>
1889CompilerA64<Adaptor, Derived, BaseTy, Config>::ScratchReg
1890 CompilerA64<Adaptor, Derived, BaseTy, Config>::tls_get_addr(
1891 Assembler::SymRef sym, TLSModel model) noexcept {
1892 switch (model) {
1893 default: // TODO: implement optimized access for non-gd-model
1894 case TLSModel::GlobalDynamic: {
1895 ScratchReg r0_scratch{this};
1896 AsmReg r0 = r0_scratch.alloc_specific(AsmReg::R0);
1897 ScratchReg r1_scratch{this};
1898 AsmReg r1 = r1_scratch.alloc_specific(AsmReg::R1);
1899 // The call only clobbers flags, x0, x1, and lr. x0 and x1 are already fixed
1900 // in the scratch registers, so only make sure that lr isn't used otherwise.
1901 if (this->register_file.is_used(Reg{AsmReg::LR})) {
1902 this->evict_reg(Reg{AsmReg::LR});
1903 }
1904
1905 this->text_writer.ensure_space(0x18);
1906 this->reloc_text(
1907 sym, R_AARCH64_TLSDESC_ADR_PAGE21, this->text_writer.offset(), 0);
1908 ASMNC(ADRP, r0, 0, 0);
1909 this->reloc_text(
1910 sym, R_AARCH64_TLSDESC_LD64_LO12, this->text_writer.offset(), 0);
1911 ASMNC(LDRxu, r1, r0, 0);
1912 this->reloc_text(
1913 sym, R_AARCH64_TLSDESC_ADD_LO12, this->text_writer.offset(), 0);
1914 ASMNC(ADDxi, r0, r0, 0);
1915 this->reloc_text(
1916 sym, R_AARCH64_TLSDESC_CALL, this->text_writer.offset(), 0);
1917 ASMNC(BLR, r1);
1918 ASMNC(MRS, r1, 0xde82); // TPIDR_EL0
1919 // TODO: maybe return expr x0+x1.
1920 ASMNC(ADDx, r0, r1, r0);
1921 return r0_scratch;
1922 }
1923 }
1924}
1925
1926} // namespace tpde::a64