-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharm-thumb-gen.c
More file actions
9225 lines (8317 loc) · 328 KB
/
arm-thumb-gen.c
File metadata and controls
9225 lines (8317 loc) · 328 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* ARMvX-m code generator for TCC
* Uses thumb instruction set
*
* Based on:
* ARM Thumb 2 instruction functions for TCC
* Copyright (c) 2020 Erlend J. Sveen
* from:
* https://git.erlendjs.no/erlendjs/tinycc/-/blob/arm-thumb/arm-thumb-gen.c
* https://git.erlendjs.no/erlendjs/tinycc/-/blob/arm-thumb/arm-thumb-instructions.c
*
* And
*
* ARMv4 code generator for TCC
*
* Copyright (c) 2003 Daniel Glöckner
* Copyright (c) 2012 Thomas Preud'homme
*
* Based on i386-gen.c by Fabrice Bellard
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if defined(TCC_ARM_EABI) && !defined(TCC_ARM_VFP)
#error "Currently TinyCC only supports float computation with VFP instructions"
#endif
#ifndef CONFIG_TCC_CPUVER
#define CONFIG_TCC_CPUVER 5
#endif
#include "arm-thumb-defs.h"
#include "ir/opt.h"
#include "tcc.h"
#include "tccir.h"
#include "tccls.h"
#include "tcctype.h"
static void load_full_const(int r, int r1, uint32_t imm_lo, uint32_t imm_hi);
/* Workaround for TCC ARM ABI bugs:
* 1. int64_t args miscount register pairs 2. 5th+ args not correctly pushed to stack
* By passing sym through a file-scope global, load_full_const stays at 4 register args.
* Set _lfc_sym before calling load_full_const; it is consumed and reset to NULL inside. */
static struct Sym *_lfc_sym;
/* Helper macro: split a 64-bit value into (lo, hi) uint32_t pair for load_full_const.
* Avoids int64_t in function signatures — TCC ARM codegen miscounts int64_t register pairs. */
#define LFC_SPLIT(v) (uint32_t)((uint64_t)(v)), (uint32_t)((uint64_t)(v) >> 32)
ThumbGeneratorState thumb_gen_state;
enum Armv8mRegisters
{
ARM_R0 = 0,
ARM_R1 = 1,
ARM_R2 = 2,
ARM_R3 = 3,
ARM_R4 = 4,
ARM_R5 = 5,
ARM_R6 = 6,
ARM_R7 = 7,
ARM_R8 = 8,
ARM_R9 = 9,
ARM_R10 = 10,
ARM_R11 = 11,
ARM_R12 = 12,
ARM_SP = 13,
ARM_LR = 14,
ARM_PC = 15
};
#define USING_GLOBALS
#include "tcc.h"
#include <stdlib.h>
/* Target ABI hook: AAPCS-like argument assignment for ARM (R0-R3 + stack).
*
* This is a pure layout function: it does not materialize values and does not
* touch SP. IR can use it to lower calls into explicit CALLSEQ/CALLARG ops.
*/
ST_FUNC int tcc_gen_machine_abi_assign_call_args(const TCCAbiArgDesc *args, int argc, TCCAbiCallLayout *out_layout)
{
if (!out_layout || (argc > 0 && (!args || !out_layout->locs)))
return -1;
/* Initialize layout state for ABI classification */
TCCAbiCallLayout call_layout;
memset(&call_layout, 0, sizeof(call_layout));
call_layout.locs = out_layout->locs;
call_layout.capacity = out_layout->capacity;
call_layout.next_reg = 0; /* ARM AAPCS: start with R0 */
call_layout.next_stack_off = 0; /* start at stack base */
call_layout.stack_align = 8; /* ARM requires 8-byte SP alignment */
for (int i = 0; i < argc; ++i)
{
const TCCAbiArgDesc *ad = &args[i];
out_layout->locs[i] = tcc_abi_classify_argument(&call_layout, i, ad);
}
/* Copy computed layout info from temporary layout to output */
out_layout->stack_size = call_layout.stack_size;
out_layout->argc = argc;
out_layout->stack_align = call_layout.stack_align;
return 0;
}
#include "arch/fpu/arm/fpv5-sp-d16.h"
#include "arm-thumb-opcodes.h"
#include <inttypes.h>
int load_word_from_base(int ir, int base, int fc, int sign);
/* Helper to validate a Sym pointer - returns NULL if invalid/unusable for relocation */
static inline Sym *validate_sym_for_reloc(Sym *sym)
{
if (!sym)
return NULL;
/* Type descriptors (SYM_FIELD) should not be used for relocations */
if (sym->v & SYM_FIELD)
{
fprintf(stderr, "[TCC-DIAG] validate_sym_for_reloc: sym->v=0x%x has SYM_FIELD, c=%d\n", sym->v, sym->c);
return NULL;
}
/* Symbols with c < 0 are not properly registered */
if (sym->c < 0)
{
const char *name = get_tok_str(sym->v & ~SYM_FIELD, NULL);
fprintf(stderr, "[TCC-DIAG] validate_sym_for_reloc: sym '%s' has c=%d (<0)\n", name ? name : "?", sym->c);
return NULL;
}
return sym;
}
ST_DATA const char *const target_machine_defs = "__arm__\0"
"__arm\0"
"arm\0"
"__arm_elf__\0"
"__arm_elf\0"
"arm_elf\0"
#if defined TCC_TARGET_ARM_ARCHV8M
"__ARM_ARCH_8M__\0"
"__ARM_ARCH_EXT_IDIV__\0"
"__thumb__\0"
#endif // TCC_TARGET_ARM_ARCHV8M
"__VFP_FP__\0"
"__ARMEL__\0"
"__APCS_32__\0"
#if defined TCC_ARM_EABI
"__ARM_EABI__\0"
#endif
;
/* Register class array - maps each register to its class flags */
ST_DATA const int reg_classes[NB_REGS] = {
RC_INT | RC_R0, RC_INT | RC_R1, RC_INT | RC_R2, RC_INT | RC_R3, RC_INT | RC_R12,
RC_FLOAT | RC_F0, RC_FLOAT | RC_F1, RC_FLOAT | RC_F2, RC_FLOAT | RC_F3,
#ifdef TCC_ARM_VFP
RC_FLOAT | RC_F4, RC_FLOAT | RC_F5, RC_FLOAT | RC_F6, RC_FLOAT | RC_F7,
#endif
};
enum float_abi float_abi;
unsigned char text_and_data_separation;
unsigned char pic;
int offset_to_args = 0;
thumb_flags_behaviour g_setflags = FLAGS_BEHAVIOUR_SET;
uint32_t caller_saved_registers;
uint32_t pushed_registers;
int allocated_stack_size;
int callee_push_size = 0; /* bytes pushed BELOW FP in two-phase push */
uint32_t callee_saved_regs = 0; /* register mask for second push (below FP) */
int vararg_push_size = 0; /* bytes pushed for variadic r0-r3 save (16 or 0) */
/* Adjust a local/spill frame offset when two-phase push is active and
* callee-saved regs are pushed below FP. Only adjusts negative non-param
* offsets (locals/spills); positive and param offsets are unchanged. */
static inline int fp_adjust_local_offset(int frame_offset, int is_param)
{
if (!is_param && frame_offset < 0 && callee_push_size > 0)
return frame_offset - callee_push_size;
return frame_offset;
}
/* Additional scratch register exclusions (e.g. to protect argument registers
* while materializing an indirect call target). Applied on top of per-call
* exclude masks. */
static uint32_t scratch_global_exclude = 0;
/* Track registers that were PUSH'ed by get_scratch_reg_with_save() in ORDER.
* We must POP in reverse order since ARM POP with register lists always pops
* in register-number order, not stack order.
* Size 128 since same register can be pushed multiple times for complex ops like
* function calls with many arguments. */
static int scratch_push_stack[128];
static int scratch_push_count = 0;
/* Debug tracking: current IR opcode being processed (set by codegen.c) */
int g_debug_current_op = -1;
int is_valid_opcode(thumb_opcode op);
int ot(thumb_opcode op);
int ot_check(thumb_opcode op);
static void thumb_require_materialized_reg(const char *ctx, const char *operand, int reg);
static bool thumb_is_hw_reg(int reg);
static int get_struct_base_addr_mop(const MachineOperand *mop, int default_reg);
int th_has_immediate_value(int r);
int load_word_from_base(int ir, int base, int fc, int sign);
int th_patch_call(int t, int a);
/* Structure to track scratch register allocation with potential save/restore */
typedef struct ScratchRegAlloc
{
int reg : 30; /* The allocated scratch register (range 0-15 for ARM) */
uint32_t saved : 1; /* Whether the register was pushed to stack (real emit only) */
uint32_t would_save : 1; /* Whether a push was needed (set in both dry-run and real emit) */
} ScratchRegAlloc;
/* Forward declarations needed by multi-scratch helpers. */
static ScratchRegAlloc get_scratch_reg_with_save(uint32_t exclude_regs);
static void restore_scratch_reg(ScratchRegAlloc *alloc);
static void load_from_base(int r, int r1, int irop_btype, int is_unsigned, int fc, int sign, uint32_t base);
static void th_store32_imm_or_reg_ex(int src_reg, uint32_t base_reg, int abs_off, int sign, uint32_t extra_exclude);
/* Resolve the base register for a captured variable access.
* For depth 1, returns R10 directly.
* For depth > 1, emits LDR chain to follow ancestor frame pointers
* and returns a scratch register holding the target ancestor's FP.
* Caller must restore scratch via *out_scratch when done. */
static int resolve_chain_base(TCCIRState *ir, int ci, uint32_t exclude_regs, ScratchRegAlloc *out_scratch,
int *used_scratch)
{
int depth = ir->captured_chain_depths[ci];
if (depth <= 1)
{
*used_scratch = 0;
return architecture_config.static_chain_reg; /* R10 */
}
/* Multi-hop: follow chain through (depth - 1) intermediate frames.
* Each frame saves its incoming R10 at [FP - 4] (CHAIN_SLOT_OFFSET). */
*out_scratch = get_scratch_reg_with_save(exclude_regs);
*used_scratch = 1;
/* Start from R10 (points to immediate parent's FP) */
thumb_shift no_shift = {THUMB_SHIFT_NONE, 0, THUMB_SHIFT_IMMEDIATE};
ot_check(th_mov_reg(out_scratch->reg, architecture_config.static_chain_reg, FLAGS_BEHAVIOUR_NOT_IMPORTANT, no_shift,
ENFORCE_ENCODING_NONE, false));
for (int hop = 1; hop < depth; hop++)
{
/* LDR temp, [temp, #-4] — follow chain link */
load_from_base(out_scratch->reg, PREG_REG_NONE, IROP_BTYPE_INT32, 0, 4 /* abs */, 1 /* sign: negative */,
out_scratch->reg);
}
return out_scratch->reg;
}
typedef struct ScratchRegAllocs
{
int regs[8]; /* The allocated scratch registers */
int count; /* Number of registers allocated */
uint32_t saved_mask; /* Bitmask of registers that were saved (pushed) */
} ScratchRegAllocs;
/* ============================================================
* MachineCodegenContext — per-instruction scratch-register tracker
* ============================================================
* Used by the MachineOperand-based (_mop) code-generation path.
* Callers allocate scratches via mach_alloc_scratch(), then call
* mach_release_all() at the end of the instruction to pop them in LIFO order.
*/
/* Forward declarations needed by the mach_* helpers (defined later in this file). */
typedef thumb_opcode (*thumb_imm_handler_t)(uint32_t rd, uint32_t rn, uint32_t imm,
thumb_flags_behaviour flags_behaviour,
thumb_enforce_encoding enforce_encoding);
int store_word_to_base(int ir, int base, int fc, int sign);
static ScratchRegAlloc th_offset_to_reg_ex(int off, int sign, uint32_t exclude_regs);
#define MACH_CTX_MAX_SCRATCH 12
typedef struct MachineCodegenContext
{
ScratchRegAlloc scratches[MACH_CTX_MAX_SCRATCH];
int n_scratch;
} MachineCodegenContext;
/* Phase-3 per-instruction scratch constraint counters.
* Incremented/set by mach_alloc_scratch(); reset and read via the
* tcc_gen_machine_insn_scratch_*() public functions.
* Declared here (before mach_alloc_scratch) to avoid a forward-reference to
* dry_run_state which is defined later in the file. */
static int g_insn_scratch_allocs = 0; /* total scratch allocs this instruction */
static uint16_t g_insn_scratch_saves = 0; /* registers that required PUSH this instruction */
/* Allocate a scratch register for the current instruction.
* excl: bitmask of registers that must not be chosen.
* The allocation is recorded in ctx so mach_release_all() can free it. */
static int mach_alloc_scratch(MachineCodegenContext *ctx, uint32_t excl)
{
if (ctx->n_scratch >= MACH_CTX_MAX_SCRATCH)
tcc_error("compiler_error: mach_alloc_scratch: per-instruction scratch limit exceeded");
ScratchRegAlloc alloc = get_scratch_reg_with_save(excl);
ctx->scratches[ctx->n_scratch++] = alloc;
/* Phase-3 constraint recording: track count and save-mask per instruction.
* Reset with tcc_gen_machine_insn_scratch_reset() before each dispatch call;
* read back with the tcc_gen_machine_insn_scratch_*() accessors after it. */
g_insn_scratch_allocs++;
if (alloc.would_save)
g_insn_scratch_saves |= (uint16_t)(1u << (unsigned)alloc.reg);
return alloc.reg;
}
/* Release all scratch registers allocated for the current instruction in
* reverse (LIFO) order — required because ARM push/pop works by register
* number, so the last-pushed register must be popped first. */
static void mach_release_all(MachineCodegenContext *ctx)
{
for (int i = ctx->n_scratch - 1; i >= 0; i--)
restore_scratch_reg(&ctx->scratches[i]);
ctx->n_scratch = 0;
}
/* Ensure a MachineOperand is in a physical register and return that register.
*
* For MACH_OP_REG without needs_deref: returns the register directly (no code).
* For all other kinds (SPILL, IMM, FRAME_ADDR, SYMBOL, PARAM_STACK) or
* MACH_OP_REG with needs_deref: allocates a scratch register, emits the
* necessary load instructions, and returns the scratch register.
*
* excl: bitmask of registers that must not be used for any scratch. */
static int mach_ensure_in_reg(MachineCodegenContext *ctx, const MachineOperand *op, uint32_t excl)
{
switch (op->kind)
{
case MACH_OP_REG:
if (!op->needs_deref)
return op->u.reg.r0;
{
/* Register-indirect: op->u.reg.r0 is an address; load the value. */
int r = mach_alloc_scratch(ctx, excl | (1u << (uint32_t)op->u.reg.r0));
load_from_base(r, PREG_REG_NONE, op->btype, (int)op->is_unsigned, 0, 0, (uint32_t)op->u.reg.r0);
return r;
}
case MACH_OP_SPILL:
if (!op->needs_deref)
{
/* Simple spill: load the word-sized register value from the spill slot. */
int r = mach_alloc_scratch(ctx, excl);
tcc_machine_load_spill_slot(r, op->u.spill.offset);
return r;
}
else
{
/* Double indirection (VT_LLOCAL): the spill slot holds a pointer.
* Step 1: load the pointer from the spill slot.
* Step 2: dereference the pointer to get the actual value. */
int ptr_r = mach_alloc_scratch(ctx, excl);
tcc_machine_load_spill_slot(ptr_r, op->u.spill.offset);
int val_r = mach_alloc_scratch(ctx, excl | (1u << (uint32_t)ptr_r));
load_from_base(val_r, PREG_REG_NONE, op->btype, (int)op->is_unsigned, 0, 0, (uint32_t)ptr_r);
return val_r;
}
case MACH_OP_IMM:
{
int r = mach_alloc_scratch(ctx, excl);
tcc_machine_load_constant(r, PREG_REG_NONE, op->u.imm.val, 0, NULL);
return r;
}
case MACH_OP_FRAME_ADDR:
{
/* Compute the address FP + offset (address-of a local variable). */
int r = mach_alloc_scratch(ctx, excl);
tcc_machine_addr_of_stack_slot(r, op->u.frame.offset, 0 /* not param */);
return r;
}
case MACH_OP_SYMBOL:
{
int r = mach_alloc_scratch(ctx, excl);
Sym *raw_sym = op->u.sym.sym;
Sym *sym = raw_sym ? validate_sym_for_reloc(raw_sym) : NULL;
if (!op->needs_deref)
{
/* Load symbol address (with addend baked in). */
tcc_machine_load_constant(r, PREG_REG_NONE, op->u.sym.addend, 0, sym);
}
else
{
/* Load symbol address into a scratch base reg, then dereference. */
int base = mach_alloc_scratch(ctx, excl | (1u << (uint32_t)r));
tcc_machine_load_constant(base, PREG_REG_NONE, 0, 0, sym);
const int32_t addend = op->u.sym.addend;
load_from_base(r, PREG_REG_NONE, op->btype, (int)op->is_unsigned, addend < 0 ? (int)(-addend) : (int)addend,
addend < 0 ? 1 : 0, (uint32_t)base);
}
return r;
}
case MACH_OP_PARAM_STACK:
{
/* Stack-passed parameter: always load the value from the caller's argument
* frame. NOTE: needs_deref may be false here (cleared by mach_resolve_deref_64
* for 64-bit split operands), but the load is still required — needs_deref=false
* in this context means "not a pointer-to-follow", not "compute address". */
int r = mach_alloc_scratch(ctx, excl);
const int adjusted = op->u.param.offset + offset_to_args;
const int base_reg = tcc_state->need_frame_pointer ? R_FP : R_SP;
const int sign = (adjusted < 0);
const int abs_off = sign ? -adjusted : adjusted;
load_from_base(r, PREG_REG_NONE, op->btype, (int)op->is_unsigned, abs_off, sign, (uint32_t)base_reg);
return r;
}
case MACH_OP_CHAIN_REL:
{
/* Captured variable: load from parent frame via static chain. */
ScratchRegAlloc chain_scratch = {0};
int chain_used = 0;
int base = resolve_chain_base(tcc_state->ir, op->u.chain.chain_index, excl, &chain_scratch, &chain_used);
int r = mach_alloc_scratch(ctx, excl | (1u << (uint32_t)base));
int32_t off = op->u.chain.offset;
int sign = (off < 0);
int abs_off = sign ? (int)(-off) : (int)off;
load_from_base(r, PREG_REG_NONE, op->btype, (int)op->is_unsigned, abs_off, sign, (uint32_t)base);
if (chain_used)
restore_scratch_reg(&chain_scratch);
return r;
}
default:
tcc_error("compiler_error: mach_ensure_in_reg: unhandled kind %d", (int)op->kind);
return PREG_REG_NONE;
}
}
/* Try to emit an immediate-form instruction for src2; if the encoding succeeds,
* sets *imm_emitted=true and returns PREG_REG_NONE. Otherwise loads src2 into
* a scratch register and returns it (like mach_ensure_in_reg). */
static int mach_ensure_imm_or_reg(MachineCodegenContext *ctx, const MachineOperand *op, uint32_t excl,
thumb_imm_handler_t imm_handler, int dest_reg, int src1_reg,
thumb_flags_behaviour flags, bool *imm_emitted)
{
*imm_emitted = false;
if (op->kind == MACH_OP_IMM && imm_handler)
{
const uint32_t imm_val = (uint32_t)op->u.imm.val;
if (ot(imm_handler((uint32_t)dest_reg, (uint32_t)src1_reg, imm_val, flags, ENFORCE_ENCODING_NONE)))
{
*imm_emitted = true;
return PREG_REG_NONE;
}
}
return mach_ensure_in_reg(ctx, op, excl);
}
/* Determine (or allocate) the destination register for the current instruction.
* Returns the physical register that should hold the result.
* If the destination is a spill slot or needs pointer write-back, allocates a
* scratch; call mach_writeback_dest() after emitting the instruction. */
static int mach_get_dest_reg(MachineCodegenContext *ctx, const MachineOperand *op, uint32_t excl)
{
if (!op || op->kind == MACH_OP_NONE)
return R0; /* CMP / flag-setting ops: Rd is ignored. */
switch (op->kind)
{
case MACH_OP_REG:
if (!op->needs_deref && op->u.reg.r0 != (int)PREG_REG_NONE)
return op->u.reg.r0;
/* No pre-allocated register or store-through-pointer: need scratch. */
return mach_alloc_scratch(ctx, excl);
case MACH_OP_SPILL:
case MACH_OP_FRAME_ADDR:
case MACH_OP_PARAM_STACK:
case MACH_OP_CHAIN_REL:
case MACH_OP_SYMBOL:
return mach_alloc_scratch(ctx, excl);
default:
tcc_error("compiler_error: mach_get_dest_reg: unexpected kind %d", (int)op->kind);
return PREG_REG_NONE;
}
}
/* Store the result in 'reg' back to the destination described by *op.
* Only needed when the destination was a spill slot, stack parameter, or an
* lvalue (store-through-pointer). Must be called after mach_get_dest_reg()
* allocated a scratch for those cases. */
static void mach_writeback_dest(const MachineOperand *op, int reg)
{
if (!op || op->kind == MACH_OP_NONE)
return;
switch (op->kind)
{
case MACH_OP_REG:
if (!op->needs_deref)
{
if (reg != op->u.reg.r0 && op->u.reg.r0 != (int)PREG_REG_NONE)
ot_check(th_mov_reg((uint32_t)op->u.reg.r0, (uint32_t)reg, FLAGS_BEHAVIOUR_NOT_IMPORTANT, THUMB_SHIFT_DEFAULT,
ENFORCE_ENCODING_NONE, false));
}
else
{
/* Store through pointer. */
if (!store_word_to_base(reg, op->u.reg.r0, 0, 0))
{
uint32_t excl = (1u << (uint32_t)reg) | (1u << (uint32_t)op->u.reg.r0);
ScratchRegAlloc rr = get_scratch_reg_with_save(excl);
ot_check(th_str_reg((uint32_t)reg, (uint32_t)op->u.reg.r0, (uint32_t)rr.reg, THUMB_SHIFT_DEFAULT,
ENFORCE_ENCODING_NONE));
restore_scratch_reg(&rr);
}
}
break;
case MACH_OP_SPILL:
tcc_machine_store_spill_slot(reg, op->u.spill.offset);
break;
case MACH_OP_FRAME_ADDR:
/* Local stack slot address used as an lvalue destination. Write the
* result back to the underlying frame slot. */
tcc_machine_store_spill_slot(reg, op->u.frame.offset);
break;
case MACH_OP_PARAM_STACK:
tcc_machine_store_param_slot(reg, op->u.param.offset);
break;
case MACH_OP_CHAIN_REL:
{
/* Captured variable: store to parent frame via static chain. */
ScratchRegAlloc chain_scratch = {0};
int chain_used = 0;
uint32_t excl = (1u << (uint32_t)reg);
int base = resolve_chain_base(tcc_state->ir, op->u.chain.chain_index, excl, &chain_scratch, &chain_used);
int32_t off = op->u.chain.offset;
int sign = (off < 0);
int abs_off = sign ? (int)(-off) : (int)off;
if (!store_word_to_base(reg, base, abs_off, sign))
{
ScratchRegAlloc rr = th_offset_to_reg_ex(abs_off, sign, excl | (1u << (uint32_t)base));
ot_check(th_str_reg((uint32_t)reg, (uint32_t)base, (uint32_t)rr.reg, THUMB_SHIFT_DEFAULT, ENFORCE_ENCODING_NONE));
restore_scratch_reg(&rr);
}
if (chain_used)
restore_scratch_reg(&chain_scratch);
break;
}
case MACH_OP_SYMBOL:
{
/* Global variable: load symbol address, then store through it. */
Sym *sym = op->u.sym.sym ? validate_sym_for_reloc(op->u.sym.sym) : NULL;
uint32_t excl = (1u << (uint32_t)reg);
ScratchRegAlloc rr = get_scratch_reg_with_save(excl);
tcc_machine_load_constant(rr.reg, PREG_REG_NONE, 0, 0, sym);
const int32_t addend = op->u.sym.addend;
const int abs_off = addend < 0 ? (int)(-addend) : (int)addend;
const int sign = addend < 0 ? 1 : 0;
if (!store_word_to_base(reg, rr.reg, abs_off, sign))
{
ScratchRegAlloc rr2 = th_offset_to_reg_ex(abs_off, sign, excl | (1u << (uint32_t)rr.reg));
ot_check(
th_str_reg((uint32_t)reg, (uint32_t)rr.reg, (uint32_t)rr2.reg, THUMB_SHIFT_DEFAULT, ENFORCE_ENCODING_NONE));
restore_scratch_reg(&rr2);
}
restore_scratch_reg(&rr);
break;
}
default:
tcc_error("compiler_error: mach_writeback_dest: unexpected kind %d", (int)op->kind);
}
}
/* Public wrappers for inline asm codegen (arm-thumb-asm.c). These
* materialise a MachineOperand into/from a specific physical register,
* managing scratch allocation internally.
*
* tcc_gen_mach_load_to_reg loads directly into dest_reg whenever possible
* (no scratch intermediary) to avoid clobbering other live registers —
* critical when asm_gen_code loads multiple operands sequentially. */
void tcc_gen_mach_load_to_reg(int dest_reg, const MachineOperand *op)
{
switch (op->kind)
{
case MACH_OP_REG:
if (!op->needs_deref)
{
if (op->u.reg.r0 != dest_reg)
ot_check(th_mov_reg((uint32_t)dest_reg, (uint32_t)op->u.reg.r0, FLAGS_BEHAVIOUR_NOT_IMPORTANT,
THUMB_SHIFT_DEFAULT, ENFORCE_ENCODING_NONE, false));
return;
}
/* Register-indirect: r0 is an address, load [r0] into dest_reg. */
load_from_base(dest_reg, PREG_REG_NONE, op->btype, (int)op->is_unsigned, 0, 0, (uint32_t)op->u.reg.r0);
return;
case MACH_OP_SPILL:
if (!op->needs_deref)
{
tcc_machine_load_spill_slot(dest_reg, op->u.spill.offset);
return;
}
else
{
/* Double indirection (VT_LLOCAL): spill slot holds a pointer.
* Load pointer into dest_reg, then dereference into dest_reg. */
tcc_machine_load_spill_slot(dest_reg, op->u.spill.offset);
load_from_base(dest_reg, PREG_REG_NONE, op->btype, (int)op->is_unsigned, 0, 0, (uint32_t)dest_reg);
return;
}
case MACH_OP_IMM:
tcc_machine_load_constant(dest_reg, PREG_REG_NONE, op->u.imm.val, 0, NULL);
return;
case MACH_OP_FRAME_ADDR:
tcc_machine_addr_of_stack_slot(dest_reg, op->u.frame.offset, 0);
return;
case MACH_OP_SYMBOL:
{
Sym *sym = op->u.sym.sym ? validate_sym_for_reloc(op->u.sym.sym) : NULL;
if (!op->needs_deref)
{
tcc_machine_load_constant(dest_reg, PREG_REG_NONE, op->u.sym.addend, 0, sym);
return;
}
/* Symbol deref: load address into dest_reg as scratch, then dereference.
* Use get_scratch_reg_with_save for the base so it won't clobber dest_reg. */
{
uint32_t excl = (1u << (uint32_t)dest_reg);
ScratchRegAlloc base_alloc = get_scratch_reg_with_save(excl);
tcc_machine_load_constant(base_alloc.reg, PREG_REG_NONE, 0, 0, sym);
const int32_t addend = op->u.sym.addend;
load_from_base(dest_reg, PREG_REG_NONE, op->btype, (int)op->is_unsigned,
addend < 0 ? (int)(-addend) : (int)addend, addend < 0 ? 1 : 0, (uint32_t)base_alloc.reg);
restore_scratch_reg(&base_alloc);
}
return;
}
case MACH_OP_PARAM_STACK:
{
const int adjusted = op->u.param.offset + offset_to_args;
const int base_reg = tcc_state->need_frame_pointer ? R_FP : R_SP;
const int sign = (adjusted < 0);
const int abs_off = sign ? -adjusted : adjusted;
load_from_base(dest_reg, PREG_REG_NONE, op->btype, (int)op->is_unsigned, abs_off, sign, (uint32_t)base_reg);
return;
}
case MACH_OP_CHAIN_REL:
{
ScratchRegAlloc chain_scratch = {0};
int chain_used = 0;
uint32_t excl = (1u << (uint32_t)dest_reg);
int base = resolve_chain_base(tcc_state->ir, op->u.chain.chain_index, excl, &chain_scratch, &chain_used);
int32_t off = op->u.chain.offset;
int sign = (off < 0);
int abs_off = sign ? (int)(-off) : (int)off;
load_from_base(dest_reg, PREG_REG_NONE, op->btype, (int)op->is_unsigned, abs_off, sign, (uint32_t)base);
if (chain_used)
restore_scratch_reg(&chain_scratch);
return;
}
default:
{
/* Fallback: use scratch + mov for anything unexpected. */
MachineCodegenContext ctx = {{}, 0};
int r = mach_ensure_in_reg(&ctx, op, (1u << (uint32_t)dest_reg));
if (r != dest_reg)
ot_check(th_mov_reg((uint32_t)dest_reg, (uint32_t)r, FLAGS_BEHAVIOUR_NOT_IMPORTANT, THUMB_SHIFT_DEFAULT,
ENFORCE_ENCODING_NONE, false));
mach_release_all(&ctx);
return;
}
}
}
void tcc_gen_mach_store_from_reg(int src_reg, const MachineOperand *op)
{
mach_writeback_dest(op, src_reg);
}
/* ============================================================
* Dry-Run Code Generation State
* ============================================================
* Two-pass code generation system for optimal register allocation.
* Pass 1 (Dry Run): Analyze register needs without emitting code
* Pass 2 (Real Emit): Generate code with optimal prologue based on Pass 1
*/
typedef struct CodeGenDryRunState
{
int active; /* 1 = dry run, 0 = real emit */
uint32_t scratch_regs_pushed; /* Bitmap of regs pushed as scratch */
int scratch_push_count; /* Total scratch push operations */
int lr_push_count; /* Times LR specifically was pushed */
int instruction_count; /* IR instructions processed */
} CodeGenDryRunState;
static CodeGenDryRunState dry_run_state;
/* Separate literal pool for dry-run mode to avoid modifying the real pool.
* This allows accurate code size tracking without affecting the real pass. */
static ThumbLiteralPoolEntry *dry_run_literal_pool = NULL;
static int dry_run_literal_pool_count = 0;
static int dry_run_literal_pool_size = 0;
/* Hash table for O(1) literal pool lookups instead of O(n) linear search.
* Key: (sym, imm), Value: index into literal pool array.
* Using open addressing with linear probing. */
#define LITERAL_POOL_HASH_SIZE 256 /* Power of 2 for fast modulo */
typedef struct LiteralPoolHashEntry
{
Sym *sym;
int64_t imm;
int pool_index; /* Index into literal pool array, or -1 if empty */
int valid; /* 1 if this slot contains a valid entry, 0 if empty */
} LiteralPoolHashEntry;
static LiteralPoolHashEntry literal_pool_hash[LITERAL_POOL_HASH_SIZE];
static LiteralPoolHashEntry dry_run_literal_pool_hash[LITERAL_POOL_HASH_SIZE];
static inline uint32_t literal_pool_hash_func(Sym *sym, int64_t imm)
{
/* Simple hash combining pointer and immediate value */
uint64_t h = (uint64_t)(uintptr_t)sym;
h ^= (uint64_t)imm;
h ^= h >> 33;
h *= 0xff51afd7ed558ccdULL;
h ^= h >> 33;
return (uint32_t)(h & (LITERAL_POOL_HASH_SIZE - 1));
}
static void literal_pool_hash_clear(LiteralPoolHashEntry *hash)
{
for (int i = 0; i < LITERAL_POOL_HASH_SIZE; i++)
{
hash[i].valid = 0;
hash[i].pool_index = -1;
}
}
static int literal_pool_hash_find(LiteralPoolHashEntry *hash, Sym *sym, int64_t imm)
{
uint32_t idx = literal_pool_hash_func(sym, imm);
for (int i = 0; i < LITERAL_POOL_HASH_SIZE; i++)
{
uint32_t probe = (idx + i) & (LITERAL_POOL_HASH_SIZE - 1);
if (!hash[probe].valid)
{
return -1; /* Empty slot - not found */
}
if (hash[probe].sym == sym && hash[probe].imm == imm)
{
return hash[probe].pool_index;
}
}
return -1; /* Table full, not found */
}
static void literal_pool_hash_insert(LiteralPoolHashEntry *hash, Sym *sym, int64_t imm, int pool_index)
{
uint32_t idx = literal_pool_hash_func(sym, imm);
for (int i = 0; i < LITERAL_POOL_HASH_SIZE; i++)
{
uint32_t probe = (idx + i) & (LITERAL_POOL_HASH_SIZE - 1);
if (!hash[probe].valid)
{
hash[probe].sym = sym;
hash[probe].imm = imm;
hash[probe].pool_index = pool_index;
hash[probe].valid = 1;
return;
}
}
/* Table full - this shouldn't happen with reasonable pool sizes */
}
static void dry_run_init(void)
{
memset(&dry_run_state, 0, sizeof(dry_run_state));
}
static void dry_run_record_push(int reg)
{
dry_run_state.scratch_regs_pushed |= (1u << reg);
dry_run_state.scratch_push_count++;
if (reg == R_LR)
dry_run_state.lr_push_count++;
}
/* Structure to save/restore thumb_gen_state for dry-run isolation */
typedef struct ThumbGenStateSnapshot
{
int code_size;
int literal_pool_count;
int literal_pool_size;
ThumbLiteralPoolEntry *literal_pool;
Sym *cached_global_sym;
int cached_global_reg;
int function_argument_count;
int call_sites_by_id_size;
ThumbGenCallSite *call_sites_by_id;
} ThumbGenStateSnapshot;
static ThumbGenStateSnapshot dry_run_snapshot;
static void thumb_gen_state_snapshot_save(ThumbGenStateSnapshot *snap)
{
snap->code_size = thumb_gen_state.code_size;
snap->literal_pool_count = thumb_gen_state.literal_pool_count;
snap->literal_pool_size = thumb_gen_state.literal_pool_size;
snap->literal_pool = thumb_gen_state.literal_pool;
snap->cached_global_sym = thumb_gen_state.cached_global_sym;
snap->cached_global_reg = thumb_gen_state.cached_global_reg;
snap->function_argument_count = thumb_gen_state.function_argument_count;
/* call_sites_by_id is more complex - save pointer and size */
snap->call_sites_by_id_size = thumb_gen_state.call_sites_by_id_size;
snap->call_sites_by_id = thumb_gen_state.call_sites_by_id;
}
static void thumb_gen_state_snapshot_restore(ThumbGenStateSnapshot *snap)
{
thumb_gen_state.code_size = snap->code_size;
/* Free any literal pool array allocated during dry-run (if reallocated) */
if (thumb_gen_state.literal_pool != snap->literal_pool)
{
tcc_free(thumb_gen_state.literal_pool);
}
thumb_gen_state.literal_pool = snap->literal_pool;
thumb_gen_state.literal_pool_count = snap->literal_pool_count;
thumb_gen_state.literal_pool_size = snap->literal_pool_size;
thumb_gen_state.cached_global_sym = snap->cached_global_sym;
thumb_gen_state.cached_global_reg = snap->cached_global_reg;
thumb_gen_state.function_argument_count = snap->function_argument_count;
/* Free any call sites created during dry-run */
if (thumb_gen_state.call_sites_by_id != snap->call_sites_by_id)
{
tcc_free(thumb_gen_state.call_sites_by_id);
}
thumb_gen_state.call_sites_by_id = snap->call_sites_by_id;
thumb_gen_state.call_sites_by_id_size = snap->call_sites_by_id_size;
}
/* ============================================================
* Branch Instruction Optimization State
* ============================================================
* Tracks branch instructions during dry-run to select optimal
* 16-bit vs 32-bit encodings based on actual jump distances.
*/
typedef enum
{
BRANCH_ENC_UNKNOWN = 0,
BRANCH_ENC_16BIT = 16,
BRANCH_ENC_32BIT = 32
} BranchEncoding;
typedef struct BranchInfo
{
int ir_index; /* IR instruction index of the branch */
int source_addr; /* Code address where branch is emitted */
int target_ir; /* Target IR instruction index */
int target_addr; /* Target code address (computed after dry-run) */
int offset; /* Computed offset = target - source - 4 */
int is_conditional; /* 1 = conditional (JUMPIF), 0 = unconditional (JUMP) */
BranchEncoding encoding; /* Selected encoding after analysis */
} BranchInfo;
typedef struct BranchOptState
{
BranchInfo *branches; /* Array of branch info */
int branch_count; /* Number of branches */
int branch_capacity; /* Allocated capacity */
int optimization_enabled; /* Flag to enable/disable */
int code_size_reduction; /* Total bytes saved */
} BranchOptState;
static BranchOptState branch_opt_state;
/* Forward declarations */
static void branch_opt_init(void);
static void branch_opt_record(int ir_index, int source_addr, int target_ir, int is_conditional);
static void branch_opt_analyze(uint32_t *ir_to_code_mapping, int mapping_size);
/* Public accessor for branch encoding - returns 16 or 32 */
ST_FUNC int tcc_gen_machine_branch_opt_get_encoding(int ir_index)
{
for (int i = 0; i < branch_opt_state.branch_count; i++)
{
if (branch_opt_state.branches[i].ir_index == ir_index)
{
return branch_opt_state.branches[i].encoding == BRANCH_ENC_16BIT ? 16 : 32;
}
}
return 32; /* Conservative fallback */
}
static BranchEncoding branch_opt_get_encoding(int ir_index);
/* Check if offset fits in 16-bit conditional branch (T1 encoding)
* Range: -256 to +254 bytes (imm8 * 2), must be even */
static int branch_fits_t1(int offset)
{
return (offset >= -256 && offset <= 254 && (offset & 1) == 0);
}
/* Check if offset fits in 16-bit unconditional branch (T2 encoding)
* Range: -2048 to +2046 bytes (imm11 * 2), must be even */
static int branch_fits_t2(int offset)
{
return (offset >= -2048 && offset <= 2046 && (offset & 1) == 0);
}
/* Initialize branch optimization state */
static void branch_opt_init(void)
{
branch_opt_state.branch_count = 0;
branch_opt_state.optimization_enabled = 0; /* Disabled: dry-run addresses diverge from real pass */
branch_opt_state.code_size_reduction = 0;
if (!branch_opt_state.branches)
{
branch_opt_state.branch_capacity = 64;
branch_opt_state.branches = tcc_malloc(branch_opt_state.branch_capacity * sizeof(BranchInfo));
}
}
/* Record a branch for later optimization analysis */
static void branch_opt_record(int ir_index, int source_addr, int target_ir, int is_conditional)
{
if (!branch_opt_state.optimization_enabled)
return;
/* Grow array if needed */
if (branch_opt_state.branch_count >= branch_opt_state.branch_capacity)
{
branch_opt_state.branch_capacity *= 2;
branch_opt_state.branches =
tcc_realloc(branch_opt_state.branches, branch_opt_state.branch_capacity * sizeof(BranchInfo));
}
BranchInfo *b = &branch_opt_state.branches[branch_opt_state.branch_count++];
b->ir_index = ir_index;
b->source_addr = source_addr;
b->target_ir = target_ir;
b->target_addr = -1; /* Unknown until targets resolved */
b->offset = 0;
b->is_conditional = is_conditional;
b->encoding = BRANCH_ENC_32BIT; /* Conservative default */
}
/* Analyze branch offsets and select optimal encodings.
* Uses iterative relaxation: shrinking branches may enable more 16-bit branches.
*/
static void branch_opt_analyze(uint32_t *ir_to_code_mapping, int mapping_size)
{
if (!branch_opt_state.optimization_enabled || branch_opt_state.branch_count == 0)
return;
/* Phase 1: Resolve target addresses from dry-run mapping */
for (int i = 0; i < branch_opt_state.branch_count; i++)
{
BranchInfo *b = &branch_opt_state.branches[i];
if (b->target_ir >= 0 && b->target_ir < mapping_size)
{
b->target_addr = ir_to_code_mapping[b->target_ir];
}
else
{
b->target_addr = b->source_addr; /* Self-loop fallback */
}