Debian Codegraph @

lib/mlrisc-lib/MLRISC/Tools/MDL/mdl-gen-schedprops.sml

raw
1 (*
2 * Generate the <arch>SchedProps functor.
3 * This structure extracts semantics and dependence
4 * information about the instruction set needed for scheduling optimizations.
5 *)
6
7 functor MDLGenSchedProps(RTLComp : MDL_RTL_COMP) : MDL_GEN_MODULE2 =
8 struct
9
10 structure RTLComp = RTLComp
11 structure Comp = RTLComp.Comp
12 structure Ast = Comp.Ast
13 structure E = Env
14 structure Env = Comp.Env
15 structure RTL = RTLComp.RTL
16 structure T = RTL.T
17
18 open Ast Comp.Util Comp.Error
19
20 exception Undefined
21
22 (* Generate a call to the bug function *)
23 fun bug funName = APP("bug",TUPLEexp[STRINGexp funName,ID "instr"])
24
25 (* Expressions building utilities *)
26 fun cons(x,LISTexp(a,b)) = LISTexp(x::a,b)
27 | cons(x,y) = LISTexp([x],SOME y)
28 fun append(x,LISTexp([],NONE)) = x
29 | append(x,y) = APP("@",TUPLEexp[x,y])
30
31 val MAX_BIT = Word.wordSize - 1 (* Implementation specific!!!! *)
32
33 (* Function to compile the reservation tables! *)
34
35 fun genRT md =
36 let val resources = Comp.resources md
37 val cpus = Comp.cpus md
38 val pipelines = Comp.pipelines md
39 val latencies = Comp.latencies md
40 val arch = Comp.name md
41
42 type 'a table = 'a E.envir * string
43 fun mkTbl name = (E.envir name, name)
44
45 fun enter(E,name) (x,y) =
46 (E.lookup E x; error(name^" "^x^" has been redefined\n"))
47 handle _ => E.update E (x,y)
48
49 (* Create tables *)
50 val resourceTbl = mkTbl "resource"
51 val cpuTbl = mkTbl "cpu"
52 val pipelineTbl = mkTbl "pipeline"
53 val latencyTbl = mkTbl "latency"
54
55 (* Enter info into tables *)
56 val _ = app (fn id => enter resourceTbl (id,id) ) resources
57 val _ = app (fn x as CPUbind{name,...} => enter cpuTbl (name,x)) cpus
58 val _ = app (fn x as PIPELINEbind(id, _) => enter pipelineTbl (id,x))
59 pipelines
60 val _ = app (fn x as LATENCYbind(id, _) => enter latencyTbl (id,x))
61 latencies
62
63 fun checkResource msg r =
64 (E.lookup (#1 resourceTbl) r; ()) handle _ =>
65 error(msg^" has undefined resource "^r)
66
67 (* Compile each CPU definition *)
68 fun compileCPU(CPUbind{name=cpuName, maxIssues, resources, ...}) =
69 let val _ =
70 print ("[Generating reservation table for "^arch^"."^cpuName^"]\n")
71
72 (* Compute the number of bits necessary for a field that can count
73 * from 0 to n, and compute the extra counts to overflow the field
74 *)
75 fun getfield(n) =
76 let fun bits(0w0, n) = n
77 | bits(w, n) = bits(Word.>>(w,0w1), n+0w1)
78 val bits = bits(Word.fromInt n, 0w0)
79 val n' = Word.toIntX(Word.<<(0w1, bits))
80 in {width=Word.toIntX bits, padding=n'-n-1}
81 end
82
83 val checkResource = checkResource("cpu "^cpuName)
84
85 fun genResources(resources) =
86 let fun addMask{word,bits,mask=[]} = [{word=word,bits=bits}]
87 | addMask{word,bits,mask={word=w,bits=b}::mask} =
88 if word=w then {word=word,bits=bits + b}::mask
89 else {word=word,bits=bits}::{word=w,bits=b}::mask
90 fun loop([], word, bit, res, mask, extra) =
91 {cpu=cpuName, maxIssues=maxIssues,
92 words=word+1, res=res, mask=rev mask, extra=rev extra}
93 | loop((n,r)::rs, word, bit, res, mask, extra) =
94 let val _ = checkResource r
95 val {width, padding} = getfield n
96 val (word, bit, mask, extra) =
97 if bit + width + 1 > MAX_BIT
98 then (word+1, 0, {word=word+1,bits=0w0}::mask,
99 {word=word+1,bits=0w0}::extra)
100 else (word, bit, mask, extra)
101 val newBit = bit + width + 1
102 val mask = addMask{word=word, bits=Word.<<(0w1,
103 Word.fromInt(bit+width)),
104 mask=mask}
105 val extra = addMask{word=word,
106 bits=Word.<<(Word.fromInt padding,
107 Word.fromInt bit),
108 mask=extra}
109 in loop(rs, word, newBit,
110 {resource=r,count=n,word=word,bit=bit}::res, mask, extra)
111 end
112 in loop(resources, 0, 0, [], [], [])
113 end
114
115 in genResources resources
116 end
117
118 (* Compile all cpu information *)
119 val cpuInfo = map compileCPU cpus
120
121 (* number of words needed to represent the state in one cycle *)
122 val W = foldr (fn ({words, ...}, w) => Int.max(words, w)) 0 cpuInfo
123
124 fun many f =
125 let fun g n = if n >= W then [] else f n::g(n+1)
126 in g 0 end
127
128 (* type of resource *)
129 val resTy = DATATYPEdecl([],
130 [TYPEbind("resource",[],TUPLEty(many (fn _ => WORDty)))])
131 val cpuTy =
132 DATATYPEdecl(
133 [DATATYPEbind
134 {id="cpu",tyvars=[],mc=NONE,asm=false, field=NONE,
135 cbs=map (fn CPUbind{name,...} => CONS(name,NONE)) cpus
136 }
137 ],
138 [])
139
140 val getCPU =
141 FUNdecl[FUNbind("cpu",
142 map (fn CPUbind{name,aliases,...} =>
143 CLAUSE([ORpat(map STRINGpat (name::aliases))],
144 NONE, ID name)) cpus
145 @ [CLAUSE([IDpat "cpuName"],
146 NONE,
147 APP("error",
148 APP("^",
149 TUPLEexp[STRINGexp "unknown architecture ",
150 ID "cpuName"])))]
151 )]
152
153 val i2s = Int.toString
154 fun w2s w = "0wx"^Word.toString w
155
156 fun get(w, []) = 0w0
157 | get(w, {word, bits}::l) =
158 if w = word then Word32.fromInt(Word.toIntX bits)
159 else get(w,l)
160
161 (*
162 * Function to merge two reservation table entries
163 *)
164 val mergeRT =
165 let val arg1 = TUPLEpat(many(fn n => IDpat("x"^i2s n)))
166 val arg2 = TUPLEpat(many(fn n => IDpat("y"^i2s n)))
167 val arg = TUPLEpat[arg1,arg2]
168 val body = TUPLEexp(many(fn n =>
169 APPexp(IDexp(IDENT(["Word"],"+")),
170 TUPLEexp[ID("x"^i2s n), ID("y"^i2s n)])))
171 in FUN("mergeRT", arg, body)
172 end
173
174 val zeroRT = VAL("zeroRT",TUPLEexp(many(fn n => WORD32exp 0w0)))
175
176 (* Generate code for each cpu *)
177 fun genCode{cpu, words, res, mask, extra, maxIssues} =
178 let fun genRes{resource, count, word, bit} =
179 (resource,
180 TUPLEexp(many(fn w => if w = word then
181 WORD32exp(Word32.<<(0w1,Word.fromInt bit)) else
182 WORD32exp 0w0)))
183
184 val mergeableRT =
185 let val arg1 = TUPLEpat(many (fn n => IDpat("x"^i2s n)))
186 val arg2 = TUPLEpat(many (fn n => IDpat("y"^i2s n)))
187 val arg = TUPLEpat[arg1,arg2]
188 val body = many (fn n =>
189 let val maskBits = get(n, mask)
190 in APP("=",
191 TUPLEexp[
192 APP("Word.andb",
193 TUPLEexp[PLUS(ID("x"^i2s n),ID("y"^i2s n)),
194 WORD32exp maskBits]),
195 WORD32exp 0w0])
196 end)
197 in FUN("mergeableRT"^cpu, arg, foldr ANDALSO TRUE body)
198 end
199
200 val emptyRT = VAL("emptyRT"^cpu,
201 TUPLEexp(many(fn n => WORD32exp(get(n,extra)))))
202
203 val maxIssues = VAL("maxIssues"^cpu,INTexp maxIssues)
204 val myResources = map genRes res
205 fun getRes res =
206 let fun loop([]) = (res,ID "zeroRT")
207 | loop((r,e)::rs) = if r = res then (r,e) else loop rs
208 in loop myResources
209 end
210 val resources = VAL("resources"^cpu,
211 RECORDexp(map getRes resources))
212
213 in SEQdecl[maxIssues,emptyRT,mergeableRT,resources]
214 end
215
216 val resourcesPat = RECORDpat(map (fn id => (id,IDpat id)) resources,false)
217
218 (* Generate a pipeline function *)
219 fun genPipelineFun(PIPELINEbind(name, clauses)) =
220 let val check = checkResource("pipeline "^name)
221 fun trans [] = []
222 | trans(IDcycle res::ps) =
223 (check res; ID res::trans ps)
224 | trans(ORcycle(a,b)::ps) =
225 merge(trans[a], trans[b])@trans ps
226 | trans(REPEATcycle(a,n)::ps) = repeat(trans[a],n)@trans ps
227
228 and merge([a],[b]) = [APP("mergeRT",TUPLEexp[a,b])]
229 | merge _ = (error("bad expression in pipeline "^name); [])
230
231 and repeat(x,0) = []
232 | repeat(x,n) = x@repeat(x,n-1)
233
234 fun genClause(pat,PIPELINE pe) =
235 CLAUSE([resourcesPat,pat],NONE,LISTexp(trans pe,NONE))
236
237 in FUNdecl[FUNbind("pipeline"^name,map genClause clauses)]
238 end
239
240 (* Generate a latency function *)
241 fun genLatencyFun(LATENCYbind(name, clauses)) =
242 let fun genClause(pat,e) = CLAUSE([resourcesPat,pat],NONE,e)
243 in FUNdecl[FUNbind("latency"^name,map genClause clauses)]
244 end
245
246 in SEQdecl(resTy::cpuTy::getCPU::zeroRT::mergeRT::
247 map genCode cpuInfo @
248 map genPipelineFun pipelines @
249 map genLatencyFun latencies
250 )
251 end
252
253 fun gen compiled_rtls =
254 let (* The machine description *)
255 val md = RTLComp.md compiled_rtls
256
257 (* name of the structure/signature *)
258 val strName = Comp.strname md "SchedProps"
259 val sigName = "SCHEDULING_PROPERTIES"
260
261 val cpus = Comp.cpus md
262 val pipelines = Comp.pipelines md
263 val latencies = Comp.latencies md
264 val rtDecl = genRT md
265
266 (* query function *)
267 val queryFun = RTLComp.queryFun compiled_rtls
268
269 (* default way of handling composite instructions *)
270 fun composite{instr,id,ty} = APP("query",ID id)
271
272 (* Arguments to the instruction functor *)
273 val args =
274 ["structure Instr : "^Comp.signame md "INSTR",
275 "structure RegionProps : REGION_PROPERTIES",
276 "structure Asm : INSTRUCTION_EMITTER where I = Instr",
277 " sharing RegionProps.Region = Instr.Region"
278 ]
279
280 (* Definition of the reservation table type *)
281 val resTableDefinition =
282 $["structure A = DynArray",
283 "type pipeline = resource list",
284 "type reservation_table = (int * resource) A.array"
285 ]
286
287 (* Make the newTable (per cpu) *)
288 val newTable =
289 $["fun newTable emptyRT n = ",
290 " A.array(n,(0,emptyRT)) : reservation_table"
291 ]
292
293 (* Make the defUse query function (shared by all cpu types) *)
294 val defUse =
295 let val defaultLat = INTexp 0
296 fun queryDefUse{instr,rtl,const} =
297 let val CONSbind{latency,...} = instr
298 val lat = case latency of SOME l => l | NONE => defaultLat
299 fun pair(e,l) = TUPLEexp[e,l]
300
301 val (defs,uses) = L.defUse rtl
302 val def =
303 RTL.queryExp rtlmd
304 {name = "defUse",
305 reg = fn (r,_,l) => cons(pair(r,lat),l),
306 fixreg = fn (r,_,l) => cons(pair(r,lat),l),
307 regs = fn (rs,_,l) => append(APP("mkSet",rs),l),
308 opnd = fn (_,l) => l,
309 lab = fn (_,l) => l,
310 imm = fn (_,l) => l,
311 cellset = fn (c,l) => append(APP("getCellSetDef",c),l),
312 region = fn (r,l) => append(APP("getRegionDef",r),l)
313 } (defs, LISTexp([],NONE))
314 val use =
315 RTL.queryExp rtlmd
316 {name = "defUse",
317 reg = fn (r,_,l) => cons(r,l),
318 fixreg = fn (r,_,l) => cons(r,l),
319 regs = fn (rs,_,l) => append(rs,l),
320 opnd = fn (x,l) => APP("getOpnd",TUPLEexp[x,l]),
321 lab = fn (_,l) => l,
322 imm = fn (_,l) => l,
323 cellset = fn (c,l) => append(APP("getCellSetUse",c),l),
324 region = fn (r,l) => append(APP("getRegionUse",r),l)
325 } (uses, LISTexp([],NONE))
326
327 in {exp=TUPLEexp[def, use], pat=[]}
328 end
329 val getOpnd = RTL.queryOpnd rtlmd
330 {name= "getOpnd",
331 extraArgs=["rest"],
332 reg = fn r => LISTexp([r],SOME(ID "rest")),
333 imm = fn r => raise Match,
334 opnd= fn r => raise Match,
335 default= ID "rest"
336 }
337 val predefined =
338 $["fun mkSet set = map (fn r => (r,0)) set",
339 "fun getRegionDef r = ",
340 "let val (d,u) = RegionProps.writeTo r",
341 "in map (fn r => (r,~1)) d end",
342 "fun getRegionUse r = RegionProps.readFrom r"
343 ]
344 val cellSets = Comp.cellSets md
345 val cellSetNames = map (fn CELLdecl{id,...} => id) cellSets
346 val getCellSetDef =
347 FUN("getCellSetDef",TUPLEpat(map IDpat cellSetNames),
348 foldr (fn (x,LISTexp ([],NONE)) => APP("mkSet",ID x)
349 | (x,e) => APP("@",TUPLEexp[APP("mkSet",ID x),e]))
350 (LISTexp([],NONE)) cellSetNames)
351 val getCellSetUse =
352 FUN("getCellSetUse",TUPLEpat(map IDpat cellSetNames),
353 foldr (fn (x,LISTexp ([],NONE)) => ID x
354 | (x,e) => APP("@",TUPLEexp[ID x,e]))
355 (LISTexp([],NONE)) cellSetNames)
356
357 in FUN("defUse",TUPLEpat[IDpat "cpu", IDpat "resources"],
358 LETexp([
359 SEQdecl(map (fn LATENCYbind(id,_) =>
360 VAL(id, APPexp(APP("latency"^id,ID "resources"),
361 ID "cpu"))) latencies),
362 queryFun{name="defUseQuery",
363 extraArgs=[],
364 args=["instr"],
365 extraExps=[],
366 localDecls=[getOpnd,predefined,getCellSetDef,getCellSetUse],
367 body=queryDefUse, composite=composite}],
368 [ID "defUseQuery"]
369 ))
370 end
371
372 (* Make the pipeline query function (shared by all cpu types) *)
373 val pipelineOf =
374 let val defaultPipeline = LISTexp([], NONE)
375 fun queryPipeline{instr,rtl,const} =
376 let val CONSbind{pipeline,...} = instr
377 val p = case pipeline of SOME p => p | NONE => defaultPipeline
378 in {exp=p, pat=[]}
379 end
380 in FUN("pipelineOf",TUPLEpat[IDpat "cpu", IDpat "resources"],
381 LETexp([
382 SEQdecl(map (fn PIPELINEbind(id,_) =>
383 VAL(id, APPexp(APP("pipeline"^id,ID "resources"),
384 ID "cpu"))) pipelines),
385 queryFun{name="pipelineQuery",
386 extraArgs=[],
387 args=["instr"],
388 extraExps=[],
389 localDecls=[],
390 body=queryPipeline,
391 composite=composite}],
392 [ID "pipelineQuery"]
393 ))
394 end
395
396
397 val findSlotBackward =
398 $["fun findSlotBackward(maxIssues, mergeable)",
399 " (rt : reservation_table, time, pipeline) = ",
400 "let fun search(t) = ",
401 " let fun fits([], t) = true",
402 " | fits(r::rs, t) =",
403 " mergeable(#2(A.sub(rt,~t)),r)",
404 " andalso fits(rs, t+1)",
405 " in if #1(A.sub(rt,~t)) < maxIssues",
406 " andalso fits(pipeline,t) then t else search(t-1)",
407 " end",
408 "in search(time) end"
409 ]
410
411 val findSlotForward =
412 $["fun findSlotForward (maxIssues, mergeable)",
413 " (rt : reservation_table, time, pipeline) = ",
414 "let fun search(t) = ",
415 " let fun fits([], t) = true",
416 " | fits(r::rs, t) =",
417 " mergeable(#2(A.sub(rt,t)),r)",
418 " andalso fits(rs, t+1)",
419 " in if #1(A.sub(rt,t)) < maxIssues",
420 " andalso fits(pipeline,t) then t else search(t+1)",
421 " end",
422 "in search time end"
423 ]
424
425 val insertBackward =
426 $["fun insertBackward(rt, time, pipeline) =",
427 "let fun update([],t) = ()",
428 " | update(r::rs,t) =",
429 " let val (n,r') = A.sub(rt,~t)",
430 " in A.update(rt,~t,(n,mergeRT(r,r')));",
431 " update(rs, t+1)",
432 " end",
433 " val _ = update(pipeline, time)",
434 " val (n, r) = A.sub(rt, ~time)",
435 "in A.update(rt, ~time, (n+1, r)) end"
436 ]
437
438 val insertForward =
439 $["fun insertForward(rt, time, pipeline) =",
440 "let fun update([],t) = ()",
441 " | update(r::rs,t) =",
442 " let val (n,r') = A.sub(rt,t)",
443 " in A.update(rt,t,(n,mergeRT(r,r')));",
444 " update(rs, t+1)",
445 " end",
446 " val _ = update(pipeline, time)",
447 " val (n, r) = A.sub(rt, time)",
448 "in A.update(rt, time, (n+1, r)) end"
449 ]
450
451 (* Create the machine info for one architecture *)
452 fun genMachineInfo cpu =
453 let val cpuAndResources = TUPLEexp[ID cpu,ID("resources"^cpu)]
454 val newTable = APP("newTable", ID("emptyRT"^cpu))
455 val defUse = APP("defUse", cpuAndResources)
456 val insertArgs = TUPLEexp[ID("maxIssues"^cpu),
457 ID("mergeableRT"^cpu)]
458 val maxIssues = ID("maxIssues"^cpu)
459 val pipeline = ID "pipeline"
460 in LOCALdecl(
461 [VAL("findSlotForward", APP("findSlotForward",insertArgs)),
462 VAL("findSlotBackward", APP("findSlotBackward",insertArgs)),
463 VAL("pipeline", APP("pipelineOf", cpuAndResources))
464 ],
465 [VAL("forwardinfo"^cpu,
466 APP("CPU_INFO",
467 RECORDexp[("maxIssues",maxIssues),
468 ("newTable",newTable),
469 ("pipeline",pipeline),
470 ("findSlot",ID "findSlotForward"),
471 ("insert",ID "insertForward"),
472 ("defUse",defUse)
473 ])),
474 VAL("backwardinfo"^cpu,
475 APP("CPU_INFO",
476 RECORDexp[("maxIssues",maxIssues),
477 ("newTable",newTable),
478 ("pipeline",pipeline),
479 ("findSlot",ID "findSlotBackward"),
480 ("insert",ID "insertBackward"),
481 ("defUse",defUse)
482 ]))
483 ]
484 )
485 end
486
487 val allMachineInfos =
488 SEQdecl(map (fn CPUbind{name,...} => genMachineInfo name) cpus)
489
490 (* The info function *)
491 val infoFun =
492 FUN("info",RECORDpat([("cpu",IDpat "cpu"),
493 ("backward",IDpat "backward")],false),
494 CASEexp(ID "cpu",
495 map (fn CPUbind{name,...} =>
496 CLAUSE([IDpat name],
497 NONE,
498 IFexp(ID "backward",
499 ID("backwardinfo"^name),ID("forwardinfo"^name))))
500 cpus))
501
502 (* The split copies function.
503 * This must work before RA or after RA
504 *)
505 val impl = Comp.hasCopyImpl md
506 val implInit = if impl then ", impl=ref NONE" else ""
507 val splitCopies =
508 $ ["structure Shuffle = Shuffle(I)",
509 "fun move{src=I.Direct rs,dst=I.Direct rd} =",
510 " [I.COPY{src=[rs], dst=[rd], tmp=NONE"^implInit^"}]",
511 "fun fmove{src=I.FDirect rs,dst=I.FDirect rd} =",
512 " [I.FCOPY{src=[rs], dst=[rd], tmp=NONE"^implInit^"}]",
513 "val shuffle = Shuffle.shuffle{mvInstr=move, ea=I.Direct}",
514 "val shufflefp = Shuffle.shuffle{mvInstr=fmove, ea=I.FDirect}",
515 "fun splitCopies(I.ANNOTATION{i,...}) = splitCopies i",
516 " | splitCopies(I.COPY{src,dst,tmp,...}) =",
517 " shuffle{tmp=tmp, src=src, dst=dst}",
518 " | splitCopies(I.FCOPY{src,dst,tmp,...}) =",
519 " shufflefp{tmp=tmp, src=src, dst=dst}",
520 " | splitCopies i = [i]"
521 ]
522
523 (* The functor *)
524 val strBody =
525 [$ ["structure I = Instr",
526 "structure C = I.C",
527 "",
528 "type latency = int",
529 "type time = int",
530 "type architecture = string",
531 ""
532 ],
533 Comp.errorHandler md "SchedProps",
534 RTLComp.complexErrorHandlerDef compiled_rtl,
535 $ ["",
536 "val source = I.SOURCE{}",
537 "val sink = I.SINK{}",
538 ""
539 ],
540 Comp.declOf md "Scheduling",
541 rtDecl,
542 resTableDefinition,
543 $[ "datatype cpu_info =",
544 " CPU_INFO of",
545 " { maxIssues : int,",
546 " pipeline : I.instruction -> pipeline,",
547 " defUse : I.instruction -> (I.C.cell * latency) list * I.C.cell list,",
548 " newTable : int -> reservation_table,",
549 " findSlot : reservation_table * time * pipeline -> time,",
550 " insert : reservation_table * time * pipeline -> unit",
551
552 " }"
553 ],
554 newTable,
555 defUse,
556 pipelineOf,
557 findSlotForward,
558 findSlotBackward,
559 insertForward,
560 insertBackward,
561 allMachineInfos,
562 infoFun,
563 splitCopies
564 ]
565
566 in Comp.codegen md "scheduling/SchedProps"
567 [Comp.mkFct md "SchedProps" args sigName (map Comp.simpDecl strBody)
568 ]
569 end
570 end