github.com/hikaru7719/go@v0.0.0-20181025140707-c8b2ac68906a/src/cmd/compile/internal/ssa/debug.go (about) 1 // Copyright 2017 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 package ssa 5 6 import ( 7 "cmd/internal/dwarf" 8 "cmd/internal/obj" 9 "encoding/hex" 10 "fmt" 11 "math/bits" 12 "sort" 13 "strings" 14 ) 15 16 type SlotID int32 17 type VarID int32 18 19 // A FuncDebug contains all the debug information for the variables in a 20 // function. Variables are identified by their LocalSlot, which may be the 21 // result of decomposing a larger variable. 22 type FuncDebug struct { 23 // Slots is all the slots used in the debug info, indexed by their SlotID. 24 Slots []LocalSlot 25 // The user variables, indexed by VarID. 26 Vars []GCNode 27 // The slots that make up each variable, indexed by VarID. 28 VarSlots [][]SlotID 29 // The location list data, indexed by VarID. Must be processed by PutLocationList. 30 LocationLists [][]byte 31 32 // Filled in by the user. Translates Block and Value ID to PC. 33 GetPC func(ID, ID) int64 34 } 35 36 type BlockDebug struct { 37 // Whether the block had any changes to user variables at all. 38 relevant bool 39 // State at the end of the block if it's fully processed. Immutable once initialized. 40 endState []liveSlot 41 } 42 43 // A liveSlot is a slot that's live in loc at entry/exit of a block. 44 type liveSlot struct { 45 // An inlined VarLoc, so it packs into 16 bytes instead of 20. 46 Registers RegisterSet 47 StackOffset 48 49 slot SlotID 50 } 51 52 func (loc liveSlot) absent() bool { 53 return loc.Registers == 0 && !loc.onStack() 54 } 55 56 // StackOffset encodes whether a value is on the stack and if so, where. It is 57 // a 31-bit integer followed by a presence flag at the low-order bit. 58 type StackOffset int32 59 60 func (s StackOffset) onStack() bool { 61 return s != 0 62 } 63 64 func (s StackOffset) stackOffsetValue() int32 { 65 return int32(s) >> 1 66 } 67 68 // stateAtPC is the current state of all variables at some point. 69 type stateAtPC struct { 70 // The location of each known slot, indexed by SlotID. 71 slots []VarLoc 72 // The slots present in each register, indexed by register number. 73 registers [][]SlotID 74 } 75 76 // reset fills state with the live variables from live. 77 func (state *stateAtPC) reset(live []liveSlot) { 78 slots, registers := state.slots, state.registers 79 for i := range slots { 80 slots[i] = VarLoc{} 81 } 82 for i := range registers { 83 registers[i] = registers[i][:0] 84 } 85 for _, live := range live { 86 slots[live.slot] = VarLoc{live.Registers, live.StackOffset} 87 if live.Registers == 0 { 88 continue 89 } 90 91 mask := uint64(live.Registers) 92 for { 93 if mask == 0 { 94 break 95 } 96 reg := uint8(bits.TrailingZeros64(mask)) 97 mask &^= 1 << reg 98 99 registers[reg] = append(registers[reg], live.slot) 100 } 101 } 102 state.slots, state.registers = slots, registers 103 } 104 105 func (s *debugState) LocString(loc VarLoc) string { 106 if loc.absent() { 107 return "<nil>" 108 } 109 110 var storage []string 111 if loc.onStack() { 112 storage = append(storage, "stack") 113 } 114 115 mask := uint64(loc.Registers) 116 for { 117 if mask == 0 { 118 break 119 } 120 reg := uint8(bits.TrailingZeros64(mask)) 121 mask &^= 1 << reg 122 123 storage = append(storage, s.registers[reg].String()) 124 } 125 return strings.Join(storage, ",") 126 } 127 128 // A VarLoc describes the storage for part of a user variable. 129 type VarLoc struct { 130 // The registers this variable is available in. There can be more than 131 // one in various situations, e.g. it's being moved between registers. 132 Registers RegisterSet 133 134 StackOffset 135 } 136 137 func (loc VarLoc) absent() bool { 138 return loc.Registers == 0 && !loc.onStack() 139 } 140 141 var BlockStart = &Value{ 142 ID: -10000, 143 Op: OpInvalid, 144 Aux: "BlockStart", 145 } 146 147 var BlockEnd = &Value{ 148 ID: -20000, 149 Op: OpInvalid, 150 Aux: "BlockEnd", 151 } 152 153 // RegisterSet is a bitmap of registers, indexed by Register.num. 154 type RegisterSet uint64 155 156 // logf prints debug-specific logging to stdout (always stdout) if the current 157 // function is tagged by GOSSAFUNC (for ssa output directed either to stdout or html). 158 func (s *debugState) logf(msg string, args ...interface{}) { 159 if s.f.PrintOrHtmlSSA { 160 fmt.Printf(msg, args...) 161 } 162 } 163 164 type debugState struct { 165 // See FuncDebug. 166 slots []LocalSlot 167 vars []GCNode 168 varSlots [][]SlotID 169 lists [][]byte 170 171 // The user variable that each slot rolls up to, indexed by SlotID. 172 slotVars []VarID 173 174 f *Func 175 loggingEnabled bool 176 registers []Register 177 stackOffset func(LocalSlot) int32 178 ctxt *obj.Link 179 180 // The names (slots) associated with each value, indexed by Value ID. 181 valueNames [][]SlotID 182 183 // The current state of whatever analysis is running. 184 currentState stateAtPC 185 liveCount []int 186 changedVars *sparseSet 187 188 // The pending location list entry for each user variable, indexed by VarID. 189 pendingEntries []pendingEntry 190 191 varParts map[GCNode][]SlotID 192 blockDebug []BlockDebug 193 pendingSlotLocs []VarLoc 194 liveSlots []liveSlot 195 liveSlotSliceBegin int 196 partsByVarOffset sort.Interface 197 } 198 199 func (state *debugState) initializeCache(f *Func, numVars, numSlots int) { 200 // One blockDebug per block. Initialized in allocBlock. 201 if cap(state.blockDebug) < f.NumBlocks() { 202 state.blockDebug = make([]BlockDebug, f.NumBlocks()) 203 } else { 204 // This local variable, and the ones like it below, enable compiler 205 // optimizations. Don't inline them. 206 b := state.blockDebug[:f.NumBlocks()] 207 for i := range b { 208 b[i] = BlockDebug{} 209 } 210 } 211 212 // A list of slots per Value. Reuse the previous child slices. 213 if cap(state.valueNames) < f.NumValues() { 214 old := state.valueNames 215 state.valueNames = make([][]SlotID, f.NumValues()) 216 copy(state.valueNames, old) 217 } 218 vn := state.valueNames[:f.NumValues()] 219 for i := range vn { 220 vn[i] = vn[i][:0] 221 } 222 223 // Slot and register contents for currentState. Cleared by reset(). 224 if cap(state.currentState.slots) < numSlots { 225 state.currentState.slots = make([]VarLoc, numSlots) 226 } else { 227 state.currentState.slots = state.currentState.slots[:numSlots] 228 } 229 if cap(state.currentState.registers) < len(state.registers) { 230 state.currentState.registers = make([][]SlotID, len(state.registers)) 231 } else { 232 state.currentState.registers = state.currentState.registers[:len(state.registers)] 233 } 234 235 // Used many times by mergePredecessors. 236 if cap(state.liveCount) < numSlots { 237 state.liveCount = make([]int, numSlots) 238 } else { 239 state.liveCount = state.liveCount[:numSlots] 240 } 241 242 // A relatively small slice, but used many times as the return from processValue. 243 state.changedVars = newSparseSet(numVars) 244 245 // A pending entry per user variable, with space to track each of its pieces. 246 numPieces := 0 247 for i := range state.varSlots { 248 numPieces += len(state.varSlots[i]) 249 } 250 if cap(state.pendingSlotLocs) < numPieces { 251 state.pendingSlotLocs = make([]VarLoc, numPieces) 252 } else { 253 psl := state.pendingSlotLocs[:numPieces] 254 for i := range psl { 255 psl[i] = VarLoc{} 256 } 257 } 258 if cap(state.pendingEntries) < numVars { 259 state.pendingEntries = make([]pendingEntry, numVars) 260 } 261 pe := state.pendingEntries[:numVars] 262 freePieceIdx := 0 263 for varID, slots := range state.varSlots { 264 pe[varID] = pendingEntry{ 265 pieces: state.pendingSlotLocs[freePieceIdx : freePieceIdx+len(slots)], 266 } 267 freePieceIdx += len(slots) 268 } 269 state.pendingEntries = pe 270 271 if cap(state.lists) < numVars { 272 state.lists = make([][]byte, numVars) 273 } else { 274 state.lists = state.lists[:numVars] 275 for i := range state.lists { 276 state.lists[i] = nil 277 } 278 } 279 280 state.liveSlots = state.liveSlots[:0] 281 state.liveSlotSliceBegin = 0 282 } 283 284 func (state *debugState) allocBlock(b *Block) *BlockDebug { 285 return &state.blockDebug[b.ID] 286 } 287 288 func (state *debugState) appendLiveSlot(ls liveSlot) { 289 state.liveSlots = append(state.liveSlots, ls) 290 } 291 292 func (state *debugState) getLiveSlotSlice() []liveSlot { 293 s := state.liveSlots[state.liveSlotSliceBegin:] 294 state.liveSlotSliceBegin = len(state.liveSlots) 295 return s 296 } 297 298 func (s *debugState) blockEndStateString(b *BlockDebug) string { 299 endState := stateAtPC{slots: make([]VarLoc, len(s.slots)), registers: make([][]SlotID, len(s.registers))} 300 endState.reset(b.endState) 301 return s.stateString(endState) 302 } 303 304 func (s *debugState) stateString(state stateAtPC) string { 305 var strs []string 306 for slotID, loc := range state.slots { 307 if !loc.absent() { 308 strs = append(strs, fmt.Sprintf("\t%v = %v\n", s.slots[slotID], s.LocString(loc))) 309 } 310 } 311 312 strs = append(strs, "\n") 313 for reg, slots := range state.registers { 314 if len(slots) != 0 { 315 var slotStrs []string 316 for _, slot := range slots { 317 slotStrs = append(slotStrs, s.slots[slot].String()) 318 } 319 strs = append(strs, fmt.Sprintf("\t%v = %v\n", &s.registers[reg], slotStrs)) 320 } 321 } 322 323 if len(strs) == 1 { 324 return "(no vars)\n" 325 } 326 return strings.Join(strs, "") 327 } 328 329 // BuildFuncDebug returns debug information for f. 330 // f must be fully processed, so that each Value is where it will be when 331 // machine code is emitted. 332 func BuildFuncDebug(ctxt *obj.Link, f *Func, loggingEnabled bool, stackOffset func(LocalSlot) int32) *FuncDebug { 333 if f.RegAlloc == nil { 334 f.Fatalf("BuildFuncDebug on func %v that has not been fully processed", f) 335 } 336 state := &f.Cache.debugState 337 state.loggingEnabled = loggingEnabled 338 state.f = f 339 state.registers = f.Config.registers 340 state.stackOffset = stackOffset 341 state.ctxt = ctxt 342 343 if state.loggingEnabled { 344 state.logf("Generating location lists for function %q\n", f.Name) 345 } 346 347 if state.varParts == nil { 348 state.varParts = make(map[GCNode][]SlotID) 349 } else { 350 for n := range state.varParts { 351 delete(state.varParts, n) 352 } 353 } 354 355 // Recompose any decomposed variables, and establish the canonical 356 // IDs for each var and slot by filling out state.vars and state.slots. 357 358 state.slots = state.slots[:0] 359 state.vars = state.vars[:0] 360 for i, slot := range f.Names { 361 state.slots = append(state.slots, slot) 362 if slot.N.IsSynthetic() { 363 continue 364 } 365 366 topSlot := &slot 367 for topSlot.SplitOf != nil { 368 topSlot = topSlot.SplitOf 369 } 370 if _, ok := state.varParts[topSlot.N]; !ok { 371 state.vars = append(state.vars, topSlot.N) 372 } 373 state.varParts[topSlot.N] = append(state.varParts[topSlot.N], SlotID(i)) 374 } 375 376 // Recreate the LocalSlot for each stack-only variable. 377 // This would probably be better as an output from stackframe. 378 for _, b := range f.Blocks { 379 for _, v := range b.Values { 380 if v.Op == OpVarDef || v.Op == OpVarKill { 381 n := v.Aux.(GCNode) 382 if n.IsSynthetic() { 383 continue 384 } 385 386 if _, ok := state.varParts[n]; !ok { 387 slot := LocalSlot{N: n, Type: v.Type, Off: 0} 388 state.slots = append(state.slots, slot) 389 state.varParts[n] = []SlotID{SlotID(len(state.slots) - 1)} 390 state.vars = append(state.vars, n) 391 } 392 } 393 } 394 } 395 396 // Fill in the var<->slot mappings. 397 if cap(state.varSlots) < len(state.vars) { 398 state.varSlots = make([][]SlotID, len(state.vars)) 399 } else { 400 state.varSlots = state.varSlots[:len(state.vars)] 401 for i := range state.varSlots { 402 state.varSlots[i] = state.varSlots[i][:0] 403 } 404 } 405 if cap(state.slotVars) < len(state.slots) { 406 state.slotVars = make([]VarID, len(state.slots)) 407 } else { 408 state.slotVars = state.slotVars[:len(state.slots)] 409 } 410 411 if state.partsByVarOffset == nil { 412 state.partsByVarOffset = &partsByVarOffset{} 413 } 414 for varID, n := range state.vars { 415 parts := state.varParts[n] 416 state.varSlots[varID] = parts 417 for _, slotID := range parts { 418 state.slotVars[slotID] = VarID(varID) 419 } 420 *state.partsByVarOffset.(*partsByVarOffset) = partsByVarOffset{parts, state.slots} 421 sort.Sort(state.partsByVarOffset) 422 } 423 424 state.initializeCache(f, len(state.varParts), len(state.slots)) 425 426 for i, slot := range f.Names { 427 if slot.N.IsSynthetic() { 428 continue 429 } 430 for _, value := range f.NamedValues[slot] { 431 state.valueNames[value.ID] = append(state.valueNames[value.ID], SlotID(i)) 432 } 433 } 434 435 blockLocs := state.liveness() 436 state.buildLocationLists(blockLocs) 437 438 return &FuncDebug{ 439 Slots: state.slots, 440 VarSlots: state.varSlots, 441 Vars: state.vars, 442 LocationLists: state.lists, 443 } 444 } 445 446 // liveness walks the function in control flow order, calculating the start 447 // and end state of each block. 448 func (state *debugState) liveness() []*BlockDebug { 449 blockLocs := make([]*BlockDebug, state.f.NumBlocks()) 450 451 // Reverse postorder: visit a block after as many as possible of its 452 // predecessors have been visited. 453 po := state.f.Postorder() 454 for i := len(po) - 1; i >= 0; i-- { 455 b := po[i] 456 457 // Build the starting state for the block from the final 458 // state of its predecessors. 459 startState, startValid := state.mergePredecessors(b, blockLocs) 460 changed := false 461 if state.loggingEnabled { 462 state.logf("Processing %v, initial state:\n%v", b, state.stateString(state.currentState)) 463 } 464 465 // Update locs/registers with the effects of each Value. 466 for _, v := range b.Values { 467 slots := state.valueNames[v.ID] 468 469 // Loads and stores inherit the names of their sources. 470 var source *Value 471 switch v.Op { 472 case OpStoreReg: 473 source = v.Args[0] 474 case OpLoadReg: 475 switch a := v.Args[0]; a.Op { 476 case OpArg, OpPhi: 477 source = a 478 case OpStoreReg: 479 source = a.Args[0] 480 default: 481 if state.loggingEnabled { 482 state.logf("at %v: load with unexpected source op: %v (%v)\n", v, a.Op, a) 483 } 484 } 485 } 486 // Update valueNames with the source so that later steps 487 // don't need special handling. 488 if source != nil { 489 slots = append(slots, state.valueNames[source.ID]...) 490 state.valueNames[v.ID] = slots 491 } 492 493 reg, _ := state.f.getHome(v.ID).(*Register) 494 c := state.processValue(v, slots, reg) 495 changed = changed || c 496 } 497 498 if state.loggingEnabled { 499 state.f.Logf("Block %v done, locs:\n%v", b, state.stateString(state.currentState)) 500 } 501 502 locs := state.allocBlock(b) 503 locs.relevant = changed 504 if !changed && startValid { 505 locs.endState = startState 506 } else { 507 for slotID, slotLoc := range state.currentState.slots { 508 if slotLoc.absent() { 509 continue 510 } 511 state.appendLiveSlot(liveSlot{slot: SlotID(slotID), Registers: slotLoc.Registers, StackOffset: slotLoc.StackOffset}) 512 } 513 locs.endState = state.getLiveSlotSlice() 514 } 515 blockLocs[b.ID] = locs 516 } 517 return blockLocs 518 } 519 520 // mergePredecessors takes the end state of each of b's predecessors and 521 // intersects them to form the starting state for b. It returns that state in 522 // the BlockDebug, and fills state.currentState with it. 523 func (state *debugState) mergePredecessors(b *Block, blockLocs []*BlockDebug) ([]liveSlot, bool) { 524 // Filter out back branches. 525 var predsBuf [10]*Block 526 preds := predsBuf[:0] 527 for _, pred := range b.Preds { 528 if blockLocs[pred.b.ID] != nil { 529 preds = append(preds, pred.b) 530 } 531 } 532 533 if state.loggingEnabled { 534 // The logf below would cause preds to be heap-allocated if 535 // it were passed directly. 536 preds2 := make([]*Block, len(preds)) 537 copy(preds2, preds) 538 state.logf("Merging %v into %v\n", preds2, b) 539 } 540 541 if len(preds) == 0 { 542 state.currentState.reset(nil) 543 return nil, true 544 } 545 546 p0 := blockLocs[preds[0].ID].endState 547 if len(preds) == 1 { 548 state.currentState.reset(p0) 549 return p0, true 550 } 551 552 if state.loggingEnabled { 553 state.logf("Starting %v with state from %v:\n%v", b, preds[0], state.blockEndStateString(blockLocs[preds[0].ID])) 554 } 555 556 slotLocs := state.currentState.slots 557 for _, predSlot := range p0 { 558 slotLocs[predSlot.slot] = VarLoc{predSlot.Registers, predSlot.StackOffset} 559 state.liveCount[predSlot.slot] = 1 560 } 561 for i := 1; i < len(preds); i++ { 562 if state.loggingEnabled { 563 state.logf("Merging in state from %v:\n%v", preds[i], state.blockEndStateString(blockLocs[preds[i].ID])) 564 } 565 for _, predSlot := range blockLocs[preds[i].ID].endState { 566 state.liveCount[predSlot.slot]++ 567 liveLoc := slotLocs[predSlot.slot] 568 if !liveLoc.onStack() || !predSlot.onStack() || liveLoc.StackOffset != predSlot.StackOffset { 569 liveLoc.StackOffset = 0 570 } 571 liveLoc.Registers &= predSlot.Registers 572 slotLocs[predSlot.slot] = liveLoc 573 } 574 } 575 576 // Check if the final state is the same as the first predecessor's 577 // final state, and reuse it if so. In principle it could match any, 578 // but it's probably not worth checking more than the first. 579 unchanged := true 580 for _, predSlot := range p0 { 581 if state.liveCount[predSlot.slot] != len(preds) || 582 slotLocs[predSlot.slot].Registers != predSlot.Registers || 583 slotLocs[predSlot.slot].StackOffset != predSlot.StackOffset { 584 unchanged = false 585 break 586 } 587 } 588 if unchanged { 589 if state.loggingEnabled { 590 state.logf("After merge, %v matches %v exactly.\n", b, preds[0]) 591 } 592 state.currentState.reset(p0) 593 return p0, true 594 } 595 596 for reg := range state.currentState.registers { 597 state.currentState.registers[reg] = state.currentState.registers[reg][:0] 598 } 599 600 // A slot is live if it was seen in all predecessors, and they all had 601 // some storage in common. 602 for _, predSlot := range p0 { 603 slotLoc := slotLocs[predSlot.slot] 604 605 if state.liveCount[predSlot.slot] != len(preds) { 606 // Seen in only some predecessors. Clear it out. 607 slotLocs[predSlot.slot] = VarLoc{} 608 continue 609 } 610 611 // Present in all predecessors. 612 mask := uint64(slotLoc.Registers) 613 for { 614 if mask == 0 { 615 break 616 } 617 reg := uint8(bits.TrailingZeros64(mask)) 618 mask &^= 1 << reg 619 620 state.currentState.registers[reg] = append(state.currentState.registers[reg], predSlot.slot) 621 } 622 } 623 return nil, false 624 } 625 626 // processValue updates locs and state.registerContents to reflect v, a value with 627 // the names in vSlots and homed in vReg. "v" becomes visible after execution of 628 // the instructions evaluating it. It returns which VarIDs were modified by the 629 // Value's execution. 630 func (state *debugState) processValue(v *Value, vSlots []SlotID, vReg *Register) bool { 631 locs := state.currentState 632 changed := false 633 setSlot := func(slot SlotID, loc VarLoc) { 634 changed = true 635 state.changedVars.add(ID(state.slotVars[slot])) 636 state.currentState.slots[slot] = loc 637 } 638 639 // Handle any register clobbering. Call operations, for example, 640 // clobber all registers even though they don't explicitly write to 641 // them. 642 clobbers := uint64(opcodeTable[v.Op].reg.clobbers) 643 for { 644 if clobbers == 0 { 645 break 646 } 647 reg := uint8(bits.TrailingZeros64(clobbers)) 648 clobbers &^= 1 << reg 649 650 for _, slot := range locs.registers[reg] { 651 if state.loggingEnabled { 652 state.logf("at %v: %v clobbered out of %v\n", v, state.slots[slot], &state.registers[reg]) 653 } 654 655 last := locs.slots[slot] 656 if last.absent() { 657 state.f.Fatalf("at %v: slot %v in register %v with no location entry", v, state.slots[slot], &state.registers[reg]) 658 continue 659 } 660 regs := last.Registers &^ (1 << reg) 661 setSlot(slot, VarLoc{regs, last.StackOffset}) 662 } 663 664 locs.registers[reg] = locs.registers[reg][:0] 665 } 666 667 switch { 668 case v.Op == OpVarDef, v.Op == OpVarKill: 669 n := v.Aux.(GCNode) 670 if n.IsSynthetic() { 671 break 672 } 673 674 slotID := state.varParts[n][0] 675 var stackOffset StackOffset 676 if v.Op == OpVarDef { 677 stackOffset = StackOffset(state.stackOffset(state.slots[slotID])<<1 | 1) 678 } 679 setSlot(slotID, VarLoc{0, stackOffset}) 680 if state.loggingEnabled { 681 if v.Op == OpVarDef { 682 state.logf("at %v: stack-only var %v now live\n", v, state.slots[slotID]) 683 } else { 684 state.logf("at %v: stack-only var %v now dead\n", v, state.slots[slotID]) 685 } 686 } 687 688 case v.Op == OpArg: 689 home := state.f.getHome(v.ID).(LocalSlot) 690 stackOffset := state.stackOffset(home)<<1 | 1 691 for _, slot := range vSlots { 692 if state.loggingEnabled { 693 state.logf("at %v: arg %v now on stack in location %v\n", v, state.slots[slot], home) 694 if last := locs.slots[slot]; !last.absent() { 695 state.logf("at %v: unexpected arg op on already-live slot %v\n", v, state.slots[slot]) 696 } 697 } 698 699 setSlot(slot, VarLoc{0, StackOffset(stackOffset)}) 700 } 701 702 case v.Op == OpStoreReg: 703 home := state.f.getHome(v.ID).(LocalSlot) 704 stackOffset := state.stackOffset(home)<<1 | 1 705 for _, slot := range vSlots { 706 last := locs.slots[slot] 707 if last.absent() { 708 if state.loggingEnabled { 709 state.logf("at %v: unexpected spill of unnamed register %s\n", v, vReg) 710 } 711 break 712 } 713 714 setSlot(slot, VarLoc{last.Registers, StackOffset(stackOffset)}) 715 if state.loggingEnabled { 716 state.logf("at %v: %v spilled to stack location %v\n", v, state.slots[slot], home) 717 } 718 } 719 720 case vReg != nil: 721 if state.loggingEnabled { 722 newSlots := make([]bool, len(state.slots)) 723 for _, slot := range vSlots { 724 newSlots[slot] = true 725 } 726 727 for _, slot := range locs.registers[vReg.num] { 728 if !newSlots[slot] { 729 state.logf("at %v: overwrote %v in register %v\n", v, state.slots[slot], vReg) 730 } 731 } 732 } 733 734 for _, slot := range locs.registers[vReg.num] { 735 last := locs.slots[slot] 736 setSlot(slot, VarLoc{last.Registers &^ (1 << uint8(vReg.num)), last.StackOffset}) 737 } 738 locs.registers[vReg.num] = locs.registers[vReg.num][:0] 739 locs.registers[vReg.num] = append(locs.registers[vReg.num], vSlots...) 740 for _, slot := range vSlots { 741 if state.loggingEnabled { 742 state.logf("at %v: %v now in %s\n", v, state.slots[slot], vReg) 743 } 744 745 last := locs.slots[slot] 746 setSlot(slot, VarLoc{1<<uint8(vReg.num) | last.Registers, last.StackOffset}) 747 } 748 } 749 return changed 750 } 751 752 // varOffset returns the offset of slot within the user variable it was 753 // decomposed from. This has nothing to do with its stack offset. 754 func varOffset(slot LocalSlot) int64 { 755 offset := slot.Off 756 s := &slot 757 for ; s.SplitOf != nil; s = s.SplitOf { 758 offset += s.SplitOffset 759 } 760 return offset 761 } 762 763 type partsByVarOffset struct { 764 slotIDs []SlotID 765 slots []LocalSlot 766 } 767 768 func (a partsByVarOffset) Len() int { return len(a.slotIDs) } 769 func (a partsByVarOffset) Less(i, j int) bool { 770 return varOffset(a.slots[a.slotIDs[i]]) < varOffset(a.slots[a.slotIDs[j]]) 771 } 772 func (a partsByVarOffset) Swap(i, j int) { a.slotIDs[i], a.slotIDs[j] = a.slotIDs[j], a.slotIDs[i] } 773 774 // A pendingEntry represents the beginning of a location list entry, missing 775 // only its end coordinate. 776 type pendingEntry struct { 777 present bool 778 startBlock, startValue ID 779 // The location of each piece of the variable, in the same order as the 780 // SlotIDs in varParts. 781 pieces []VarLoc 782 } 783 784 func (e *pendingEntry) clear() { 785 e.present = false 786 e.startBlock = 0 787 e.startValue = 0 788 for i := range e.pieces { 789 e.pieces[i] = VarLoc{} 790 } 791 } 792 793 // canMerge returns true if the location description for new is the same as 794 // pending. 795 func canMerge(pending, new VarLoc) bool { 796 if pending.absent() && new.absent() { 797 return true 798 } 799 if pending.absent() || new.absent() { 800 return false 801 } 802 if pending.onStack() { 803 return pending.StackOffset == new.StackOffset 804 } 805 if pending.Registers != 0 && new.Registers != 0 { 806 return firstReg(pending.Registers) == firstReg(new.Registers) 807 } 808 return false 809 } 810 811 // firstReg returns the first register in set that is present. 812 func firstReg(set RegisterSet) uint8 { 813 if set == 0 { 814 // This is wrong, but there seem to be some situations where we 815 // produce locations with no storage. 816 return 0 817 } 818 return uint8(bits.TrailingZeros64(uint64(set))) 819 } 820 821 // buildLocationLists builds location lists for all the user variables in 822 // state.f, using the information about block state in blockLocs. 823 // The returned location lists are not fully complete. They are in terms of 824 // SSA values rather than PCs, and have no base address/end entries. They will 825 // be finished by PutLocationList. 826 func (state *debugState) buildLocationLists(blockLocs []*BlockDebug) { 827 // Run through the function in program text order, building up location 828 // lists as we go. The heavy lifting has mostly already been done. 829 for _, b := range state.f.Blocks { 830 if !blockLocs[b.ID].relevant { 831 continue 832 } 833 834 state.mergePredecessors(b, blockLocs) 835 836 zeroWidthPending := false 837 for _, v := range b.Values { 838 slots := state.valueNames[v.ID] 839 reg, _ := state.f.getHome(v.ID).(*Register) 840 changed := state.processValue(v, slots, reg) 841 842 if opcodeTable[v.Op].zeroWidth { 843 if changed { 844 zeroWidthPending = true 845 } 846 continue 847 } 848 849 if !changed && !zeroWidthPending { 850 continue 851 } 852 853 zeroWidthPending = false 854 for _, varID := range state.changedVars.contents() { 855 state.updateVar(VarID(varID), v, state.currentState.slots) 856 } 857 state.changedVars.clear() 858 } 859 } 860 861 if state.loggingEnabled { 862 state.logf("location lists:\n") 863 } 864 865 // Flush any leftover entries live at the end of the last block. 866 for varID := range state.lists { 867 state.writePendingEntry(VarID(varID), state.f.Blocks[len(state.f.Blocks)-1].ID, BlockEnd.ID) 868 list := state.lists[varID] 869 if state.loggingEnabled { 870 if len(list) == 0 { 871 state.logf("\t%v : empty list\n", state.vars[varID]) 872 } else { 873 state.logf("\t%v : %q\n", state.vars[varID], hex.EncodeToString(state.lists[varID])) 874 } 875 } 876 } 877 } 878 879 // updateVar updates the pending location list entry for varID to 880 // reflect the new locations in curLoc, caused by v. 881 func (state *debugState) updateVar(varID VarID, v *Value, curLoc []VarLoc) { 882 // Assemble the location list entry with whatever's live. 883 empty := true 884 for _, slotID := range state.varSlots[varID] { 885 if !curLoc[slotID].absent() { 886 empty = false 887 break 888 } 889 } 890 pending := &state.pendingEntries[varID] 891 if empty { 892 state.writePendingEntry(varID, v.Block.ID, v.ID) 893 pending.clear() 894 return 895 } 896 897 // Extend the previous entry if possible. 898 if pending.present { 899 merge := true 900 for i, slotID := range state.varSlots[varID] { 901 if !canMerge(pending.pieces[i], curLoc[slotID]) { 902 merge = false 903 break 904 } 905 } 906 if merge { 907 return 908 } 909 } 910 911 state.writePendingEntry(varID, v.Block.ID, v.ID) 912 pending.present = true 913 pending.startBlock = v.Block.ID 914 pending.startValue = v.ID 915 for i, slot := range state.varSlots[varID] { 916 pending.pieces[i] = curLoc[slot] 917 } 918 } 919 920 // writePendingEntry writes out the pending entry for varID, if any, 921 // terminated at endBlock/Value. 922 func (state *debugState) writePendingEntry(varID VarID, endBlock, endValue ID) { 923 pending := state.pendingEntries[varID] 924 if !pending.present { 925 return 926 } 927 928 // Pack the start/end coordinates into the start/end addresses 929 // of the entry, for decoding by PutLocationList. 930 start, startOK := encodeValue(state.ctxt, pending.startBlock, pending.startValue) 931 end, endOK := encodeValue(state.ctxt, endBlock, endValue) 932 if !startOK || !endOK { 933 // If someone writes a function that uses >65K values, 934 // they get incomplete debug info on 32-bit platforms. 935 return 936 } 937 list := state.lists[varID] 938 list = appendPtr(state.ctxt, list, start) 939 list = appendPtr(state.ctxt, list, end) 940 // Where to write the length of the location description once 941 // we know how big it is. 942 sizeIdx := len(list) 943 list = list[:len(list)+2] 944 945 if state.loggingEnabled { 946 var partStrs []string 947 for i, slot := range state.varSlots[varID] { 948 partStrs = append(partStrs, fmt.Sprintf("%v@%v", state.slots[slot], state.LocString(pending.pieces[i]))) 949 } 950 state.logf("Add entry for %v: \tb%vv%v-b%vv%v = \t%v\n", state.vars[varID], pending.startBlock, pending.startValue, endBlock, endValue, strings.Join(partStrs, " ")) 951 } 952 953 for i, slotID := range state.varSlots[varID] { 954 loc := pending.pieces[i] 955 slot := state.slots[slotID] 956 957 if !loc.absent() { 958 if loc.onStack() { 959 if loc.stackOffsetValue() == 0 { 960 list = append(list, dwarf.DW_OP_call_frame_cfa) 961 } else { 962 list = append(list, dwarf.DW_OP_fbreg) 963 list = dwarf.AppendSleb128(list, int64(loc.stackOffsetValue())) 964 } 965 } else { 966 regnum := state.ctxt.Arch.DWARFRegisters[state.registers[firstReg(loc.Registers)].ObjNum()] 967 if regnum < 32 { 968 list = append(list, dwarf.DW_OP_reg0+byte(regnum)) 969 } else { 970 list = append(list, dwarf.DW_OP_regx) 971 list = dwarf.AppendUleb128(list, uint64(regnum)) 972 } 973 } 974 } 975 976 if len(state.varSlots[varID]) > 1 { 977 list = append(list, dwarf.DW_OP_piece) 978 list = dwarf.AppendUleb128(list, uint64(slot.Type.Size())) 979 } 980 } 981 state.ctxt.Arch.ByteOrder.PutUint16(list[sizeIdx:], uint16(len(list)-sizeIdx-2)) 982 state.lists[varID] = list 983 } 984 985 // PutLocationList adds list (a location list in its intermediate representation) to listSym. 986 func (debugInfo *FuncDebug) PutLocationList(list []byte, ctxt *obj.Link, listSym, startPC *obj.LSym) { 987 getPC := debugInfo.GetPC 988 // Re-read list, translating its address from block/value ID to PC. 989 for i := 0; i < len(list); { 990 begin := getPC(decodeValue(ctxt, readPtr(ctxt, list[i:]))) 991 end := getPC(decodeValue(ctxt, readPtr(ctxt, list[i+ctxt.Arch.PtrSize:]))) 992 993 // Horrible hack. If a range contains only zero-width 994 // instructions, e.g. an Arg, and it's at the beginning of the 995 // function, this would be indistinguishable from an 996 // end entry. Fudge it. 997 if begin == 0 && end == 0 { 998 end = 1 999 } 1000 1001 writePtr(ctxt, list[i:], uint64(begin)) 1002 writePtr(ctxt, list[i+ctxt.Arch.PtrSize:], uint64(end)) 1003 i += 2 * ctxt.Arch.PtrSize 1004 i += 2 + int(ctxt.Arch.ByteOrder.Uint16(list[i:])) 1005 } 1006 1007 // Base address entry. 1008 listSym.WriteInt(ctxt, listSym.Size, ctxt.Arch.PtrSize, ^0) 1009 listSym.WriteAddr(ctxt, listSym.Size, ctxt.Arch.PtrSize, startPC, 0) 1010 // Location list contents, now with real PCs. 1011 listSym.WriteBytes(ctxt, listSym.Size, list) 1012 // End entry. 1013 listSym.WriteInt(ctxt, listSym.Size, ctxt.Arch.PtrSize, 0) 1014 listSym.WriteInt(ctxt, listSym.Size, ctxt.Arch.PtrSize, 0) 1015 } 1016 1017 // Pack a value and block ID into an address-sized uint, returning ~0 if they 1018 // don't fit. 1019 func encodeValue(ctxt *obj.Link, b, v ID) (uint64, bool) { 1020 if ctxt.Arch.PtrSize == 8 { 1021 result := uint64(b)<<32 | uint64(uint32(v)) 1022 //ctxt.Logf("b %#x (%d) v %#x (%d) -> %#x\n", b, b, v, v, result) 1023 return result, true 1024 } 1025 if ctxt.Arch.PtrSize != 4 { 1026 panic("unexpected pointer size") 1027 } 1028 if ID(int16(b)) != b || ID(int16(v)) != v { 1029 return 0, false 1030 } 1031 return uint64(b)<<16 | uint64(uint16(v)), true 1032 } 1033 1034 // Unpack a value and block ID encoded by encodeValue. 1035 func decodeValue(ctxt *obj.Link, word uint64) (ID, ID) { 1036 if ctxt.Arch.PtrSize == 8 { 1037 b, v := ID(word>>32), ID(word) 1038 //ctxt.Logf("%#x -> b %#x (%d) v %#x (%d)\n", word, b, b, v, v) 1039 return b, v 1040 } 1041 if ctxt.Arch.PtrSize != 4 { 1042 panic("unexpected pointer size") 1043 } 1044 return ID(word >> 16), ID(int16(word)) 1045 } 1046 1047 // Append a pointer-sized uint to buf. 1048 func appendPtr(ctxt *obj.Link, buf []byte, word uint64) []byte { 1049 if cap(buf) < len(buf)+20 { 1050 b := make([]byte, len(buf), 20+cap(buf)*2) 1051 copy(b, buf) 1052 buf = b 1053 } 1054 writeAt := len(buf) 1055 buf = buf[0 : len(buf)+ctxt.Arch.PtrSize] 1056 writePtr(ctxt, buf[writeAt:], word) 1057 return buf 1058 } 1059 1060 // Write a pointer-sized uint to the beginning of buf. 1061 func writePtr(ctxt *obj.Link, buf []byte, word uint64) { 1062 switch ctxt.Arch.PtrSize { 1063 case 4: 1064 ctxt.Arch.ByteOrder.PutUint32(buf, uint32(word)) 1065 case 8: 1066 ctxt.Arch.ByteOrder.PutUint64(buf, word) 1067 default: 1068 panic("unexpected pointer size") 1069 } 1070 1071 } 1072 1073 // Read a pointer-sized uint from the beginning of buf. 1074 func readPtr(ctxt *obj.Link, buf []byte) uint64 { 1075 switch ctxt.Arch.PtrSize { 1076 case 4: 1077 return uint64(ctxt.Arch.ByteOrder.Uint32(buf)) 1078 case 8: 1079 return ctxt.Arch.ByteOrder.Uint64(buf) 1080 default: 1081 panic("unexpected pointer size") 1082 } 1083 1084 }