| 1 |
(* cfg.sml |
| 2 |
* |
| 3 |
* COPYRIGHT (c) 2002 Bell Labs, Lucent Technologies |
| 4 |
* |
| 5 |
* The control flow graph representation used for optimizations. |
| 6 |
* |
| 7 |
* -- Allen |
| 8 |
*) |
| 9 |
|
| 10 |
functor ControlFlowGraph |
| 11 |
(structure I : INSTRUCTIONS |
| 12 |
structure GraphImpl : GRAPH_IMPLEMENTATION |
| 13 |
structure InsnProps : INSN_PROPERTIES (* where I = I *) |
| 14 |
where type I.addressing_mode = I.addressing_mode |
| 15 |
and type I.ea = I.ea |
| 16 |
and type I.instr = I.instr |
| 17 |
and type I.instruction = I.instruction |
| 18 |
and type I.operand = I.operand |
| 19 |
structure Asm : INSTRUCTION_EMITTER (* where I = I *) |
| 20 |
where type I.addressing_mode = I.addressing_mode |
| 21 |
and type I.ea = I.ea |
| 22 |
and type I.instr = I.instr |
| 23 |
and type I.instruction = I.instruction |
| 24 |
and type I.operand = I.operand |
| 25 |
) : CONTROL_FLOW_GRAPH = |
| 26 |
struct |
| 27 |
|
| 28 |
structure I = I |
| 29 |
structure P = Asm.S.P |
| 30 |
structure C = I.C |
| 31 |
structure G = Graph |
| 32 |
structure S = Asm.S |
| 33 |
structure A = Array |
| 34 |
structure H = IntHashTable |
| 35 |
|
| 36 |
type weight = real |
| 37 |
|
| 38 |
datatype block_kind = |
| 39 |
START (* entry node *) |
| 40 |
| STOP (* exit node *) |
| 41 |
| NORMAL (* normal node *) |
| 42 |
|
| 43 |
and block = |
| 44 |
BLOCK of |
| 45 |
{ id : int, (* block id *) |
| 46 |
kind : block_kind, (* block kind *) |
| 47 |
freq : weight ref, (* execution frequency *) |
| 48 |
labels : Label.label list ref, (* labels on blocks *) |
| 49 |
insns : I.instruction list ref, (* in rev order *) |
| 50 |
align : P.pseudo_op option ref, (* alignment only *) |
| 51 |
annotations : Annotations.annotations ref (* annotations *) |
| 52 |
} |
| 53 |
|
| 54 |
and edge_kind (* edge kinds (see cfg.sig for more info) *) |
| 55 |
= ENTRY (* entry edge *) |
| 56 |
| EXIT (* exit edge *) |
| 57 |
| JUMP (* unconditional jump *) |
| 58 |
| FALLSTHRU (* falls through to next block *) |
| 59 |
| BRANCH of bool (* branch *) |
| 60 |
| SWITCH of int (* computed goto *) |
| 61 |
| FLOWSTO (* FLOW_TO edge *) |
| 62 |
|
| 63 |
and edge_info = EDGE of { |
| 64 |
k : edge_kind, (* edge kind *) |
| 65 |
w : weight ref, (* edge freq *) |
| 66 |
a : Annotations.annotations ref (* annotations *) |
| 67 |
} |
| 68 |
|
| 69 |
type edge = edge_info Graph.edge |
| 70 |
type node = block Graph.node |
| 71 |
|
| 72 |
datatype info = |
| 73 |
INFO of { annotations : Annotations.annotations ref, |
| 74 |
firstBlock : int ref, |
| 75 |
reorder : bool ref, |
| 76 |
data : P.pseudo_op list ref, |
| 77 |
decls : P.pseudo_op list ref |
| 78 |
} |
| 79 |
|
| 80 |
type cfg = (block,edge_info,info) Graph.graph |
| 81 |
|
| 82 |
fun error msg = MLRiscErrorMsg.error("ControlFlowGraph",msg) |
| 83 |
|
| 84 |
(*======================================================================== |
| 85 |
* |
| 86 |
* Various kinds of annotations |
| 87 |
* |
| 88 |
*========================================================================*) |
| 89 |
(* escaping live out information *) |
| 90 |
val LIVEOUT = Annotations.new |
| 91 |
(SOME(fn c => "Liveout: "^ |
| 92 |
(LineBreak.lineBreak 75 |
| 93 |
(CellsBasis.CellSet.toString c)))) |
| 94 |
exception Changed of string * (unit -> unit) |
| 95 |
val CHANGED = Annotations.new' |
| 96 |
{create=Changed, |
| 97 |
get=fn Changed x => x | e => raise e, |
| 98 |
toString=fn (name,_) => "CHANGED:"^name |
| 99 |
} |
| 100 |
|
| 101 |
(*======================================================================== |
| 102 |
* |
| 103 |
* Methods for manipulating basic blocks |
| 104 |
* |
| 105 |
*========================================================================*) |
| 106 |
fun defineLabel(BLOCK{labels=ref(l::_),...}) = l |
| 107 |
| defineLabel(BLOCK{labels, ...}) = let |
| 108 |
val l = Label.anon () |
| 109 |
in |
| 110 |
labels := [l]; |
| 111 |
l |
| 112 |
end |
| 113 |
fun insns(BLOCK{insns, ...}) = insns |
| 114 |
fun freq(BLOCK{freq, ...}) = freq |
| 115 |
fun edgeFreq(_,_,EDGE{w, ...}) = w |
| 116 |
fun sumEdgeFreqs es = foldr (fn (e,w) => !(edgeFreq e) + w) 0.0 es |
| 117 |
|
| 118 |
fun newBlock'(id,kind,insns,freq) = |
| 119 |
BLOCK{ id = id, |
| 120 |
kind = kind, |
| 121 |
freq = freq, |
| 122 |
labels = ref [], |
| 123 |
insns = ref insns, |
| 124 |
align = ref NONE, |
| 125 |
annotations = ref [] |
| 126 |
} |
| 127 |
|
| 128 |
fun copyBlock(id,BLOCK{kind,freq,align,labels,insns,annotations,...}) = |
| 129 |
BLOCK{ id = id, |
| 130 |
kind = kind, |
| 131 |
freq = ref (!freq), |
| 132 |
labels = ref [], |
| 133 |
align = ref (!align), |
| 134 |
insns = ref (!insns), |
| 135 |
annotations = ref (!annotations) |
| 136 |
} |
| 137 |
|
| 138 |
fun newBlock(id,freq) = newBlock'(id,NORMAL,[],freq) |
| 139 |
fun newStart(id,freq) = newBlock'(id,START,[],freq) |
| 140 |
fun newStop(id,freq) = newBlock'(id,STOP,[],freq) |
| 141 |
|
| 142 |
fun newNode (G.GRAPH graph) wt = let |
| 143 |
val id = #new_id graph () |
| 144 |
val nd = (id, newBlock (id, ref wt)) |
| 145 |
in |
| 146 |
#add_node graph nd; |
| 147 |
nd |
| 148 |
end |
| 149 |
|
| 150 |
fun branchOf(EDGE{k=BRANCH b,...}) = SOME b |
| 151 |
| branchOf _ = NONE |
| 152 |
fun edgeDir(_,_,e) = branchOf e |
| 153 |
|
| 154 |
(*======================================================================== |
| 155 |
* |
| 156 |
* Emit a basic block |
| 157 |
* |
| 158 |
*========================================================================*) |
| 159 |
fun kindName START = "START" |
| 160 |
| kindName STOP = "STOP" |
| 161 |
| kindName NORMAL = "Block" |
| 162 |
|
| 163 |
fun nl() = TextIO.output(!AsmStream.asmOutStream,"\n") |
| 164 |
|
| 165 |
fun emitHeader (S.STREAM{comment,annotation,...}) |
| 166 |
(BLOCK{id,kind,freq,annotations,...}) = |
| 167 |
(comment(kindName kind ^"["^Int.toString id^ |
| 168 |
"] ("^Real.toString (!freq)^")"); |
| 169 |
nl(); |
| 170 |
app annotation (!annotations) |
| 171 |
) |
| 172 |
|
| 173 |
fun emitFooter (S.STREAM{comment,...}) (BLOCK{annotations,...}) = |
| 174 |
(case #get LIVEOUT (!annotations) of |
| 175 |
SOME s => |
| 176 |
let val regs = String.tokens Char.isSpace(CellsBasis.CellSet.toString s) |
| 177 |
val K = 7 |
| 178 |
fun f(_,[],s,l) = s::l |
| 179 |
| f(0,vs,s,l) = f(K,vs," ",s::l) |
| 180 |
| f(n,[v],s,l) = v^s::l |
| 181 |
| f(n,v::vs,s,l) = f(n-1,vs,s^" "^v,l) |
| 182 |
val text = rev(f(K,regs,"",[])) |
| 183 |
in app (fn c => (comment c; nl())) text |
| 184 |
end |
| 185 |
| NONE => () |
| 186 |
) handle Overflow => print("Bad footer\n") |
| 187 |
|
| 188 |
fun emitStuff outline annotations |
| 189 |
(block as BLOCK{insns,labels,...}) = |
| 190 |
let val S as S.STREAM{pseudoOp,defineLabel,emit,...} = |
| 191 |
Asm.makeStream annotations |
| 192 |
in emitHeader S block; |
| 193 |
app defineLabel (!labels); |
| 194 |
if outline then () else app emit (rev (!insns)); |
| 195 |
emitFooter S block |
| 196 |
end |
| 197 |
|
| 198 |
val emit = emitStuff false |
| 199 |
val emitOutline = emitStuff true [] |
| 200 |
|
| 201 |
(*======================================================================== |
| 202 |
* |
| 203 |
* Methods for manipulating CFG |
| 204 |
* |
| 205 |
*========================================================================*) |
| 206 |
fun cfg info = GraphImpl.graph("CFG",info,10) |
| 207 |
fun new() = |
| 208 |
let val info = INFO{ annotations = ref [], |
| 209 |
firstBlock = ref 0, |
| 210 |
reorder = ref false, |
| 211 |
data = ref [], |
| 212 |
decls = ref [] |
| 213 |
} |
| 214 |
in cfg info end |
| 215 |
|
| 216 |
fun subgraph(CFG as G.GRAPH{graph_info=INFO graph_info,...}) = |
| 217 |
let val info = INFO{ annotations = ref [], |
| 218 |
firstBlock = #firstBlock graph_info, |
| 219 |
reorder = #reorder graph_info, |
| 220 |
data = #data graph_info, |
| 221 |
decls = #decls graph_info |
| 222 |
} |
| 223 |
in UpdateGraphInfo.update CFG info end |
| 224 |
|
| 225 |
fun init(G.GRAPH cfg) = |
| 226 |
(case #entries cfg () of |
| 227 |
[] => |
| 228 |
let val i = #new_id cfg () |
| 229 |
val start = newStart(i,ref 0.0) |
| 230 |
val _ = #add_node cfg (i,start) |
| 231 |
val j = #new_id cfg () |
| 232 |
val stop = newStop(j,ref 0.0) |
| 233 |
val _ = #add_node cfg (j,stop) |
| 234 |
in (* #add_edge cfg (i,j,EDGE{k=ENTRY,w=ref 0,a=ref []}); *) |
| 235 |
#set_entries cfg [i]; |
| 236 |
#set_exits cfg [j] |
| 237 |
end |
| 238 |
| _ => () |
| 239 |
) |
| 240 |
|
| 241 |
fun changed(G.GRAPH{graph_info=INFO{reorder,annotations,...},...}) = |
| 242 |
let fun signal [] = () |
| 243 |
| signal(Changed(_,f)::an) = (f (); signal an) |
| 244 |
| signal(_::an) = signal an |
| 245 |
in signal(!annotations); |
| 246 |
reorder := true |
| 247 |
end |
| 248 |
|
| 249 |
fun annotations(G.GRAPH{graph_info=INFO{annotations=a,...},...}) = a |
| 250 |
|
| 251 |
fun liveOut (BLOCK{annotations, ...}) = |
| 252 |
case #get LIVEOUT (!annotations) of |
| 253 |
SOME s => s |
| 254 |
| NONE => C.empty |
| 255 |
fun fallsThruFrom(G.GRAPH cfg,b) = |
| 256 |
let fun f [] = NONE |
| 257 |
| f((i,_,EDGE{k=BRANCH false,...})::_) = SOME i |
| 258 |
| f((i,_,EDGE{k=FALLSTHRU,...})::_) = SOME i |
| 259 |
| f(_::es) = f es |
| 260 |
in f(#in_edges cfg b) |
| 261 |
end |
| 262 |
fun fallsThruTo(G.GRAPH cfg,b) = |
| 263 |
let fun f [] = NONE |
| 264 |
| f((_,j,EDGE{k=BRANCH false,...})::_) = SOME j |
| 265 |
| f((_,j,EDGE{k=FALLSTHRU,...})::_) = SOME j |
| 266 |
| f(_::es) = f es |
| 267 |
in f(#out_edges cfg b) |
| 268 |
end |
| 269 |
fun removeEdge CFG (i,j,EDGE{a,...}) = |
| 270 |
Graph.remove_edge' CFG (i,j,fn EDGE{a=a',...} => a = a') |
| 271 |
|
| 272 |
fun setBranch (CFG as G.GRAPH cfg,b,cond) = |
| 273 |
let fun loop((i,j,EDGE{k=BRANCH cond',w,a})::es,es',x,y) = |
| 274 |
if cond' = cond then |
| 275 |
loop(es, (i,j,EDGE{k=JUMP,w=w,a=a})::es',j,y) |
| 276 |
else |
| 277 |
loop(es, es', x, j) |
| 278 |
| loop([],es',target,elim) = (es',target,elim) |
| 279 |
| loop _ = error "setBranch" |
| 280 |
val outEdges = #out_edges cfg b |
| 281 |
val (outEdges',target,elim) = loop(outEdges,[],~1,~1) |
| 282 |
val _ = if elim < 0 then error "setBranch: bad edges" else (); |
| 283 |
val lab = defineLabel(#node_info cfg target) |
| 284 |
val jmp = InsnProps.jump lab |
| 285 |
val insns = insns(#node_info cfg b) |
| 286 |
in #set_out_edges cfg (b,outEdges'); |
| 287 |
case !insns of |
| 288 |
[] => error "setBranch: missing branch" |
| 289 |
| branch::rest => |
| 290 |
case InsnProps.instrKind branch of |
| 291 |
InsnProps.IK_JUMP => insns := jmp::rest |
| 292 |
| _ => error "setBranch: bad branch instruction"; |
| 293 |
jmp |
| 294 |
end |
| 295 |
|
| 296 |
local |
| 297 |
fun getNode (G.GRAPH{node_info, ...}, id) = (id, node_info id) |
| 298 |
in |
| 299 |
fun entryId (G.GRAPH{entries, ...}) = (case entries() |
| 300 |
of [id] => id |
| 301 |
| _ => error "no unique entry block" |
| 302 |
(* end case *)) |
| 303 |
fun entry cfg = getNode(cfg, entryId cfg) |
| 304 |
fun exitId (G.GRAPH{exits, node_info, ...}) = (case exits() |
| 305 |
of [id] => id |
| 306 |
| _ => error "no unique exit block" |
| 307 |
(* end case *)) |
| 308 |
fun exit cfg = getNode(cfg, exitId cfg) |
| 309 |
end |
| 310 |
|
| 311 |
exception Can'tMerge |
| 312 |
exception NotFound |
| 313 |
|
| 314 |
fun labelOf(G.GRAPH cfg) node = defineLabel(#node_info cfg node) |
| 315 |
|
| 316 |
fun copyEdge(EDGE{a,w,k}) = EDGE{a=ref(!a),w=ref(!w),k=k} |
| 317 |
|
| 318 |
(*===================================================================== |
| 319 |
* |
| 320 |
* Check whether block i must preceed block j in any linear layout. |
| 321 |
* This may be true if i falls through to j (transitively) |
| 322 |
* |
| 323 |
*=====================================================================*) |
| 324 |
fun mustPreceed (G.GRAPH cfg) (i,j) = |
| 325 |
let val visited = H.mkTable(23,NotFound) |
| 326 |
fun chase [] = false |
| 327 |
| chase((u,v,EDGE{k=(FALLSTHRU|BRANCH false),...})::_) = |
| 328 |
if H.inDomain visited u then false |
| 329 |
else u = i orelse (H.insert visited (u,true); chase(#in_edges cfg u)) |
| 330 |
| chase(_::es) = chase es |
| 331 |
in i = j orelse chase(#in_edges cfg j) |
| 332 |
end |
| 333 |
|
| 334 |
(*===================================================================== |
| 335 |
* |
| 336 |
* Predicates on nodes and edges |
| 337 |
* |
| 338 |
*=====================================================================*) |
| 339 |
fun isMerge (G.GRAPH cfg) node = length(#in_edges cfg node) > 1 |
| 340 |
fun isSplit (G.GRAPH cfg) node = length(#out_edges cfg node) > 1 |
| 341 |
(* |
| 342 |
fun hasSideExits (G.GRAPH cfg) node = |
| 343 |
List.exists (fn (_,_,EDGE{k=SIDEEXIT _,...}) => true |
| 344 |
| _ => false) (#out_edges cfg node) |
| 345 |
*) |
| 346 |
fun hasSideExits _ _ = false |
| 347 |
fun isCriticalEdge CFG (_,_,EDGE{k=ENTRY,...}) = false |
| 348 |
| isCriticalEdge CFG (_,_,EDGE{k=EXIT,...}) = false |
| 349 |
| isCriticalEdge CFG (i,j,_) = isSplit CFG i andalso isMerge CFG j |
| 350 |
|
| 351 |
(*===================================================================== |
| 352 |
* |
| 353 |
* Update the label of the branch instruction in a certain block |
| 354 |
* to be consistent with the control flow edges. This doesn't work |
| 355 |
* on hyperblocks!!! |
| 356 |
* |
| 357 |
*=====================================================================*) |
| 358 |
fun updateJumpLabel(CFG as G.GRAPH cfg) = |
| 359 |
let val labelOf = labelOf CFG |
| 360 |
fun update node = |
| 361 |
case #node_info cfg node of |
| 362 |
BLOCK{insns=ref [],...} => () |
| 363 |
| BLOCK{kind=START,...} => () |
| 364 |
| BLOCK{kind=STOP,...} => () |
| 365 |
| BLOCK{insns=insns as ref(jmp::rest),...} => |
| 366 |
(case #out_edges cfg node of |
| 367 |
[] => () |
| 368 |
| [(_,_,EDGE{k=(ENTRY | EXIT),...})] => () |
| 369 |
| [(i,j,_)] => |
| 370 |
if InsnProps.instrKind jmp = InsnProps.IK_JUMP then |
| 371 |
insns := InsnProps.setJumpTarget(jmp,labelOf j)::rest |
| 372 |
else () |
| 373 |
| [(_,i,EDGE{k=BRANCH x,...}), |
| 374 |
(_,j,EDGE{k=BRANCH y,...})] => |
| 375 |
let val (no,yes) = if x then (j,i) else (i,j) |
| 376 |
in insns := |
| 377 |
InsnProps.setBranchTargets{i=jmp, |
| 378 |
f=labelOf no,t=labelOf yes}::rest |
| 379 |
end |
| 380 |
| es => |
| 381 |
let fun gt ((_,_,EDGE{k=SWITCH i,...}), |
| 382 |
(_,_,EDGE{k=SWITCH j,...})) = i > j |
| 383 |
| gt _ = error "gt" |
| 384 |
val es = ListMergeSort.sort gt es |
| 385 |
val labels = map (fn (_,j,_) => labelOf j) es |
| 386 |
in error "updateJumpLabel" |
| 387 |
end |
| 388 |
) |
| 389 |
in update |
| 390 |
end |
| 391 |
|
| 392 |
(*===================================================================== |
| 393 |
* |
| 394 |
* Merge a control flow edge i -> j. |
| 395 |
* Raise Can't Merge if it is illegal. |
| 396 |
* After merging blocks i and j will become block i. |
| 397 |
* |
| 398 |
*=====================================================================*) |
| 399 |
fun mergeEdge (CFG as G.GRAPH cfg) (i,j,e as EDGE{w,k,...}) = |
| 400 |
let val _ = case k of |
| 401 |
(ENTRY | EXIT) => raise Can'tMerge |
| 402 |
| _ => () |
| 403 |
val _ = case (#out_edges cfg i,#in_edges cfg j) of |
| 404 |
([(_,j',_)],[(i',_,_)]) => |
| 405 |
if j' <> j orelse i' <> i then raise Can'tMerge |
| 406 |
else () |
| 407 |
| _ => raise Can'tMerge |
| 408 |
val _ = if mustPreceed CFG (i,j) then raise Can'tMerge else () |
| 409 |
val BLOCK{align=d2,insns=i2,annotations=a2,...} = #node_info cfg j |
| 410 |
val _ = case !d2 of SOME _ => () | _ => raise Can'tMerge |
| 411 |
val BLOCK{align=d1,insns=i1,annotations=a1,...} = #node_info cfg i |
| 412 |
(* If both blocks have annotations then don't merge them. |
| 413 |
* But instead, just try to removed the jump instruction instead. |
| 414 |
*) |
| 415 |
val canMerge = case (!a1, !a2) of |
| 416 |
(_::_, _::_) => false |
| 417 |
| _ => true |
| 418 |
val insns1 = case !i1 of |
| 419 |
[] => [] |
| 420 |
| insns as jmp::rest => |
| 421 |
if InsnProps.instrKind jmp = InsnProps.IK_JUMP |
| 422 |
then rest else insns |
| 423 |
in if canMerge then |
| 424 |
(i1 := !i2 @ insns1; |
| 425 |
a1 := !a1 @ !a2; |
| 426 |
#set_out_edges cfg |
| 427 |
(i,map (fn (_,j',e) => (i,j',e)) (#out_edges cfg j)); |
| 428 |
#remove_node cfg j; |
| 429 |
updateJumpLabel CFG i |
| 430 |
) |
| 431 |
else (* Just eliminate the jump instruction at the end *) |
| 432 |
(i1 := insns1; |
| 433 |
#set_out_edges cfg |
| 434 |
(i,map (fn (i,j,EDGE{w,a,...}) => |
| 435 |
(i,j,EDGE{k=FALLSTHRU,w=w,a=a})) |
| 436 |
(#out_edges cfg i)) |
| 437 |
); |
| 438 |
true |
| 439 |
end handle Can'tMerge => false |
| 440 |
|
| 441 |
(*===================================================================== |
| 442 |
* |
| 443 |
* Eliminate the jump at the end of a basic block if feasible |
| 444 |
* |
| 445 |
*=====================================================================*) |
| 446 |
fun eliminateJump (CFG as G.GRAPH cfg) i = |
| 447 |
(case #out_edges cfg i of |
| 448 |
[e as (i,j,EDGE{k,w,a})] => |
| 449 |
(case fallsThruFrom(CFG,j) of |
| 450 |
SOME _ => false |
| 451 |
| NONE => |
| 452 |
if mustPreceed CFG (j,i) then false |
| 453 |
else |
| 454 |
let val BLOCK{insns,...} = #node_info cfg i |
| 455 |
val BLOCK{align,...} = #node_info cfg j |
| 456 |
in case (!align,!insns) of |
| 457 |
(NONE,jmp::rest) => |
| 458 |
if InsnProps.instrKind jmp = InsnProps.IK_JUMP then |
| 459 |
(insns := rest; |
| 460 |
removeEdge CFG e; |
| 461 |
#add_edge cfg (i,j,EDGE{k=FALLSTHRU,w=w,a=a}); |
| 462 |
true |
| 463 |
) |
| 464 |
else false |
| 465 |
| _ => false |
| 466 |
end |
| 467 |
) |
| 468 |
| _ => false |
| 469 |
) |
| 470 |
|
| 471 |
(*===================================================================== |
| 472 |
* |
| 473 |
* Insert a jump at the end of a basic block if feasible |
| 474 |
* |
| 475 |
*=====================================================================*) |
| 476 |
fun insertJump (CFG as G.GRAPH cfg) i = |
| 477 |
(case #out_edges cfg i of |
| 478 |
[e as (i,j,EDGE{k=FALLSTHRU,w,a,...})] => |
| 479 |
let val BLOCK{insns,...} = #node_info cfg i |
| 480 |
in insns := InsnProps.jump(labelOf CFG j) :: !insns; |
| 481 |
removeEdge CFG e; |
| 482 |
#add_edge cfg (i,j,EDGE{k=JUMP,w=w,a=a}); |
| 483 |
true |
| 484 |
end |
| 485 |
| _ => false |
| 486 |
) |
| 487 |
|
| 488 |
|
| 489 |
(*===================================================================== |
| 490 |
* |
| 491 |
* Split a group of control flow edge. |
| 492 |
* |
| 493 |
* Split n groups of control flow edges, all initially entering block j, |
| 494 |
* |
| 495 |
* i_11 -> j, i_12 -> j, ... group 1 |
| 496 |
* i_21 -> j, i_22 -> j, ... group 2 |
| 497 |
* .... |
| 498 |
* i_n1 -> j, i_n2 -> j, ... group n |
| 499 |
* |
| 500 |
* into |
| 501 |
* |
| 502 |
* i_11 -> k_1 |
| 503 |
* i_12 -> k_1 |
| 504 |
* ... |
| 505 |
* i_21 -> k_2 |
| 506 |
* i_22 -> k_2 |
| 507 |
* ... |
| 508 |
* i_n1 -> k_n |
| 509 |
* i_n2 -> k_n |
| 510 |
* ... |
| 511 |
* |
| 512 |
* and k_1 -> k_2 |
| 513 |
* k_2 -> k_3 |
| 514 |
* ... |
| 515 |
* k_n -> j |
| 516 |
* |
| 517 |
* Return the new edges |
| 518 |
* k_1->j,...,k_n -> j |
| 519 |
* |
| 520 |
* and the new blocks |
| 521 |
* k_1, ..., k_n. |
| 522 |
* |
| 523 |
* Each block k_1, ..., k_n can have instructions placed in them. |
| 524 |
* |
| 525 |
* If the jump flag is true, then a jump is always placed in the |
| 526 |
* new block k_n; otherwise, we try to eliminate the jump when feasible. |
| 527 |
* |
| 528 |
*=====================================================================*) |
| 529 |
fun splitEdges (CFG as G.GRAPH cfg) {groups=[], jump} = [] |
| 530 |
| splitEdges (CFG as G.GRAPH cfg) {groups as ((first,_)::_), jump} = |
| 531 |
let (* target of all the edges *) |
| 532 |
val j = let val (_,j,_) = hd first in j end |
| 533 |
|
| 534 |
(* Insert an edge i->j with frequency freq. |
| 535 |
* It is a jump edge iff jump flag is true or |
| 536 |
* some other block is already falling into j |
| 537 |
*) |
| 538 |
fun insertEdge(i,j,node_i,freq,jump) = |
| 539 |
let val kind = |
| 540 |
if jump orelse isSome(fallsThruFrom(CFG,j)) then |
| 541 |
let val insns_i = insns node_i |
| 542 |
in insns_i := InsnProps.jump(labelOf CFG j) :: !insns_i; |
| 543 |
JUMP |
| 544 |
end |
| 545 |
else |
| 546 |
FALLSTHRU |
| 547 |
val edge_info = EDGE{k=kind, w=ref freq, a=ref []} |
| 548 |
val edge = (i,j,edge_info) |
| 549 |
in #add_edge cfg edge; |
| 550 |
edge |
| 551 |
end |
| 552 |
|
| 553 |
(* Redirect all edges *) |
| 554 |
fun redirect([], freq, new) = new |
| 555 |
| redirect((edges, insns)::groups, freq, new) = |
| 556 |
let |
| 557 |
val freq = sumEdgeFreqs edges + freq (* freq of new block *) |
| 558 |
|
| 559 |
(* Sanity check |
| 560 |
*) |
| 561 |
fun check [] = () |
| 562 |
| check((u,v,_)::es) = |
| 563 |
(if v <> j then error "splitEdge: bad edge" else (); |
| 564 |
check es |
| 565 |
) |
| 566 |
|
| 567 |
val () = check edges |
| 568 |
|
| 569 |
val k = #new_id cfg () (* new block id *) |
| 570 |
val node_k = |
| 571 |
BLOCK{id=k, kind=NORMAL, |
| 572 |
freq= ref freq, align=ref NONE, labels = ref [], |
| 573 |
insns=ref insns, annotations=ref []} |
| 574 |
|
| 575 |
in app (removeEdge CFG) edges; |
| 576 |
app (fn (i,_,e) => #add_edge cfg (i,k,e)) edges; |
| 577 |
#add_node cfg (k,node_k); |
| 578 |
redirect(groups, freq, (k, node_k, edges, freq)::new) |
| 579 |
end |
| 580 |
|
| 581 |
val new = redirect(groups, 0.0, []) |
| 582 |
|
| 583 |
(* Add the edges on the chain *) |
| 584 |
fun postprocess([], next, new) = new |
| 585 |
| postprocess((k, node_k, edges, freq)::rest, next, new) = |
| 586 |
let val jump = next = j andalso jump |
| 587 |
val edge = insertEdge(k, next, node_k, freq, jump) |
| 588 |
in postprocess(rest, k, ((k,node_k),edge)::new) |
| 589 |
end |
| 590 |
|
| 591 |
val new = postprocess(new, j, []) |
| 592 |
|
| 593 |
in (* Update the labels on the groups *) |
| 594 |
app (fn (es, _) => app (fn (i,_,_) => updateJumpLabel CFG i) es) groups; |
| 595 |
new |
| 596 |
end |
| 597 |
|
| 598 |
(*===================================================================== |
| 599 |
* |
| 600 |
* Split all critical edges in the CFG |
| 601 |
* |
| 602 |
*=====================================================================*) |
| 603 |
fun splitAllCriticalEdges (CFG as G.GRAPH cfg) = |
| 604 |
let val hasChanged = ref false |
| 605 |
in #forall_edges cfg |
| 606 |
(fn e => if isCriticalEdge CFG e then |
| 607 |
(splitEdges CFG {groups=[([e],[])],jump=false}; |
| 608 |
hasChanged := true) |
| 609 |
else ()); |
| 610 |
if !hasChanged then changed CFG else () |
| 611 |
end |
| 612 |
|
| 613 |
(*===================================================================== |
| 614 |
* |
| 615 |
* Tail duplicate a region until there are no side entry edges |
| 616 |
* entering into the region. Return the set of new edges and nodes |
| 617 |
* |
| 618 |
*=====================================================================*) |
| 619 |
fun tailDuplicate (CFG as G.GRAPH cfg : cfg) |
| 620 |
{subgraph=G.GRAPH subgraph : cfg,root} = |
| 621 |
let |
| 622 |
val blockMap = H.mkTable(10,NotFound) |
| 623 |
val _ = print("[root "^Int.toString root^"]\n") |
| 624 |
|
| 625 |
fun duplicate v = |
| 626 |
H.lookup blockMap v handle NotFound => |
| 627 |
let val w = #new_id cfg () |
| 628 |
val w' = copyBlock(w,#node_info cfg v) |
| 629 |
in #add_node cfg (w,w'); |
| 630 |
H.insert blockMap (v,(w,w')); |
| 631 |
app (#add_edge cfg) |
| 632 |
(map (fn (i,j,e) => (w,j,copyEdge e)) (#out_edges cfg v)); |
| 633 |
updateJumpLabel CFG w; |
| 634 |
(w,w') |
| 635 |
end |
| 636 |
|
| 637 |
fun process((n,_)::rest,ns,Ns,Es) = |
| 638 |
process(rest,collect(#entry_edges subgraph n,ns),Ns,Es) |
| 639 |
| process([],ns,Ns,Es) = dupl(ns,Ns,Es,false) |
| 640 |
|
| 641 |
and collect([],ns) = ns |
| 642 |
| collect((i,_,_)::es,ns) = collect(es,if i = root then ns else i::ns) |
| 643 |
|
| 644 |
and dupl([],Ns,Es,changed) = (Ns,Es,changed) |
| 645 |
| dupl(n::ns,Ns,Es,changed) = |
| 646 |
redirect(#out_edges cfg n,ns,Ns,Es,changed) |
| 647 |
|
| 648 |
and redirect([],ns,Ns,Es,changed) = dupl(ns,Ns,Es,changed) |
| 649 |
| redirect((u,v,e)::es,ns,Ns,Es,changed) = |
| 650 |
if v <> root andalso |
| 651 |
#has_edge cfg (u,v) andalso |
| 652 |
#has_node subgraph v andalso |
| 653 |
not(#has_edge subgraph (u,v)) then |
| 654 |
(* |
| 655 |
* u -> v is a side entry edge, duplicate v |
| 656 |
*) |
| 657 |
let val _ = print("[tail duplicating "^Int.toString u^" -> "^ |
| 658 |
Int.toString v^"]\n") |
| 659 |
val (w,w') = duplicate v |
| 660 |
in removeEdge CFG (u,v,e); |
| 661 |
#add_edge cfg (u,w,e); |
| 662 |
updateJumpLabel CFG u; |
| 663 |
redirect(es,w::ns,(w,w')::Ns,(u,w,e)::Es,true) |
| 664 |
end |
| 665 |
else redirect(es,ns,Ns,Es,changed) |
| 666 |
|
| 667 |
fun iter(Ns,Es) = |
| 668 |
let val (Ns,Es,hasChanged) = process(#nodes subgraph (),[],Ns,Es) |
| 669 |
in if hasChanged then (changed CFG; iter(Ns,Es)) |
| 670 |
else {nodes=Ns,edges=Es} |
| 671 |
end |
| 672 |
|
| 673 |
in iter([],[]) |
| 674 |
end |
| 675 |
|
| 676 |
|
| 677 |
(*===================================================================== |
| 678 |
* |
| 679 |
* Remove unreachable code in the CFG |
| 680 |
* |
| 681 |
*=====================================================================*) |
| 682 |
fun removeUnreachableCode(CFG as G.GRAPH cfg) = |
| 683 |
let val N = #capacity cfg () |
| 684 |
val visited = A.array(N,false) |
| 685 |
fun mark n = if A.sub(visited,n) then () |
| 686 |
else (A.update(visited,n,true); app mark (#succ cfg n)) |
| 687 |
val hasChanged = ref false |
| 688 |
fun remove(b,BLOCK{align,insns,...}) = |
| 689 |
if A.sub(visited,b) then () |
| 690 |
else |
| 691 |
(hasChanged :=true; |
| 692 |
case #in_edges cfg b of |
| 693 |
[] => #remove_node cfg b |
| 694 |
| _ => (insns := []; #set_out_edges cfg (b,[])) |
| 695 |
) |
| 696 |
in app mark (#entries cfg ()); |
| 697 |
#forall_nodes cfg remove; |
| 698 |
if !hasChanged then changed CFG else () |
| 699 |
end |
| 700 |
|
| 701 |
|
| 702 |
(*===================================================================== |
| 703 |
* |
| 704 |
* Merge all edges in the CFG. |
| 705 |
* Merge higher frequency edges first |
| 706 |
* |
| 707 |
*=====================================================================*) |
| 708 |
fun mergeAllEdges(CFG as G.GRAPH cfg) = |
| 709 |
let val mergeEdge = mergeEdge CFG |
| 710 |
fun higherFreq((_,_,EDGE{w=x,...}),(_,_,EDGE{w=y,...}))= !x < !y |
| 711 |
fun mergeAll([],changed) = changed |
| 712 |
| mergeAll(e::es,changed) = mergeAll(es,mergeEdge e orelse changed) |
| 713 |
(* note: sort expects the gt operator and sorts in ascending order *) |
| 714 |
val hasChanged = mergeAll(ListMergeSort.sort higherFreq (#edges cfg ()), |
| 715 |
false) |
| 716 |
in if hasChanged then changed CFG else () |
| 717 |
end |
| 718 |
|
| 719 |
(*======================================================================== |
| 720 |
* |
| 721 |
* Miscellaneous |
| 722 |
* |
| 723 |
*========================================================================*) |
| 724 |
fun cdgEdge(EDGE{k, ...}) = |
| 725 |
case k of |
| 726 |
(JUMP | FALLSTHRU) => false |
| 727 |
| _ => true |
| 728 |
|
| 729 |
(*======================================================================== |
| 730 |
* |
| 731 |
* Pretty Printing and Viewing |
| 732 |
* |
| 733 |
*========================================================================*) |
| 734 |
|
| 735 |
structure F = Format |
| 736 |
|
| 737 |
fun show_edge (EDGE{k,w,a,...}) = let |
| 738 |
val kind = (case k |
| 739 |
of JUMP => "jump" |
| 740 |
| FALLSTHRU => "fallsthru" |
| 741 |
| BRANCH b => Bool.toString b |
| 742 |
| SWITCH i => Int.toString i |
| 743 |
| ENTRY => "entry" |
| 744 |
| EXIT => "exit" |
| 745 |
| FLOWSTO => "flowsto" |
| 746 |
(* end case *)) |
| 747 |
in |
| 748 |
F.format "%s[%f]" [F.STR kind, F.REAL(!w)] |
| 749 |
end |
| 750 |
|
| 751 |
fun getString f x = let |
| 752 |
val buffer = StringOutStream.mkStreamBuf() |
| 753 |
val S = StringOutStream.openStringOut buffer |
| 754 |
val _ = AsmStream.withStream S f x |
| 755 |
in |
| 756 |
StringOutStream.getString buffer |
| 757 |
end |
| 758 |
|
| 759 |
fun show_block an block = let |
| 760 |
val text = getString (emit an) block |
| 761 |
in |
| 762 |
foldr (fn (x,"") => x | (x,y) => x^" "^y) "" |
| 763 |
(String.tokens (fn #" " => true | _ => false) text) |
| 764 |
end |
| 765 |
|
| 766 |
fun dumpBlock (outS, cfg as G.GRAPH g) = let |
| 767 |
fun pr str = TextIO.output(outS, str) |
| 768 |
fun prList [] = () |
| 769 |
| prList [i] = pr i |
| 770 |
| prList (h::t) = (pr (h ^ ", "); prList t) |
| 771 |
val Asm.S.STREAM{emit,defineLabel,annotation,...} = |
| 772 |
AsmStream.withStream outS Asm.makeStream [] |
| 773 |
fun showFreq (ref w) = F.format "[%f]" [F.REAL w] |
| 774 |
fun showEdge (blknum,e) = |
| 775 |
F.format "%d:%s" [F.INT blknum, F.STR(show_edge e)] |
| 776 |
fun showSucc (_, x, e) = showEdge(x,e) |
| 777 |
fun showPred (x, _, e) = showEdge(x,e) |
| 778 |
fun showSuccs b = ( |
| 779 |
pr "\tsucc: "; |
| 780 |
prList (map showSucc (#out_edges g b)); |
| 781 |
pr "\n") |
| 782 |
fun showPreds b = ( |
| 783 |
pr "\tpred: "; |
| 784 |
prList (map showPred (#in_edges g b)); |
| 785 |
pr "\n") |
| 786 |
fun printBlock (_, BLOCK{kind=START, id, freq, ...}) = ( |
| 787 |
pr (F.format "ENTRY %d %s\n" [F.INT id, F.STR(showFreq freq)]); |
| 788 |
showSuccs id) |
| 789 |
| printBlock (_, BLOCK{kind=STOP, id, freq, ...}) = ( |
| 790 |
pr (F.format "EXIT %d %s\n" [F.INT id, F.STR(showFreq freq)]); |
| 791 |
showPreds id) |
| 792 |
| printBlock ( |
| 793 |
_, BLOCK{id, align, freq, insns, annotations, labels, ...} |
| 794 |
) = ( |
| 795 |
pr (F.format "BLOCK %d %s\n" [F.INT id, F.STR(showFreq freq)]); |
| 796 |
case !align of NONE => () | SOME p => (pr (P.toString p ^ "\n")); |
| 797 |
List.app annotation (!annotations); |
| 798 |
List.app defineLabel (!labels); |
| 799 |
showSuccs id; |
| 800 |
showPreds id; |
| 801 |
List.app emit (List.rev (!insns))) |
| 802 |
in |
| 803 |
printBlock |
| 804 |
end |
| 805 |
|
| 806 |
fun dump (outS, title, cfg as G.GRAPH g) = let |
| 807 |
fun pr str = TextIO.output(outS, str) |
| 808 |
val annotations = !(annotations cfg) |
| 809 |
val Asm.S.STREAM{annotation, ...} = |
| 810 |
AsmStream.withStream outS Asm.makeStream annotations |
| 811 |
fun printData () = let |
| 812 |
val INFO{data, ...} = #graph_info g |
| 813 |
in |
| 814 |
List.app (pr o P.toString) (rev(!data)) |
| 815 |
end |
| 816 |
in |
| 817 |
pr(F.format "[ %s ]\n" [F.STR title]); |
| 818 |
List.app annotation annotations; |
| 819 |
(* printBlock entry; *) |
| 820 |
AsmStream.withStream outS (#forall_nodes g) (dumpBlock (outS, cfg)); |
| 821 |
(* printBlock exit; *) |
| 822 |
AsmStream.withStream outS printData (); |
| 823 |
TextIO.flushOut outS |
| 824 |
end |
| 825 |
|
| 826 |
end |
| 827 |
|