Debian Codegraph @

lib/mlrisc-lib/MLRISC/x86/c-calls/ia32-svid.sml

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