TPDE
Loading...
Searching...
No Matches
CompilerBase.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 <algorithm>
7#include <functional>
8#include <unordered_map>
9#include <variant>
10
11#include "Analyzer.hpp"
12#include "Compiler.hpp"
13#include "CompilerConfig.hpp"
14#include "IRAdaptor.hpp"
15#include "tpde/AssignmentPartRef.hpp"
16#include "tpde/FunctionWriter.hpp"
17#include "tpde/RegisterFile.hpp"
18#include "tpde/ValLocalIdx.hpp"
19#include "tpde/ValueAssignment.hpp"
20#include "tpde/base.hpp"
21#include "tpde/util/function_ref.hpp"
22#include "tpde/util/misc.hpp"
23
24namespace tpde {
25// TODO(ts): formulate concept for full compiler so that there is *some* check
26// whether all the required derived methods are implemented?
27
28/// Thread-local storage access mode
29enum class TLSModel {
30 GlobalDynamic,
31 LocalDynamic,
32 InitialExec,
33 LocalExec,
34};
35
36struct CCAssignment {
37 Reg reg = Reg::make_invalid(); ///< Assigned register, invalid implies stack.
38
39 /// If non-zero, indicates that this and the next N values must be
40 /// assigned to consecutive registers, or to the stack. The following
41 /// values must be in the same register bank as this value. u8 is sufficient,
42 /// no architecture has more than 255 parameter registers in a single bank.
43 u8 consecutive = 0;
44 bool sret : 1 = false; ///< Argument is return value pointer.
45
46 /// The argument is passed by value on the stack. The provided argument is a
47 /// pointer; for the call, size bytes will be copied into the corresponding
48 /// stack slot. Behaves like LLVM's byval.
49 ///
50 /// Note: On x86-64 SysV, this is used to pass larger structs in memory. Note
51 /// that AArch64 AAPCS doesn't use byval for structs, instead, the pointer is
52 /// passed without byval and it is the responsibility of the caller to
53 /// explicitly copy the value.
54 bool byval : 1 = false;
55
56 /// Extend integer argument. Highest bit indicates signed-ness, lower bits
57 /// indicate the source width from which the argument should be extended.
58 u8 int_ext = 0;
59
60 u8 align = 0; ///< Argument alignment
61 RegBank bank = RegBank{}; ///< Register bank to assign the value to.
62 u32 size = 0; ///< Argument size, for byval the stack slot size.
63 u32 stack_off = 0; ///< Assigned stack slot, only valid if reg is invalid.
64};
65
66struct CCInfo {
67 // TODO: use RegBitSet
68 const u64 allocatable_regs;
69 const u64 callee_saved_regs;
70 /// Possible argument registers; these registers will not be allocated until
71 /// all arguments have been assigned.
72 const u64 arg_regs;
73 /// Size of red zone below stack pointer.
74 const u8 red_zone_size = 0;
75};
76
77class CCAssigner {
78public:
79 const CCInfo *ccinfo;
80
81 CCAssigner(const CCInfo &ccinfo) : ccinfo(&ccinfo) {}
82 virtual ~CCAssigner() {}
83
84 virtual void reset() = 0;
85
86 const CCInfo &get_ccinfo() const { return *ccinfo; }
87
88 virtual void assign_arg(CCAssignment &cca) = 0;
89 virtual u32 get_stack_size() = 0;
90 /// Some calling conventions need different call behavior when calling a
91 /// vararg function.
92 virtual bool is_vararg() const { return false; }
93 virtual void assign_ret(CCAssignment &cca) = 0;
94};
95
96/// The base class for the compiler.
97/// It implements the main platform independent compilation logic and houses the
98/// analyzer
99template <IRAdaptor Adaptor,
100 typename Derived,
101 CompilerConfig Config = CompilerConfigDefault>
103 // some forwards for the IR type defs
104 using IRValueRef = typename Adaptor::IRValueRef;
105 using IRInstRef = typename Adaptor::IRInstRef;
106 using IRBlockRef = typename Adaptor::IRBlockRef;
107 using IRFuncRef = typename Adaptor::IRFuncRef;
108
109 using BlockIndex = typename Analyzer<Adaptor>::BlockIndex;
110
111 using AsmReg = typename Config::AsmReg;
112
113 using RegisterFile = tpde::RegisterFile<Config::NUM_BANKS, 32>;
114
115 /// A default implementation for ValRefSpecial.
116 // Note: Subclasses can override this, always used Derived::ValRefSpecial.
118 uint8_t mode = 4;
119 u64 const_data;
120 };
121
122#pragma region CompilerData
123 Adaptor *adaptor;
124 Analyzer<Adaptor> analyzer;
125
126 // data for frame management
127
128 struct {
129 /// The current size of the stack frame
130 u32 frame_size = 0;
131 /// Whether the stack frame might have dynamic alloca. Dynamic allocas may
132 /// require a different and less efficient frame setup. As static allocas
133 /// can be converted into dynamic allocas, this is only valid after static
134 /// allocas were processed.
136 /// Whether the function is guaranteed to be a leaf function. Throughout the
137 /// entire function, the compiler may assume the absence of function calls.
139 /// Whether the function actually includes a call. There are cases, where it
140 /// is not clear from the beginning whether a function has function calls.
141 /// If a function has no calls, this will allow using the red zone
142 /// guaranteed by some ABIs.
144 /// Whether the stack frame is used. If the stack frame is never used, the
145 /// frame setup can in some cases be omitted entirely.
147 /// Free-Lists for 1/2/4/8/16 sized allocations
148 // TODO(ts): make the allocations for 4/8 different from the others
149 // since they are probably the one's most used?
150 util::SmallVector<i32, 16> fixed_free_lists[5] = {};
151 /// Free-Lists for all other sizes
152 // TODO(ts): think about which data structure we want here
153 std::unordered_map<u32, std::vector<i32>> dynamic_free_lists{};
154 } stack = {};
155
156 typename Analyzer<Adaptor>::BlockIndex cur_block_idx;
157
158 // Assignments
159
160 static constexpr ValLocalIdx INVALID_VAL_LOCAL_IDX =
161 static_cast<ValLocalIdx>(~0u);
162
163 // TODO(ts): think about different ways to store this that are maybe more
164 // compact?
165 struct {
166 AssignmentAllocator allocator;
167
168 std::array<u32, Config::NUM_BANKS> cur_fixed_assignment_count = {};
169 util::SmallVector<ValueAssignment *, Analyzer<Adaptor>::SMALL_VALUE_NUM>
170 value_ptrs;
171
172 ValLocalIdx variable_ref_list;
173 util::SmallVector<ValLocalIdx, Analyzer<Adaptor>::SMALL_BLOCK_NUM>
174 delayed_free_lists;
175 } assignments = {};
176
177 RegisterFile register_file;
178#ifndef NDEBUG
179 /// Whether we are currently in the middle of generating branch-related code
180 /// and therefore must not change any value-related state.
181 bool generating_branch = false;
182#endif
183
184private:
185 /// Default CCAssigner if the implementation doesn't override cur_cc_assigner.
186 typename Config::DefaultCCAssigner default_cc_assigner;
187
188public:
189 typename Config::Assembler assembler;
190 Config::FunctionWriter text_writer;
191 // TODO(ts): smallvector?
192 std::vector<SymRef> func_syms;
193 // TODO(ts): combine this with the block vectors in the analyzer to save on
194 // allocations
195 util::SmallVector<Label> block_labels;
196
197 util::SmallVector<std::pair<SymRef, SymRef>, 4> personality_syms = {};
198
199 struct ScratchReg;
200 class ValuePart;
201 struct ValuePartRef;
202 struct ValueRef;
203 struct GenericValuePart;
204#pragma endregion
205
206 struct InstRange {
207 using Range = decltype(std::declval<Adaptor>().block_insts(
208 std::declval<IRBlockRef>()));
209 using Iter = decltype(std::declval<Range>().begin());
210 using EndIter = decltype(std::declval<Range>().end());
211 Iter from;
212 EndIter to;
213 };
214
215 /// Call argument, enhancing an IRValueRef with information on how to pass it.
216 struct CallArg {
217 enum class Flag : u8 {
218 none, ///< No extra handling.
219 zext, ///< Scalar integer, zero-extend to target-specific size.
220 sext, ///< Scalar integer, sign-extend to target-specific size.
221 sret, ///< Struct return pointer.
222 byval, ///< Value is copied into corresponding stack slot.
223 allow_split, ///< Value parts can be split across stack/registers.
224 };
225
226 explicit CallArg(IRValueRef value,
227 Flag flags = Flag::none,
228 u8 byval_align = 1,
229 u32 byval_size = 0)
230 : value(value),
231 flag(flags),
234
235 IRValueRef value; ///< Argument IR value.
236 Flag flag; ///< Value handling flag.
237 u8 byval_align; ///< For Flag::byval, the stack alignment.
238 u8 ext_bits = 0; ///< For Flag::zext and Flag::sext, the source bit width.
239 u32 byval_size; ///< For Flag::byval, the argument size.
240 };
241
242 /// Base class for target-specific CallBuilder implementations.
243 template <typename CBDerived>
244 class CallBuilderBase {
245 protected:
246 Derived &compiler;
247 CCAssigner &assigner;
248
249 RegisterFile::RegBitSet arg_regs{};
250
251 CallBuilderBase(Derived &compiler, CCAssigner &assigner)
252 : compiler(compiler), assigner(assigner) {}
253
254 // CBDerived needs:
255 // void add_arg_byval(ValuePart &vp, CCAssignment &cca);
256 // void add_arg_stack(ValuePart &vp, CCAssignment &cca);
257 // void call_impl(std::variant<SymRef, ValuePart> &&);
258 CBDerived *derived() { return static_cast<CBDerived *>(this); }
259
260 public:
261 /// Add a value part as argument. cca must be populated with information
262 /// about the argument, except for the reg/stack_off, which are set by the
263 /// CCAssigner. If no register bank is assigned, the register bank and size
264 /// are retrieved from the value part, otherwise, the size must be set, too.
265 void add_arg(ValuePart &&vp, CCAssignment cca);
266 /// Add a full IR value as argument, with an explicit number of parts.
267 /// Values are decomposed into their parts and are typically either fully
268 /// in registers or fully on the stack (except CallArg::Flag::allow_split).
269 void add_arg(const CallArg &arg, u32 part_count);
270 /// Add a full IR value as argument. The number of value parts must be
271 /// exposed via val_parts. Values are decomposed into their parts and are
272 /// typically either fully in registers or fully on the stack (except
273 /// CallArg::Flag::allow_split).
274 void add_arg(const CallArg &arg) {
275 add_arg(std::move(arg), compiler.val_parts(arg.value).count());
276 }
277
278 /// Generate the function call (evict registers, call, reset stack frame).
279 void call(std::variant<SymRef, ValuePart>);
280
281 /// Assign next return value part to vp.
282 void add_ret(ValuePart &vp, CCAssignment cca);
283 /// Assign next return value part to vp.
284 void add_ret(ValuePart &&vp, CCAssignment cca) { add_ret(vp, cca); }
285 /// Assign return values to the IR value.
286 void add_ret(ValueRef &vr);
287 };
288
289 class RetBuilder {
290 Derived &compiler;
291 CCAssigner &assigner;
292
293 RegisterFile::RegBitSet ret_regs{};
294
295 public:
296 RetBuilder(Derived &compiler, CCAssigner &assigner)
297 : compiler(compiler), assigner(assigner) {
298 assigner.reset();
299 }
300
301 void add(ValuePart &&vp, CCAssignment cca);
302 void add(IRValueRef val);
303
304 void ret();
305 };
306
307 /// Initialize a CompilerBase, should be called by the derived classes
308 explicit CompilerBase(Adaptor *adaptor)
309 : adaptor(adaptor), analyzer(adaptor), assembler() {
310 static_assert(std::is_base_of_v<CompilerBase, Derived>);
311 static_assert(Compiler<Derived, Config>);
312 }
313
314 /// shortcut for casting to the Derived class so that overloading
315 /// works
316 Derived *derived() { return static_cast<Derived *>(this); }
317
318 const Derived *derived() const { return static_cast<const Derived *>(this); }
319
320 [[nodiscard]] ValLocalIdx val_idx(const IRValueRef value) const {
321 return analyzer.adaptor->val_local_idx(value);
322 }
323
324 [[nodiscard]] ValueAssignment *val_assignment(const ValLocalIdx idx) {
325 return assignments.value_ptrs[static_cast<u32>(idx)];
326 }
327
328 /// Compile the functions returned by Adaptor::funcs
329 ///
330 /// \warning If you intend to call this multiple times, you must call reset
331 /// in-between the calls.
332 ///
333 /// \returns Whether the compilation was successful
334 bool compile();
335
336 /// Reset any leftover data from the previous compilation such that it will
337 /// not affect the next compilation
338 void reset();
339
340 /// Get CCAssigner for current function.
341 CCAssigner *cur_cc_assigner() { return &default_cc_assigner; }
342
343 void init_assignment(IRValueRef value, ValLocalIdx local_idx);
344
345private:
346 /// Frees an assignment, its stack slot and registers
347 void free_assignment(ValLocalIdx local_idx, ValueAssignment *);
348
349public:
350 /// Release an assignment when reference count drops to zero, either frees
351 /// the assignment immediately or delays free to the end of the live range.
352 void release_assignment(ValLocalIdx local_idx, ValueAssignment *);
353
354 /// Init a variable-ref assignment
355 void init_variable_ref(ValLocalIdx local_idx, u32 var_ref_data);
356 /// Init a variable-ref assignment
357 void init_variable_ref(IRValueRef value, u32 var_ref_data) {
358 init_variable_ref(adaptor->val_local_idx(value), var_ref_data);
359 }
360
361 /// \name Stack Slots
362 /// @{
363
364 /// Allocate a static stack slot.
365 i32 allocate_stack_slot(u32 size);
366 /// Free a static stack slot.
367 void free_stack_slot(u32 slot, u32 size);
368
369 /// @}
370
371 /// Assign function argument in prologue. \ref align can be used to increase
372 /// the minimal stack alignment of the first part of the argument. If \ref
373 /// allow_split is set, the argument can be passed partially in registers,
374 /// otherwise (default) it must be either passed completely in registers or
375 /// completely on the stack.
376 void prologue_assign_arg(CCAssigner *cc_assigner,
377 u32 arg_idx,
378 IRValueRef arg,
379 u32 align = 1,
380 bool allow_split = false);
381
382 /// \name Value References
383 /// @{
384
385 /// Get a using reference to a value.
386 ValueRef val_ref(IRValueRef value);
387
388 /// Get a using reference to a single-part value and provide direct access to
389 /// the only part. This is a convenience function; note that the ValueRef must
390 /// outlive the ValuePartRef (i.e. auto p = val_ref().part(0); won't work, as
391 /// the value will possibly be deallocated when the ValueRef is destroyed).
392 std::pair<ValueRef, ValuePartRef> val_ref_single(IRValueRef value);
393
394 /// Get a defining reference to a value.
395 ValueRef result_ref(IRValueRef value);
396
397 /// Get a defining reference to a single-part value and provide direct access
398 /// to the only part. Similar to val_ref_single().
399 std::pair<ValueRef, ValuePartRef> result_ref_single(IRValueRef value);
400
401 /// Make dst an alias for src, which must be a non-constant value with an
402 /// identical part configuration. src must be in its last use (is_owned()),
403 /// and the assignment will be repurposed for dst, keeping all assigned
404 /// registers and stack slots.
405 ValueRef result_ref_alias(IRValueRef dst, ValueRef &&src);
406
407 /// Initialize value as a pointer into a stack variable (i.e., a value
408 /// allocated from cur_static_allocas() or similar) with an offset. The
409 /// result value will be a stack variable itself.
410 ValueRef
411 result_ref_stack_slot(IRValueRef value, AssignmentPartRef base, i32 off);
412
413 /// @}
414
415 [[deprecated("Use ValuePartRef::set_value")]]
416 void set_value(ValuePartRef &val_ref, ScratchReg &scratch);
417 [[deprecated("Use ValuePartRef::set_value")]]
418 void set_value(ValuePartRef &&val_ref, ScratchReg &scratch) {
419 set_value(val_ref, scratch);
420 }
421
422 /// Get generic value part into a single register, evaluating expressions
423 /// and materializing immediates as required.
424 AsmReg gval_as_reg(GenericValuePart &gv);
425
426 /// Like gval_as_reg; if the GenericValuePart owns a reusable register
427 /// (either a ScratchReg, possibly due to materialization, or a reusable
428 /// ValuePartRef), store it in dst.
429 AsmReg gval_as_reg_reuse(GenericValuePart &gv, ScratchReg &dst);
430
431 /// Like gval_as_reg; if the GenericValuePart owns a reusable register
432 /// (either a ScratchReg, possibly due to materialization, or a reusable
433 /// ValuePartRef), store it in dst.
434 AsmReg gval_as_reg_reuse(GenericValuePart &gv, ValuePart &dst);
435
436private:
437 /// @internal Select register when a value needs to be evicted.
438 Reg select_reg_evict(RegBank bank);
439
440public:
441 /// \name Low-Level Assignment Register Handling
442 /// @{
443
444 /// Select an available register, evicting loaded values if needed.
445 Reg select_reg(RegBank bank) {
446 Reg res = register_file.find_first_free_excluding(bank, 0);
447 if (res.valid()) [[likely]] {
448 return res;
449 }
450 return select_reg_evict(bank);
451 }
452
453 /// Reload a value part from memory or recompute variable address.
454 void reload_to_reg(AsmReg dst, AssignmentPartRef ap);
455
456 /// Allocate a stack slot for an assignment.
457 void allocate_spill_slot(AssignmentPartRef ap);
458
459 /// Ensure the value is spilled in its stack slot (except variable refs).
460 void spill(AssignmentPartRef ap);
461
462 /// Evict the value from its register, spilling if needed, and free register.
463 void evict(AssignmentPartRef ap);
464
465 /// Evict the value from the register, spilling if needed, and free register.
466 void evict_reg(Reg reg);
467
468 /// Free the register. Requires that the contained value is already spilled.
469 void free_reg(Reg reg);
470
471 /// @}
472
473 /// \name High-Level Branch Generation
474 /// @{
475
476 /// Generate an unconditional branch at the end of a basic block. No further
477 /// instructions must follow. If target is the next block in the block order,
478 /// the branch is omitted.
479 void generate_uncond_branch(IRBlockRef target);
480
481 /// Generate an conditional branch at the end of a basic block.
482 template <typename Jump>
483 void generate_cond_branch(Jump jmp,
484 IRBlockRef true_target,
485 IRBlockRef false_target);
486
487 /// Generate a switch at the end of a basic block. Only the lowest bits of the
488 /// condition are considered. The condition must be a general-purpose
489 /// register. The cases must be sorted and every case value must appear at
490 /// most once.
491 void generate_switch(ScratchReg &&cond,
492 u32 width,
493 IRBlockRef default_block,
494 std::span<const std::pair<u64, IRBlockRef>> cases);
495
496 /// @}
497
498 /// \name Low-Level Branch Primitives
499 /// The general flow of using these low-level primitive is:
500 /// 1. spill_before_branch()
501 /// 2. begin_branch_region()
502 /// 3. One or more calls to generate_branch_to_block()
503 /// 4. end_branch_region()
504 /// 5. release_spilled_regs()
505 /// @{
506
507 // TODO(ts): switch to a branch_spill_before naming style?
508 /// Spill values that need to be spilled for later blocks. Returns the set
509 /// of registers that will be free'd at the end of the block; pass this to
510 /// release_spilled_regs().
511 typename RegisterFile::RegBitSet
512 spill_before_branch(bool force_spill = false);
513 /// Free registers marked by spill_before_branch().
514 void release_spilled_regs(typename RegisterFile::RegBitSet);
515
516 /// When reaching a point in the function where no other blocks will be
517 /// reached anymore, use this function to release register assignments after
518 /// the end of that block so the compiler does not accidentally use
519 /// registers which don't contain any values
521
522 /// Indicate beginning of region where value-state must not change.
524#ifndef NDEBUG
525 assert(!generating_branch);
526 generating_branch = true;
527#endif
528 }
529
530 /// Indicate end of region where value-state must not change.
532#ifndef NDEBUG
533 assert(generating_branch);
534 generating_branch = false;
535#endif
536 }
537
538 /// Generate a branch to a basic block; execution continues afterwards.
539 /// Multiple calls to this function can be used to build conditional branches.
540 /// @tparam Jump Target-defined Jump type (e.g., CompilerX64::Jump).
541 /// @param needs_split Result of branch_needs_split(); pass false for an
542 /// unconditional branch.
543 /// @param last_inst Whether fall-through to target is possible.
544 template <typename Jump>
546 IRBlockRef target,
547 bool needs_split,
548 bool last_inst);
549
550#ifndef NDEBUG
551 bool may_change_value_state() const { return !generating_branch; }
552#endif
553
554 void move_to_phi_nodes(BlockIndex target) {
555 if (analyzer.block_has_phis(target)) {
556 move_to_phi_nodes_impl(target);
557 }
558 }
559
560 void move_to_phi_nodes_impl(BlockIndex target);
561
562 /// Whether branch to a block requires additional instructions and therefore
563 /// a direct jump to the block is not possible.
564 bool branch_needs_split(IRBlockRef target) {
565 // for now, if the target has PHI-nodes, we split
566 return analyzer.block_has_phis(target);
567 }
568
569 /// @}
570
571 BlockIndex next_block() const;
572
573 bool try_force_fixed_assignment(IRValueRef) const { return false; }
574
575 bool hook_post_func_sym_init() { return true; }
576
577 void analysis_start() {}
578
579 void analysis_end() {}
580
581 void reloc_text(SymRef sym, u32 type, u64 offset, i64 addend = 0) {
582 this->assembler.reloc_sec(
583 text_writer.get_sec_ref(), sym, type, offset, addend);
584 }
585
586 /// Convenience function to place a label at the current position.
587 void label_place(Label label) {
588 this->text_writer.label_place(label, text_writer.offset());
589 }
590
591protected:
592 SymRef get_personality_sym();
593
594 bool compile_func(IRFuncRef func, u32 func_idx);
595
596 bool compile_block(IRBlockRef block, u32 block_idx);
597};
598} // namespace tpde
599
600#include "GenericValuePart.hpp"
601#include "ScratchReg.hpp"
602#include "ValuePartRef.hpp"
603#include "ValueRef.hpp"
604
605namespace tpde {
606
607template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
608template <typename CBDerived>
610 CBDerived>::add_arg(ValuePart &&vp, CCAssignment cca) {
611 if (!cca.byval && cca.bank == RegBank{}) {
612 cca.bank = vp.bank();
613 cca.size = vp.part_size();
614 }
615
616 assigner.assign_arg(cca);
617 bool needs_ext = cca.int_ext != 0;
618 bool ext_sign = cca.int_ext >> 7;
619 unsigned ext_bits = cca.int_ext & 0x3f;
620
621 if (cca.byval) {
622 derived()->add_arg_byval(vp, cca);
623 vp.reset(&compiler);
624 } else if (!cca.reg.valid()) {
625 if (needs_ext) {
626 auto ext = std::move(vp).into_extended(&compiler, ext_sign, ext_bits, 64);
627 derived()->add_arg_stack(ext, cca);
628 ext.reset(&compiler);
629 } else {
630 derived()->add_arg_stack(vp, cca);
631 }
632 vp.reset(&compiler);
633 } else {
634 if (vp.is_in_reg(cca.reg)) {
635 if (!vp.can_salvage()) {
636 compiler.evict_reg(cca.reg);
637 } else {
638 vp.salvage(&compiler);
639 }
640 if (needs_ext) {
641 compiler.generate_raw_intext(cca.reg, cca.reg, ext_sign, ext_bits, 64);
642 }
643 } else {
644 if (compiler.register_file.is_used(cca.reg)) {
645 compiler.evict_reg(cca.reg);
646 }
647 if (vp.can_salvage()) {
648 AsmReg vp_reg = vp.salvage(&compiler);
649 if (needs_ext) {
650 compiler.generate_raw_intext(cca.reg, vp_reg, ext_sign, ext_bits, 64);
651 } else {
652 compiler.mov(cca.reg, vp_reg, cca.size);
653 }
654 } else if (needs_ext && vp.is_const()) {
655 u64 val = vp.const_data()[0];
656 u64 extended =
657 ext_sign ? util::sext(val, ext_bits) : util::zext(val, ext_bits);
658 compiler.materialize_constant(&extended, cca.bank, 8, cca.reg);
659 } else {
660 vp.reload_into_specific_fixed(&compiler, cca.reg);
661 if (needs_ext) {
662 compiler.generate_raw_intext(
663 cca.reg, cca.reg, ext_sign, ext_bits, 64);
664 }
665 }
666 }
667 vp.reset(&compiler);
668 assert(!compiler.register_file.is_used(cca.reg));
669 compiler.register_file.mark_clobbered(cca.reg);
670 compiler.register_file.allocatable &= ~(u64{1} << cca.reg.id());
671 arg_regs |= (1ull << cca.reg.id());
672 }
673}
674
675template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
676template <typename CBDerived>
678 CBDerived>::add_arg(const CallArg &arg, u32 part_count) {
679 ValueRef vr = compiler.val_ref(arg.value);
680
681 if (arg.flag == CallArg::Flag::byval) {
682 assert(part_count == 1);
683 add_arg(vr.part(0),
684 CCAssignment{
685 .byval = true,
686 .align = arg.byval_align,
687 .size = arg.byval_size,
688 });
689 return;
690 }
691
692 u32 align = arg.byval_align;
693 bool allow_split = arg.flag == CallArg::Flag::allow_split;
694
695 for (u32 part_idx = 0; part_idx < part_count; ++part_idx) {
696 u8 int_ext = 0;
697 if (arg.flag == CallArg::Flag::sext || arg.flag == CallArg::Flag::zext) {
698 assert(arg.ext_bits != 0 && "cannot extend zero-bit integer");
699 int_ext = arg.ext_bits | (arg.flag == CallArg::Flag::sext ? 0x80 : 0);
700 }
701 u32 remaining = part_count < 256 ? part_count - part_idx - 1 : 255;
702 derived()->add_arg(vr.part(part_idx),
703 CCAssignment{
704 .consecutive = u8(allow_split ? 0 : remaining),
705 .sret = arg.flag == CallArg::Flag::sret,
706 .int_ext = int_ext,
707 .align = u8(part_idx == 0 ? align : 1),
708 });
709 }
710}
711
712template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
713template <typename CBDerived>
715 std::variant<SymRef, ValuePart> target) {
716 assert(!compiler.stack.is_leaf_function && "leaf func must not have calls");
717 compiler.stack.generated_call = true;
718 typename RegisterFile::RegBitSet skip_evict = arg_regs;
719 if (auto *vp = std::get_if<ValuePart>(&target); vp && vp->can_salvage()) {
720 // call_impl will reset vp, thereby unlock+free the register.
721 assert(vp->cur_reg_unlocked().valid() && "can_salvage implies register");
722 skip_evict |= (1ull << vp->cur_reg_unlocked().id());
723 }
724
725 auto clobbered = ~assigner.get_ccinfo().callee_saved_regs;
726 for (auto reg_id : util::BitSetIterator<>{compiler.register_file.used &
727 clobbered & ~skip_evict}) {
728 compiler.evict_reg(AsmReg{reg_id});
729 compiler.register_file.mark_clobbered(Reg{reg_id});
730 }
731
732 derived()->call_impl(std::move(target));
733
734 assert((compiler.register_file.allocatable & arg_regs) == 0);
735 compiler.register_file.allocatable |= arg_regs;
736}
737
738template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
739template <typename CBDerived>
741 CBDerived>::add_ret(ValuePart &vp, CCAssignment cca) {
742 cca.bank = vp.bank();
743 cca.size = vp.part_size();
744 assigner.assign_ret(cca);
745 assert(cca.reg.valid() && "return value must be in register");
746 vp.set_value_reg(&compiler, cca.reg);
747}
748
749template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
750template <typename CBDerived>
752 CBDerived>::add_ret(ValueRef &vr) {
753 assert(vr.has_assignment());
754 u32 part_count = vr.assignment()->part_count;
755 for (u32 part_idx = 0; part_idx < part_count; ++part_idx) {
756 CCAssignment cca;
757 add_ret(vr.part(part_idx), cca);
758 }
759}
760
761template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
762void CompilerBase<Adaptor, Derived, Config>::RetBuilder::add(ValuePart &&vp,
763 CCAssignment cca) {
764 cca.bank = vp.bank();
765 u32 size = cca.size = vp.part_size();
766 assigner.assign_ret(cca);
767 assert(cca.reg.valid() && "indirect return value must use sret argument");
768
769 bool needs_ext = cca.int_ext != 0;
770 bool ext_sign = cca.int_ext >> 7;
771 unsigned ext_bits = cca.int_ext & 0x3f;
772
773 if (vp.is_in_reg(cca.reg)) {
774 if (!vp.can_salvage()) {
775 compiler.evict_reg(cca.reg);
776 } else {
777 vp.salvage(&compiler);
778 }
779 if (needs_ext) {
780 compiler.generate_raw_intext(cca.reg, cca.reg, ext_sign, ext_bits, 64);
781 }
782 } else {
783 if (compiler.register_file.is_used(cca.reg)) {
784 compiler.evict_reg(cca.reg);
785 }
786 if (vp.can_salvage()) {
787 AsmReg vp_reg = vp.salvage(&compiler);
788 if (needs_ext) {
789 compiler.generate_raw_intext(cca.reg, vp_reg, ext_sign, ext_bits, 64);
790 } else {
791 compiler.mov(cca.reg, vp_reg, size);
792 }
793 } else {
794 vp.reload_into_specific_fixed(&compiler, cca.reg);
795 if (needs_ext) {
796 compiler.generate_raw_intext(cca.reg, cca.reg, ext_sign, ext_bits, 64);
797 }
798 }
799 }
800 vp.reset(&compiler);
801 assert(!compiler.register_file.is_used(cca.reg));
802 compiler.register_file.mark_clobbered(cca.reg);
803 compiler.register_file.allocatable &= ~(u64{1} << cca.reg.id());
804 ret_regs |= (1ull << cca.reg.id());
805}
806
807template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
809 u32 part_count = compiler.val_parts(val).count();
810 ValueRef vr = compiler.val_ref(val);
811 for (u32 part_idx = 0; part_idx < part_count; ++part_idx) {
812 add(vr.part(part_idx), CCAssignment{});
813 }
814}
815
816template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
818 assert((compiler.register_file.allocatable & ret_regs) == 0);
819 compiler.register_file.allocatable |= ret_regs;
820
821 compiler.gen_func_epilog();
822 compiler.release_regs_after_return();
823}
824
825template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
827 // create function symbols
828 text_writer.begin_module(assembler);
829 text_writer.switch_section(
830 assembler.get_section(assembler.get_default_section(SectionKind::Text)));
831
832 assert(func_syms.empty());
833 for (const IRFuncRef func : adaptor->funcs()) {
834 auto binding = Assembler::SymBinding::GLOBAL;
835 if (adaptor->func_has_weak_linkage(func)) {
837 } else if (adaptor->func_only_local(func)) {
839 }
840 if (adaptor->func_extern(func)) {
841 func_syms.push_back(derived()->assembler.sym_add_undef(
842 adaptor->func_link_name(func), binding));
843 } else {
844 func_syms.push_back(derived()->assembler.sym_predef_func(
845 adaptor->func_link_name(func), binding));
846 }
847 derived()->define_func_idx(func, func_syms.size() - 1);
848 }
849
850 if (!derived()->hook_post_func_sym_init()) {
851 TPDE_LOG_ERR("hook_pust_func_sym_init failed");
852 return false;
853 }
854
855 // TODO(ts): create function labels?
856
857 bool success = true;
858
859 u32 func_idx = 0;
860 for (const IRFuncRef func : adaptor->funcs()) {
861 if (adaptor->func_extern(func)) {
862 TPDE_LOG_TRACE("Skipping compilation of func {}",
863 adaptor->func_link_name(func));
864 ++func_idx;
865 continue;
866 }
867
868 TPDE_LOG_TRACE("Compiling func {}", adaptor->func_link_name(func));
869 if (!derived()->compile_func(func, func_idx)) {
870 TPDE_LOG_ERR("Failed to compile function {}",
871 adaptor->func_link_name(func));
872 success = false;
873 }
874 ++func_idx;
875 }
876
877 text_writer.flush();
878 text_writer.end_module();
879 assembler.finalize();
880
881 // TODO(ts): generate object/map?
882
883 return success;
884}
885
886template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
888 adaptor->reset();
889
890 for (auto &e : stack.fixed_free_lists) {
891 e.clear();
892 }
893 stack.dynamic_free_lists.clear();
894
895 assembler.reset();
896 func_syms.clear();
897 block_labels.clear();
898 personality_syms.clear();
899}
900
901template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
902void CompilerBase<Adaptor, Derived, Config>::init_assignment(
903 IRValueRef value, ValLocalIdx local_idx) {
904 assert(val_assignment(local_idx) == nullptr);
905 TPDE_LOG_TRACE("Initializing assignment for value {}",
906 static_cast<u32>(local_idx));
907
908 const auto parts = derived()->val_parts(value);
909 const u32 part_count = parts.count();
910 assert(part_count > 0);
911 auto *assignment = assignments.allocator.allocate(part_count);
912 assignments.value_ptrs[static_cast<u32>(local_idx)] = assignment;
913
914 u32 max_part_size = 0;
915 for (u32 part_idx = 0; part_idx < part_count; ++part_idx) {
916 auto ap = AssignmentPartRef{assignment, part_idx};
917 ap.reset();
918 ap.set_bank(parts.reg_bank(part_idx));
919 const u32 size = parts.size_bytes(part_idx);
920 assert(size > 0);
921 max_part_size = std::max(max_part_size, size);
922 ap.set_part_size(size);
923 }
924
925 const auto &liveness = analyzer.liveness_info(local_idx);
926
927 // if there is only one part, try to hand out a fixed assignment
928 // if the value is used for longer than one block and there aren't too many
929 // definitions in child loops this could interfere with
930 // TODO(ts): try out only fixed assignments if the value is live for more
931 // than two blocks?
932 // TODO(ts): move this to ValuePartRef::alloc_reg to be able to defer this
933 // for results?
934 if (part_count == 1) {
935 const auto &cur_loop =
936 analyzer.loop_from_idx(analyzer.block_loop_idx(cur_block_idx));
937 auto ap = AssignmentPartRef{assignment, 0};
938
939 auto try_fixed =
940 liveness.last > cur_block_idx &&
941 cur_loop.definitions_in_childs +
942 assignments.cur_fixed_assignment_count[ap.bank().id()] <
943 Derived::NUM_FIXED_ASSIGNMENTS[ap.bank().id()];
944 if (derived()->try_force_fixed_assignment(value)) {
945 try_fixed = assignments.cur_fixed_assignment_count[ap.bank().id()] <
946 Derived::NUM_FIXED_ASSIGNMENTS[ap.bank().id()];
947 }
948
949 if (try_fixed) {
950 // check if there is a fixed register available
951 AsmReg reg = derived()->select_fixed_assignment_reg(ap, value);
952 TPDE_LOG_TRACE("Trying to assign fixed reg to value {}",
953 static_cast<u32>(local_idx));
954
955 // TODO: if the register is used, we can free it most of the time, but not
956 // always, e.g. for PHI nodes. Detect this case and free_reg otherwise.
957 if (!reg.invalid() && !register_file.is_used(reg)) {
958 TPDE_LOG_TRACE("Assigning fixed assignment to reg {} for value {}",
959 reg.id(),
960 static_cast<u32>(local_idx));
961 ap.set_reg(reg);
962 ap.set_register_valid(true);
963 ap.set_fixed_assignment(true);
964 register_file.mark_used(reg, local_idx, 0);
965 register_file.inc_lock_count(reg); // fixed assignments always locked
966 register_file.mark_clobbered(reg);
967 ++assignments.cur_fixed_assignment_count[ap.bank().id()];
968 }
969 }
970 }
971
972 const auto last_full = liveness.last_full;
973 const auto ref_count = liveness.ref_count;
974
975 assert(max_part_size <= 256);
976 assignment->max_part_size = max_part_size;
977 assignment->pending_free = false;
978 assignment->variable_ref = false;
979 assignment->stack_variable = false;
980 assignment->delay_free = last_full;
981 assignment->part_count = part_count;
982 assignment->frame_off = 0;
983 assignment->references_left = ref_count;
984}
985
986template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
988 ValLocalIdx local_idx, ValueAssignment *assignment) {
989 TPDE_LOG_TRACE("Freeing assignment for value {}",
990 static_cast<u32>(local_idx));
991
992 assert(assignments.value_ptrs[static_cast<u32>(local_idx)] == assignment);
993 assignments.value_ptrs[static_cast<u32>(local_idx)] = nullptr;
994 const auto is_var_ref = assignment->variable_ref;
995 const u32 part_count = assignment->part_count;
996
997 // free registers
998 for (u32 part_idx = 0; part_idx < part_count; ++part_idx) {
999 auto ap = AssignmentPartRef{assignment, part_idx};
1000 if (ap.fixed_assignment()) [[unlikely]] {
1001 const auto reg = ap.get_reg();
1002 assert(register_file.is_fixed(reg));
1003 assert(register_file.reg_local_idx(reg) == local_idx);
1004 assert(register_file.reg_part(reg) == part_idx);
1005 --assignments.cur_fixed_assignment_count[ap.bank().id()];
1006 register_file.dec_lock_count_must_zero(reg); // release lock for fixed reg
1007 register_file.unmark_used(reg);
1008 } else if (ap.register_valid()) {
1009 const auto reg = ap.get_reg();
1010 assert(!register_file.is_fixed(reg));
1011 register_file.unmark_used(reg);
1012 }
1013 }
1014
1015 if constexpr (WithAsserts) {
1016 for (auto reg_id : register_file.used_regs()) {
1017 assert(register_file.reg_local_idx(AsmReg{reg_id}) != local_idx &&
1018 "freeing assignment that is still referenced by a register");
1019 }
1020 }
1021
1022 // variable references do not have a stack slot
1023 bool has_stack = Config::FRAME_INDEXING_NEGATIVE ? assignment->frame_off < 0
1024 : assignment->frame_off != 0;
1025 if (!is_var_ref && has_stack) {
1026 free_stack_slot(assignment->frame_off, assignment->size());
1027 }
1028
1029 assignments.allocator.deallocate(assignment);
1030}
1031
1032template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1033[[gnu::noinline]] void
1035 ValLocalIdx local_idx, ValueAssignment *assignment) {
1036 if (!assignment->delay_free) {
1037 free_assignment(local_idx, assignment);
1038 return;
1039 }
1040
1041 // need to wait until release
1042 TPDE_LOG_TRACE("Delay freeing assignment for value {}",
1043 static_cast<u32>(local_idx));
1044 const auto &liveness = analyzer.liveness_info(local_idx);
1045 auto &free_list_head = assignments.delayed_free_lists[u32(liveness.last)];
1046 assignment->next_delayed_free_entry = free_list_head;
1047 assignment->pending_free = true;
1048 free_list_head = local_idx;
1049}
1050
1051template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1053 ValLocalIdx local_idx, u32 var_ref_data) {
1054 TPDE_LOG_TRACE("Initializing variable-ref assignment for value {}",
1055 static_cast<u32>(local_idx));
1056
1057 assert(val_assignment(local_idx) == nullptr);
1058 auto *assignment = assignments.allocator.allocate_slow(1, true);
1059 assignments.value_ptrs[static_cast<u32>(local_idx)] = assignment;
1060
1061 assignment->max_part_size = Config::PLATFORM_POINTER_SIZE;
1062 assignment->variable_ref = true;
1063 assignment->stack_variable = false;
1064 assignment->part_count = 1;
1065 assignment->var_ref_custom_idx = var_ref_data;
1066 assignment->next_delayed_free_entry = assignments.variable_ref_list;
1067
1068 assignments.variable_ref_list = local_idx;
1069
1070 AssignmentPartRef ap{assignment, 0};
1071 ap.reset();
1072 ap.set_bank(Config::GP_BANK);
1073 ap.set_part_size(Config::PLATFORM_POINTER_SIZE);
1074}
1075
1076template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1078 this->stack.frame_used = true;
1079 unsigned align_bits = 4;
1080 if (size == 0) {
1081 return 0; // 0 is the "invalid" stack slot
1082 } else if (size <= 16) {
1083 // Align up to next power of two.
1084 u32 free_list_idx = size == 1 ? 0 : 32 - util::cnt_lz<u32>(size - 1);
1085 assert(size <= 1u << free_list_idx);
1086 size = 1 << free_list_idx;
1087 align_bits = free_list_idx;
1088
1089 if (!stack.fixed_free_lists[free_list_idx].empty()) {
1090 auto slot = stack.fixed_free_lists[free_list_idx].back();
1091 stack.fixed_free_lists[free_list_idx].pop_back();
1092 return slot;
1093 }
1094 } else {
1095 size = util::align_up(size, 16);
1096 auto it = stack.dynamic_free_lists.find(size);
1097 if (it != stack.dynamic_free_lists.end() && !it->second.empty()) {
1098 const auto slot = it->second.back();
1099 it->second.pop_back();
1100 return slot;
1101 }
1102 }
1103
1104 assert(stack.frame_size != ~0u &&
1105 "cannot allocate stack slot before stack frame is initialized");
1106
1107 // Align frame_size to align_bits
1108 for (u32 list_idx = util::cnt_tz(stack.frame_size); list_idx < align_bits;
1109 list_idx = util::cnt_tz(stack.frame_size)) {
1110 i32 slot = stack.frame_size;
1111 if constexpr (Config::FRAME_INDEXING_NEGATIVE) {
1112 slot = -(slot + (1ull << list_idx));
1113 }
1114 stack.fixed_free_lists[list_idx].push_back(slot);
1115 stack.frame_size += 1ull << list_idx;
1116 }
1117
1118 auto slot = stack.frame_size;
1119 assert(slot != 0 && "stack slot 0 is reserved");
1120 stack.frame_size += size;
1121
1122 if constexpr (Config::FRAME_INDEXING_NEGATIVE) {
1123 slot = -(slot + size);
1124 }
1125 return slot;
1126}
1127
1128template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1130 u32 size) {
1131 if (size == 0) [[unlikely]] {
1132 assert(slot == 0 && "unexpected slot for zero-sized stack-slot?");
1133 // Do nothing.
1134 } else if (size <= 16) [[likely]] {
1135 u32 free_list_idx = size == 1 ? 0 : 32 - util::cnt_lz<u32>(size - 1);
1136 stack.fixed_free_lists[free_list_idx].push_back(slot);
1137 } else {
1138 size = util::align_up(size, 16);
1139 stack.dynamic_free_lists[size].push_back(slot);
1140 }
1141}
1142
1143template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1145 CCAssigner *cc_assigner,
1146 u32 arg_idx,
1147 IRValueRef arg,
1148 u32 align,
1149 bool allow_split) {
1150 ValueRef vr = derived()->result_ref(arg);
1151 if (adaptor->cur_arg_is_byval(arg_idx)) {
1152 CCAssignment cca{
1153 .byval = true,
1154 .align = u8(adaptor->cur_arg_byval_align(arg_idx)),
1155 .size = adaptor->cur_arg_byval_size(arg_idx),
1156 };
1157 cc_assigner->assign_arg(cca);
1158 std::optional<i32> byval_frame_off =
1159 derived()->prologue_assign_arg_part(vr.part(0), cca);
1160
1161 if (byval_frame_off) {
1162 // We need to convert the assignment into a stack variable ref.
1163 ValLocalIdx local_idx = val_idx(arg);
1164 // TODO: we shouldn't create the result_ref for such cases in the first
1165 // place. However, this is not easy to detect up front, it depends on the
1166 // target and the calling convention whether this is possible.
1167 vr.reset();
1168 // Value assignment might have been free'd by ValueRef reset.
1169 if (ValueAssignment *assignment = val_assignment(local_idx)) {
1170 free_assignment(local_idx, assignment);
1171 }
1172 init_variable_ref(local_idx, 0);
1173 ValueAssignment *assignment = this->val_assignment(local_idx);
1174 assignment->stack_variable = true;
1175 assignment->frame_off = *byval_frame_off;
1176 }
1177 return;
1178 }
1179
1180 if (adaptor->cur_arg_is_sret(arg_idx)) {
1181 assert(vr.assignment()->part_count == 1 && "sret must be single-part");
1182 ValuePartRef vp = vr.part(0);
1183 CCAssignment cca{
1184 .sret = true, .bank = vp.bank(), .size = Config::PLATFORM_POINTER_SIZE};
1185 cc_assigner->assign_arg(cca);
1186 derived()->prologue_assign_arg_part(std::move(vp), cca);
1187 return;
1188 }
1189
1190 const u32 part_count = vr.assignment()->part_count;
1191 for (u32 part_idx = 0; part_idx < part_count; ++part_idx) {
1192 ValuePartRef vp = vr.part(part_idx);
1193 u32 remaining = part_count < 256 ? part_count - part_idx - 1 : 255;
1194 CCAssignment cca{
1195 .consecutive = u8(allow_split ? 0 : remaining),
1196 .align = u8(part_idx == 0 ? align : 1),
1197 .bank = vp.bank(),
1198 .size = vp.part_size(),
1199 };
1200 cc_assigner->assign_arg(cca);
1201 derived()->prologue_assign_arg_part(std::move(vp), cca);
1202 }
1203}
1204
1205template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1206typename CompilerBase<Adaptor, Derived, Config>::ValueRef
1208 if (auto special = derived()->val_ref_special(value); special) {
1209 return ValueRef{this, std::move(*special)};
1210 }
1211
1212 const ValLocalIdx local_idx = analyzer.adaptor->val_local_idx(value);
1213 assert(val_assignment(local_idx) != nullptr && "value use before def");
1214 return ValueRef{this, local_idx};
1215}
1216
1217template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1218std::pair<typename CompilerBase<Adaptor, Derived, Config>::ValueRef,
1219 typename CompilerBase<Adaptor, Derived, Config>::ValuePartRef>
1221 std::pair<ValueRef, ValuePartRef> res{val_ref(value), this};
1222 res.second = res.first.part(0);
1223 return res;
1224}
1225
1226template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1227typename CompilerBase<Adaptor, Derived, Config>::ValueRef
1229 const ValLocalIdx local_idx = analyzer.adaptor->val_local_idx(value);
1230 if (val_assignment(local_idx) == nullptr) {
1231 init_assignment(value, local_idx);
1232 }
1233 return ValueRef{this, local_idx};
1234}
1235
1236template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1237std::pair<typename CompilerBase<Adaptor, Derived, Config>::ValueRef,
1238 typename CompilerBase<Adaptor, Derived, Config>::ValuePartRef>
1240 IRValueRef value) {
1241 std::pair<ValueRef, ValuePartRef> res{result_ref(value), this};
1242 res.second = res.first.part(0);
1243 return res;
1244}
1245
1246template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1247typename CompilerBase<Adaptor, Derived, Config>::ValueRef
1249 ValueRef &&src) {
1250 const ValLocalIdx local_idx = analyzer.adaptor->val_local_idx(dst);
1251 assert(!val_assignment(local_idx) && "alias target already defined");
1252 assert(src.has_assignment() && "alias src must have an assignment");
1253 // Consider implementing aliases where multiple values share the same
1254 // assignment, e.g. for implementing trunc as a no-op sharing registers. Live
1255 // ranges can be merged and reference counts added. However, this needs
1256 // additional infrastructure to clear one of the value_ptrs.
1257 assert(src.is_owned() && "alias src must be owned");
1258
1259 ValueAssignment *assignment = src.assignment();
1260 u32 part_count = assignment->part_count;
1261 assert(!assignment->pending_free);
1262 assert(!assignment->variable_ref);
1263 assert(!assignment->pending_free);
1264 if constexpr (WithAsserts) {
1265 const auto &src_liveness = analyzer.liveness_info(src.local_idx());
1266 assert(!src_liveness.last_full); // implied by is_owned()
1267 assert(assignment->references_left == 1); // implied by is_owned()
1268
1269 // Validate that part configuration is identical.
1270 const auto parts = derived()->val_parts(dst);
1271 assert(parts.count() == part_count);
1272 for (u32 part_idx = 0; part_idx < part_count; ++part_idx) {
1273 AssignmentPartRef ap{assignment, part_idx};
1274 assert(parts.reg_bank(part_idx) == ap.bank());
1275 assert(parts.size_bytes(part_idx) == ap.part_size());
1276 }
1277 }
1278
1279 // Update local_idx of registers.
1280 for (u32 part_idx = 0; part_idx < part_count; ++part_idx) {
1281 AssignmentPartRef ap{assignment, part_idx};
1282 if (ap.register_valid()) {
1283 register_file.update_reg_assignment(ap.get_reg(), local_idx, part_idx);
1284 }
1285 }
1286
1287 const auto &liveness = analyzer.liveness_info(local_idx);
1288 assignment->delay_free = liveness.last_full;
1289 assignment->references_left = liveness.ref_count;
1290 assignments.value_ptrs[static_cast<u32>(src.local_idx())] = nullptr;
1291 assignments.value_ptrs[static_cast<u32>(local_idx)] = assignment;
1292 src.disown();
1293 src.reset();
1294
1295 return ValueRef{this, local_idx};
1296}
1297
1298template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1299typename CompilerBase<Adaptor, Derived, Config>::ValueRef
1301 IRValueRef dst, AssignmentPartRef base, i32 off) {
1302 const ValLocalIdx local_idx = analyzer.adaptor->val_local_idx(dst);
1303 assert(!val_assignment(local_idx) && "new value already defined");
1304 init_variable_ref(local_idx, 0);
1305 ValueAssignment *assignment = this->val_assignment(local_idx);
1306 assignment->stack_variable = true;
1307 assignment->frame_off = base.variable_stack_off() + off;
1308 return ValueRef{this, local_idx};
1309}
1310
1311template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1312void CompilerBase<Adaptor, Derived, Config>::set_value(ValuePartRef &val_ref,
1313 ScratchReg &scratch) {
1314 val_ref.set_value(std::move(scratch));
1315}
1316
1317template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1318typename CompilerBase<Adaptor, Derived, Config>::AsmReg
1320 if (std::holds_alternative<ScratchReg>(gv.state)) {
1321 return std::get<ScratchReg>(gv.state).cur_reg();
1322 }
1323 if (std::holds_alternative<ValuePartRef>(gv.state)) {
1324 auto &vpr = std::get<ValuePartRef>(gv.state);
1325 if (vpr.has_reg()) {
1326 return vpr.cur_reg();
1327 }
1328 return vpr.load_to_reg();
1329 }
1330 if (auto *expr = std::get_if<typename GenericValuePart::Expr>(&gv.state)) {
1331 if (expr->has_base() && !expr->has_index() && expr->disp == 0) {
1332 return expr->base_reg();
1333 }
1334 return derived()->gval_expr_as_reg(gv);
1335 }
1336 TPDE_UNREACHABLE("gval_as_reg on empty GenericValuePart");
1337}
1338
1339template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1340typename CompilerBase<Adaptor, Derived, Config>::AsmReg
1342 GenericValuePart &gv, ScratchReg &dst) {
1343 AsmReg reg = gval_as_reg(gv);
1344 if (!dst.has_reg()) {
1345 if (auto *scratch = std::get_if<ScratchReg>(&gv.state)) {
1346 dst = std::move(*scratch);
1347 } else if (auto *val_ref = std::get_if<ValuePartRef>(&gv.state)) {
1348 if (val_ref->can_salvage()) {
1349 dst.alloc_specific(val_ref->salvage());
1350 assert(dst.cur_reg() == reg && "salvaging unsuccessful");
1351 }
1352 }
1353 }
1354 return reg;
1355}
1356
1357template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1358typename CompilerBase<Adaptor, Derived, Config>::AsmReg
1360 GenericValuePart &gv, ValuePart &dst) {
1361 AsmReg reg = gval_as_reg(gv);
1362 if (!dst.has_reg() &&
1363 (!dst.has_assignment() || !dst.assignment().fixed_assignment())) {
1364 // TODO: make this less expensive
1365 if (auto *scratch = std::get_if<ScratchReg>(&gv.state)) {
1366 dst.set_value(this, std::move(*scratch));
1367 if (dst.has_assignment()) {
1368 dst.lock(this);
1369 }
1370 } else if (auto *val_ref = std::get_if<ValuePartRef>(&gv.state)) {
1371 if (val_ref->can_salvage()) {
1372 dst.set_value(this, std::move(*val_ref));
1373 if (dst.has_assignment()) {
1374 dst.lock(this);
1375 }
1376 }
1377 }
1378 }
1379 return reg;
1380}
1381
1382template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1383Reg CompilerBase<Adaptor, Derived, Config>::select_reg_evict(RegBank bank) {
1384 TPDE_LOG_DBG("select_reg_evict for bank {}", bank.id());
1385 auto candidates = register_file.used & register_file.bank_regs(bank);
1386
1387 Reg candidate = Reg::make_invalid();
1388 u32 max_score = 0;
1389 for (auto reg_id : util::BitSetIterator<>(candidates)) {
1390 Reg reg{reg_id};
1391 if (register_file.is_fixed(reg)) {
1392 continue;
1393 }
1394
1395 // Must be an evictable value, not a temporary.
1396 auto local_idx = register_file.reg_local_idx(reg);
1397 u32 part = register_file.reg_part(Reg{reg});
1398 assert(local_idx != INVALID_VAL_LOCAL_IDX);
1399 ValueAssignment *va = val_assignment(local_idx);
1400 AssignmentPartRef ap{va, part};
1401
1402 // We want to sort registers by the following (ordered by priority):
1403 // - stack variable ref (~1 add/sub to reconstruct)
1404 // - other variable ref (1-2 instrs to reconstruct)
1405 // - already spilled (no store needed)
1406 // - last use farthest away (most likely to get spilled anyhow, so there's
1407 // not much harm in spilling earlier)
1408 // - lowest ref-count (least used)
1409 //
1410 // TODO: evaluate and refine this heuristic
1411
1412 // TODO: evict stack variable refs before others
1413 if (ap.variable_ref()) {
1414 TPDE_LOG_DBG(" r{} ({}) is variable-ref", reg_id, u32(local_idx));
1415 candidate = reg;
1416 break;
1417 }
1418
1419 u32 score = 0;
1420 if (ap.stack_valid()) {
1421 score |= u32{1} << 31;
1422 }
1423
1424 const auto &liveness = analyzer.liveness_info(local_idx);
1425 u32 last_use_dist = u32(liveness.last) - u32(cur_block_idx);
1426 score |= (last_use_dist < 0x8000 ? 0x8000 - last_use_dist : 0) << 16;
1427
1428 u32 refs_left = va->pending_free ? 0 : va->references_left;
1429 score |= (refs_left < 0xffff ? 0x10000 - refs_left : 1);
1430
1431 TPDE_LOG_DBG(" r{} ({}:{}) rc={}/{} live={}-{}{} spilled={} score={:#x}",
1432 reg_id,
1433 u32(local_idx),
1434 part,
1435 refs_left,
1436 liveness.ref_count,
1437 u32(liveness.first),
1438 u32(liveness.last),
1439 &"*"[!liveness.last_full],
1440 ap.stack_valid(),
1441 score);
1442
1443 assert(score != 0);
1444 if (score > max_score) {
1445 candidate = reg;
1446 max_score = score;
1447 }
1448 }
1449 if (candidate.invalid()) [[unlikely]] {
1450 TPDE_FATAL("ran out of registers for scratch registers");
1451 }
1452 TPDE_LOG_DBG(" selected r{}", candidate.id());
1453 evict_reg(candidate);
1454 return candidate;
1455}
1456
1457template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1459 AsmReg dst, AssignmentPartRef ap) {
1460 if (!ap.variable_ref()) {
1461 assert(ap.stack_valid());
1462 derived()->load_from_stack(dst, ap.frame_off(), ap.part_size());
1463 } else if (ap.is_stack_variable()) {
1464 derived()->load_address_of_stack_var(dst, ap);
1465 } else if constexpr (!Config::DEFAULT_VAR_REF_HANDLING) {
1466 derived()->load_address_of_var_reference(dst, ap);
1467 } else {
1468 TPDE_UNREACHABLE("non-stack-variable needs custom var-ref handling");
1469 }
1470}
1471
1472template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1474 AssignmentPartRef ap) {
1475 assert(!ap.variable_ref() && "cannot allocate spill slot for variable ref");
1476 if (ap.assignment()->frame_off == 0) {
1477 assert(!ap.stack_valid() && "stack-valid set without spill slot");
1478 ap.assignment()->frame_off = allocate_stack_slot(ap.assignment()->size());
1479 assert(ap.assignment()->frame_off != 0);
1480 }
1481}
1482
1483template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1485 assert(may_change_value_state());
1486 if (!ap.stack_valid() && !ap.variable_ref()) {
1487 assert(ap.register_valid() && "cannot spill uninitialized assignment part");
1489 derived()->spill_reg(ap.get_reg(), ap.frame_off(), ap.part_size());
1490 ap.set_stack_valid();
1491 }
1492}
1493
1494template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1496 assert(may_change_value_state());
1497 assert(ap.register_valid());
1498 derived()->spill(ap);
1499 ap.set_register_valid(false);
1500 register_file.unmark_used(ap.get_reg());
1501}
1502
1503template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1505 assert(may_change_value_state());
1506 assert(!register_file.is_fixed(reg));
1507 assert(register_file.reg_local_idx(reg) != INVALID_VAL_LOCAL_IDX);
1508
1509 ValLocalIdx local_idx = register_file.reg_local_idx(reg);
1510 auto part = register_file.reg_part(reg);
1511 AssignmentPartRef evict_part{val_assignment(local_idx), part};
1512 assert(evict_part.register_valid());
1513 assert(evict_part.get_reg() == reg);
1514 derived()->spill(evict_part);
1515 evict_part.set_register_valid(false);
1516 register_file.unmark_used(reg);
1517}
1518
1519template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1521 assert(may_change_value_state());
1522 assert(!register_file.is_fixed(reg));
1523 assert(register_file.reg_local_idx(reg) != INVALID_VAL_LOCAL_IDX);
1524
1525 ValLocalIdx local_idx = register_file.reg_local_idx(reg);
1526 auto part = register_file.reg_part(reg);
1527 AssignmentPartRef ap{val_assignment(local_idx), part};
1528 assert(ap.register_valid());
1529 assert(ap.get_reg() == reg);
1530 assert(!ap.modified() || ap.variable_ref());
1531 ap.set_register_valid(false);
1532 register_file.unmark_used(reg);
1533}
1534
1535template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1536typename CompilerBase<Adaptor, Derived, Config>::RegisterFile::RegBitSet
1538 bool force_spill) {
1539 // since we do not explicitly keep track of register assignments per block,
1540 // whenever we might branch off to a block that we do not directly compile
1541 // afterwards (i.e. the register assignments might change in between), we
1542 // need to spill all registers which are not fixed and remove them from the
1543 // register state.
1544 //
1545 // This leads to worse codegen but saves a significant overhead to
1546 // store/manage the register assignment for each block (256 bytes/block for
1547 // x64) and possible compile-time as there might be additional logic to move
1548 // values around
1549
1550 // First, we consider the case that the current block only has one successor
1551 // which is compiled directly after the current one, in which case we do not
1552 // have to spill anything.
1553 //
1554 // Secondly, if the next block has multiple incoming edges, we always have
1555 // to spill and remove from the register assignment. Otherwise, we
1556 // only need to spill values if they are alive in any successor which is not
1557 // the next block.
1558 //
1559 // Values which are only read from PHI-Nodes and have no extended lifetimes,
1560 // do not need to be spilled as they die at the edge.
1561
1562 using RegBitSet = typename RegisterFile::RegBitSet;
1563
1564 assert(may_change_value_state());
1565
1566 const IRBlockRef cur_block_ref = analyzer.block_ref(cur_block_idx);
1567 // Earliest succeeding block after the current block that is not the
1568 // immediately succeeding block. Used to determine whether a value needs to
1569 // be spilled.
1570 BlockIndex earliest_next_succ = Analyzer<Adaptor>::INVALID_BLOCK_IDX;
1571
1572 bool must_spill = force_spill;
1573 if (!must_spill) {
1574 // We must always spill if no block is immediately succeeding or that block
1575 // has multiple incoming edges.
1576 auto next_block_is_succ = false;
1577 auto next_block_has_multiple_incoming = false;
1578 u32 succ_count = 0;
1579 for (const IRBlockRef succ : adaptor->block_succs(cur_block_ref)) {
1580 ++succ_count;
1581 BlockIndex succ_idx = analyzer.block_idx(succ);
1582 if (u32(succ_idx) == u32(cur_block_idx) + 1) {
1583 next_block_is_succ = true;
1584 if (analyzer.block_has_multiple_incoming(succ)) {
1585 next_block_has_multiple_incoming = true;
1586 }
1587 } else if (succ_idx > cur_block_idx && succ_idx < earliest_next_succ) {
1588 earliest_next_succ = succ_idx;
1589 }
1590 }
1591
1592 must_spill = !next_block_is_succ || next_block_has_multiple_incoming;
1593
1594 if (succ_count == 1 && !must_spill) {
1595 return RegBitSet{};
1596 }
1597 }
1598
1599 auto release_regs = RegBitSet{};
1600 // TODO(ts): just use register_file.used_nonfixed_regs()?
1601 for (auto reg : register_file.used_regs()) {
1602 auto local_idx = register_file.reg_local_idx(Reg{reg});
1603 auto part = register_file.reg_part(Reg{reg});
1604 if (local_idx == INVALID_VAL_LOCAL_IDX) {
1605 // scratch regs can never be held across blocks
1606 continue;
1607 }
1608 AssignmentPartRef ap{val_assignment(local_idx), part};
1609 if (ap.fixed_assignment()) {
1610 // fixed registers do not need to be spilled
1611 continue;
1612 }
1613
1614 // Remove from register assignment if the next block cannot rely on the
1615 // value being in the specific register.
1616 if (must_spill) {
1617 release_regs |= RegBitSet{1ull} << reg;
1618 }
1619
1620 if (!ap.modified() || ap.variable_ref()) {
1621 // No need to spill values that were already spilled or are variable refs.
1622 continue;
1623 }
1624
1625 const auto &liveness = analyzer.liveness_info(local_idx);
1626 if (liveness.last <= cur_block_idx) {
1627 // No need to spill value if it dies immediately after the block.
1628 continue;
1629 }
1630
1631 // If the value is live in a different block, we might need to spill it.
1632 // Cases:
1633 // - Live in successor that precedes current block => ignore, value must
1634 // have been spilled already due to RPO.
1635 // - Live only in successor that immediately follows this block => no need
1636 // to spill, value can be kept in register, register state for next block
1637 // is still valid.
1638 // - Live in successor in some distance after current block => spill
1639 if (must_spill || earliest_next_succ <= liveness.last) {
1640 spill(ap);
1641 }
1642 }
1643
1644 return release_regs;
1645}
1646
1647template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1649 typename RegisterFile::RegBitSet regs) {
1650 assert(may_change_value_state());
1651
1652 // TODO(ts): needs changes for other RegisterFile impls
1653 for (auto reg_id : util::BitSetIterator<>{regs & register_file.used}) {
1654 if (!register_file.is_fixed(Reg{reg_id})) {
1655 free_reg(Reg{reg_id});
1656 }
1657 }
1658}
1659
1660template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1662 // we essentially have to free all non-fixed registers
1663 for (auto reg_id : register_file.used_regs()) {
1664 if (!register_file.is_fixed(Reg{reg_id})) {
1665 free_reg(Reg{reg_id});
1666 }
1667 }
1668}
1669
1670template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1671template <typename Jump>
1673 Jump jmp, IRBlockRef target, bool needs_split, bool last_inst) {
1674 BlockIndex target_idx = this->analyzer.block_idx(target);
1675 Label target_label = this->block_labels[u32(target_idx)];
1676 if (!needs_split) {
1677 move_to_phi_nodes(target_idx);
1678 if (!last_inst || target_idx != this->next_block()) {
1679 derived()->generate_raw_jump(jmp, target_label);
1680 }
1681 } else {
1682 Label tmp_label = this->text_writer.label_create();
1683 derived()->generate_raw_jump(derived()->invert_jump(jmp), tmp_label);
1684 move_to_phi_nodes(target_idx);
1685 derived()->generate_raw_jump(Jump::jmp, target_label);
1686 this->label_place(tmp_label);
1687 }
1688}
1689
1690template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1692 IRBlockRef target) {
1693 auto spilled = spill_before_branch();
1695
1696 generate_branch_to_block(Derived::Jump::jmp, target, false, true);
1697
1699 release_spilled_regs(spilled);
1700}
1701
1702template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1703template <typename Jump>
1705 Jump jmp, IRBlockRef true_target, IRBlockRef false_target) {
1706 IRBlockRef next = analyzer.block_ref(next_block());
1707
1708 bool true_needs_split = branch_needs_split(true_target);
1709 bool false_needs_split = branch_needs_split(false_target);
1710
1711 auto spilled = spill_before_branch();
1713
1714 if (next == true_target || (next != false_target && true_needs_split)) {
1716 derived()->invert_jump(jmp), false_target, false_needs_split, false);
1717 generate_branch_to_block(Derived::Jump::jmp, true_target, false, true);
1718 } else if (next == false_target) {
1719 generate_branch_to_block(jmp, true_target, true_needs_split, false);
1720 generate_branch_to_block(Derived::Jump::jmp, false_target, false, true);
1721 } else {
1722 assert(!true_needs_split);
1723 generate_branch_to_block(jmp, true_target, false, false);
1724 generate_branch_to_block(Derived::Jump::jmp, false_target, false, true);
1725 }
1726
1728 release_spilled_regs(spilled);
1729}
1730
1731template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1733 ScratchReg &&cond,
1734 u32 width,
1735 IRBlockRef default_block,
1736 std::span<const std::pair<u64, IRBlockRef>> cases) {
1737 // This function takes cond as a ScratchReg as opposed to a ValuePart, because
1738 // the ValueRef for the condition must be ref-counted before we enter the
1739 // branch region.
1740
1741 assert(width <= 64);
1742 // We don't support sections with more than 4 GiB, so switches with more than
1743 // 4G cases are impossible to support.
1744 assert(cases.size() < UINT32_MAX && "large switches are unsupported");
1745
1746 AsmReg cmp_reg = cond.cur_reg();
1747 bool width_is_32 = width <= 32;
1748 if (u32 dst_width = util::align_up(width, 32); width != dst_width) {
1749 derived()->generate_raw_intext(cmp_reg, cmp_reg, false, width, dst_width);
1750 }
1751
1752 // We must not evict any registers in the branching code, as we don't track
1753 // the individual value states per block. Hence, we must not allocate any
1754 // registers (e.g., for constants, jump table address) below.
1755 ScratchReg tmp_scratch{this};
1756 AsmReg tmp_reg = tmp_scratch.alloc_gp();
1757
1758 const auto spilled = this->spill_before_branch();
1759 this->begin_branch_region();
1760
1761 tpde::util::SmallVector<tpde::Label, 64> case_labels;
1762 // Labels that need an intermediate block to setup registers. This is
1763 // separate, because most switch targets don't need this.
1764 tpde::util::SmallVector<std::pair<tpde::Label, IRBlockRef>, 64> case_blocks;
1765 for (auto i = 0u; i < cases.size(); ++i) {
1766 // If the target might need additional register moves, we can't branch there
1767 // immediately.
1768 // TODO: more precise condition?
1769 BlockIndex target = this->analyzer.block_idx(cases[i].second);
1770 if (analyzer.block_has_phis(target)) {
1771 case_labels.push_back(this->text_writer.label_create());
1772 case_blocks.emplace_back(case_labels.back(), cases[i].second);
1773 } else {
1774 case_labels.push_back(this->block_labels[u32(target)]);
1775 }
1776 }
1777
1778 const auto default_label = this->text_writer.label_create();
1779
1780 const auto build_range = [&,
1781 this](size_t begin, size_t end, const auto &self) {
1782 assert(begin <= end);
1783 const auto num_cases = end - begin;
1784 if (num_cases <= 4) {
1785 // if there are four or less cases we just compare the values
1786 // against each of them
1787 for (auto i = 0u; i < num_cases; ++i) {
1788 derived()->switch_emit_cmpeq(case_labels[begin + i],
1789 cmp_reg,
1790 tmp_reg,
1791 cases[begin + i].first,
1792 width_is_32);
1793 }
1794
1795 derived()->generate_raw_jump(Derived::Jump::jmp, default_label);
1796 return;
1797 }
1798
1799 // check if the density of the values is high enough to warrant building
1800 // a jump table
1801 u64 low_bound = cases[begin].first;
1802 u64 high_bound = cases[end - 1].first;
1803 auto range = high_bound - low_bound + 1;
1804 // we will get wrong results if range is 0 so skip the jump table if
1805 // that is the case
1806 if (range != 0 && (range / num_cases) < 8) {
1807 // for gcc, it seems that if there are less than 8 values per
1808 // case it will build a jump table so we do that, too
1809
1810 // Give target the option to emit a jump table.
1811 auto *jt = derived()->switch_create_jump_table(
1812 default_label, cmp_reg, tmp_reg, low_bound, high_bound, width_is_32);
1813 if (jt) {
1814 if (range == num_cases) {
1815 std::copy(case_labels.begin() + begin,
1816 case_labels.begin() + end,
1817 jt->labels().begin());
1818 } else {
1819 std::ranges::fill(jt->labels(), default_label);
1820 for (auto i = begin; i != end; ++i) {
1821 jt->labels()[cases[i].first - low_bound] = case_labels[i];
1822 }
1823 }
1824 return;
1825 }
1826 }
1827
1828 // do a binary search step
1829 const auto half_len = num_cases / 2;
1830 const auto half_value = cases[begin + half_len].first;
1831 const auto gt_label = this->text_writer.label_create();
1832
1833 // this will cmp against the input value, jump to the case if it is
1834 // equal or to gt_label if the value is greater. Otherwise it will
1835 // fall-through
1836 derived()->switch_emit_binary_step(case_labels[begin + half_len],
1837 gt_label,
1838 cmp_reg,
1839 tmp_reg,
1840 half_value,
1841 width_is_32);
1842 // search the lower half
1843 self(begin, begin + half_len, self);
1844
1845 // and the upper half
1846 this->label_place(gt_label);
1847 self(begin + half_len + 1, end, self);
1848 };
1849
1850 build_range(0, case_labels.size(), build_range);
1851
1852 // write out the labels
1853 this->label_place(default_label);
1854 derived()->generate_branch_to_block(
1855 Derived::Jump::jmp, default_block, false, false);
1856
1857 for (const auto &[label, target] : case_blocks) {
1858 // Branch predictors typically have problems if too many branches follow too
1859 // closely. Ensure a minimum alignment.
1860 this->text_writer.align(8);
1861 this->label_place(label);
1862 derived()->generate_branch_to_block(
1863 Derived::Jump::jmp, target, false, false);
1864 }
1865
1866 this->end_branch_region();
1867 this->release_spilled_regs(spilled);
1868}
1869
1870template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
1871void CompilerBase<Adaptor, Derived, Config>::move_to_phi_nodes_impl(
1872 BlockIndex target) {
1873 // PHI-nodes are always moved to their stack-slot (unless they are fixed)
1874 //
1875 // However, we need to take care of PHI-dependencies (cycles and chains)
1876 // as to not overwrite values which might be needed.
1877 //
1878 // In most cases, we expect the number of PHIs to be small but we want to
1879 // stay reasonably efficient even with larger numbers of PHIs
1880
1881 struct ScratchWrapper {
1882 Derived *self;
1883 AsmReg cur_reg = AsmReg::make_invalid();
1884 bool backed_up = false;
1885 bool was_modified = false;
1886 u8 part = 0;
1887 ValLocalIdx local_idx = INVALID_VAL_LOCAL_IDX;
1888
1889 ScratchWrapper(Derived *self) : self{self} {}
1890
1891 ~ScratchWrapper() { reset(); }
1892
1893 void reset() {
1894 if (cur_reg.invalid()) {
1895 return;
1896 }
1897
1898 self->register_file.unmark_fixed(cur_reg);
1899 self->register_file.unmark_used(cur_reg);
1900
1901 if (backed_up) {
1902 // restore the register state
1903 // TODO(ts): do we actually need the reload?
1904 auto *assignment = self->val_assignment(local_idx);
1905 // check if the value was free'd, then we dont need to restore
1906 // it
1907 if (assignment) {
1908 auto ap = AssignmentPartRef{assignment, part};
1909 if (!ap.variable_ref()) {
1910 // TODO(ts): assert that this always happens?
1911 assert(ap.stack_valid());
1912 self->load_from_stack(cur_reg, ap.frame_off(), ap.part_size());
1913 }
1914 ap.set_reg(cur_reg);
1915 ap.set_register_valid(true);
1916 ap.set_modified(was_modified);
1917 self->register_file.mark_used(cur_reg, local_idx, part);
1918 }
1919 backed_up = false;
1920 }
1921 cur_reg = AsmReg::make_invalid();
1922 }
1923
1924 AsmReg alloc_from_bank(RegBank bank) {
1925 if (cur_reg.valid() && self->register_file.reg_bank(cur_reg) == bank) {
1926 return cur_reg;
1927 }
1928 if (cur_reg.valid()) {
1929 reset();
1930 }
1931
1932 // TODO(ts): try to first find a non callee-saved/clobbered
1933 // register...
1934 auto &reg_file = self->register_file;
1935 auto reg = reg_file.find_first_free_excluding(bank, 0);
1936 if (reg.invalid()) {
1937 // TODO(ts): use clock here?
1938 reg = reg_file.find_first_nonfixed_excluding(bank, 0);
1939 if (reg.invalid()) {
1940 TPDE_FATAL("ran out of registers for scratch registers");
1941 }
1942
1943 backed_up = true;
1944 local_idx = reg_file.reg_local_idx(reg);
1945 part = reg_file.reg_part(reg);
1946 AssignmentPartRef ap{self->val_assignment(local_idx), part};
1947 was_modified = ap.modified();
1948 // TODO(ts): this does not spill for variable refs
1949 // We don't use evict_reg here, as we know that we can't change the
1950 // value state.
1951 assert(ap.register_valid() && ap.get_reg() == reg);
1952 if (!ap.stack_valid() && !ap.variable_ref()) {
1953 self->allocate_spill_slot(ap);
1954 self->spill_reg(ap.get_reg(), ap.frame_off(), ap.part_size());
1955 ap.set_stack_valid();
1956 }
1957 ap.set_register_valid(false);
1958 reg_file.unmark_used(reg);
1959 }
1960
1961 reg_file.mark_used(reg, INVALID_VAL_LOCAL_IDX, 0);
1962 reg_file.mark_clobbered(reg);
1963 reg_file.mark_fixed(reg);
1964 cur_reg = reg;
1965 return reg;
1966 }
1967
1968 ScratchWrapper &operator=(const ScratchWrapper &) = delete;
1969 ScratchWrapper &operator=(ScratchWrapper &&) = delete;
1970 };
1971
1972 IRBlockRef target_ref = analyzer.block_ref(target);
1973 IRBlockRef cur_ref = analyzer.block_ref(cur_block_idx);
1974
1975 // collect all the nodes
1976 struct NodeEntry {
1977 IRValueRef phi;
1978 IRValueRef incoming_val;
1979 ValLocalIdx phi_local_idx;
1980 // local idx of same-block phi node that needs special handling
1981 ValLocalIdx incoming_phi_local_idx = INVALID_VAL_LOCAL_IDX;
1982 // bool incoming_is_phi;
1983 u32 ref_count;
1984
1985 bool operator<(const NodeEntry &other) const {
1986 return phi_local_idx < other.phi_local_idx;
1987 }
1988
1989 bool operator<(ValLocalIdx other) const { return phi_local_idx < other; }
1990 };
1991
1992 util::SmallVector<NodeEntry, 16> nodes;
1993 for (IRValueRef phi : adaptor->block_phis(target_ref)) {
1994 ValLocalIdx phi_local_idx = adaptor->val_local_idx(phi);
1995 auto incoming = adaptor->val_as_phi(phi).incoming_val_for_block(cur_ref);
1996 nodes.emplace_back(NodeEntry{
1997 .phi = phi, .incoming_val = incoming, .phi_local_idx = phi_local_idx});
1998 }
1999
2000 // We check that the block has phi nodes before getting here.
2001 assert(!nodes.empty() && "block marked has having phi nodes has none");
2002
2003 ScratchWrapper scratch{derived()};
2004 const auto move_to_phi = [this, &scratch](IRValueRef phi,
2005 IRValueRef incoming_val) {
2006 auto phi_vr = derived()->result_ref(phi);
2007 auto val_vr = derived()->val_ref(incoming_val);
2008 if (phi == incoming_val) {
2009 return;
2010 }
2011
2012 u32 part_count = phi_vr.assignment()->part_count;
2013 for (u32 i = 0; i < part_count; ++i) {
2014 AssignmentPartRef phi_ap{phi_vr.assignment(), i};
2015 ValuePartRef val_vpr = val_vr.part(i);
2016
2017 if (phi_ap.fixed_assignment()) {
2018 if (AsmReg reg = val_vpr.cur_reg_unlocked(); reg.valid()) {
2019 derived()->mov(phi_ap.get_reg(), reg, phi_ap.part_size());
2020 } else {
2021 val_vpr.reload_into_specific_fixed(phi_ap.get_reg());
2022 }
2023 } else {
2024 AsmReg reg = val_vpr.cur_reg_unlocked();
2025 if (!reg.valid()) {
2026 reg = scratch.alloc_from_bank(val_vpr.bank());
2027 val_vpr.reload_into_specific_fixed(reg);
2028 }
2029 allocate_spill_slot(phi_ap);
2030 derived()->spill_reg(reg, phi_ap.frame_off(), phi_ap.part_size());
2031 phi_ap.set_stack_valid();
2032 }
2033 }
2034 };
2035
2036 if (nodes.size() == 1) {
2037 move_to_phi(nodes[0].phi, nodes[0].incoming_val);
2038 return;
2039 }
2040
2041 // sort so we can binary search later
2042 std::sort(nodes.begin(), nodes.end());
2043
2044 // fill in the refcount
2045 auto all_zero_ref = true;
2046 for (auto &node : nodes) {
2047 // We don't need to do anything for PHIs that don't reference other PHIs or
2048 // self-referencing PHIs.
2049 bool incoming_is_phi = adaptor->val_is_phi(node.incoming_val);
2050 if (!incoming_is_phi || node.incoming_val == node.phi) {
2051 continue;
2052 }
2053
2054 ValLocalIdx inc_local_idx = adaptor->val_local_idx(node.incoming_val);
2055 auto it = std::lower_bound(nodes.begin(), nodes.end(), inc_local_idx);
2056 if (it == nodes.end() || it->phi != node.incoming_val) {
2057 // Incoming value is a PHI node, but it's not from our block, so we don't
2058 // need to be particularly careful when assigning values.
2059 continue;
2060 }
2061 node.incoming_phi_local_idx = inc_local_idx;
2062 ++it->ref_count;
2063 all_zero_ref = false;
2064 }
2065
2066 if (all_zero_ref) {
2067 // no cycles/chain that we need to take care of
2068 for (auto &node : nodes) {
2069 move_to_phi(node.phi, node.incoming_val);
2070 }
2071 return;
2072 }
2073
2074 // TODO(ts): this is rather inefficient...
2075 util::SmallVector<u32, 32> ready_indices;
2076 ready_indices.reserve(nodes.size());
2077 util::SmallBitSet<256> waiting_nodes;
2078 waiting_nodes.resize(nodes.size());
2079 for (u32 i = 0; i < nodes.size(); ++i) {
2080 if (nodes[i].ref_count) {
2081 waiting_nodes.mark_set(i);
2082 } else {
2083 ready_indices.push_back(i);
2084 }
2085 }
2086
2087 u32 handled_count = 0;
2088 u32 cur_tmp_part_count = 0;
2089 i32 cur_tmp_slot = 0;
2090 u32 cur_tmp_slot_size = 0;
2091 IRValueRef cur_tmp_val = Adaptor::INVALID_VALUE_REF;
2092 ScratchWrapper tmp_reg1{derived()}, tmp_reg2{derived()};
2093
2094 const auto move_from_tmp_phi = [&](IRValueRef target_phi) {
2095 auto phi_vr = val_ref(target_phi);
2096 if (cur_tmp_part_count <= 2) {
2097 AssignmentPartRef ap{phi_vr.assignment(), 0};
2098 assert(!tmp_reg1.cur_reg.invalid());
2099 if (ap.fixed_assignment()) {
2100 derived()->mov(ap.get_reg(), tmp_reg1.cur_reg, ap.part_size());
2101 } else {
2102 derived()->spill_reg(tmp_reg1.cur_reg, ap.frame_off(), ap.part_size());
2103 }
2104
2105 if (cur_tmp_part_count == 2) {
2106 AssignmentPartRef ap_high{phi_vr.assignment(), 1};
2107 assert(!ap_high.fixed_assignment());
2108 assert(!tmp_reg2.cur_reg.invalid());
2109 derived()->spill_reg(
2110 tmp_reg2.cur_reg, ap_high.frame_off(), ap_high.part_size());
2111 }
2112 return;
2113 }
2114
2115 for (u32 i = 0; i < cur_tmp_part_count; ++i) {
2116 AssignmentPartRef phi_ap{phi_vr.assignment(), i};
2117 assert(!phi_ap.fixed_assignment());
2118
2119 auto slot_off = cur_tmp_slot + phi_ap.part_off();
2120 auto reg = tmp_reg1.alloc_from_bank(phi_ap.bank());
2121 derived()->load_from_stack(reg, slot_off, phi_ap.part_size());
2122 derived()->spill_reg(reg, phi_ap.frame_off(), phi_ap.part_size());
2123 }
2124 };
2125
2126 while (handled_count != nodes.size()) {
2127 if (ready_indices.empty()) {
2128 // need to break a cycle
2129 auto cur_idx_opt = waiting_nodes.first_set();
2130 assert(cur_idx_opt);
2131 auto cur_idx = *cur_idx_opt;
2132 assert(nodes[cur_idx].ref_count == 1);
2133 assert(cur_tmp_val == Adaptor::INVALID_VALUE_REF);
2134
2135 auto phi_val = nodes[cur_idx].phi;
2136 auto phi_vr = this->val_ref(phi_val);
2137 auto *assignment = phi_vr.assignment();
2138 cur_tmp_part_count = assignment->part_count;
2139 cur_tmp_val = phi_val;
2140
2141 if (cur_tmp_part_count > 2) {
2142 // use a stack slot to store the temporaries
2143 cur_tmp_slot_size = assignment->size();
2144 cur_tmp_slot = allocate_stack_slot(cur_tmp_slot_size);
2145
2146 for (u32 i = 0; i < cur_tmp_part_count; ++i) {
2147 auto ap = AssignmentPartRef{assignment, i};
2148 assert(!ap.fixed_assignment());
2149 auto slot_off = cur_tmp_slot + ap.part_off();
2150
2151 if (ap.register_valid()) {
2152 auto reg = ap.get_reg();
2153 derived()->spill_reg(reg, slot_off, ap.part_size());
2154 } else {
2155 auto reg = tmp_reg1.alloc_from_bank(ap.bank());
2156 assert(ap.stack_valid());
2157 derived()->load_from_stack(reg, ap.frame_off(), ap.part_size());
2158 derived()->spill_reg(reg, slot_off, ap.part_size());
2159 }
2160 }
2161 } else {
2162 // TODO(ts): if the PHI is not fixed, then we can just reuse its
2163 // register if it has one
2164 auto phi_vpr = phi_vr.part(0);
2165 auto reg = tmp_reg1.alloc_from_bank(phi_vpr.bank());
2166 phi_vpr.reload_into_specific_fixed(this, reg);
2167
2168 if (cur_tmp_part_count == 2) {
2169 // TODO(ts): just change the part ref on the lower ref?
2170 auto phi_vpr_high = phi_vr.part(1);
2171 auto reg_high = tmp_reg2.alloc_from_bank(phi_vpr_high.bank());
2172 phi_vpr_high.reload_into_specific_fixed(this, reg_high);
2173 }
2174 }
2175
2176 nodes[cur_idx].ref_count = 0;
2177 ready_indices.push_back(cur_idx);
2178 waiting_nodes.mark_unset(cur_idx);
2179 }
2180
2181 for (u32 i = 0; i < ready_indices.size(); ++i) {
2182 ++handled_count;
2183 auto cur_idx = ready_indices[i];
2184 auto phi_val = nodes[cur_idx].phi;
2185 IRValueRef incoming_val = nodes[cur_idx].incoming_val;
2186 if (incoming_val == phi_val) {
2187 // no need to do anything, except ref-counting
2188 (void)val_ref(incoming_val);
2189 (void)val_ref(phi_val);
2190 continue;
2191 }
2192
2193 if (incoming_val == cur_tmp_val) {
2194 move_from_tmp_phi(phi_val);
2195
2196 if (cur_tmp_part_count > 2) {
2197 free_stack_slot(cur_tmp_slot, cur_tmp_slot_size);
2198 cur_tmp_slot = 0xFFFF'FFFF;
2199 cur_tmp_slot_size = 0;
2200 }
2201 cur_tmp_val = Adaptor::INVALID_VALUE_REF;
2202 // skip the code below as the ref count of the temp val is
2203 // already 0 and we don't want to reinsert it into the ready
2204 // list
2205 continue;
2206 }
2207
2208 move_to_phi(phi_val, incoming_val);
2209
2210 if (nodes[cur_idx].incoming_phi_local_idx == INVALID_VAL_LOCAL_IDX) {
2211 continue;
2212 }
2213
2214 auto it = std::lower_bound(
2215 nodes.begin(), nodes.end(), nodes[cur_idx].incoming_phi_local_idx);
2216 assert(it != nodes.end() && it->phi == incoming_val &&
2217 "incoming_phi_local_idx set incorrectly");
2218
2219 assert(it->ref_count > 0);
2220 if (--it->ref_count == 0) {
2221 auto node_idx = static_cast<u32>(it - nodes.begin());
2222 ready_indices.push_back(node_idx);
2223 waiting_nodes.mark_unset(node_idx);
2224 }
2225 }
2226 ready_indices.clear();
2227 }
2228}
2229
2230template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
2233 return static_cast<BlockIndex>(static_cast<u32>(cur_block_idx) + 1);
2234}
2235
2236template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
2238 SymRef personality_sym;
2239 if (this->adaptor->cur_needs_unwind_info()) {
2240 SymRef personality_func = derived()->cur_personality_func();
2241 if (personality_func.valid()) {
2242 for (const auto &[fn_sym, ptr_sym] : personality_syms) {
2243 if (fn_sym == personality_func) {
2244 personality_sym = ptr_sym;
2245 break;
2246 }
2247 }
2248
2249 if (!personality_sym.valid()) {
2250 // create symbol that contains the address of the personality
2251 // function
2252 u32 off;
2253 static constexpr std::array<u8, 8> zero{};
2254
2255 auto rodata =
2256 this->assembler.get_default_section(SectionKind::DataRelRO);
2257 personality_sym = this->assembler.sym_def_data(
2258 rodata, "", zero, 8, Assembler::SymBinding::LOCAL, &off);
2259 this->assembler.reloc_abs(rodata, personality_func, off, 0);
2260
2261 personality_syms.emplace_back(personality_func, personality_sym);
2262 }
2263 }
2264 }
2265 return personality_sym;
2266}
2267
2268template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
2270 const u32 func_idx) {
2271 if (!adaptor->switch_func(func)) {
2272 return false;
2273 }
2274 derived()->analysis_start();
2275 analyzer.switch_func(func);
2276 derived()->analysis_end();
2277
2278 if constexpr (WithAsserts) {
2279 stack.frame_size = ~0u;
2280 }
2281 for (auto &e : stack.fixed_free_lists) {
2282 e.clear();
2283 }
2284 stack.dynamic_free_lists.clear();
2285 // TODO: sort out the inconsistency about adaptor vs. compiler methods.
2286 stack.has_dynamic_alloca = this->adaptor->cur_has_dynamic_alloca();
2287 stack.is_leaf_function = !derived()->cur_func_may_emit_calls();
2288 stack.generated_call = false;
2289 stack.frame_used = false;
2290
2291 assignments.cur_fixed_assignment_count = {};
2292 assert(std::ranges::none_of(assignments.value_ptrs, std::identity{}));
2293 if (assignments.value_ptrs.size() < analyzer.liveness.size()) {
2294 assignments.value_ptrs.resize(analyzer.liveness.size());
2295 }
2296
2297 assignments.allocator.reset();
2298 assignments.variable_ref_list = INVALID_VAL_LOCAL_IDX;
2299 assignments.delayed_free_lists.clear();
2300 assignments.delayed_free_lists.resize(analyzer.block_layout.size(),
2301 INVALID_VAL_LOCAL_IDX);
2302
2303 cur_block_idx =
2304 static_cast<BlockIndex>(analyzer.block_idx(adaptor->cur_entry_block()));
2305
2306 register_file.reset();
2307#ifndef NDEBUG
2308 generating_branch = false;
2309#endif
2310
2311 // Simple heuristic for initial allocation size
2312 u32 expected_code_size = 0x8 * analyzer.num_insts + 0x40;
2313 this->text_writer.begin_func(/*alignment=*/16, expected_code_size);
2314
2315 derived()->start_func(func_idx);
2316
2317 block_labels.clear();
2318 block_labels.resize_uninitialized(analyzer.block_layout.size());
2319 for (u32 i = 0; i < analyzer.block_layout.size(); ++i) {
2320 block_labels[i] = text_writer.label_create();
2321 }
2322
2323 // TODO(ts): place function label
2324 // TODO(ts): make function labels optional?
2325
2326 CCAssigner *cc_assigner = derived()->cur_cc_assigner();
2327 assert(cc_assigner != nullptr);
2328
2329 register_file.allocatable = cc_assigner->get_ccinfo().allocatable_regs;
2330
2331 cc_assigner->reset();
2332 // Temporarily prevent argument registers from being assigned.
2333 const CCInfo &cc_info = cc_assigner->get_ccinfo();
2334 assert((cc_info.allocatable_regs & cc_info.arg_regs) == cc_info.arg_regs &&
2335 "argument registers must also be allocatable");
2336 this->register_file.allocatable &= ~cc_info.arg_regs;
2337
2338 // Begin prologue, prepare for handling arguments.
2339 derived()->prologue_begin(cc_assigner);
2340 u32 arg_idx = 0;
2341 for (const IRValueRef arg : this->adaptor->cur_args()) {
2342 // Init assignment for all arguments. This can be substituted for more
2343 // complex mappings of arguments to value parts.
2344 derived()->prologue_assign_arg(cc_assigner, arg_idx++, arg);
2345 }
2346 // Finish prologue, storing relevant data from the argument cc_assigner.
2347 derived()->prologue_end(cc_assigner);
2348
2349 this->register_file.allocatable |= cc_info.arg_regs;
2350
2351 // Small allocas get stack slot, larger allocas need dynamic allocations.
2352 util::SmallVector<std::tuple<IRValueRef, u32, u32>> dyn_allocas;
2353 for (const IRValueRef alloca : adaptor->cur_static_allocas()) {
2354 auto size = adaptor->val_alloca_size(alloca);
2355 auto align = adaptor->val_alloca_align(alloca);
2356 if (align > 16 || size > Derived::MaxStaticAllocaSize) {
2357 stack.has_dynamic_alloca = true;
2358 dyn_allocas.emplace_back(alloca, size, align);
2359 continue;
2360 }
2361
2362 ValLocalIdx local_idx = adaptor->val_local_idx(alloca);
2363 init_variable_ref(local_idx, 0);
2364 ValueAssignment *assignment = val_assignment(local_idx);
2365 assignment->stack_variable = true;
2366 assignment->frame_off = allocate_stack_slot(util::align_up(size, align));
2367 }
2368
2369 if constexpr (!Config::DEFAULT_VAR_REF_HANDLING) {
2370 derived()->setup_var_ref_assignments();
2371 }
2372
2373 for (auto &[alloca, size, align] : dyn_allocas) {
2374 auto [_, vr] = this->result_ref_single(alloca);
2375 derived()->alloca_fixed(size, align, vr);
2376 }
2377
2378 for (u32 i = 0; i < analyzer.block_layout.size(); ++i) {
2379 const auto block_ref = analyzer.block_layout[i];
2380 TPDE_LOG_TRACE(
2381 "Compiling block {} ({})", i, adaptor->block_fmt_ref(block_ref));
2382 if (!derived()->compile_block(block_ref, i)) [[unlikely]] {
2383 TPDE_LOG_ERR("Failed to compile block {} ({})",
2384 i,
2385 adaptor->block_fmt_ref(block_ref));
2386 // Ensure invariant that value_ptrs only contains nullptr at the end.
2387 assignments.value_ptrs.clear();
2388 return false;
2389 }
2390 }
2391
2392 // Reset all variable-ref assignment pointers to nullptr.
2393 ValLocalIdx variable_ref_list = assignments.variable_ref_list;
2394 while (variable_ref_list != INVALID_VAL_LOCAL_IDX) {
2395 u32 idx = u32(variable_ref_list);
2396 ValLocalIdx next = assignments.value_ptrs[idx]->next_delayed_free_entry;
2397 assignments.value_ptrs[idx] = nullptr;
2398 variable_ref_list = next;
2399 }
2400
2401 assert(std::ranges::none_of(assignments.value_ptrs, std::identity{}) &&
2402 "found non-freed ValueAssignment, maybe missing ref-count?");
2403
2404 derived()->finish_func(func_idx);
2405 this->text_writer.finish_func();
2406
2407 return true;
2408}
2409
2410template <IRAdaptor Adaptor, typename Derived, CompilerConfig Config>
2412 const IRBlockRef block, const u32 block_idx) {
2413 cur_block_idx =
2414 static_cast<typename Analyzer<Adaptor>::BlockIndex>(block_idx);
2415
2416 label_place(block_labels[block_idx]);
2417 auto &&val_range = adaptor->block_insts(block);
2418 auto end = val_range.end();
2419 for (auto it = val_range.begin(); it != end; ++it) {
2420 const IRInstRef inst = *it;
2421 if (this->adaptor->inst_fused(inst)) {
2422 continue;
2423 }
2424
2425 auto it_cpy = it;
2426 ++it_cpy;
2427 if (!derived()->compile_inst(inst, InstRange{.from = it_cpy, .to = end}))
2428 [[unlikely]] {
2429 TPDE_LOG_ERR("Failed to compile instruction {}",
2430 this->adaptor->inst_fmt_ref(inst));
2431 return false;
2432 }
2433 }
2434
2435 if constexpr (WithAsserts) {
2436 // Some consistency checks. Register assignment information must match, all
2437 // used registers must have an assignment (no temporaries across blocks),
2438 // and fixed registers must be fixed assignments.
2439 for (auto reg_id : register_file.used_regs()) {
2440 Reg reg{reg_id};
2441 assert(register_file.reg_local_idx(reg) != INVALID_VAL_LOCAL_IDX);
2442 AssignmentPartRef ap{val_assignment(register_file.reg_local_idx(reg)),
2443 register_file.reg_part(reg)};
2444 assert(ap.register_valid());
2445 assert(ap.get_reg() == reg);
2446 assert(!register_file.is_fixed(reg) || ap.fixed_assignment());
2447 }
2448 }
2449
2450 if (static_cast<u32>(assignments.delayed_free_lists[block_idx]) != ~0u) {
2451 auto list_entry = assignments.delayed_free_lists[block_idx];
2452 while (static_cast<u32>(list_entry) != ~0u) {
2453 auto *assignment = assignments.value_ptrs[static_cast<u32>(list_entry)];
2454 auto next_entry = assignment->next_delayed_free_entry;
2455 derived()->free_assignment(list_entry, assignment);
2456 list_entry = next_entry;
2457 }
2458 }
2459 return true;
2460}
2461
2462} // namespace tpde
@ LOCAL
Symbol with local linkage, must be defined.
Base class for target-specific CallBuilder implementations.
void call(std::variant< SymRef, ValuePart >)
Generate the function call (evict registers, call, reset stack frame).
void add_ret(ValuePart &&vp, CCAssignment cca)
Assign next return value part to vp.
void add_arg(ValuePart &&vp, CCAssignment cca)
Add a value part as argument.
void add_arg(const CallArg &arg)
Add a full IR value as argument.
void add_ret(ValuePart &vp, CCAssignment cca)
Assign next return value part to vp.
The IRAdaptor specifies the interface with which the IR-independent parts of the compiler interact wi...
Definition IRAdaptor.hpp:91
Call argument, enhancing an IRValueRef with information on how to pass it.
u8 ext_bits
For Flag::zext and Flag::sext, the source bit width.
@ byval
Value is copied into corresponding stack slot.
@ zext
Scalar integer, zero-extend to target-specific size.
@ sext
Scalar integer, sign-extend to target-specific size.
@ allow_split
Value parts can be split across stack/registers.
Flag flag
Value handling flag.
u8 byval_align
For Flag::byval, the stack alignment.
u32 byval_size
For Flag::byval, the argument size.
IRValueRef value
Argument IR value.
Owned unspillable and unevictable temporary register with RAII semantics.
AsmReg cur_reg() const
The allocated register.
bool has_reg() const
Whether a register is currently allocated.
AsmReg alloc_specific(AsmReg reg)
Allocate a specific register.
AsmReg alloc_gp()
Allocate a general-purpose register.
A default implementation for ValRefSpecial.
RegisterFile::RegBitSet spill_before_branch(bool force_spill=false)
Spill values that need to be spilled for later blocks.
void generate_switch(ScratchReg &&cond, u32 width, IRBlockRef default_block, std::span< const std::pair< u64, IRBlockRef > > cases)
Generate a switch at the end of a basic block.
bool has_dynamic_alloca
Whether the stack frame might have dynamic alloca.
void reset()
Reset any leftover data from the previous compilation such that it will not affect the next compilati...
void free_reg(Reg reg)
Free the register. Requires that the contained value is already spilled.
AsmReg gval_as_reg_reuse(GenericValuePart &gv, ValuePart &dst)
Like gval_as_reg; if the GenericValuePart owns a reusable register (either a ScratchReg,...
ValueRef result_ref_stack_slot(IRValueRef value, AssignmentPartRef base, i32 off)
Initialize value as a pointer into a stack variable (i.e., a value allocated from cur_static_allocas(...
CCAssigner * cur_cc_assigner()
Get CCAssigner for current function.
bool compile()
Compile the functions returned by Adaptor::funcs.
std::pair< ValueRef, ValuePartRef > result_ref_single(IRValueRef value)
Get a defining reference to a single-part value and provide direct access to the only part.
ValueRef val_ref(IRValueRef value)
Get a using reference to a value.
bool generated_call
Whether the function actually includes a call.
ValueRef result_ref_alias(IRValueRef dst, ValueRef &&src)
Make dst an alias for src, which must be a non-constant value with an identical part configuration.
void allocate_spill_slot(AssignmentPartRef ap)
Allocate a stack slot for an assignment.
std::unordered_map< u32, std::vector< i32 > > dynamic_free_lists
Free-Lists for all other sizes.
bool branch_needs_split(IRBlockRef target)
Whether branch to a block requires additional instructions and therefore a direct jump to the block i...
std::pair< ValueRef, ValuePartRef > val_ref_single(IRValueRef value)
Get a using reference to a single-part value and provide direct access to the only part.
void release_spilled_regs(typename RegisterFile::RegBitSet)
Free registers marked by spill_before_branch().
void reload_to_reg(AsmReg dst, AssignmentPartRef ap)
Reload a value part from memory or recompute variable address.
u32 frame_size
The current size of the stack frame.
void generate_cond_branch(Jump jmp, IRBlockRef true_target, IRBlockRef false_target)
Generate an conditional branch at the end of a basic block.
i32 allocate_stack_slot(u32 size)
Allocate a static stack slot.
void spill(AssignmentPartRef ap)
Ensure the value is spilled in its stack slot (except variable refs).
void label_place(Label label)
Convenience function to place a label at the current position.
bool frame_used
Whether the stack frame is used.
bool generating_branch
Whether we are currently in the middle of generating branch-related code and therefore must not chang...
ValueRef result_ref(IRValueRef value)
Get a defining reference to a value.
void free_stack_slot(u32 slot, u32 size)
Free a static stack slot.
Reg select_reg(RegBank bank)
Select an available register, evicting loaded values if needed.
void evict(AssignmentPartRef ap)
Evict the value from its register, spilling if needed, and free register.
Derived * derived()
shortcut for casting to the Derived class so that overloading works
void generate_uncond_branch(IRBlockRef target)
Generate an unconditional branch at the end of a basic block.
void release_regs_after_return()
When reaching a point in the function where no other blocks will be reached anymore,...
void begin_branch_region()
Indicate beginning of region where value-state must not change.
util::SmallVector< i32, 16 > fixed_free_lists[5]
Free-Lists for 1/2/4/8/16 sized allocations.
AsmReg gval_as_reg_reuse(GenericValuePart &gv, ScratchReg &dst)
Like gval_as_reg; if the GenericValuePart owns a reusable register (either a ScratchReg,...
CompilerBase(Adaptor *adaptor)
Initialize a CompilerBase, should be called by the derived classes.
void end_branch_region()
Indicate end of region where value-state must not change.
void release_assignment(ValLocalIdx local_idx, ValueAssignment *)
Release an assignment when reference count drops to zero, either frees the assignment immediately or ...
AsmReg gval_as_reg(GenericValuePart &gv)
Get generic value part into a single register, evaluating expressions and materializing immediates as...
void prologue_assign_arg(CCAssigner *cc_assigner, u32 arg_idx, IRValueRef arg, u32 align=1, bool allow_split=false)
Assign function argument in prologue.
void init_variable_ref(IRValueRef value, u32 var_ref_data)
Init a variable-ref assignment.
void generate_branch_to_block(Jump jmp, IRBlockRef target, bool needs_split, bool last_inst)
Generate a branch to a basic block; execution continues afterwards.
bool is_leaf_function
Whether the function is guaranteed to be a leaf function.
void evict_reg(Reg reg)
Evict the value from the register, spilling if needed, and free register.
void init_variable_ref(ValLocalIdx local_idx, u32 var_ref_data)
Init a variable-ref assignment.