github.com/rakyll/go@v0.0.0-20170216000551-64c02460d703/src/cmd/compile/internal/ssa/regalloc.go (about) 1 // Copyright 2015 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Register allocation. 6 // 7 // We use a version of a linear scan register allocator. We treat the 8 // whole function as a single long basic block and run through 9 // it using a greedy register allocator. Then all merge edges 10 // (those targeting a block with len(Preds)>1) are processed to 11 // shuffle data into the place that the target of the edge expects. 12 // 13 // The greedy allocator moves values into registers just before they 14 // are used, spills registers only when necessary, and spills the 15 // value whose next use is farthest in the future. 16 // 17 // The register allocator requires that a block is not scheduled until 18 // at least one of its predecessors have been scheduled. The most recent 19 // such predecessor provides the starting register state for a block. 20 // 21 // It also requires that there are no critical edges (critical = 22 // comes from a block with >1 successor and goes to a block with >1 23 // predecessor). This makes it easy to add fixup code on merge edges - 24 // the source of a merge edge has only one successor, so we can add 25 // fixup code to the end of that block. 26 27 // Spilling 28 // 29 // For every value, we generate a spill immediately after the value itself. 30 // x = Op y z : AX 31 // x2 = StoreReg x 32 // While AX still holds x, any uses of x will use that value. When AX is needed 33 // for another value, we simply reuse AX. Spill code has already been generated 34 // so there is no code generated at "spill" time. When x is referenced 35 // subsequently, we issue a load to restore x to a register using x2 as 36 // its argument: 37 // x3 = Restore x2 : CX 38 // x3 can then be used wherever x is referenced again. 39 // If the spill (x2) is never used, it will be removed at the end of regalloc. 40 // 41 // Phi values are special, as always. We define two kinds of phis, those 42 // where the merge happens in a register (a "register" phi) and those where 43 // the merge happens in a stack location (a "stack" phi). 44 // 45 // A register phi must have the phi and all of its inputs allocated to the 46 // same register. Register phis are spilled similarly to regular ops: 47 // b1: y = ... : AX b2: z = ... : AX 48 // goto b3 goto b3 49 // b3: x = phi(y, z) : AX 50 // x2 = StoreReg x 51 // 52 // A stack phi must have the phi and all of its inputs allocated to the same 53 // stack location. Stack phis start out life already spilled - each phi 54 // input must be a store (using StoreReg) at the end of the corresponding 55 // predecessor block. 56 // b1: y = ... : AX b2: z = ... : BX 57 // y2 = StoreReg y z2 = StoreReg z 58 // goto b3 goto b3 59 // b3: x = phi(y2, z2) 60 // The stack allocator knows that StoreReg args of stack-allocated phis 61 // must be allocated to the same stack slot as the phi that uses them. 62 // x is now a spilled value and a restore must appear before its first use. 63 64 // TODO 65 66 // Use an affinity graph to mark two values which should use the 67 // same register. This affinity graph will be used to prefer certain 68 // registers for allocation. This affinity helps eliminate moves that 69 // are required for phi implementations and helps generate allocations 70 // for 2-register architectures. 71 72 // Note: regalloc generates a not-quite-SSA output. If we have: 73 // 74 // b1: x = ... : AX 75 // x2 = StoreReg x 76 // ... AX gets reused for something else ... 77 // if ... goto b3 else b4 78 // 79 // b3: x3 = LoadReg x2 : BX b4: x4 = LoadReg x2 : CX 80 // ... use x3 ... ... use x4 ... 81 // 82 // b2: ... use x3 ... 83 // 84 // If b3 is the primary predecessor of b2, then we use x3 in b2 and 85 // add a x4:CX->BX copy at the end of b4. 86 // But the definition of x3 doesn't dominate b2. We should really 87 // insert a dummy phi at the start of b2 (x5=phi(x3,x4):BX) to keep 88 // SSA form. For now, we ignore this problem as remaining in strict 89 // SSA form isn't needed after regalloc. We'll just leave the use 90 // of x3 not dominated by the definition of x3, and the CX->BX copy 91 // will have no use (so don't run deadcode after regalloc!). 92 // TODO: maybe we should introduce these extra phis? 93 94 // Additional not-quite-SSA output occurs when spills are sunk out 95 // of loops to the targets of exit edges from the loop. Before sinking, 96 // there is one spill site (one StoreReg) targeting stack slot X, after 97 // sinking there may be multiple spill sites targeting stack slot X, 98 // with no phi functions at any join points reachable by the multiple 99 // spill sites. In addition, uses of the spill from copies of the original 100 // will not name the copy in their reference; instead they will name 101 // the original, though both will have the same spill location. The 102 // first sunk spill will be the original, but moved, to an exit block, 103 // thus ensuring that there is a definition somewhere corresponding to 104 // the original spill's uses. 105 106 package ssa 107 108 import ( 109 "cmd/internal/obj" 110 "cmd/internal/src" 111 "fmt" 112 "unsafe" 113 ) 114 115 const ( 116 moveSpills = iota 117 logSpills 118 regDebug 119 stackDebug 120 ) 121 122 // distance is a measure of how far into the future values are used. 123 // distance is measured in units of instructions. 124 const ( 125 likelyDistance = 1 126 normalDistance = 10 127 unlikelyDistance = 100 128 ) 129 130 // regalloc performs register allocation on f. It sets f.RegAlloc 131 // to the resulting allocation. 132 func regalloc(f *Func) { 133 var s regAllocState 134 s.init(f) 135 s.regalloc(f) 136 } 137 138 type register uint8 139 140 const noRegister register = 255 141 142 type regMask uint64 143 144 func (m regMask) String() string { 145 s := "" 146 for r := register(0); m != 0; r++ { 147 if m>>r&1 == 0 { 148 continue 149 } 150 m &^= regMask(1) << r 151 if s != "" { 152 s += " " 153 } 154 s += fmt.Sprintf("r%d", r) 155 } 156 return s 157 } 158 159 // countRegs returns the number of set bits in the register mask. 160 func countRegs(r regMask) int { 161 n := 0 162 for r != 0 { 163 n += int(r & 1) 164 r >>= 1 165 } 166 return n 167 } 168 169 // pickReg picks an arbitrary register from the register mask. 170 func pickReg(r regMask) register { 171 // pick the lowest one 172 if r == 0 { 173 panic("can't pick a register from an empty set") 174 } 175 for i := register(0); ; i++ { 176 if r&1 != 0 { 177 return i 178 } 179 r >>= 1 180 } 181 } 182 183 type use struct { 184 dist int32 // distance from start of the block to a use of a value 185 pos src.XPos // source position of the use 186 next *use // linked list of uses of a value in nondecreasing dist order 187 } 188 189 type valState struct { 190 regs regMask // the set of registers holding a Value (usually just one) 191 uses *use // list of uses in this block 192 spill *Value // spilled copy of the Value 193 spillUsed bool 194 spillUsedShuffle bool // true if used in shuffling, after ordinary uses 195 needReg bool // cached value of !v.Type.IsMemory() && !v.Type.IsVoid() && !.v.Type.IsFlags() 196 rematerializeable bool // cached value of v.rematerializeable() 197 } 198 199 type regState struct { 200 v *Value // Original (preregalloc) Value stored in this register. 201 c *Value // A Value equal to v which is currently in a register. Might be v or a copy of it. 202 // If a register is unused, v==c==nil 203 } 204 205 type regAllocState struct { 206 f *Func 207 208 registers []Register 209 numRegs register 210 SPReg register 211 SBReg register 212 GReg register 213 allocatable regMask 214 215 // for each block, its primary predecessor. 216 // A predecessor of b is primary if it is the closest 217 // predecessor that appears before b in the layout order. 218 // We record the index in the Preds list where the primary predecessor sits. 219 primary []int32 220 221 // live values at the end of each block. live[b.ID] is a list of value IDs 222 // which are live at the end of b, together with a count of how many instructions 223 // forward to the next use. 224 live [][]liveInfo 225 // desired register assignments at the end of each block. 226 // Note that this is a static map computed before allocation occurs. Dynamic 227 // register desires (from partially completed allocations) will trump 228 // this information. 229 desired []desiredState 230 231 // current state of each (preregalloc) Value 232 values []valState 233 234 // For each Value, map from its value ID back to the 235 // preregalloc Value it was derived from. 236 orig []*Value 237 238 // current state of each register 239 regs []regState 240 241 // registers that contain values which can't be kicked out 242 nospill regMask 243 244 // mask of registers currently in use 245 used regMask 246 247 // mask of registers used in the current instruction 248 tmpused regMask 249 250 // current block we're working on 251 curBlock *Block 252 253 // cache of use records 254 freeUseRecords *use 255 256 // endRegs[blockid] is the register state at the end of each block. 257 // encoded as a set of endReg records. 258 endRegs [][]endReg 259 260 // startRegs[blockid] is the register state at the start of merge blocks. 261 // saved state does not include the state of phi ops in the block. 262 startRegs [][]startReg 263 264 // spillLive[blockid] is the set of live spills at the end of each block 265 spillLive [][]ID 266 267 // a set of copies we generated to move things around, and 268 // whether it is used in shuffle. Unused copies will be deleted. 269 copies map[*Value]bool 270 271 loopnest *loopnest 272 } 273 274 type spillToSink struct { 275 spill *Value // Spill instruction to move (a StoreReg) 276 dests int32 // Bitmask indicating exit blocks from loop in which spill/val is defined. 1<<i set means val is live into loop.exitBlocks[i] 277 } 278 279 func (sts *spillToSink) spilledValue() *Value { 280 return sts.spill.Args[0] 281 } 282 283 type endReg struct { 284 r register 285 v *Value // pre-regalloc value held in this register (TODO: can we use ID here?) 286 c *Value // cached version of the value 287 } 288 289 type startReg struct { 290 r register 291 vid ID // pre-regalloc value needed in this register 292 pos src.XPos // source position of use of this register 293 } 294 295 // freeReg frees up register r. Any current user of r is kicked out. 296 func (s *regAllocState) freeReg(r register) { 297 v := s.regs[r].v 298 if v == nil { 299 s.f.Fatalf("tried to free an already free register %d\n", r) 300 } 301 302 // Mark r as unused. 303 if s.f.pass.debug > regDebug { 304 fmt.Printf("freeReg %s (dump %s/%s)\n", s.registers[r].Name(), v, s.regs[r].c) 305 } 306 s.regs[r] = regState{} 307 s.values[v.ID].regs &^= regMask(1) << r 308 s.used &^= regMask(1) << r 309 } 310 311 // freeRegs frees up all registers listed in m. 312 func (s *regAllocState) freeRegs(m regMask) { 313 for m&s.used != 0 { 314 s.freeReg(pickReg(m & s.used)) 315 } 316 } 317 318 // setOrig records that c's original value is the same as 319 // v's original value. 320 func (s *regAllocState) setOrig(c *Value, v *Value) { 321 for int(c.ID) >= len(s.orig) { 322 s.orig = append(s.orig, nil) 323 } 324 if s.orig[c.ID] != nil { 325 s.f.Fatalf("orig value set twice %s %s", c, v) 326 } 327 s.orig[c.ID] = s.orig[v.ID] 328 } 329 330 // assignReg assigns register r to hold c, a copy of v. 331 // r must be unused. 332 func (s *regAllocState) assignReg(r register, v *Value, c *Value) { 333 if s.f.pass.debug > regDebug { 334 fmt.Printf("assignReg %s %s/%s\n", s.registers[r].Name(), v, c) 335 } 336 if s.regs[r].v != nil { 337 s.f.Fatalf("tried to assign register %d to %s/%s but it is already used by %s", r, v, c, s.regs[r].v) 338 } 339 340 // Update state. 341 s.regs[r] = regState{v, c} 342 s.values[v.ID].regs |= regMask(1) << r 343 s.used |= regMask(1) << r 344 s.f.setHome(c, &s.registers[r]) 345 } 346 347 // allocReg chooses a register from the set of registers in mask. 348 // If there is no unused register, a Value will be kicked out of 349 // a register to make room. 350 func (s *regAllocState) allocReg(mask regMask, v *Value) register { 351 mask &= s.allocatable 352 mask &^= s.nospill 353 if mask == 0 { 354 s.f.Fatalf("no register available for %s", v) 355 } 356 357 // Pick an unused register if one is available. 358 if mask&^s.used != 0 { 359 return pickReg(mask &^ s.used) 360 } 361 362 // Pick a value to spill. Spill the value with the 363 // farthest-in-the-future use. 364 // TODO: Prefer registers with already spilled Values? 365 // TODO: Modify preference using affinity graph. 366 // TODO: if a single value is in multiple registers, spill one of them 367 // before spilling a value in just a single register. 368 369 // Find a register to spill. We spill the register containing the value 370 // whose next use is as far in the future as possible. 371 // https://en.wikipedia.org/wiki/Page_replacement_algorithm#The_theoretically_optimal_page_replacement_algorithm 372 var r register 373 maxuse := int32(-1) 374 for t := register(0); t < s.numRegs; t++ { 375 if mask>>t&1 == 0 { 376 continue 377 } 378 v := s.regs[t].v 379 if n := s.values[v.ID].uses.dist; n > maxuse { 380 // v's next use is farther in the future than any value 381 // we've seen so far. A new best spill candidate. 382 r = t 383 maxuse = n 384 } 385 } 386 if maxuse == -1 { 387 s.f.Fatalf("couldn't find register to spill") 388 } 389 390 // Try to move it around before kicking out, if there is a free register. 391 // We generate a Copy and record it. It will be deleted if never used. 392 v2 := s.regs[r].v 393 m := s.compatRegs(v2.Type) &^ s.used &^ s.tmpused &^ (regMask(1) << r) 394 if m != 0 && !s.values[v2.ID].rematerializeable && countRegs(s.values[v2.ID].regs) == 1 { 395 r2 := pickReg(m) 396 c := s.curBlock.NewValue1(v2.Pos, OpCopy, v2.Type, s.regs[r].c) 397 s.copies[c] = false 398 if s.f.pass.debug > regDebug { 399 fmt.Printf("copy %s to %s : %s\n", v2, c, s.registers[r2].Name()) 400 } 401 s.setOrig(c, v2) 402 s.assignReg(r2, v2, c) 403 } 404 s.freeReg(r) 405 return r 406 } 407 408 // allocValToReg allocates v to a register selected from regMask and 409 // returns the register copy of v. Any previous user is kicked out and spilled 410 // (if necessary). Load code is added at the current pc. If nospill is set the 411 // allocated register is marked nospill so the assignment cannot be 412 // undone until the caller allows it by clearing nospill. Returns a 413 // *Value which is either v or a copy of v allocated to the chosen register. 414 func (s *regAllocState) allocValToReg(v *Value, mask regMask, nospill bool, pos src.XPos) *Value { 415 vi := &s.values[v.ID] 416 417 // Check if v is already in a requested register. 418 if mask&vi.regs != 0 { 419 r := pickReg(mask & vi.regs) 420 if s.regs[r].v != v || s.regs[r].c == nil { 421 panic("bad register state") 422 } 423 if nospill { 424 s.nospill |= regMask(1) << r 425 } 426 return s.regs[r].c 427 } 428 429 // Allocate a register. 430 r := s.allocReg(mask, v) 431 432 // Allocate v to the new register. 433 var c *Value 434 if vi.regs != 0 { 435 // Copy from a register that v is already in. 436 r2 := pickReg(vi.regs) 437 if s.regs[r2].v != v { 438 panic("bad register state") 439 } 440 c = s.curBlock.NewValue1(pos, OpCopy, v.Type, s.regs[r2].c) 441 } else if v.rematerializeable() { 442 // Rematerialize instead of loading from the spill location. 443 c = v.copyInto(s.curBlock) 444 } else { 445 switch { 446 // Load v from its spill location. 447 case vi.spill != nil: 448 if s.f.pass.debug > logSpills { 449 s.f.Config.Warnl(vi.spill.Pos, "load spill for %v from %v", v, vi.spill) 450 } 451 c = s.curBlock.NewValue1(pos, OpLoadReg, v.Type, vi.spill) 452 vi.spillUsed = true 453 default: 454 s.f.Fatalf("attempt to load unspilled value %v", v.LongString()) 455 } 456 } 457 s.setOrig(c, v) 458 s.assignReg(r, v, c) 459 if nospill { 460 s.nospill |= regMask(1) << r 461 } 462 return c 463 } 464 465 // isLeaf reports whether f performs any calls. 466 func isLeaf(f *Func) bool { 467 for _, b := range f.Blocks { 468 for _, v := range b.Values { 469 if opcodeTable[v.Op].call { 470 return false 471 } 472 } 473 } 474 return true 475 } 476 477 func (s *regAllocState) init(f *Func) { 478 s.f = f 479 s.f.RegAlloc = s.f.Config.locs[:0] 480 s.registers = f.Config.registers 481 if nr := len(s.registers); nr == 0 || nr > int(noRegister) || nr > int(unsafe.Sizeof(regMask(0))*8) { 482 s.f.Fatalf("bad number of registers: %d", nr) 483 } else { 484 s.numRegs = register(nr) 485 } 486 // Locate SP, SB, and g registers. 487 s.SPReg = noRegister 488 s.SBReg = noRegister 489 s.GReg = noRegister 490 for r := register(0); r < s.numRegs; r++ { 491 switch s.registers[r].Name() { 492 case "SP": 493 s.SPReg = r 494 case "SB": 495 s.SBReg = r 496 case "g": 497 s.GReg = r 498 } 499 } 500 // Make sure we found all required registers. 501 switch noRegister { 502 case s.SPReg: 503 s.f.Fatalf("no SP register found") 504 case s.SBReg: 505 s.f.Fatalf("no SB register found") 506 case s.GReg: 507 if f.Config.hasGReg { 508 s.f.Fatalf("no g register found") 509 } 510 } 511 512 // Figure out which registers we're allowed to use. 513 s.allocatable = s.f.Config.gpRegMask | s.f.Config.fpRegMask | s.f.Config.specialRegMask 514 s.allocatable &^= 1 << s.SPReg 515 s.allocatable &^= 1 << s.SBReg 516 if s.f.Config.hasGReg { 517 s.allocatable &^= 1 << s.GReg 518 } 519 if s.f.Config.ctxt.Framepointer_enabled && s.f.Config.FPReg >= 0 { 520 s.allocatable &^= 1 << uint(s.f.Config.FPReg) 521 } 522 if s.f.Config.ctxt.Flag_shared { 523 switch s.f.Config.arch { 524 case "ppc64le": // R2 already reserved. 525 s.allocatable &^= 1 << 12 // R12 526 } 527 } 528 if s.f.Config.LinkReg != -1 { 529 if isLeaf(f) { 530 // Leaf functions don't save/restore the link register. 531 s.allocatable &^= 1 << uint(s.f.Config.LinkReg) 532 } 533 if s.f.Config.arch == "arm" && obj.GOARM == 5 { 534 // On ARMv5 we insert softfloat calls at each FP instruction. 535 // This clobbers LR almost everywhere. Disable allocating LR 536 // on ARMv5. 537 s.allocatable &^= 1 << uint(s.f.Config.LinkReg) 538 } 539 } 540 if s.f.Config.ctxt.Flag_dynlink { 541 switch s.f.Config.arch { 542 case "amd64": 543 s.allocatable &^= 1 << 15 // R15 544 case "arm": 545 s.allocatable &^= 1 << 9 // R9 546 case "ppc64le": // R2 already reserved. 547 s.allocatable &^= 1 << 12 // R12 548 case "arm64": 549 // nothing to do? 550 case "386": 551 // nothing to do. 552 // Note that for Flag_shared (position independent code) 553 // we do need to be careful, but that carefulness is hidden 554 // in the rewrite rules so we always have a free register 555 // available for global load/stores. See gen/386.rules (search for Flag_shared). 556 case "s390x": 557 // nothing to do, R10 & R11 already reserved 558 default: 559 s.f.Config.fe.Fatalf(src.NoXPos, "arch %s not implemented", s.f.Config.arch) 560 } 561 } 562 if s.f.Config.nacl { 563 switch s.f.Config.arch { 564 case "arm": 565 s.allocatable &^= 1 << 9 // R9 is "thread pointer" on nacl/arm 566 case "amd64p32": 567 s.allocatable &^= 1 << 5 // BP - reserved for nacl 568 s.allocatable &^= 1 << 15 // R15 - reserved for nacl 569 } 570 } 571 if s.f.Config.use387 { 572 s.allocatable &^= 1 << 15 // X7 disallowed (one 387 register is used as scratch space during SSE->387 generation in ../x86/387.go) 573 } 574 575 s.regs = make([]regState, s.numRegs) 576 s.values = make([]valState, f.NumValues()) 577 s.orig = make([]*Value, f.NumValues()) 578 s.copies = make(map[*Value]bool) 579 for _, b := range f.Blocks { 580 for _, v := range b.Values { 581 if !v.Type.IsMemory() && !v.Type.IsVoid() && !v.Type.IsFlags() && !v.Type.IsTuple() { 582 s.values[v.ID].needReg = true 583 s.values[v.ID].rematerializeable = v.rematerializeable() 584 s.orig[v.ID] = v 585 } 586 // Note: needReg is false for values returning Tuple types. 587 // Instead, we mark the corresponding Selects as needReg. 588 } 589 } 590 s.computeLive() 591 592 // Compute block order. This array allows us to distinguish forward edges 593 // from backward edges and compute how far they go. 594 blockOrder := make([]int32, f.NumBlocks()) 595 for i, b := range f.Blocks { 596 blockOrder[b.ID] = int32(i) 597 } 598 599 // Compute primary predecessors. 600 s.primary = make([]int32, f.NumBlocks()) 601 for _, b := range f.Blocks { 602 best := -1 603 for i, e := range b.Preds { 604 p := e.b 605 if blockOrder[p.ID] >= blockOrder[b.ID] { 606 continue // backward edge 607 } 608 if best == -1 || blockOrder[p.ID] > blockOrder[b.Preds[best].b.ID] { 609 best = i 610 } 611 } 612 s.primary[b.ID] = int32(best) 613 } 614 615 s.endRegs = make([][]endReg, f.NumBlocks()) 616 s.startRegs = make([][]startReg, f.NumBlocks()) 617 s.spillLive = make([][]ID, f.NumBlocks()) 618 } 619 620 // Adds a use record for id at distance dist from the start of the block. 621 // All calls to addUse must happen with nonincreasing dist. 622 func (s *regAllocState) addUse(id ID, dist int32, pos src.XPos) { 623 r := s.freeUseRecords 624 if r != nil { 625 s.freeUseRecords = r.next 626 } else { 627 r = &use{} 628 } 629 r.dist = dist 630 r.pos = pos 631 r.next = s.values[id].uses 632 s.values[id].uses = r 633 if r.next != nil && dist > r.next.dist { 634 s.f.Fatalf("uses added in wrong order") 635 } 636 } 637 638 // advanceUses advances the uses of v's args from the state before v to the state after v. 639 // Any values which have no more uses are deallocated from registers. 640 func (s *regAllocState) advanceUses(v *Value) { 641 for _, a := range v.Args { 642 if !s.values[a.ID].needReg { 643 continue 644 } 645 ai := &s.values[a.ID] 646 r := ai.uses 647 ai.uses = r.next 648 if r.next == nil { 649 // Value is dead, free all registers that hold it. 650 s.freeRegs(ai.regs) 651 } 652 r.next = s.freeUseRecords 653 s.freeUseRecords = r 654 } 655 } 656 657 // liveAfterCurrentInstruction reports whether v is live after 658 // the current instruction is completed. v must be used by the 659 // current instruction. 660 func (s *regAllocState) liveAfterCurrentInstruction(v *Value) bool { 661 u := s.values[v.ID].uses 662 d := u.dist 663 for u != nil && u.dist == d { 664 u = u.next 665 } 666 return u != nil && u.dist > d 667 } 668 669 // Sets the state of the registers to that encoded in regs. 670 func (s *regAllocState) setState(regs []endReg) { 671 s.freeRegs(s.used) 672 for _, x := range regs { 673 s.assignReg(x.r, x.v, x.c) 674 } 675 } 676 677 // compatRegs returns the set of registers which can store a type t. 678 func (s *regAllocState) compatRegs(t Type) regMask { 679 var m regMask 680 if t.IsTuple() || t.IsFlags() { 681 return 0 682 } 683 if t.IsFloat() || t == TypeInt128 { 684 m = s.f.Config.fpRegMask 685 } else { 686 m = s.f.Config.gpRegMask 687 } 688 return m & s.allocatable 689 } 690 691 // loopForBlock returns the loop containing block b, 692 // provided that the loop is "interesting" for purposes 693 // of improving register allocation (= is inner, and does 694 // not contain a call) 695 func (s *regAllocState) loopForBlock(b *Block) *loop { 696 loop := s.loopnest.b2l[b.ID] 697 698 // Minor for-the-time-being optimization: nothing happens 699 // unless a loop is both inner and call-free, therefore 700 // don't bother with other loops. 701 if loop != nil && (loop.containsCall || !loop.isInner) { 702 loop = nil 703 } 704 return loop 705 } 706 707 func (s *regAllocState) regalloc(f *Func) { 708 liveSet := f.newSparseSet(f.NumValues()) 709 defer f.retSparseSet(liveSet) 710 var oldSched []*Value 711 var phis []*Value 712 var phiRegs []register 713 var args []*Value 714 715 // statistics 716 var nSpills int // # of spills remaining 717 var nSpillsInner int // # of spills remaining in inner loops 718 var nSpillsSunk int // # of sunk spills remaining 719 var nSpillsChanged int // # of sunk spills lost because of register use change 720 var nSpillsSunkUnused int // # of spills not sunk because they were removed completely 721 var nSpillsNotSunkLateUse int // # of spills not sunk because of very late use (in shuffle) 722 723 // Data structure used for computing desired registers. 724 var desired desiredState 725 726 // Desired registers for inputs & outputs for each instruction in the block. 727 type dentry struct { 728 out [4]register // desired output registers 729 in [3][4]register // desired input registers (for inputs 0,1, and 2) 730 } 731 var dinfo []dentry 732 733 if f.Entry != f.Blocks[0] { 734 f.Fatalf("entry block must be first") 735 } 736 737 // Get loop nest so that spills in inner loops can be 738 // tracked. When the last block of a loop is processed, 739 // attempt to move spills out of the loop. 740 s.loopnest.findExits() 741 742 // Spills are moved from one block's slice of values to another's. 743 // This confuses register allocation if it occurs before it is 744 // complete, so candidates are recorded, then rechecked and 745 // moved after all allocation (register and stack) is complete. 746 // Because movement is only within a stack slot's lifetime, it 747 // is safe to do this. 748 var toSink []spillToSink 749 // Will be used to figure out live inputs to exit blocks of inner loops. 750 entryCandidates := newSparseMap(f.NumValues()) 751 752 for _, b := range f.Blocks { 753 s.curBlock = b 754 loop := s.loopForBlock(b) 755 756 // Initialize liveSet and uses fields for this block. 757 // Walk backwards through the block doing liveness analysis. 758 liveSet.clear() 759 for _, e := range s.live[b.ID] { 760 s.addUse(e.ID, int32(len(b.Values))+e.dist, e.pos) // pseudo-uses from beyond end of block 761 liveSet.add(e.ID) 762 } 763 if v := b.Control; v != nil && s.values[v.ID].needReg { 764 s.addUse(v.ID, int32(len(b.Values)), b.Pos) // pseudo-use by control value 765 liveSet.add(v.ID) 766 } 767 for i := len(b.Values) - 1; i >= 0; i-- { 768 v := b.Values[i] 769 liveSet.remove(v.ID) 770 if v.Op == OpPhi { 771 // Remove v from the live set, but don't add 772 // any inputs. This is the state the len(b.Preds)>1 773 // case below desires; it wants to process phis specially. 774 continue 775 } 776 for _, a := range v.Args { 777 if !s.values[a.ID].needReg { 778 continue 779 } 780 s.addUse(a.ID, int32(i), v.Pos) 781 liveSet.add(a.ID) 782 } 783 } 784 if s.f.pass.debug > regDebug { 785 fmt.Printf("uses for %s:%s\n", s.f.Name, b) 786 for i := range s.values { 787 vi := &s.values[i] 788 u := vi.uses 789 if u == nil { 790 continue 791 } 792 fmt.Printf(" v%d:", i) 793 for u != nil { 794 fmt.Printf(" %d", u.dist) 795 u = u.next 796 } 797 fmt.Println() 798 } 799 } 800 801 // Make a copy of the block schedule so we can generate a new one in place. 802 // We make a separate copy for phis and regular values. 803 nphi := 0 804 for _, v := range b.Values { 805 if v.Op != OpPhi { 806 break 807 } 808 nphi++ 809 } 810 phis = append(phis[:0], b.Values[:nphi]...) 811 oldSched = append(oldSched[:0], b.Values[nphi:]...) 812 b.Values = b.Values[:0] 813 814 // Initialize start state of block. 815 if b == f.Entry { 816 // Regalloc state is empty to start. 817 if nphi > 0 { 818 f.Fatalf("phis in entry block") 819 } 820 } else if len(b.Preds) == 1 { 821 // Start regalloc state with the end state of the previous block. 822 s.setState(s.endRegs[b.Preds[0].b.ID]) 823 if nphi > 0 { 824 f.Fatalf("phis in single-predecessor block") 825 } 826 // Drop any values which are no longer live. 827 // This may happen because at the end of p, a value may be 828 // live but only used by some other successor of p. 829 for r := register(0); r < s.numRegs; r++ { 830 v := s.regs[r].v 831 if v != nil && !liveSet.contains(v.ID) { 832 s.freeReg(r) 833 } 834 } 835 } else { 836 // This is the complicated case. We have more than one predecessor, 837 // which means we may have Phi ops. 838 839 // Copy phi ops into new schedule. 840 b.Values = append(b.Values, phis...) 841 842 // Start with the final register state of the primary predecessor 843 idx := s.primary[b.ID] 844 if idx < 0 { 845 f.Fatalf("block with no primary predecessor %s", b) 846 } 847 p := b.Preds[idx].b 848 s.setState(s.endRegs[p.ID]) 849 850 if s.f.pass.debug > regDebug { 851 fmt.Printf("starting merge block %s with end state of %s:\n", b, p) 852 for _, x := range s.endRegs[p.ID] { 853 fmt.Printf(" %s: orig:%s cache:%s\n", s.registers[x.r].Name(), x.v, x.c) 854 } 855 } 856 857 // Decide on registers for phi ops. Use the registers determined 858 // by the primary predecessor if we can. 859 // TODO: pick best of (already processed) predecessors? 860 // Majority vote? Deepest nesting level? 861 phiRegs = phiRegs[:0] 862 var phiUsed regMask 863 for _, v := range phis { 864 if !s.values[v.ID].needReg { 865 phiRegs = append(phiRegs, noRegister) 866 continue 867 } 868 a := v.Args[idx] 869 // Some instructions target not-allocatable registers. 870 // They're not suitable for further (phi-function) allocation. 871 m := s.values[a.ID].regs &^ phiUsed & s.allocatable 872 if m != 0 { 873 r := pickReg(m) 874 phiUsed |= regMask(1) << r 875 phiRegs = append(phiRegs, r) 876 } else { 877 phiRegs = append(phiRegs, noRegister) 878 } 879 } 880 881 // Second pass - deallocate any phi inputs which are now dead. 882 for i, v := range phis { 883 if !s.values[v.ID].needReg { 884 continue 885 } 886 a := v.Args[idx] 887 if !liveSet.contains(a.ID) { 888 // Input is dead beyond the phi, deallocate 889 // anywhere else it might live. 890 s.freeRegs(s.values[a.ID].regs) 891 } else { 892 // Input is still live. 893 // Try to move it around before kicking out, if there is a free register. 894 // We generate a Copy in the predecessor block and record it. It will be 895 // deleted if never used. 896 r := phiRegs[i] 897 if r == noRegister { 898 continue 899 } 900 // Pick a free register. At this point some registers used in the predecessor 901 // block may have been deallocated. Those are the ones used for Phis. Exclude 902 // them (and they are not going to be helpful anyway). 903 m := s.compatRegs(a.Type) &^ s.used &^ phiUsed 904 if m != 0 && !s.values[a.ID].rematerializeable && countRegs(s.values[a.ID].regs) == 1 { 905 r2 := pickReg(m) 906 c := p.NewValue1(a.Pos, OpCopy, a.Type, s.regs[r].c) 907 s.copies[c] = false 908 if s.f.pass.debug > regDebug { 909 fmt.Printf("copy %s to %s : %s\n", a, c, s.registers[r2].Name()) 910 } 911 s.setOrig(c, a) 912 s.assignReg(r2, a, c) 913 s.endRegs[p.ID] = append(s.endRegs[p.ID], endReg{r2, a, c}) 914 } 915 s.freeReg(r) 916 } 917 } 918 919 // Third pass - pick registers for phis whose inputs 920 // were not in a register. 921 for i, v := range phis { 922 if !s.values[v.ID].needReg { 923 continue 924 } 925 if phiRegs[i] != noRegister { 926 continue 927 } 928 if s.f.Config.use387 && v.Type.IsFloat() { 929 continue // 387 can't handle floats in registers between blocks 930 } 931 m := s.compatRegs(v.Type) &^ phiUsed &^ s.used 932 if m != 0 { 933 r := pickReg(m) 934 phiRegs[i] = r 935 phiUsed |= regMask(1) << r 936 } 937 } 938 939 // Set registers for phis. Add phi spill code. 940 for i, v := range phis { 941 if !s.values[v.ID].needReg { 942 continue 943 } 944 r := phiRegs[i] 945 if r == noRegister { 946 // stack-based phi 947 // Spills will be inserted in all the predecessors below. 948 s.values[v.ID].spill = v // v starts life spilled 949 s.values[v.ID].spillUsed = true // use is guaranteed 950 continue 951 } 952 // register-based phi 953 s.assignReg(r, v, v) 954 // Spill the phi in case we need to restore it later. 955 spill := b.NewValue1(v.Pos, OpStoreReg, v.Type, v) 956 s.setOrig(spill, v) 957 s.values[v.ID].spill = spill 958 s.values[v.ID].spillUsed = false 959 if loop != nil { 960 loop.spills = append(loop.spills, v) 961 nSpillsInner++ 962 } 963 nSpills++ 964 } 965 966 // Save the starting state for use by merge edges. 967 var regList []startReg 968 for r := register(0); r < s.numRegs; r++ { 969 v := s.regs[r].v 970 if v == nil { 971 continue 972 } 973 if phiUsed>>r&1 != 0 { 974 // Skip registers that phis used, we'll handle those 975 // specially during merge edge processing. 976 continue 977 } 978 regList = append(regList, startReg{r, v.ID, s.values[v.ID].uses.pos}) 979 } 980 s.startRegs[b.ID] = regList 981 982 if s.f.pass.debug > regDebug { 983 fmt.Printf("after phis\n") 984 for _, x := range s.startRegs[b.ID] { 985 fmt.Printf(" %s: v%d\n", s.registers[x.r].Name(), x.vid) 986 } 987 } 988 } 989 990 // Allocate space to record the desired registers for each value. 991 dinfo = dinfo[:0] 992 for i := 0; i < len(oldSched); i++ { 993 dinfo = append(dinfo, dentry{}) 994 } 995 996 // Load static desired register info at the end of the block. 997 desired.copy(&s.desired[b.ID]) 998 999 // Check actual assigned registers at the start of the next block(s). 1000 // Dynamically assigned registers will trump the static 1001 // desired registers computed during liveness analysis. 1002 // Note that we do this phase after startRegs is set above, so that 1003 // we get the right behavior for a block which branches to itself. 1004 for _, e := range b.Succs { 1005 succ := e.b 1006 // TODO: prioritize likely successor? 1007 for _, x := range s.startRegs[succ.ID] { 1008 desired.add(x.vid, x.r) 1009 } 1010 // Process phi ops in succ. 1011 pidx := e.i 1012 for _, v := range succ.Values { 1013 if v.Op != OpPhi { 1014 break 1015 } 1016 if !s.values[v.ID].needReg { 1017 continue 1018 } 1019 rp, ok := s.f.getHome(v.ID).(*Register) 1020 if !ok { 1021 continue 1022 } 1023 desired.add(v.Args[pidx].ID, register(rp.num)) 1024 } 1025 } 1026 // Walk values backwards computing desired register info. 1027 // See computeLive for more comments. 1028 for i := len(oldSched) - 1; i >= 0; i-- { 1029 v := oldSched[i] 1030 prefs := desired.remove(v.ID) 1031 desired.clobber(opcodeTable[v.Op].reg.clobbers) 1032 for _, j := range opcodeTable[v.Op].reg.inputs { 1033 if countRegs(j.regs) != 1 { 1034 continue 1035 } 1036 desired.clobber(j.regs) 1037 desired.add(v.Args[j.idx].ID, pickReg(j.regs)) 1038 } 1039 if opcodeTable[v.Op].resultInArg0 { 1040 if opcodeTable[v.Op].commutative { 1041 desired.addList(v.Args[1].ID, prefs) 1042 } 1043 desired.addList(v.Args[0].ID, prefs) 1044 } 1045 // Save desired registers for this value. 1046 dinfo[i].out = prefs 1047 for j, a := range v.Args { 1048 if j >= len(dinfo[i].in) { 1049 break 1050 } 1051 dinfo[i].in[j] = desired.get(a.ID) 1052 } 1053 } 1054 1055 // Process all the non-phi values. 1056 for idx, v := range oldSched { 1057 if s.f.pass.debug > regDebug { 1058 fmt.Printf(" processing %s\n", v.LongString()) 1059 } 1060 regspec := opcodeTable[v.Op].reg 1061 if v.Op == OpPhi { 1062 f.Fatalf("phi %s not at start of block", v) 1063 } 1064 if v.Op == OpSP { 1065 s.assignReg(s.SPReg, v, v) 1066 b.Values = append(b.Values, v) 1067 s.advanceUses(v) 1068 continue 1069 } 1070 if v.Op == OpSB { 1071 s.assignReg(s.SBReg, v, v) 1072 b.Values = append(b.Values, v) 1073 s.advanceUses(v) 1074 continue 1075 } 1076 if v.Op == OpSelect0 || v.Op == OpSelect1 { 1077 if s.values[v.ID].needReg { 1078 var i = 0 1079 if v.Op == OpSelect1 { 1080 i = 1 1081 } 1082 s.assignReg(register(s.f.getHome(v.Args[0].ID).(LocPair)[i].(*Register).num), v, v) 1083 } 1084 b.Values = append(b.Values, v) 1085 s.advanceUses(v) 1086 goto issueSpill 1087 } 1088 if v.Op == OpGetG && s.f.Config.hasGReg { 1089 // use hardware g register 1090 if s.regs[s.GReg].v != nil { 1091 s.freeReg(s.GReg) // kick out the old value 1092 } 1093 s.assignReg(s.GReg, v, v) 1094 b.Values = append(b.Values, v) 1095 s.advanceUses(v) 1096 goto issueSpill 1097 } 1098 if v.Op == OpArg { 1099 // Args are "pre-spilled" values. We don't allocate 1100 // any register here. We just set up the spill pointer to 1101 // point at itself and any later user will restore it to use it. 1102 s.values[v.ID].spill = v 1103 s.values[v.ID].spillUsed = true // use is guaranteed 1104 b.Values = append(b.Values, v) 1105 s.advanceUses(v) 1106 continue 1107 } 1108 if v.Op == OpKeepAlive { 1109 // Make sure the argument to v is still live here. 1110 s.advanceUses(v) 1111 vi := &s.values[v.Args[0].ID] 1112 if vi.spillUsed { 1113 // Use the spill location. 1114 v.SetArg(0, vi.spill) 1115 } else { 1116 // No need to keep unspilled values live. 1117 // These are typically rematerializeable constants like nil, 1118 // or values of a variable that were modified since the last call. 1119 v.Op = OpCopy 1120 v.SetArgs1(v.Args[1]) 1121 } 1122 b.Values = append(b.Values, v) 1123 continue 1124 } 1125 if len(regspec.inputs) == 0 && len(regspec.outputs) == 0 { 1126 // No register allocation required (or none specified yet) 1127 s.freeRegs(regspec.clobbers) 1128 b.Values = append(b.Values, v) 1129 s.advanceUses(v) 1130 continue 1131 } 1132 1133 if s.values[v.ID].rematerializeable { 1134 // Value is rematerializeable, don't issue it here. 1135 // It will get issued just before each use (see 1136 // allocValueToReg). 1137 for _, a := range v.Args { 1138 a.Uses-- 1139 } 1140 s.advanceUses(v) 1141 continue 1142 } 1143 1144 if s.f.pass.debug > regDebug { 1145 fmt.Printf("value %s\n", v.LongString()) 1146 fmt.Printf(" out:") 1147 for _, r := range dinfo[idx].out { 1148 if r != noRegister { 1149 fmt.Printf(" %s", s.registers[r].Name()) 1150 } 1151 } 1152 fmt.Println() 1153 for i := 0; i < len(v.Args) && i < 3; i++ { 1154 fmt.Printf(" in%d:", i) 1155 for _, r := range dinfo[idx].in[i] { 1156 if r != noRegister { 1157 fmt.Printf(" %s", s.registers[r].Name()) 1158 } 1159 } 1160 fmt.Println() 1161 } 1162 } 1163 1164 // Move arguments to registers. Process in an ordering defined 1165 // by the register specification (most constrained first). 1166 args = append(args[:0], v.Args...) 1167 for _, i := range regspec.inputs { 1168 mask := i.regs 1169 if mask&s.values[args[i.idx].ID].regs == 0 { 1170 // Need a new register for the input. 1171 mask &= s.allocatable 1172 mask &^= s.nospill 1173 // Used desired register if available. 1174 if i.idx < 3 { 1175 for _, r := range dinfo[idx].in[i.idx] { 1176 if r != noRegister && (mask&^s.used)>>r&1 != 0 { 1177 // Desired register is allowed and unused. 1178 mask = regMask(1) << r 1179 break 1180 } 1181 } 1182 } 1183 // Avoid registers we're saving for other values. 1184 if mask&^desired.avoid != 0 { 1185 mask &^= desired.avoid 1186 } 1187 } 1188 args[i.idx] = s.allocValToReg(args[i.idx], mask, true, v.Pos) 1189 } 1190 1191 // If the output clobbers the input register, make sure we have 1192 // at least two copies of the input register so we don't 1193 // have to reload the value from the spill location. 1194 if opcodeTable[v.Op].resultInArg0 { 1195 var m regMask 1196 if !s.liveAfterCurrentInstruction(v.Args[0]) { 1197 // arg0 is dead. We can clobber its register. 1198 goto ok 1199 } 1200 if s.values[v.Args[0].ID].rematerializeable { 1201 // We can rematerialize the input, don't worry about clobbering it. 1202 goto ok 1203 } 1204 if countRegs(s.values[v.Args[0].ID].regs) >= 2 { 1205 // we have at least 2 copies of arg0. We can afford to clobber one. 1206 goto ok 1207 } 1208 if opcodeTable[v.Op].commutative { 1209 if !s.liveAfterCurrentInstruction(v.Args[1]) { 1210 args[0], args[1] = args[1], args[0] 1211 goto ok 1212 } 1213 if s.values[v.Args[1].ID].rematerializeable { 1214 args[0], args[1] = args[1], args[0] 1215 goto ok 1216 } 1217 if countRegs(s.values[v.Args[1].ID].regs) >= 2 { 1218 args[0], args[1] = args[1], args[0] 1219 goto ok 1220 } 1221 } 1222 1223 // We can't overwrite arg0 (or arg1, if commutative). So we 1224 // need to make a copy of an input so we have a register we can modify. 1225 1226 // Possible new registers to copy into. 1227 m = s.compatRegs(v.Args[0].Type) &^ s.used 1228 if m == 0 { 1229 // No free registers. In this case we'll just clobber 1230 // an input and future uses of that input must use a restore. 1231 // TODO(khr): We should really do this like allocReg does it, 1232 // spilling the value with the most distant next use. 1233 goto ok 1234 } 1235 1236 // Try to move an input to the desired output. 1237 for _, r := range dinfo[idx].out { 1238 if r != noRegister && m>>r&1 != 0 { 1239 m = regMask(1) << r 1240 args[0] = s.allocValToReg(v.Args[0], m, true, v.Pos) 1241 // Note: we update args[0] so the instruction will 1242 // use the register copy we just made. 1243 goto ok 1244 } 1245 } 1246 // Try to copy input to its desired location & use its old 1247 // location as the result register. 1248 for _, r := range dinfo[idx].in[0] { 1249 if r != noRegister && m>>r&1 != 0 { 1250 m = regMask(1) << r 1251 c := s.allocValToReg(v.Args[0], m, true, v.Pos) 1252 s.copies[c] = false 1253 // Note: no update to args[0] so the instruction will 1254 // use the original copy. 1255 goto ok 1256 } 1257 } 1258 if opcodeTable[v.Op].commutative { 1259 for _, r := range dinfo[idx].in[1] { 1260 if r != noRegister && m>>r&1 != 0 { 1261 m = regMask(1) << r 1262 c := s.allocValToReg(v.Args[1], m, true, v.Pos) 1263 s.copies[c] = false 1264 args[0], args[1] = args[1], args[0] 1265 goto ok 1266 } 1267 } 1268 } 1269 // Avoid future fixed uses if we can. 1270 if m&^desired.avoid != 0 { 1271 m &^= desired.avoid 1272 } 1273 // Save input 0 to a new register so we can clobber it. 1274 c := s.allocValToReg(v.Args[0], m, true, v.Pos) 1275 s.copies[c] = false 1276 } 1277 1278 ok: 1279 // Now that all args are in regs, we're ready to issue the value itself. 1280 // Before we pick a register for the output value, allow input registers 1281 // to be deallocated. We do this here so that the output can use the 1282 // same register as a dying input. 1283 if !opcodeTable[v.Op].resultNotInArgs { 1284 s.tmpused = s.nospill 1285 s.nospill = 0 1286 s.advanceUses(v) // frees any registers holding args that are no longer live 1287 } 1288 1289 // Dump any registers which will be clobbered 1290 s.freeRegs(regspec.clobbers) 1291 s.tmpused |= regspec.clobbers 1292 1293 // Pick registers for outputs. 1294 { 1295 outRegs := [2]register{noRegister, noRegister} 1296 var used regMask 1297 for _, out := range regspec.outputs { 1298 mask := out.regs & s.allocatable &^ used 1299 if mask == 0 { 1300 continue 1301 } 1302 if opcodeTable[v.Op].resultInArg0 && out.idx == 0 { 1303 if !opcodeTable[v.Op].commutative { 1304 // Output must use the same register as input 0. 1305 r := register(s.f.getHome(args[0].ID).(*Register).num) 1306 mask = regMask(1) << r 1307 } else { 1308 // Output must use the same register as input 0 or 1. 1309 r0 := register(s.f.getHome(args[0].ID).(*Register).num) 1310 r1 := register(s.f.getHome(args[1].ID).(*Register).num) 1311 // Check r0 and r1 for desired output register. 1312 found := false 1313 for _, r := range dinfo[idx].out { 1314 if (r == r0 || r == r1) && (mask&^s.used)>>r&1 != 0 { 1315 mask = regMask(1) << r 1316 found = true 1317 if r == r1 { 1318 args[0], args[1] = args[1], args[0] 1319 } 1320 break 1321 } 1322 } 1323 if !found { 1324 // Neither are desired, pick r0. 1325 mask = regMask(1) << r0 1326 } 1327 } 1328 } 1329 for _, r := range dinfo[idx].out { 1330 if r != noRegister && (mask&^s.used)>>r&1 != 0 { 1331 // Desired register is allowed and unused. 1332 mask = regMask(1) << r 1333 break 1334 } 1335 } 1336 // Avoid registers we're saving for other values. 1337 if mask&^desired.avoid != 0 { 1338 mask &^= desired.avoid 1339 } 1340 r := s.allocReg(mask, v) 1341 outRegs[out.idx] = r 1342 used |= regMask(1) << r 1343 s.tmpused |= regMask(1) << r 1344 } 1345 // Record register choices 1346 if v.Type.IsTuple() { 1347 var outLocs LocPair 1348 if r := outRegs[0]; r != noRegister { 1349 outLocs[0] = &s.registers[r] 1350 } 1351 if r := outRegs[1]; r != noRegister { 1352 outLocs[1] = &s.registers[r] 1353 } 1354 s.f.setHome(v, outLocs) 1355 // Note that subsequent SelectX instructions will do the assignReg calls. 1356 } else { 1357 if r := outRegs[0]; r != noRegister { 1358 s.assignReg(r, v, v) 1359 } 1360 } 1361 } 1362 1363 // deallocate dead args, if we have not done so 1364 if opcodeTable[v.Op].resultNotInArgs { 1365 s.nospill = 0 1366 s.advanceUses(v) // frees any registers holding args that are no longer live 1367 } 1368 s.tmpused = 0 1369 1370 // Issue the Value itself. 1371 for i, a := range args { 1372 v.SetArg(i, a) // use register version of arguments 1373 } 1374 b.Values = append(b.Values, v) 1375 1376 // Issue a spill for this value. We issue spills unconditionally, 1377 // then at the end of regalloc delete the ones we never use. 1378 // TODO: schedule the spill at a point that dominates all restores. 1379 // The restore may be off in an unlikely branch somewhere and it 1380 // would be better to have the spill in that unlikely branch as well. 1381 // v := ... 1382 // if unlikely { 1383 // f() 1384 // } 1385 // It would be good to have both spill and restore inside the IF. 1386 issueSpill: 1387 if s.values[v.ID].needReg { 1388 spill := b.NewValue1(v.Pos, OpStoreReg, v.Type, v) 1389 s.setOrig(spill, v) 1390 s.values[v.ID].spill = spill 1391 s.values[v.ID].spillUsed = false 1392 if loop != nil { 1393 loop.spills = append(loop.spills, v) 1394 nSpillsInner++ 1395 } 1396 nSpills++ 1397 } 1398 } 1399 1400 // Load control value into reg. 1401 if v := b.Control; v != nil && s.values[v.ID].needReg { 1402 if s.f.pass.debug > regDebug { 1403 fmt.Printf(" processing control %s\n", v.LongString()) 1404 } 1405 // We assume that a control input can be passed in any 1406 // type-compatible register. If this turns out not to be true, 1407 // we'll need to introduce a regspec for a block's control value. 1408 b.Control = s.allocValToReg(v, s.compatRegs(v.Type), false, b.Pos) 1409 if b.Control != v { 1410 v.Uses-- 1411 b.Control.Uses++ 1412 } 1413 // Remove this use from the uses list. 1414 vi := &s.values[v.ID] 1415 u := vi.uses 1416 vi.uses = u.next 1417 if u.next == nil { 1418 s.freeRegs(vi.regs) // value is dead 1419 } 1420 u.next = s.freeUseRecords 1421 s.freeUseRecords = u 1422 } 1423 1424 // Spill any values that can't live across basic block boundaries. 1425 if s.f.Config.use387 { 1426 s.freeRegs(s.f.Config.fpRegMask) 1427 } 1428 1429 // If we are approaching a merge point and we are the primary 1430 // predecessor of it, find live values that we use soon after 1431 // the merge point and promote them to registers now. 1432 if len(b.Succs) == 1 { 1433 // For this to be worthwhile, the loop must have no calls in it. 1434 top := b.Succs[0].b 1435 loop := s.loopnest.b2l[top.ID] 1436 if loop == nil || loop.header != top || loop.containsCall { 1437 goto badloop 1438 } 1439 1440 // TODO: sort by distance, pick the closest ones? 1441 for _, live := range s.live[b.ID] { 1442 if live.dist >= unlikelyDistance { 1443 // Don't preload anything live after the loop. 1444 continue 1445 } 1446 vid := live.ID 1447 vi := &s.values[vid] 1448 if vi.regs != 0 { 1449 continue 1450 } 1451 if vi.rematerializeable { 1452 continue 1453 } 1454 v := s.orig[vid] 1455 if s.f.Config.use387 && v.Type.IsFloat() { 1456 continue // 387 can't handle floats in registers between blocks 1457 } 1458 m := s.compatRegs(v.Type) &^ s.used 1459 if m&^desired.avoid != 0 { 1460 m &^= desired.avoid 1461 } 1462 if m != 0 { 1463 s.allocValToReg(v, m, false, b.Pos) 1464 } 1465 } 1466 } 1467 badloop: 1468 ; 1469 1470 // Save end-of-block register state. 1471 // First count how many, this cuts allocations in half. 1472 k := 0 1473 for r := register(0); r < s.numRegs; r++ { 1474 v := s.regs[r].v 1475 if v == nil { 1476 continue 1477 } 1478 k++ 1479 } 1480 regList := make([]endReg, 0, k) 1481 for r := register(0); r < s.numRegs; r++ { 1482 v := s.regs[r].v 1483 if v == nil { 1484 continue 1485 } 1486 regList = append(regList, endReg{r, v, s.regs[r].c}) 1487 } 1488 s.endRegs[b.ID] = regList 1489 1490 if checkEnabled { 1491 liveSet.clear() 1492 for _, x := range s.live[b.ID] { 1493 liveSet.add(x.ID) 1494 } 1495 for r := register(0); r < s.numRegs; r++ { 1496 v := s.regs[r].v 1497 if v == nil { 1498 continue 1499 } 1500 if !liveSet.contains(v.ID) { 1501 s.f.Fatalf("val %s is in reg but not live at end of %s", v, b) 1502 } 1503 } 1504 } 1505 1506 // If a value is live at the end of the block and 1507 // isn't in a register, remember that its spill location 1508 // is live. We need to remember this information so that 1509 // the liveness analysis in stackalloc is correct. 1510 for _, e := range s.live[b.ID] { 1511 if s.values[e.ID].regs != 0 { 1512 // in a register, we'll use that source for the merge. 1513 continue 1514 } 1515 spill := s.values[e.ID].spill 1516 if spill == nil { 1517 // rematerializeable values will have spill==nil. 1518 continue 1519 } 1520 s.spillLive[b.ID] = append(s.spillLive[b.ID], spill.ID) 1521 s.values[e.ID].spillUsed = true 1522 } 1523 1524 // Keep track of values that are spilled in the loop, but whose spill 1525 // is not used in the loop. It may be possible to move ("sink") the 1526 // spill out of the loop into one or more exit blocks. 1527 if loop != nil { 1528 loop.scratch++ // increment count of blocks in this loop that have been processed 1529 if loop.scratch == loop.nBlocks { // just processed last block of loop, if it is an inner loop. 1530 // This check is redundant with code at the top of the loop. 1531 // This is definitive; the one at the top of the loop is an optimization. 1532 if loop.isInner && // Common case, easier, most likely to be profitable 1533 !loop.containsCall && // Calls force spills, also lead to puzzling spill info. 1534 len(loop.exits) <= 32 { // Almost no inner loops have more than 32 exits, 1535 // and this allows use of a bitvector and a sparseMap. 1536 1537 // TODO: exit calculation is messed up for non-inner loops 1538 // because of multilevel exits that are not part of the "exit" 1539 // count. 1540 1541 // Compute the set of spill-movement candidates live at entry to exit blocks. 1542 // isLoopSpillCandidate filters for 1543 // (1) defined in appropriate loop 1544 // (2) needs a register 1545 // (3) spill not already used (in the loop) 1546 // Condition (3) === "in a register at all loop exits" 1547 1548 entryCandidates.clear() 1549 1550 for whichExit, ss := range loop.exits { 1551 // Start with live at end. 1552 for _, li := range s.live[ss.ID] { 1553 if s.isLoopSpillCandidate(loop, s.orig[li.ID]) { 1554 // s.live contains original IDs, use s.orig above to map back to *Value 1555 entryCandidates.setBit(li.ID, uint(whichExit)) 1556 } 1557 } 1558 // Control can also be live. 1559 if ss.Control != nil && s.orig[ss.Control.ID] != nil && s.isLoopSpillCandidate(loop, s.orig[ss.Control.ID]) { 1560 entryCandidates.setBit(s.orig[ss.Control.ID].ID, uint(whichExit)) 1561 } 1562 // Walk backwards, filling in locally live values, removing those defined. 1563 for i := len(ss.Values) - 1; i >= 0; i-- { 1564 v := ss.Values[i] 1565 vorig := s.orig[v.ID] 1566 if vorig != nil { 1567 entryCandidates.remove(vorig.ID) // Cannot be an issue, only keeps the sets smaller. 1568 } 1569 for _, a := range v.Args { 1570 aorig := s.orig[a.ID] 1571 if aorig != nil && s.isLoopSpillCandidate(loop, aorig) { 1572 entryCandidates.setBit(aorig.ID, uint(whichExit)) 1573 } 1574 } 1575 } 1576 } 1577 1578 for _, e := range loop.spills { 1579 whichblocks := entryCandidates.get(e.ID) 1580 oldSpill := s.values[e.ID].spill 1581 if whichblocks != 0 && whichblocks != -1 { // -1 = not in map. 1582 toSink = append(toSink, spillToSink{spill: oldSpill, dests: whichblocks}) 1583 } 1584 } 1585 1586 } // loop is inner etc 1587 loop.scratch = 0 // Don't leave a mess, just in case. 1588 loop.spills = nil 1589 } // if scratch == nBlocks 1590 } // if loop is not nil 1591 1592 // Clear any final uses. 1593 // All that is left should be the pseudo-uses added for values which 1594 // are live at the end of b. 1595 for _, e := range s.live[b.ID] { 1596 u := s.values[e.ID].uses 1597 if u == nil { 1598 f.Fatalf("live at end, no uses v%d", e.ID) 1599 } 1600 if u.next != nil { 1601 f.Fatalf("live at end, too many uses v%d", e.ID) 1602 } 1603 s.values[e.ID].uses = nil 1604 u.next = s.freeUseRecords 1605 s.freeUseRecords = u 1606 } 1607 } 1608 1609 // Erase any spills we never used 1610 for i := range s.values { 1611 vi := s.values[i] 1612 if vi.spillUsed { 1613 if s.f.pass.debug > logSpills && vi.spill.Op != OpArg { 1614 s.f.Config.Warnl(vi.spill.Pos, "spilled value at %v remains", vi.spill) 1615 } 1616 continue 1617 } 1618 spill := vi.spill 1619 if spill == nil { 1620 // Constants, SP, SB, ... 1621 continue 1622 } 1623 loop := s.loopForBlock(spill.Block) 1624 if loop != nil { 1625 nSpillsInner-- 1626 } 1627 1628 spill.Args[0].Uses-- 1629 f.freeValue(spill) 1630 nSpills-- 1631 } 1632 1633 for _, b := range f.Blocks { 1634 i := 0 1635 for _, v := range b.Values { 1636 if v.Op == OpInvalid { 1637 continue 1638 } 1639 b.Values[i] = v 1640 i++ 1641 } 1642 b.Values = b.Values[:i] 1643 // TODO: zero b.Values[i:], recycle Values 1644 // Not important now because this is the last phase that manipulates Values 1645 } 1646 1647 // Must clear these out before any potential recycling, though that's 1648 // not currently implemented. 1649 for i, ts := range toSink { 1650 vsp := ts.spill 1651 if vsp.Op == OpInvalid { // This spill was completely eliminated 1652 toSink[i].spill = nil 1653 } 1654 } 1655 1656 // Anything that didn't get a register gets a stack location here. 1657 // (StoreReg, stack-based phis, inputs, ...) 1658 stacklive := stackalloc(s.f, s.spillLive) 1659 1660 // Fix up all merge edges. 1661 s.shuffle(stacklive) 1662 1663 // Insert moved spills (that have not been marked invalid above) 1664 // at start of appropriate block and remove the originals from their 1665 // location within loops. Notice that this can break SSA form; 1666 // if a spill is sunk to multiple exits, there will be no phi for that 1667 // spill at a join point downstream of those two exits, though the 1668 // two spills will target the same stack slot. Notice also that this 1669 // takes place after stack allocation, so the stack allocator does 1670 // not need to process these malformed flow graphs. 1671 sinking: 1672 for _, ts := range toSink { 1673 vsp := ts.spill 1674 if vsp == nil { // This spill was completely eliminated 1675 nSpillsSunkUnused++ 1676 continue sinking 1677 } 1678 e := ts.spilledValue() 1679 if s.values[e.ID].spillUsedShuffle { 1680 nSpillsNotSunkLateUse++ 1681 continue sinking 1682 } 1683 1684 // move spills to a better (outside of loop) block. 1685 // This would be costly if it occurred very often, but it doesn't. 1686 b := vsp.Block 1687 loop := s.loopnest.b2l[b.ID] 1688 dests := ts.dests 1689 1690 // Pre-check to be sure that spilled value is still in expected register on all exits where live. 1691 check_val_still_in_reg: 1692 for i := uint(0); i < 32 && dests != 0; i++ { 1693 1694 if dests&(1<<i) == 0 { 1695 continue 1696 } 1697 dests ^= 1 << i 1698 d := loop.exits[i] 1699 if len(d.Preds) > 1 { 1700 panic("Should be impossible given critical edges removed") 1701 } 1702 p := d.Preds[0].b // block in loop exiting to d. 1703 1704 endregs := s.endRegs[p.ID] 1705 for _, regrec := range endregs { 1706 if regrec.v == e && regrec.r != noRegister && regrec.c == e { // TODO: regrec.c != e implies different spill possible. 1707 continue check_val_still_in_reg 1708 } 1709 } 1710 // If here, the register assignment was lost down at least one exit and it can't be sunk 1711 if s.f.pass.debug > moveSpills { 1712 s.f.Config.Warnl(e.Pos, "lost register assignment for spill %v in %v at exit %v to %v", 1713 vsp, b, p, d) 1714 } 1715 nSpillsChanged++ 1716 continue sinking 1717 } 1718 1719 nSpillsSunk++ 1720 nSpillsInner-- 1721 // don't update nSpills, since spill is only moved, and if it is duplicated, the spills-on-a-path is not increased. 1722 1723 dests = ts.dests 1724 1725 // remove vsp from b.Values 1726 i := 0 1727 for _, w := range b.Values { 1728 if vsp == w { 1729 continue 1730 } 1731 b.Values[i] = w 1732 i++ 1733 } 1734 b.Values = b.Values[:i] 1735 1736 first := true 1737 for i := uint(0); i < 32 && dests != 0; i++ { 1738 1739 if dests&(1<<i) == 0 { 1740 continue 1741 } 1742 1743 dests ^= 1 << i 1744 1745 d := loop.exits[i] 1746 vspnew := vsp // reuse original for first sunk spill, saves tracking down and renaming uses 1747 if !first { // any sunk spills after first must make a copy 1748 vspnew = d.NewValue1(e.Pos, OpStoreReg, e.Type, e) 1749 f.setHome(vspnew, f.getHome(vsp.ID)) // copy stack home 1750 if s.f.pass.debug > moveSpills { 1751 s.f.Config.Warnl(e.Pos, "copied spill %v in %v for %v to %v in %v", 1752 vsp, b, e, vspnew, d) 1753 } 1754 } else { 1755 first = false 1756 vspnew.Block = d 1757 d.Values = append(d.Values, vspnew) 1758 if s.f.pass.debug > moveSpills { 1759 s.f.Config.Warnl(e.Pos, "moved spill %v in %v for %v to %v in %v", 1760 vsp, b, e, vspnew, d) 1761 } 1762 } 1763 1764 // shuffle vspnew to the beginning of its block 1765 copy(d.Values[1:], d.Values[0:len(d.Values)-1]) 1766 d.Values[0] = vspnew 1767 1768 } 1769 } 1770 1771 // Erase any copies we never used. 1772 // Also, an unused copy might be the only use of another copy, 1773 // so continue erasing until we reach a fixed point. 1774 for { 1775 progress := false 1776 for c, used := range s.copies { 1777 if !used && c.Uses == 0 { 1778 if s.f.pass.debug > regDebug { 1779 fmt.Printf("delete copied value %s\n", c.LongString()) 1780 } 1781 c.Args[0].Uses-- 1782 f.freeValue(c) 1783 delete(s.copies, c) 1784 progress = true 1785 } 1786 } 1787 if !progress { 1788 break 1789 } 1790 } 1791 1792 for _, b := range f.Blocks { 1793 i := 0 1794 for _, v := range b.Values { 1795 if v.Op == OpInvalid { 1796 continue 1797 } 1798 b.Values[i] = v 1799 i++ 1800 } 1801 b.Values = b.Values[:i] 1802 } 1803 1804 if f.pass.stats > 0 { 1805 f.LogStat("spills_info", 1806 nSpills, "spills", nSpillsInner, "inner_spills_remaining", nSpillsSunk, "inner_spills_sunk", nSpillsSunkUnused, "inner_spills_unused", nSpillsNotSunkLateUse, "inner_spills_shuffled", nSpillsChanged, "inner_spills_changed") 1807 } 1808 } 1809 1810 // isLoopSpillCandidate indicates whether the spill for v satisfies preliminary 1811 // spill-sinking conditions just after the last block of loop has been processed. 1812 // In particular: 1813 // v needs a register. 1814 // v's spill is not (YET) used. 1815 // v's definition is within loop. 1816 // The spill may be used in the future, either by an outright use 1817 // in the code, or by shuffling code inserted after stack allocation. 1818 // Outright uses cause sinking; shuffling (within the loop) inhibits it. 1819 func (s *regAllocState) isLoopSpillCandidate(loop *loop, v *Value) bool { 1820 return s.values[v.ID].needReg && !s.values[v.ID].spillUsed && s.loopnest.b2l[v.Block.ID] == loop 1821 } 1822 1823 // lateSpillUse notes a late (after stack allocation) use of the spill of value with ID vid. 1824 // This will inhibit spill sinking. 1825 func (s *regAllocState) lateSpillUse(vid ID) { 1826 // TODO investigate why this is necessary. 1827 // It appears that an outside-the-loop use of 1828 // an otherwise sinkable spill makes the spill 1829 // a candidate for shuffling, when it would not 1830 // otherwise have been the case (spillUsed was not 1831 // true when isLoopSpillCandidate was called, yet 1832 // it was shuffled). Such shuffling cuts the amount 1833 // of spill sinking by more than half (in make.bash) 1834 s.values[vid].spillUsedShuffle = true 1835 } 1836 1837 // shuffle fixes up all the merge edges (those going into blocks of indegree > 1). 1838 func (s *regAllocState) shuffle(stacklive [][]ID) { 1839 var e edgeState 1840 e.s = s 1841 e.cache = map[ID][]*Value{} 1842 e.contents = map[Location]contentRecord{} 1843 if s.f.pass.debug > regDebug { 1844 fmt.Printf("shuffle %s\n", s.f.Name) 1845 fmt.Println(s.f.String()) 1846 } 1847 1848 for _, b := range s.f.Blocks { 1849 if len(b.Preds) <= 1 { 1850 continue 1851 } 1852 e.b = b 1853 for i, edge := range b.Preds { 1854 p := edge.b 1855 e.p = p 1856 e.setup(i, s.endRegs[p.ID], s.startRegs[b.ID], stacklive[p.ID]) 1857 e.process() 1858 } 1859 } 1860 } 1861 1862 type edgeState struct { 1863 s *regAllocState 1864 p, b *Block // edge goes from p->b. 1865 1866 // for each pre-regalloc value, a list of equivalent cached values 1867 cache map[ID][]*Value 1868 cachedVals []ID // (superset of) keys of the above map, for deterministic iteration 1869 1870 // map from location to the value it contains 1871 contents map[Location]contentRecord 1872 1873 // desired destination locations 1874 destinations []dstRecord 1875 extra []dstRecord 1876 1877 usedRegs regMask // registers currently holding something 1878 uniqueRegs regMask // registers holding the only copy of a value 1879 finalRegs regMask // registers holding final target 1880 } 1881 1882 type contentRecord struct { 1883 vid ID // pre-regalloc value 1884 c *Value // cached value 1885 final bool // this is a satisfied destination 1886 pos src.XPos // source position of use of the value 1887 } 1888 1889 type dstRecord struct { 1890 loc Location // register or stack slot 1891 vid ID // pre-regalloc value it should contain 1892 splice **Value // place to store reference to the generating instruction 1893 pos src.XPos // source position of use of this location 1894 } 1895 1896 // setup initializes the edge state for shuffling. 1897 func (e *edgeState) setup(idx int, srcReg []endReg, dstReg []startReg, stacklive []ID) { 1898 if e.s.f.pass.debug > regDebug { 1899 fmt.Printf("edge %s->%s\n", e.p, e.b) 1900 } 1901 1902 // Clear state. 1903 for _, vid := range e.cachedVals { 1904 delete(e.cache, vid) 1905 } 1906 e.cachedVals = e.cachedVals[:0] 1907 for k := range e.contents { 1908 delete(e.contents, k) 1909 } 1910 e.usedRegs = 0 1911 e.uniqueRegs = 0 1912 e.finalRegs = 0 1913 1914 // Live registers can be sources. 1915 for _, x := range srcReg { 1916 e.set(&e.s.registers[x.r], x.v.ID, x.c, false, src.NoXPos) // don't care the position of the source 1917 } 1918 // So can all of the spill locations. 1919 for _, spillID := range stacklive { 1920 v := e.s.orig[spillID] 1921 spill := e.s.values[v.ID].spill 1922 e.set(e.s.f.getHome(spillID), v.ID, spill, false, src.NoXPos) // don't care the position of the source 1923 } 1924 1925 // Figure out all the destinations we need. 1926 dsts := e.destinations[:0] 1927 for _, x := range dstReg { 1928 dsts = append(dsts, dstRecord{&e.s.registers[x.r], x.vid, nil, x.pos}) 1929 } 1930 // Phis need their args to end up in a specific location. 1931 for _, v := range e.b.Values { 1932 if v.Op != OpPhi { 1933 break 1934 } 1935 loc := e.s.f.getHome(v.ID) 1936 if loc == nil { 1937 continue 1938 } 1939 dsts = append(dsts, dstRecord{loc, v.Args[idx].ID, &v.Args[idx], v.Pos}) 1940 } 1941 e.destinations = dsts 1942 1943 if e.s.f.pass.debug > regDebug { 1944 for _, vid := range e.cachedVals { 1945 a := e.cache[vid] 1946 for _, c := range a { 1947 fmt.Printf("src %s: v%d cache=%s\n", e.s.f.getHome(c.ID).Name(), vid, c) 1948 } 1949 } 1950 for _, d := range e.destinations { 1951 fmt.Printf("dst %s: v%d\n", d.loc.Name(), d.vid) 1952 } 1953 } 1954 } 1955 1956 // process generates code to move all the values to the right destination locations. 1957 func (e *edgeState) process() { 1958 dsts := e.destinations 1959 1960 // Process the destinations until they are all satisfied. 1961 for len(dsts) > 0 { 1962 i := 0 1963 for _, d := range dsts { 1964 if !e.processDest(d.loc, d.vid, d.splice, d.pos) { 1965 // Failed - save for next iteration. 1966 dsts[i] = d 1967 i++ 1968 } 1969 } 1970 if i < len(dsts) { 1971 // Made some progress. Go around again. 1972 dsts = dsts[:i] 1973 1974 // Append any extras destinations we generated. 1975 dsts = append(dsts, e.extra...) 1976 e.extra = e.extra[:0] 1977 continue 1978 } 1979 1980 // We made no progress. That means that any 1981 // remaining unsatisfied moves are in simple cycles. 1982 // For example, A -> B -> C -> D -> A. 1983 // A ----> B 1984 // ^ | 1985 // | | 1986 // | v 1987 // D <---- C 1988 1989 // To break the cycle, we pick an unused register, say R, 1990 // and put a copy of B there. 1991 // A ----> B 1992 // ^ | 1993 // | | 1994 // | v 1995 // D <---- C <---- R=copyofB 1996 // When we resume the outer loop, the A->B move can now proceed, 1997 // and eventually the whole cycle completes. 1998 1999 // Copy any cycle location to a temp register. This duplicates 2000 // one of the cycle entries, allowing the just duplicated value 2001 // to be overwritten and the cycle to proceed. 2002 d := dsts[0] 2003 loc := d.loc 2004 vid := e.contents[loc].vid 2005 c := e.contents[loc].c 2006 r := e.findRegFor(c.Type) 2007 if e.s.f.pass.debug > regDebug { 2008 fmt.Printf("breaking cycle with v%d in %s:%s\n", vid, loc.Name(), c) 2009 } 2010 if _, isReg := loc.(*Register); isReg { 2011 c = e.p.NewValue1(d.pos, OpCopy, c.Type, c) 2012 } else { 2013 e.s.lateSpillUse(vid) 2014 c = e.p.NewValue1(d.pos, OpLoadReg, c.Type, c) 2015 } 2016 e.set(r, vid, c, false, d.pos) 2017 } 2018 } 2019 2020 // processDest generates code to put value vid into location loc. Returns true 2021 // if progress was made. 2022 func (e *edgeState) processDest(loc Location, vid ID, splice **Value, pos src.XPos) bool { 2023 occupant := e.contents[loc] 2024 if occupant.vid == vid { 2025 // Value is already in the correct place. 2026 e.contents[loc] = contentRecord{vid, occupant.c, true, pos} 2027 if splice != nil { 2028 (*splice).Uses-- 2029 *splice = occupant.c 2030 occupant.c.Uses++ 2031 if occupant.c.Op == OpStoreReg { 2032 e.s.lateSpillUse(vid) 2033 } 2034 } 2035 // Note: if splice==nil then c will appear dead. This is 2036 // non-SSA formed code, so be careful after this pass not to run 2037 // deadcode elimination. 2038 if _, ok := e.s.copies[occupant.c]; ok { 2039 // The copy at occupant.c was used to avoid spill. 2040 e.s.copies[occupant.c] = true 2041 } 2042 return true 2043 } 2044 2045 // Check if we're allowed to clobber the destination location. 2046 if len(e.cache[occupant.vid]) == 1 && !e.s.values[occupant.vid].rematerializeable { 2047 // We can't overwrite the last copy 2048 // of a value that needs to survive. 2049 return false 2050 } 2051 2052 // Copy from a source of v, register preferred. 2053 v := e.s.orig[vid] 2054 var c *Value 2055 var src Location 2056 if e.s.f.pass.debug > regDebug { 2057 fmt.Printf("moving v%d to %s\n", vid, loc.Name()) 2058 fmt.Printf("sources of v%d:", vid) 2059 } 2060 for _, w := range e.cache[vid] { 2061 h := e.s.f.getHome(w.ID) 2062 if e.s.f.pass.debug > regDebug { 2063 fmt.Printf(" %s:%s", h.Name(), w) 2064 } 2065 _, isreg := h.(*Register) 2066 if src == nil || isreg { 2067 c = w 2068 src = h 2069 } 2070 } 2071 if e.s.f.pass.debug > regDebug { 2072 if src != nil { 2073 fmt.Printf(" [use %s]\n", src.Name()) 2074 } else { 2075 fmt.Printf(" [no source]\n") 2076 } 2077 } 2078 _, dstReg := loc.(*Register) 2079 var x *Value 2080 if c == nil { 2081 if !e.s.values[vid].rematerializeable { 2082 e.s.f.Fatalf("can't find source for %s->%s: %s\n", e.p, e.b, v.LongString()) 2083 } 2084 if dstReg { 2085 x = v.copyInto(e.p) 2086 } else { 2087 // Rematerialize into stack slot. Need a free 2088 // register to accomplish this. 2089 e.erase(loc) // see pre-clobber comment below 2090 r := e.findRegFor(v.Type) 2091 x = v.copyInto(e.p) 2092 e.set(r, vid, x, false, pos) 2093 // Make sure we spill with the size of the slot, not the 2094 // size of x (which might be wider due to our dropping 2095 // of narrowing conversions). 2096 x = e.p.NewValue1(pos, OpStoreReg, loc.(LocalSlot).Type, x) 2097 } 2098 } else { 2099 // Emit move from src to dst. 2100 _, srcReg := src.(*Register) 2101 if srcReg { 2102 if dstReg { 2103 x = e.p.NewValue1(pos, OpCopy, c.Type, c) 2104 } else { 2105 x = e.p.NewValue1(pos, OpStoreReg, loc.(LocalSlot).Type, c) 2106 } 2107 } else { 2108 if dstReg { 2109 e.s.lateSpillUse(vid) 2110 x = e.p.NewValue1(pos, OpLoadReg, c.Type, c) 2111 } else { 2112 // mem->mem. Use temp register. 2113 2114 // Pre-clobber destination. This avoids the 2115 // following situation: 2116 // - v is currently held in R0 and stacktmp0. 2117 // - We want to copy stacktmp1 to stacktmp0. 2118 // - We choose R0 as the temporary register. 2119 // During the copy, both R0 and stacktmp0 are 2120 // clobbered, losing both copies of v. Oops! 2121 // Erasing the destination early means R0 will not 2122 // be chosen as the temp register, as it will then 2123 // be the last copy of v. 2124 e.erase(loc) 2125 2126 r := e.findRegFor(c.Type) 2127 e.s.lateSpillUse(vid) 2128 t := e.p.NewValue1(pos, OpLoadReg, c.Type, c) 2129 e.set(r, vid, t, false, pos) 2130 x = e.p.NewValue1(pos, OpStoreReg, loc.(LocalSlot).Type, t) 2131 } 2132 } 2133 } 2134 e.set(loc, vid, x, true, pos) 2135 if splice != nil { 2136 (*splice).Uses-- 2137 *splice = x 2138 x.Uses++ 2139 } 2140 return true 2141 } 2142 2143 // set changes the contents of location loc to hold the given value and its cached representative. 2144 func (e *edgeState) set(loc Location, vid ID, c *Value, final bool, pos src.XPos) { 2145 e.s.f.setHome(c, loc) 2146 e.erase(loc) 2147 e.contents[loc] = contentRecord{vid, c, final, pos} 2148 a := e.cache[vid] 2149 if len(a) == 0 { 2150 e.cachedVals = append(e.cachedVals, vid) 2151 } 2152 a = append(a, c) 2153 e.cache[vid] = a 2154 if r, ok := loc.(*Register); ok { 2155 e.usedRegs |= regMask(1) << uint(r.num) 2156 if final { 2157 e.finalRegs |= regMask(1) << uint(r.num) 2158 } 2159 if len(a) == 1 { 2160 e.uniqueRegs |= regMask(1) << uint(r.num) 2161 } 2162 if len(a) == 2 { 2163 if t, ok := e.s.f.getHome(a[0].ID).(*Register); ok { 2164 e.uniqueRegs &^= regMask(1) << uint(t.num) 2165 } 2166 } 2167 } 2168 if e.s.f.pass.debug > regDebug { 2169 fmt.Printf("%s\n", c.LongString()) 2170 fmt.Printf("v%d now available in %s:%s\n", vid, loc.Name(), c) 2171 } 2172 } 2173 2174 // erase removes any user of loc. 2175 func (e *edgeState) erase(loc Location) { 2176 cr := e.contents[loc] 2177 if cr.c == nil { 2178 return 2179 } 2180 vid := cr.vid 2181 2182 if cr.final { 2183 // Add a destination to move this value back into place. 2184 // Make sure it gets added to the tail of the destination queue 2185 // so we make progress on other moves first. 2186 e.extra = append(e.extra, dstRecord{loc, cr.vid, nil, cr.pos}) 2187 } 2188 2189 // Remove c from the list of cached values. 2190 a := e.cache[vid] 2191 for i, c := range a { 2192 if e.s.f.getHome(c.ID) == loc { 2193 if e.s.f.pass.debug > regDebug { 2194 fmt.Printf("v%d no longer available in %s:%s\n", vid, loc.Name(), c) 2195 } 2196 a[i], a = a[len(a)-1], a[:len(a)-1] 2197 break 2198 } 2199 } 2200 e.cache[vid] = a 2201 2202 // Update register masks. 2203 if r, ok := loc.(*Register); ok { 2204 e.usedRegs &^= regMask(1) << uint(r.num) 2205 if cr.final { 2206 e.finalRegs &^= regMask(1) << uint(r.num) 2207 } 2208 } 2209 if len(a) == 1 { 2210 if r, ok := e.s.f.getHome(a[0].ID).(*Register); ok { 2211 e.uniqueRegs |= regMask(1) << uint(r.num) 2212 } 2213 } 2214 } 2215 2216 // findRegFor finds a register we can use to make a temp copy of type typ. 2217 func (e *edgeState) findRegFor(typ Type) Location { 2218 // Which registers are possibilities. 2219 var m regMask 2220 if typ.IsFloat() { 2221 m = e.s.compatRegs(e.s.f.Config.fe.TypeFloat64()) 2222 } else { 2223 m = e.s.compatRegs(e.s.f.Config.fe.TypeInt64()) 2224 } 2225 2226 // Pick a register. In priority order: 2227 // 1) an unused register 2228 // 2) a non-unique register not holding a final value 2229 // 3) a non-unique register 2230 x := m &^ e.usedRegs 2231 if x != 0 { 2232 return &e.s.registers[pickReg(x)] 2233 } 2234 x = m &^ e.uniqueRegs &^ e.finalRegs 2235 if x != 0 { 2236 return &e.s.registers[pickReg(x)] 2237 } 2238 x = m &^ e.uniqueRegs 2239 if x != 0 { 2240 return &e.s.registers[pickReg(x)] 2241 } 2242 2243 // No register is available. Allocate a temp location to spill a register to. 2244 // The type of the slot is immaterial - it will not be live across 2245 // any safepoint. Just use a type big enough to hold any register. 2246 typ = e.s.f.Config.fe.TypeInt64() 2247 t := LocalSlot{e.s.f.Config.fe.Auto(typ), typ, 0} 2248 // TODO: reuse these slots. 2249 2250 // Pick a register to spill. 2251 for _, vid := range e.cachedVals { 2252 a := e.cache[vid] 2253 for _, c := range a { 2254 if r, ok := e.s.f.getHome(c.ID).(*Register); ok && m>>uint(r.num)&1 != 0 { 2255 x := e.p.NewValue1(c.Pos, OpStoreReg, c.Type, c) 2256 e.set(t, vid, x, false, c.Pos) 2257 if e.s.f.pass.debug > regDebug { 2258 fmt.Printf(" SPILL %s->%s %s\n", r.Name(), t.Name(), x.LongString()) 2259 } 2260 // r will now be overwritten by the caller. At some point 2261 // later, the newly saved value will be moved back to its 2262 // final destination in processDest. 2263 return r 2264 } 2265 } 2266 } 2267 2268 fmt.Printf("m:%d unique:%d final:%d\n", m, e.uniqueRegs, e.finalRegs) 2269 for _, vid := range e.cachedVals { 2270 a := e.cache[vid] 2271 for _, c := range a { 2272 fmt.Printf("v%d: %s %s\n", vid, c, e.s.f.getHome(c.ID).Name()) 2273 } 2274 } 2275 e.s.f.Fatalf("can't find empty register on edge %s->%s", e.p, e.b) 2276 return nil 2277 } 2278 2279 // rematerializeable reports whether the register allocator should recompute 2280 // a value instead of spilling/restoring it. 2281 func (v *Value) rematerializeable() bool { 2282 if !opcodeTable[v.Op].rematerializeable { 2283 return false 2284 } 2285 for _, a := range v.Args { 2286 // SP and SB (generated by OpSP and OpSB) are always available. 2287 if a.Op != OpSP && a.Op != OpSB { 2288 return false 2289 } 2290 } 2291 return true 2292 } 2293 2294 type liveInfo struct { 2295 ID ID // ID of value 2296 dist int32 // # of instructions before next use 2297 pos src.XPos // source position of next use 2298 } 2299 2300 // dblock contains information about desired & avoid registers at the end of a block. 2301 type dblock struct { 2302 prefers []desiredStateEntry 2303 avoid regMask 2304 } 2305 2306 // computeLive computes a map from block ID to a list of value IDs live at the end 2307 // of that block. Together with the value ID is a count of how many instructions 2308 // to the next use of that value. The resulting map is stored in s.live. 2309 // computeLive also computes the desired register information at the end of each block. 2310 // This desired register information is stored in s.desired. 2311 // TODO: this could be quadratic if lots of variables are live across lots of 2312 // basic blocks. Figure out a way to make this function (or, more precisely, the user 2313 // of this function) require only linear size & time. 2314 func (s *regAllocState) computeLive() { 2315 f := s.f 2316 s.live = make([][]liveInfo, f.NumBlocks()) 2317 s.desired = make([]desiredState, f.NumBlocks()) 2318 var phis []*Value 2319 2320 live := newSparseMap(f.NumValues()) 2321 t := newSparseMap(f.NumValues()) 2322 2323 // Keep track of which value we want in each register. 2324 var desired desiredState 2325 2326 // Instead of iterating over f.Blocks, iterate over their postordering. 2327 // Liveness information flows backward, so starting at the end 2328 // increases the probability that we will stabilize quickly. 2329 // TODO: Do a better job yet. Here's one possibility: 2330 // Calculate the dominator tree and locate all strongly connected components. 2331 // If a value is live in one block of an SCC, it is live in all. 2332 // Walk the dominator tree from end to beginning, just once, treating SCC 2333 // components as single blocks, duplicated calculated liveness information 2334 // out to all of them. 2335 po := f.postorder() 2336 s.loopnest = f.loopnest() 2337 for { 2338 changed := false 2339 2340 for _, b := range po { 2341 // Start with known live values at the end of the block. 2342 // Add len(b.Values) to adjust from end-of-block distance 2343 // to beginning-of-block distance. 2344 live.clear() 2345 for _, e := range s.live[b.ID] { 2346 live.set(e.ID, e.dist+int32(len(b.Values)), e.pos) 2347 } 2348 2349 // Mark control value as live 2350 if b.Control != nil && s.values[b.Control.ID].needReg { 2351 live.set(b.Control.ID, int32(len(b.Values)), b.Pos) 2352 } 2353 2354 // Propagate backwards to the start of the block 2355 // Assumes Values have been scheduled. 2356 phis = phis[:0] 2357 for i := len(b.Values) - 1; i >= 0; i-- { 2358 v := b.Values[i] 2359 live.remove(v.ID) 2360 if v.Op == OpPhi { 2361 // save phi ops for later 2362 phis = append(phis, v) 2363 continue 2364 } 2365 if opcodeTable[v.Op].call { 2366 c := live.contents() 2367 for i := range c { 2368 c[i].val += unlikelyDistance 2369 } 2370 } 2371 for _, a := range v.Args { 2372 if s.values[a.ID].needReg { 2373 live.set(a.ID, int32(i), v.Pos) 2374 } 2375 } 2376 } 2377 // Propagate desired registers backwards. 2378 desired.copy(&s.desired[b.ID]) 2379 for i := len(b.Values) - 1; i >= 0; i-- { 2380 v := b.Values[i] 2381 prefs := desired.remove(v.ID) 2382 if v.Op == OpPhi { 2383 // TODO: if v is a phi, save desired register for phi inputs. 2384 // For now, we just drop it and don't propagate 2385 // desired registers back though phi nodes. 2386 continue 2387 } 2388 // Cancel desired registers if they get clobbered. 2389 desired.clobber(opcodeTable[v.Op].reg.clobbers) 2390 // Update desired registers if there are any fixed register inputs. 2391 for _, j := range opcodeTable[v.Op].reg.inputs { 2392 if countRegs(j.regs) != 1 { 2393 continue 2394 } 2395 desired.clobber(j.regs) 2396 desired.add(v.Args[j.idx].ID, pickReg(j.regs)) 2397 } 2398 // Set desired register of input 0 if this is a 2-operand instruction. 2399 if opcodeTable[v.Op].resultInArg0 { 2400 if opcodeTable[v.Op].commutative { 2401 desired.addList(v.Args[1].ID, prefs) 2402 } 2403 desired.addList(v.Args[0].ID, prefs) 2404 } 2405 } 2406 2407 // For each predecessor of b, expand its list of live-at-end values. 2408 // invariant: live contains the values live at the start of b (excluding phi inputs) 2409 for i, e := range b.Preds { 2410 p := e.b 2411 // Compute additional distance for the edge. 2412 // Note: delta must be at least 1 to distinguish the control 2413 // value use from the first user in a successor block. 2414 delta := int32(normalDistance) 2415 if len(p.Succs) == 2 { 2416 if p.Succs[0].b == b && p.Likely == BranchLikely || 2417 p.Succs[1].b == b && p.Likely == BranchUnlikely { 2418 delta = likelyDistance 2419 } 2420 if p.Succs[0].b == b && p.Likely == BranchUnlikely || 2421 p.Succs[1].b == b && p.Likely == BranchLikely { 2422 delta = unlikelyDistance 2423 } 2424 } 2425 2426 // Update any desired registers at the end of p. 2427 s.desired[p.ID].merge(&desired) 2428 2429 // Start t off with the previously known live values at the end of p. 2430 t.clear() 2431 for _, e := range s.live[p.ID] { 2432 t.set(e.ID, e.dist, e.pos) 2433 } 2434 update := false 2435 2436 // Add new live values from scanning this block. 2437 for _, e := range live.contents() { 2438 d := e.val + delta 2439 if !t.contains(e.key) || d < t.get(e.key) { 2440 update = true 2441 t.set(e.key, d, e.aux) 2442 } 2443 } 2444 // Also add the correct arg from the saved phi values. 2445 // All phis are at distance delta (we consider them 2446 // simultaneously happening at the start of the block). 2447 for _, v := range phis { 2448 id := v.Args[i].ID 2449 if s.values[id].needReg && (!t.contains(id) || delta < t.get(id)) { 2450 update = true 2451 t.set(id, delta, v.Pos) 2452 } 2453 } 2454 2455 if !update { 2456 continue 2457 } 2458 // The live set has changed, update it. 2459 l := s.live[p.ID][:0] 2460 if cap(l) < t.size() { 2461 l = make([]liveInfo, 0, t.size()) 2462 } 2463 for _, e := range t.contents() { 2464 l = append(l, liveInfo{e.key, e.val, e.aux}) 2465 } 2466 s.live[p.ID] = l 2467 changed = true 2468 } 2469 } 2470 2471 if !changed { 2472 break 2473 } 2474 } 2475 if f.pass.debug > regDebug { 2476 fmt.Println("live values at end of each block") 2477 for _, b := range f.Blocks { 2478 fmt.Printf(" %s:", b) 2479 for _, x := range s.live[b.ID] { 2480 fmt.Printf(" v%d", x.ID) 2481 for _, e := range s.desired[b.ID].entries { 2482 if e.ID != x.ID { 2483 continue 2484 } 2485 fmt.Printf("[") 2486 first := true 2487 for _, r := range e.regs { 2488 if r == noRegister { 2489 continue 2490 } 2491 if !first { 2492 fmt.Printf(",") 2493 } 2494 fmt.Print(s.registers[r].Name()) 2495 first = false 2496 } 2497 fmt.Printf("]") 2498 } 2499 } 2500 fmt.Printf(" avoid=%x", int64(s.desired[b.ID].avoid)) 2501 fmt.Println() 2502 } 2503 } 2504 } 2505 2506 // A desiredState represents desired register assignments. 2507 type desiredState struct { 2508 // Desired assignments will be small, so we just use a list 2509 // of valueID+registers entries. 2510 entries []desiredStateEntry 2511 // Registers that other values want to be in. This value will 2512 // contain at least the union of the regs fields of entries, but 2513 // may contain additional entries for values that were once in 2514 // this data structure but are no longer. 2515 avoid regMask 2516 } 2517 type desiredStateEntry struct { 2518 // (pre-regalloc) value 2519 ID ID 2520 // Registers it would like to be in, in priority order. 2521 // Unused slots are filled with noRegister. 2522 regs [4]register 2523 } 2524 2525 func (d *desiredState) clear() { 2526 d.entries = d.entries[:0] 2527 d.avoid = 0 2528 } 2529 2530 // get returns a list of desired registers for value vid. 2531 func (d *desiredState) get(vid ID) [4]register { 2532 for _, e := range d.entries { 2533 if e.ID == vid { 2534 return e.regs 2535 } 2536 } 2537 return [4]register{noRegister, noRegister, noRegister, noRegister} 2538 } 2539 2540 // add records that we'd like value vid to be in register r. 2541 func (d *desiredState) add(vid ID, r register) { 2542 d.avoid |= regMask(1) << r 2543 for i := range d.entries { 2544 e := &d.entries[i] 2545 if e.ID != vid { 2546 continue 2547 } 2548 if e.regs[0] == r { 2549 // Already known and highest priority 2550 return 2551 } 2552 for j := 1; j < len(e.regs); j++ { 2553 if e.regs[j] == r { 2554 // Move from lower priority to top priority 2555 copy(e.regs[1:], e.regs[:j]) 2556 e.regs[0] = r 2557 return 2558 } 2559 } 2560 copy(e.regs[1:], e.regs[:]) 2561 e.regs[0] = r 2562 return 2563 } 2564 d.entries = append(d.entries, desiredStateEntry{vid, [4]register{r, noRegister, noRegister, noRegister}}) 2565 } 2566 2567 func (d *desiredState) addList(vid ID, regs [4]register) { 2568 // regs is in priority order, so iterate in reverse order. 2569 for i := len(regs) - 1; i >= 0; i-- { 2570 r := regs[i] 2571 if r != noRegister { 2572 d.add(vid, r) 2573 } 2574 } 2575 } 2576 2577 // clobber erases any desired registers in the set m. 2578 func (d *desiredState) clobber(m regMask) { 2579 for i := 0; i < len(d.entries); { 2580 e := &d.entries[i] 2581 j := 0 2582 for _, r := range e.regs { 2583 if r != noRegister && m>>r&1 == 0 { 2584 e.regs[j] = r 2585 j++ 2586 } 2587 } 2588 if j == 0 { 2589 // No more desired registers for this value. 2590 d.entries[i] = d.entries[len(d.entries)-1] 2591 d.entries = d.entries[:len(d.entries)-1] 2592 continue 2593 } 2594 for ; j < len(e.regs); j++ { 2595 e.regs[j] = noRegister 2596 } 2597 i++ 2598 } 2599 d.avoid &^= m 2600 } 2601 2602 // copy copies a desired state from another desiredState x. 2603 func (d *desiredState) copy(x *desiredState) { 2604 d.entries = append(d.entries[:0], x.entries...) 2605 d.avoid = x.avoid 2606 } 2607 2608 // remove removes the desired registers for vid and returns them. 2609 func (d *desiredState) remove(vid ID) [4]register { 2610 for i := range d.entries { 2611 if d.entries[i].ID == vid { 2612 regs := d.entries[i].regs 2613 d.entries[i] = d.entries[len(d.entries)-1] 2614 d.entries = d.entries[:len(d.entries)-1] 2615 return regs 2616 } 2617 } 2618 return [4]register{noRegister, noRegister, noRegister, noRegister} 2619 } 2620 2621 // merge merges another desired state x into d. 2622 func (d *desiredState) merge(x *desiredState) { 2623 d.avoid |= x.avoid 2624 // There should only be a few desired registers, so 2625 // linear insert is ok. 2626 for _, e := range x.entries { 2627 d.addList(e.ID, e.regs) 2628 } 2629 }