%ifndef CALLS_INC
%define CALLS_INC

%macro pbegin 1-*
; procedure header < (sub, reg1, reg2, reg3, ...)
; Keep rsp divisible by 16 before calling another function.
	push	rbp
	mov	rbp, rsp
	sub	rsp, %1
  %rep %0 - 1
    %rotate 1
	push	%1
  %endrep
%endmacro

%macro pend 0-*
; procedure tail < (reg1, reg2, reg3, ...)
  %rep %0
    %rotate -1
	pop	%1
  %endrep
	mov	rsp, rbp
	pop	rbp
	ret
%endmacro

%macro pcall 1-7
; System V call < (name, param1, ..., param6)
; Integer/pointer arguments only. Use 64-bit registers or qword memory.
; Capture operands before changing argument registers; no RSP operands.
; The caller must already have aligned RSP to 16 bytes.
  %rep %0 - 1
    %rotate -1
	push	qword %1
  %endrep
  %rotate -1
  %if %0 > 1
	pop	rdi
  %endif
  %if %0 > 2
	pop	rsi
  %endif
  %if %0 > 3
	pop	rdx
  %endif
  %if %0 > 4
	pop	rcx
  %endif
  %if %0 > 5
	pop	r8
  %endif
  %if %0 > 6
	pop	r9
  %endif
	call	%1
%endmacro

%macro scall 1-4 0, 0, 0
; system call
;   < (syscall number, param1, param2, param3) > rax
	push	rdi
	push	rsi
	push	rdx
	push	rcx
	push	r11
	push	qword %4
	push	qword %3
	push	qword %2
	pop	rdi
	pop	rsi
	pop	rdx
	mov	eax, %1
	syscall
	pop	r11
	pop	rcx
	pop	rdx
	pop	rsi
	pop	rdi
%endmacro

%endif
