#include <stdio.h>
#include "misc.h"
#include "mpconfig.h"
#include "gc.h"

#if MICROPY_ENABLE_GC

extern void *stack_top;

#ifdef __x86_64__
typedef machine_uint_t regs_t[6];

void gc_helper_get_regs(regs_t arr) {
    register long rbx __asm__ ("rbx");
    register long rbp __asm__ ("rbp");
    register long r12 __asm__ ("r12");
    register long r13 __asm__ ("r13");
    register long r14 __asm__ ("r14");
    register long r15 __asm__ ("r15");
    arr[0] = rbx;
    arr[1] = rbp;
    arr[2] = r12;
    arr[3] = r13;
    arr[4] = r14;
    arr[5] = r15;
}
#endif

#ifdef __i386__
typedef machine_uint_t regs_t[4];

void gc_helper_get_regs(regs_t arr) {
    register long ebx __asm__ ("ebx");
    register long esi __asm__ ("esi");
    register long edi __asm__ ("edi");
    register long ebp __asm__ ("ebp");
    arr[0] = ebx;
    arr[1] = esi;
    arr[2] = edi;
    arr[3] = ebp;
}
#endif

#ifdef __thumb2__
typedef machine_uint_t regs_t[10];

void gc_helper_get_regs(regs_t arr) {
    register long r4 __asm__ ("r4");
    register long r5 __asm__ ("r5");
    register long r6 __asm__ ("r6");
    register long r7 __asm__ ("r7");
    register long r8 __asm__ ("r8");
    register long r9 __asm__ ("r9");
    register long r10 __asm__ ("r10");
    register long r11 __asm__ ("r11");
    register long r12 __asm__ ("r12");
    register long r13 __asm__ ("r13");
    arr[0] = r4;
    arr[1] = r5;
    arr[2] = r6;
    arr[3] = r7;
    arr[4] = r8;
    arr[5] = r9;
    arr[6] = r10;
    arr[7] = r11;
    arr[8] = r12;
    arr[9] = r13;
}
#endif

void gc_collect(void) {
    gc_collect_start();
    
    // Trace .bss section
    #ifdef __CYGWIN__
    #define BSS_START __bss_start__
    #else
    #define BSS_START __bss_start
    #endif
    extern char BSS_START, _end;
    gc_collect_root((void**)&BSS_START, 
                   ((machine_uint_t)&_end - (machine_uint_t)&BSS_START) / sizeof(machine_uint_t));

    // Capture registers and GC stack
    regs_t regs;
    gc_helper_get_regs(regs);
    gc_collect_root((void**)&regs, 
                   ((machine_uint_t)stack_top - (machine_uint_t)&regs) / sizeof(machine_uint_t));
    
    gc_collect_end();
}

#endif // MICROPY_ENABLE_GC
