Debian Codegraph @

lib/mlrisc-lib/MLRISC/amd64/c-calls/amd64-svid.sml

raw
1 (* amd64-svid.sml
2 *
3 * COPYRIGHT (c) 2000 Bell Labs, Lucent Technologies
4 *
5 * C function calls for the AMD64 using the System V ABI
6 *
7 * Register conventions:
8 *
9 * %rdi 1st argument
10 * %rsi 2nd
11 * %rdx 3rd
12 * %rcx 4th
13 * %r8 5th
14 * %r9 6th
15 *
16 * Calling convention:
17 *
18 * Return result:
19 * + Integer and pointer results are returned in %eax. Small
20 * integer results are not promoted.
21 * + 64-bit integers (long long) returned in %eax/%edx
22 * + Floating point results are returned in %st(0) (all types).
23 * + Struct results are returned in space provided by the caller.
24 * The address of this space is passed to the callee as an
25 * implicit 0th argument, and on return %eax contains this
26 * address. The called function is responsible for removing
27 * this argument from the stack using a "ret $4" instruction.
28 * NOTE: the MacOS X ABI returns small structs in %eax/%edx.
29 *
30 * Function arguments:
31 * + Arguments are pushed on the stack right to left.
32 * + Integral and pointer arguments take one word on the stack.
33 * + float arguments take one word on the stack.
34 * + double arguments take two words on the stack. The i386 ABI does
35 * not require double word alignment for these arguments.
36 * + long double arguments take three words on the stack.
37 * + struct arguments are padded out to word length.
38 *
39 * Questions:
40 * - what about stack frame alignment?
41 *)
42
43 functor AMD64SVID_CCalls (
44 structure T : MLTREE
45 ) : C_CALLS = struct
46 structure MLTreeUtils = MLTreeUtils
47 (structure T = T
48 fun hashSext _ _ = 0w0
49 fun hashRext _ _ = 0w0
50 fun hashFext _ _ = 0w0
51 fun hashCCext _ _ = 0w0
52
53 (* Equality extensions *)
54 fun eqSext _ _ = false
55 fun eqRext _ _ = false
56 fun eqFext _ _ = false
57 fun eqCCext _ _ = false
58
59 (* Pretty printing extensions *)
60 fun showSext _ _ = ""
61 fun showRext _ _ = ""
62 fun showFext _ _ = ""
63 fun showCCext _ _ = ""
64 )
65
66 val frameAlign = 16
67
68 structure T = T
69 structure Ty = CTypes
70 structure C = AMD64Cells
71
72 fun error msg = MLRiscErrorMsg.error ("AMD64SVID_CCalls", msg)
73
74 datatype c_arg
75 = ARG of T.rexp
76 | FARG of T.fexp
77 | ARGS of c_arg list
78
79 val mem = T.Region.memory
80 val stack = T.Region.stack
81
82 (* MLRISC types *)
83 val wordTy = 64
84 val fltTy = 32
85 val dblTy = 64
86
87 (* shorts and chars are promoted to 32-bits *)
88 val naturalIntSz = wordTy
89
90 val paramAreaOffset = 0 (* stack offset to param area *)
91
92 (* This annotation is used to indicate that a call returns a fp value
93 * in %st(0)
94 *)
95 val fpReturnValueInXmm0 = #create MLRiscAnnotations.RETURN_ARG C.xmm0
96
97 val sp = C.rsp
98 val spR = T.REG(wordTy, sp)
99
100 fun fpr(sz,f) = T.FPR(T.FREG(sz, f))
101 fun gpr(sz,r) = T.GPR(T.REG(sz, r))
102 val rax = C.rax
103 val xmm0 = C.xmm0
104
105 (* the C calling convention requires that the FP stack be empty on function
106 * entry. We add the fpStk list to the defs when the fast_floating_point flag
107 * is set.
108 *)
109 val fpStk =
110 [fpr (dblTy, C.xmm0), fpr (dblTy, C.xmm1),
111 fpr (dblTy, C.xmm2), fpr (dblTy, C.xmm3),
112 fpr (dblTy, C.xmm4), fpr (dblTy, C.xmm5),
113 fpr (dblTy, C.xmm6), fpr (dblTy, C.xmm7),
114 fpr (dblTy, C.xmm8), fpr (dblTy, C.xmm9),
115 fpr (dblTy, C.xmm10), fpr (dblTy, C.xmm11),
116 fpr (dblTy, C.xmm12), fpr (dblTy, C.xmm13),
117 fpr (dblTy, C.xmm14), fpr (dblTy, C.xmm15)]
118
119 (* note that the caller saves includes the result register (%eax) *)
120 val callerSaves =
121 [gpr(wordTy, rax), gpr(wordTy, C.rcx), gpr(wordTy, C.rdx),
122 gpr(wordTy, C.rsi), gpr(wordTy, C.rdi),
123 gpr(wordTy, C.r8), gpr(wordTy, C.r9),
124 gpr(wordTy, C.r10), gpr(wordTy, C.r11)]
125
126 (* C callee-save registers *)
127 val calleeSaveRegs =
128 [C.rbx, C.rbp,
129 C.r12, C.r13, C.r14, C.r15] (* C callee-save registers *)
130 val calleeSaveFRegs = [] (* C callee-save floating-point registers *)
131
132 (* align the address to the given alignment, which must be a power of 2 *)
133 fun alignAddr (addr, align) = let
134 val mask = Word.fromInt(align-1)
135 in
136 Word.toIntX(Word.andb(Word.fromInt addr + mask, Word.notb mask))
137 end
138
139 fun align4 addr = Word.toIntX(Word.andb(Word.fromInt addr + 0w3, Word.notb 0w3))
140 fun align8 addr = Word.toIntX(Word.andb(Word.fromInt addr + 0w7, Word.notb 0w7))
141
142 (* size and natural alignment for integer types. *)
143 (* arguments are always aling 8 structs may align differently *)
144 fun sizeOfInt Ty.I_char = {ty = 8, sz = 1, align = 8 (* 1 *) }
145 | sizeOfInt Ty.I_short = {ty = 16, sz = 2, align = 8 (* 2 *) }
146 | sizeOfInt Ty.I_int = {ty = 32, sz = 4, align = 8 (* 4 *) }
147 | sizeOfInt Ty.I_long = {ty = 32, sz = 4, align = 8 (* 4 *) }
148 | sizeOfInt Ty.I_long_long = {ty = 64, sz = 8, align = 8 (* 4 *) }
149
150 (* sizes of other C types *)
151 val sizeOfPtr = {ty = 64, sz = 8, align = 8}
152
153 (* compute the size and alignment information for a struct; tys is the list
154 * of member types.
155 * The total size is padded to agree with the struct's alignment.
156 *)
157 fun sizeOfStruct tys = let
158 fun ssz ([], maxAlign, offset) =
159 {sz = alignAddr(offset, maxAlign), align = maxAlign}
160 | ssz (ty::tys, maxAlign, offset) = let
161 val {sz, align} = sizeOfTy ty
162 val offset = alignAddr(offset, align)
163 in
164 ssz (tys, Int.max(maxAlign, align), offset+sz)
165 end
166 in
167 ssz (tys, 1, 0)
168 end
169
170 (* the size alignment of a union type is the maximum of the sizes and alignments of the
171 * members. The final size is padded to agree with the alignment.
172 *)
173 and sizeOfUnion tys = let
174 fun usz ([], maxAlign, maxSz) =
175 {sz = alignAddr(maxSz, maxAlign), align = maxAlign}
176 | usz (ty::tys, maxAlign, maxSz) = let
177 val {sz, align} = sizeOfTy ty
178 in
179 usz (tys, Int.max(maxAlign, align), Int.max(sz, maxSz))
180 end
181 in
182 usz (tys, 1, 0)
183 end
184
185 and sizeOfTy Ty.C_void = error "unexpected void argument type"
186 | sizeOfTy Ty.C_float = {sz = 4, align = 4}
187 | sizeOfTy Ty.C_double = {sz = 8, align = 4}
188 | sizeOfTy Ty.C_long_double = {sz = 12, align = 4}
189 | sizeOfTy (Ty.C_unsigned isz) = let
190 val {sz, align, ...} = sizeOfInt isz
191 in
192 {sz = sz, align = align}
193 end
194 | sizeOfTy (Ty.C_signed isz) = let
195 val {sz, align, ...} = sizeOfInt isz
196 in
197 {sz = sz, align = align}
198 end
199 | sizeOfTy Ty.C_PTR = {sz = 8, align = 8}
200 | sizeOfTy (Ty.C_ARRAY(ty, n)) = let
201 val {sz, align} = sizeOfTy ty
202 in
203 {sz = n*sz, align = align}
204 end
205 | sizeOfTy (Ty.C_STRUCT tys) = sizeOfStruct tys
206 | sizeOfTy (Ty.C_UNION tys) = sizeOfUnion tys
207
208 (* the location of arguments/parameters; offsets are given with respect to the
209 * low end of the parameter area (see paramAreaOffset above).
210 *)
211 datatype arg_location
212 = Reg of T.ty * T.reg * T.I.machine_int option
213 (* integer/pointer argument in register *)
214 | FReg of T.fty * T.reg * T.I.machine_int option
215 (* floating-point argument in register *)
216 | Stk of T.ty * T.I.machine_int (* integer/pointer argument in parameter area *)
217 | FStk of T.fty * T.I.machine_int (* floating-point argument in parameter area *)
218 | Args of arg_location list
219
220 fun intResult iTy = (case #ty(sizeOfInt iTy)
221 of 64 => raise Fail "register pair result"
222 | ty => (SOME(Reg(ty, rax, NONE)), NONE, 0)
223 (* end case *))
224
225 fun layout {conv, retTy, paramTys} = let
226 (* get the location of the result (resLoc) and the offset of the first
227 * parameter/argument. If the result is a struct or union, then we also
228 * compute the size and alignment of the result type (structRetLoc).
229 *)
230 val (resLoc, structRetLoc, argOffset) = (case retTy
231 of Ty.C_void => (NONE, NONE, 0)
232 | Ty.C_float => (SOME(FReg(fltTy, xmm0, NONE)), NONE, 0)
233 | Ty.C_double => (SOME(FReg(dblTy, xmm0, NONE)), NONE, 0)
234 (*
235 | Ty.C_long_double => (SOME(FReg(xdblTy, st0, NONE)), NONE, 0)
236 *)
237 | Ty.C_unsigned iTy => intResult iTy
238 | Ty.C_signed iTy => intResult iTy
239 | Ty.C_PTR => (SOME(Reg(wordTy, rax, NONE)), NONE, 0)
240 | Ty.C_ARRAY _ => error "array return type"
241 (*
242 | Ty.C_STRUCT tys => let
243 val {sz, align} = sizeOfStruct tys
244 in
245 if (sz > 8) orelse (not returnSmallStructsInRegs)
246 then (SOME(Reg(wordTy, eax, NONE)), SOME{szb=sz, align=align}, 4)
247 else raise Fail "small struct return not implemented yet"
248 end
249 | Ty.C_UNION tys => let
250 val {sz, align} = sizeOfUnion tys
251 in
252 if (sz > 8) orelse (not returnSmallStructsInRegs)
253 then (SOME(Reg(wordTy, rax, NONE)), SOME{szb=sz, align=align}, 4)
254 else raise Fail "small union return not implemented yet"
255 end
256 *)
257 (* end case *))
258 fun assign ([], frees, offset, locs) = (List.rev locs, align8 offset)
259 | assign (paramTy::params, frees, offset, locs) = let
260 fun next {ty, align, sz} =
261 if null frees
262 then
263 let
264 val offset = alignAddr (offset, align)
265 in
266 assign (params, [], offset+sz, Stk(ty, IntInf.fromInt offset)::locs)
267 end
268 else
269 assign
270 (params, tl frees, offset, Reg(ty, hd frees, NONE)::locs)
271 fun nextFlt (ty, szb) = let
272 val offset = alignAddr (offset, 4)
273 in
274 assign (params, [], offset+szb, FStk(ty, IntInf.fromInt offset)::locs)
275 end
276 fun assignMem {sz, align} = let
277 fun f (nb, offset, locs') =
278 if (nb >= 4)
279 then f(nb-4, offset+4, Stk(wordTy, IntInf.fromInt offset)::locs')
280 else if (nb >= 2)
281 then f(nb-2, offset+2, Stk(16, IntInf.fromInt offset)::locs')
282 else if (nb = 1)
283 then f(nb, offset+1, Stk(8, IntInf.fromInt offset)::locs')
284 else assign(params, [], align4 offset, Args(List.rev locs')::locs)
285 in
286 f (sz, offset, [])
287 end
288 in
289 case paramTy
290 of Ty.C_void => error "void argument type"
291 | Ty.C_float => nextFlt (fltTy, 4)
292 | Ty.C_double => nextFlt (dblTy, 8)
293 (*
294 | Ty.C_long_double => nextFlt (xdblTy, 12)
295 *)
296 | Ty.C_unsigned iTy => next (sizeOfInt iTy)
297 | Ty.C_signed iTy => next (sizeOfInt iTy)
298 | Ty.C_PTR => next sizeOfPtr
299 | Ty.C_ARRAY _ => next sizeOfPtr
300 | Ty.C_STRUCT tys => assignMem(sizeOfStruct tys)
301 | Ty.C_UNION tys => assignMem(sizeOfUnion tys)
302 (* end case *)
303 end
304 val (argLocs, argSz) =
305 assign
306 (paramTys,
307 [C.rdi, C.rsi, C.rdx, C.rcx, C.r8, C.r9],
308 argOffset, [])
309 val argMem = {szb = alignAddr (argSz, frameAlign), align = frameAlign}
310 in {
311 argLocs = argLocs, argMem = argMem,
312 resLoc = resLoc, structRetLoc = structRetLoc
313 } end
314
315 (* List of registers defined by a C Call with the given return type; this list
316 * is the result registers plus the caller-save registers.
317 *)
318 fun definedRegs resTy = let
319 val defs = callerSaves @ fpStk
320 in
321 case resTy
322 of (Ty.C_unsigned(Ty.I_long_long)) => gpr(wordTy, C.rdx) :: defs
323 | (Ty.C_signed(Ty.I_long_long)) => gpr(wordTy, C.rdx) :: defs
324 | _ => defs
325 (* end case *)
326 end
327
328 (*
329 fun fstp (32, f) = T.EXT(ix(IX.FSTPS(f)))
330 | fstp (64, f) = T.EXT(ix(IX.FSTPL(f)))
331 | fstp (80, f) = T.EXT(ix(IX.FSTPT(f)))
332 | fstp (sz, f) = error ("fstp(" ^ Int.toString sz ^ ",_)")
333 *)
334
335 fun genCall {
336 name, proto, paramAlloc, structRet, saveRestoreDedicated, callComment, args
337 } = let
338 val {argLocs, argMem, resLoc, structRetLoc} = layout proto
339 fun finduses (Reg(ty, r, _)::t) = gpr (ty, r)::finduses t
340 | finduses (_::t) = finduses t
341 | finduses [] = []
342 val uses = finduses argLocs
343 (* instruction to save frame pointer in rbp *)
344 (*
345 val rbpFramePointer =
346 [T.MV(wordTy, C.rbp, spR)]
347 *)
348 (* instruction to allocate space for arguments *)
349 val argAlloc = if ((#szb argMem = 0) orelse paramAlloc argMem)
350 then []
351 else [T.MV(wordTy, sp, T.SUB(wordTy, spR, T.LI(IntInf.fromInt(#szb argMem))))]
352 (* for functions that return a struct/union, pass the location as an
353 * implicit first argument. Because the callee removes this implicit
354 * argument from the stack, we must also keep track of the size of the
355 * explicit arguments.
356 *)
357 val (args, argLocs, explicitArgSzB) = (case structRetLoc
358 of SOME pos =>
359 (ARG(structRet pos)::args, Stk(wordTy, 0)::argLocs, #szb argMem - 4)
360 | NONE => (args, argLocs, #szb argMem)
361 (* end case *))
362 (* generate instructions to copy arguments into argument area
363 * using %rsp to address the argument area.
364 * stmsDelay can delay copying of the arguments.
365 *)
366 val (copyArgs, copyArgsDelay) = let
367 fun offSP 0 = spR
368 | offSP offset = T.ADD(wordTy, spR, T.LI offset)
369 fun f ([], [], stms, stmsDelay) = (List.rev stms, List.rev stmsDelay)
370 | f (arg::args, loc::locs, stms, stmsDelay) = let
371 val stms = (case (arg, loc)
372 of (ARG(rexp as T.REG _), Stk(mty, offset)) =>
373 (
374 T.STORE(mty, offSP offset, rexp, stack)
375 :: stms
376 )
377 | (ARG rexp, Stk(mty, offset)) => let
378 val tmp = C.newReg()
379 in
380 T.STORE(wordTy, offSP offset, T.REG(wordTy, tmp), stack)
381 :: T.MV(wordTy, tmp, rexp)
382 :: stms
383 end
384 | (ARG rexp, Args memLocs) => let
385 (* addrR is used to address the source of the memory object
386 * being passed to the memLocs. loadAddr is the code to
387 * initialize addrR.
388 *)
389 val (loadAddr, addrR) = (case rexp
390 of T.REG _ => ([], rexp)
391 | _ => let
392 val r = C.newReg()
393 in
394 ([T.MV(wordTy, r, rexp)], T.REG(wordTy, r))
395 end
396 (* end case *))
397 fun addr 0 = addrR
398 | addr offset = T.ADD(wordTy, addrR, T.LI offset)
399 (* stack offset of first destination word *)
400 val baseOffset = (case memLocs
401 of Stk(ty, offset)::_ => offset
402 | _ => error "bogus Args"
403 (* end case *))
404 fun copy ([], stms) = stms
405 | copy (Stk(ty, offset)::locs, stms) = let
406 val tmp = C.newReg()
407 val stms =
408 T.STORE(ty, offSP offset, T.REG(ty, tmp), stack)
409 :: T.MV(ty, tmp, T.LOAD(ty, addr(offset - baseOffset), mem))
410 :: stms
411 in
412 copy (locs, stms)
413 end
414 | copy _ = error "bogus memory location"
415 in
416 copy (memLocs, loadAddr @ stms)
417 end
418 | (FARG(fexp as T.FREG _), FStk(ty, offset)) =>
419 (
420 T.FSTORE(ty, offSP offset, fexp, stack) :: stms
421 )
422 | (FARG fexp, FStk(ty, offset)) => let
423 val tmp = C.newFreg()
424 in
425 T.FSTORE(ty, offSP offset, T.FREG(ty, tmp), stack)
426 :: T.FMV(ty, tmp, fexp)
427 :: stms
428 end
429 | (ARGS _, _) => raise Fail "ARGS obsolete"
430 | _ => stms
431 (* end case *))
432 val stmsDelay = (case (arg, loc)
433 of (ARG rexp, Reg(mty, mreg, NONE)) => let
434 val CellsBasis.CELL{id,...} = mreg
435 in
436 T.MV(wordTy, mreg, rexp) :: stmsDelay
437 end
438 | _ => stmsDelay
439 (* end case *))
440
441 in
442 f (args, locs, stms, stmsDelay)
443 end
444 | f _ = error "argument arity error"
445 in
446 f (args, argLocs, [], [])
447 end
448 (* the SVID specifies that the caller pops arguments, but the callee
449 * pops the arguments in a stdcall on Windows. I'm not sure what other
450 * differences there might be between the SVID and Windows ABIs. (JHR)
451 *)
452 val calleePops = (case #conv proto
453 of (""|"ccall") => false
454 | "stdcall" => true
455 | conv => error (concat [
456 "unknown calling convention \"", String.toString conv, "\""
457 ])
458 (* end case *))
459 val defs = definedRegs(#retTy proto)
460 val { save, restore } = saveRestoreDedicated defs
461 val callStm = T.CALL{
462 funct=name, targets=[], defs=defs, uses=uses,
463 region = mem,
464 pops = if calleePops
465 then Int32.fromInt(#szb argMem)
466 else Int32.fromInt(#szb argMem - explicitArgSzB)
467 }
468 val callStm = (case callComment
469 of NONE => callStm
470 | SOME c => T.ANNOTATION (callStm, #create MLRiscAnnotations.COMMENT c)
471 (* end case *))
472 (* If return type is floating point then add an annotation RETURN_ARG
473 * This is currently a hack. Eventually MLTREE *should* support
474 * return arguments for CALLs.
475 * --- Allen
476 *)
477 val callStm = if
478 ((#retTy proto = Ty.C_float)
479 orelse (#retTy proto = Ty.C_double)
480 orelse (#retTy proto = Ty.C_long_double))
481 then T.ANNOTATION(callStm, fpReturnValueInXmm0)
482 else callStm
483 (* code to pop the arguments from the stack *)
484 val popArgs = if calleePops orelse (explicitArgSzB = 0)
485 then []
486 else [T.MV(wordTy, sp, T.ADD(wordTy, spR, T.LI(IntInf.fromInt explicitArgSzB)))]
487 (* code to copy the result into fresh pseudo registers *)
488 val (resultRegs, copyResult) = (case resLoc
489 of NONE => ([], [])
490 | SOME(Reg(ty, r, _)) => let
491 val resReg = C.newReg()
492 in
493 ([T.GPR(T.REG(ty, resReg))], [T.COPY(ty, [resReg], [r])])
494 end
495 | SOME(FReg(ty, r, _)) => let
496 val resReg = C.newFreg()
497 val res = [T.FPR(T.FREG(ty, resReg))]
498 in
499 (* If we are using fast floating point mode then do NOT
500 * generate FSTP.
501 * --- Allen
502 *)
503 (res, [T.FCOPY(ty, [resReg], [r])])
504 end
505 | _ => error "bogus result location"
506 (* end case *))
507 (* assemble the call sequence *)
508 val callSeq = argAlloc @ (* rbpFramePointer @ *) copyArgs @ save @ copyArgsDelay @ [callStm] @ restore @ popArgs @ copyResult
509 in
510 {callseq=callSeq, result=resultRegs}
511 end
512
513 end