plive.go 41.8 KB
Newer Older
1 2 3 4
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

5 6 7 8 9 10 11 12 13 14
// Garbage collector liveness bitmap generation.

// The command line flag -live causes this code to print debug information.
// The levels are:
//
//	-live (aka -live=1): print liveness lists as code warnings at safe points
//	-live=2: print an assembly listing with liveness annotations
//
// Each level includes the earlier output as well.

15 16 17
package gc

import (
18
	"cmd/compile/internal/ssa"
19
	"cmd/compile/internal/types"
20
	"cmd/internal/obj"
21 22
	"cmd/internal/objabi"
	"cmd/internal/src"
23
	"crypto/md5"
24
	"crypto/sha1"
25
	"fmt"
26
	"os"
27
	"strings"
28 29
)

30
// OpVarDef is an annotation for the liveness analysis, marking a place
31 32
// where a complete initialization (definition) of a variable begins.
// Since the liveness analysis can see initialization of single-word
33 34 35
// variables quite easy, OpVarDef is only needed for multi-word
// variables satisfying isfat(n.Type). For simplicity though, buildssa
// emits OpVarDef regardless of variable width.
36
//
37
// An 'OpVarDef x' annotation in the instruction stream tells the liveness
38
// analysis to behave as though the variable x is being initialized at that
39
// point in the instruction stream. The OpVarDef must appear before the
40 41 42 43 44 45 46 47
// actual (multi-instruction) initialization, and it must also appear after
// any uses of the previous value, if any. For example, if compiling:
//
//	x = x[1:]
//
// it is important to generate code like:
//
//	base, len, cap = pieces of x[1:]
48
//	OpVarDef x
49 50 51 52
//	x = {base, len, cap}
//
// If instead the generated code looked like:
//
53
//	OpVarDef x
54 55 56 57 58 59 60 61 62
//	base, len, cap = pieces of x[1:]
//	x = {base, len, cap}
//
// then the liveness analysis would decide the previous value of x was
// unnecessary even though it is about to be used by the x[1:] computation.
// Similarly, if the generated code looked like:
//
//	base, len, cap = pieces of x[1:]
//	x = {base, len, cap}
63
//	OpVarDef x
64 65
//
// then the liveness analysis will not preserve the new value of x, because
66
// the OpVarDef appears to have "overwritten" it.
67
//
68
// OpVarDef is a bit of a kludge to work around the fact that the instruction
69 70 71 72 73 74 75
// stream is working on single-word values but the liveness analysis
// wants to work on individual variables, which might be multi-word
// aggregates. It might make sense at some point to look into letting
// the liveness analysis work on single-word values as well, although
// there are complications around interface values, slices, and strings,
// all of which cannot be treated as individual words.
//
76 77
// OpVarKill is the opposite of OpVarDef: it marks a value as no longer needed,
// even if its address has been taken. That is, an OpVarKill annotation asserts
78 79 80
// that its argument is certainly dead, for use when the liveness analysis
// would not otherwise be able to deduce that fact.

81 82
// BlockEffects summarizes the liveness effects on an SSA block.
type BlockEffects struct {
83
	lastbitmapindex int // for Liveness.epilogue
84

85
	// Computed during Liveness.prologue using only the content of
86 87 88 89 90
	// individual blocks:
	//
	//	uevar: upward exposed variables (used before set in block)
	//	varkill: killed variables (set in block)
	//	avarinit: addrtaken variables set or used (proof of initialization)
91 92 93
	uevar    bvec
	varkill  bvec
	avarinit bvec
94

95
	// Computed during Liveness.solve using control flow information:
96 97 98 99 100 101 102
	//
	//	livein: variables live at block entry
	//	liveout: variables live at block exit
	//	avarinitany: addrtaken variables possibly initialized at block exit
	//		(initialized in block or at exit from any predecessor block)
	//	avarinitall: addrtaken variables certainly initialized at block exit
	//		(initialized in block or at exit from all predecessor blocks)
103 104 105 106
	livein      bvec
	liveout     bvec
	avarinitany bvec
	avarinitall bvec
107 108 109 110
}

// A collection of global state used by liveness analysis.
type Liveness struct {
111
	fn         *Node
112
	f          *ssa.Func
113
	vars       []*Node
114
	idx        map[*Node]int32
115
	stkptrsize int64
116

117 118
	be []BlockEffects

119 120 121
	// unsafePoints bit i is set if Value ID i is not a safe point.
	unsafePoints bvec

122
	// An array with a bit vector for each safe point tracking live variables.
123
	// Indexed sequentially by safe points in Block and Value order.
124
	livevars []bvec
125

126 127 128 129 130 131 132
	// livenessMap maps from safe points (i.e., CALLs) to their
	// liveness map indexes.
	//
	// TODO(austin): Now that we have liveness at almost every PC,
	// should this be a dense structure?
	livenessMap LivenessMap
	stackMaps   []bvec
133

134 135 136
	cache progeffectscache
}

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
// LivenessMap maps from *ssa.Value to LivenessIndex.
type LivenessMap struct {
	m map[*ssa.Value]LivenessIndex
}

func (m LivenessMap) Get(v *ssa.Value) LivenessIndex {
	if i, ok := m.m[v]; ok {
		return i
	}
	// Not a safe point.
	return LivenessInvalid
}

// LivenessIndex stores the liveness map index for a safe-point.
type LivenessIndex struct {
	stackMapIndex int
}

// LivenessInvalid indicates an unsafe point.
156 157 158 159 160 161 162
//
// We use index -2 because PCDATA tables conventionally start at -1,
// so -1 is used to mean the entry liveness map (which is actually at
// index 0; sigh). TODO(austin): Maybe we should use PCDATA+1 as the
// index into the liveness map so -1 uniquely refers to the entry
// liveness map.
var LivenessInvalid = LivenessIndex{-2}
163 164 165 166 167

func (idx LivenessIndex) Valid() bool {
	return idx.stackMapIndex >= 0
}

168 169
type progeffectscache struct {
	textavarinit []int32
170 171
	retuevar     []int32
	tailuevar    []int32
172
	initialized  bool
173 174
}

175 176 177 178 179 180 181
// livenessShouldTrack reports whether the liveness analysis
// should track the variable n.
// We don't care about variables that have no pointers,
// nor do we care about non-local variables,
// nor do we care about empty structs (handled by the pointer check),
// nor do we care about the fake PAUTOHEAP variables.
func livenessShouldTrack(n *Node) bool {
182
	return n.Op == ONAME && (n.Class() == PAUTO || n.Class() == PPARAM || n.Class() == PPARAMOUT) && types.Haspointers(n.Type)
183
}
184

185 186 187
// getvariables returns the list of on-stack variables that we need to track
// and a map for looking up indices by *Node.
func getvariables(fn *Node) ([]*Node, map[*Node]int32) {
188 189 190 191
	var vars []*Node
	for _, n := range fn.Func.Dcl {
		if livenessShouldTrack(n) {
			vars = append(vars, n)
192 193
		}
	}
194 195 196 197 198
	idx := make(map[*Node]int32, len(vars))
	for i, n := range vars {
		idx[n] = int32(i)
	}
	return vars, idx
199 200
}

201 202 203 204 205 206 207 208
func (lv *Liveness) initcache() {
	if lv.cache.initialized {
		Fatalf("liveness cache initialized twice")
		return
	}
	lv.cache.initialized = true

	for i, node := range lv.vars {
209
		switch node.Class() {
210 211 212 213 214 215 216
		case PPARAM:
			// A return instruction with a p.to is a tail return, which brings
			// the stack pointer back up (if it ever went down) and then jumps
			// to a new function entirely. That form of instruction must read
			// all the parameters for correctness, and similarly it must not
			// read the out arguments - they won't be set until the new
			// function runs.
217

218 219
			lv.cache.tailuevar = append(lv.cache.tailuevar, int32(i))

220
			if node.Addrtaken() {
221 222 223 224 225 226 227 228 229 230 231
				lv.cache.textavarinit = append(lv.cache.textavarinit, int32(i))
			}

		case PPARAMOUT:
			// If the result had its address taken, it is being tracked
			// by the avarinit code, which does not use uevar.
			// If we added it to uevar too, we'd not see any kill
			// and decide that the variable was live entry, which it is not.
			// So only use uevar in the non-addrtaken case.
			// The p.to.type == obj.TYPE_NONE limits the bvset to
			// non-tail-call return instructions; see note below for details.
232
			if !node.Addrtaken() {
233 234 235 236 237 238
				lv.cache.retuevar = append(lv.cache.retuevar, int32(i))
			}
		}
	}
}

239 240
// A liveEffect is a set of flags that describe an instruction's
// liveness effects on a variable.
241
//
242 243 244
// The possible flags are:
//	uevar - used by the instruction
//	varkill - killed by the instruction
245 246
//		for variables without address taken, means variable was set
//		for variables with address taken, means variable was marked dead
247
//	avarinit - initialized or referred to by the instruction,
248 249 250 251 252
//		only for variables with address taken but not escaping to heap
//
// The avarinit output serves as a signal that the data has been
// initialized, because any use of a variable must come after its
// initialization.
253
type liveEffect int
254

255 256 257 258 259 260 261 262 263
const (
	uevar liveEffect = 1 << iota
	varkill
	avarinit
)

// valueEffects returns the index of a variable in lv.vars and the
// liveness effects v has on that variable.
// If v does not affect any tracked variables, it returns -1, 0.
264
func (lv *Liveness) valueEffects(v *ssa.Value) (int32, liveEffect) {
265
	n, e := affectedNode(v)
266
	if e == 0 || n == nil || n.Op != ONAME { // cheapest checks first
267
		return -1, 0
268 269
	}

270 271 272 273 274 275
	// AllocFrame has dropped unused variables from
	// lv.fn.Func.Dcl, but they might still be referenced by
	// OpVarFoo pseudo-ops. Ignore them to prevent "lost track of
	// variable" ICEs (issue 19632).
	switch v.Op {
	case ssa.OpVarDef, ssa.OpVarKill, ssa.OpVarLive, ssa.OpKeepAlive:
276
		if !n.Name.Used() {
277 278 279 280
			return -1, 0
		}
	}

281
	var effect liveEffect
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
	if n.Addrtaken() {
		if v.Op != ssa.OpVarKill {
			effect |= avarinit
		}
		if v.Op == ssa.OpVarDef || v.Op == ssa.OpVarKill {
			effect |= varkill
		}
	} else {
		// Read is a read, obviously.
		// Addr by itself is also implicitly a read.
		//
		// Addr|Write means that the address is being taken
		// but only so that the instruction can write to the value.
		// It is not a read.

		if e&ssa.SymRead != 0 || e&(ssa.SymAddr|ssa.SymWrite) == ssa.SymAddr {
			effect |= uevar
		}
		if e&ssa.SymWrite != 0 && (!isfat(n.Type) || v.Op == ssa.OpVarDef) {
			effect |= varkill
302 303 304
		}
	}

305 306 307 308 309 310 311 312
	if effect == 0 {
		return -1, 0
	}

	if pos, ok := lv.idx[n]; ok {
		return pos, effect
	}
	return -1, 0
313 314 315 316 317 318 319 320 321 322 323 324 325 326
}

// affectedNode returns the *Node affected by v
func affectedNode(v *ssa.Value) (*Node, ssa.SymEffect) {
	// Special cases.
	switch v.Op {
	case ssa.OpLoadReg:
		n, _ := AutoVar(v.Args[0])
		return n, ssa.SymRead
	case ssa.OpStoreReg:
		n, _ := AutoVar(v)
		return n, ssa.SymWrite

	case ssa.OpVarLive:
327
		return v.Aux.(*Node), ssa.SymRead
328 329 330 331 332 333 334 335 336 337 338 339 340
	case ssa.OpVarDef, ssa.OpVarKill:
		return v.Aux.(*Node), ssa.SymWrite
	case ssa.OpKeepAlive:
		n, _ := AutoVar(v.Args[0])
		return n, ssa.SymRead
	}

	e := v.Op.SymEffect()
	if e == 0 {
		return nil, 0
	}

	switch a := v.Aux.(type) {
341
	case nil, *obj.LSym:
342
		// ok, but no node
343
		return nil, e
344
	case *Node:
345
		return a, e
346 347
	default:
		Fatalf("weird aux: %s", v.LongString())
348
		return nil, e
349 350 351 352
	}
}

// Constructs a new liveness structure used to hold the global state of the
353 354
// liveness computation. The cfg argument is a slice of *BasicBlocks and the
// vars argument is a slice of *Nodes.
355
func newliveness(fn *Node, f *ssa.Func, vars []*Node, idx map[*Node]int32, stkptrsize int64) *Liveness {
356
	lv := &Liveness{
357
		fn:         fn,
358
		f:          f,
359
		vars:       vars,
360
		idx:        idx,
361
		stkptrsize: stkptrsize,
362
		be:         make([]BlockEffects, f.NumBlocks()),
363
	}
364

365
	nblocks := int32(len(f.Blocks))
366
	nvars := int32(len(vars))
367
	bulk := bvbulkalloc(nvars, nblocks*7)
368 369 370 371 372 373 374 375 376 377 378
	for _, b := range f.Blocks {
		be := lv.blockEffects(b)

		be.uevar = bulk.next()
		be.varkill = bulk.next()
		be.livein = bulk.next()
		be.liveout = bulk.next()
		be.avarinit = bulk.next()
		be.avarinitany = bulk.next()
		be.avarinitall = bulk.next()
	}
379 380

	lv.markUnsafePoints()
381
	return lv
382 383
}

384 385
func (lv *Liveness) blockEffects(b *ssa.Block) *BlockEffects {
	return &lv.be[b.ID]
386 387
}

388 389 390
// NOTE: The bitmap for a specific type t could be cached in t after
// the first run and then simply copied into bv at the correct offset
// on future calls with the same type t.
391 392
func onebitwalktype1(t *types.Type, off int64, bv bvec) {
	if t.Align > 0 && off&int64(t.Align-1) != 0 {
393
		Fatalf("onebitwalktype1: invalid initial alignment: type %v has alignment %d, but offset is %v", t, t.Align, off)
394 395 396
	}

	switch t.Etype {
397 398 399 400 401 402 403
	case TINT8, TUINT8, TINT16, TUINT16,
		TINT32, TUINT32, TINT64, TUINT64,
		TINT, TUINT, TUINTPTR, TBOOL,
		TFLOAT32, TFLOAT64, TCOMPLEX64, TCOMPLEX128:

	case TPTR32, TPTR64, TUNSAFEPTR, TFUNC, TCHAN, TMAP:
		if off&int64(Widthptr-1) != 0 {
404
			Fatalf("onebitwalktype1: invalid alignment, %v", t)
405
		}
406
		bv.Set(int32(off / int64(Widthptr))) // pointer
407 408

	case TSTRING:
409
		// struct { byte *str; intgo len; }
410
		if off&int64(Widthptr-1) != 0 {
411
			Fatalf("onebitwalktype1: invalid alignment, %v", t)
412
		}
413
		bv.Set(int32(off / int64(Widthptr))) //pointer in first slot
414 415

	case TINTER:
416 417 418
		// struct { Itab *tab;	void *data; }
		// or, when isnilinter(t)==true:
		// struct { Type *type; void *data; }
419
		if off&int64(Widthptr-1) != 0 {
420
			Fatalf("onebitwalktype1: invalid alignment, %v", t)
421
		}
422 423 424 425 426 427 428 429 430 431 432 433
		// The first word of an interface is a pointer, but we don't
		// treat it as such.
		// 1. If it is a non-empty interface, the pointer points to an itab
		//    which is always in persistentalloc space.
		// 2. If it is an empty interface, the pointer points to a _type.
		//   a. If it is a compile-time-allocated type, it points into
		//      the read-only data section.
		//   b. If it is a reflect-allocated type, it points into the Go heap.
		//      Reflect is responsible for keeping a reference to
		//      the underlying type so it won't be GCd.
		// If we ever have a moving GC, we need to change this for 2b (as
		// well as scan itabs to update their itab._type fields).
434
		bv.Set(int32(off/int64(Widthptr) + 1)) // pointer in second slot
435

436 437
	case TSLICE:
		// struct { byte *array; uintgo len; uintgo cap; }
438
		if off&int64(Widthptr-1) != 0 {
439 440
			Fatalf("onebitwalktype1: invalid TARRAY alignment, %v", t)
		}
441
		bv.Set(int32(off / int64(Widthptr))) // pointer in first slot (BitsPointer)
442

443
	case TARRAY:
444 445 446 447 448
		elt := t.Elem()
		if elt.Width == 0 {
			// Short-circuit for #20739.
			break
		}
449
		for i := int64(0); i < t.NumElem(); i++ {
450 451
			onebitwalktype1(elt, off, bv)
			off += elt.Width
452 453 454
		}

	case TSTRUCT:
455 456
		for _, f := range t.Fields().Slice() {
			onebitwalktype1(f.Type, off+f.Offset, bv)
457 458 459
		}

	default:
460
		Fatalf("onebitwalktype1: unexpected type, %v", t)
461 462 463
	}
}

464 465
// Generates live pointer value maps for arguments and local variables. The
// this argument and the in arguments are always assumed live. The vars
466
// argument is a slice of *Nodes.
467
func (lv *Liveness) pointerMap(liveout bvec, vars []*Node, args, locals bvec) {
468
	for i := int32(0); ; i++ {
469
		i = liveout.Next(i)
470
		if i < 0 {
471 472
			break
		}
473
		node := vars[i]
474
		switch node.Class() {
475
		case PAUTO:
476
			onebitwalktype1(node.Type, node.Xoffset+lv.stkptrsize, locals)
477

478
		case PPARAM, PPARAMOUT:
479
			onebitwalktype1(node.Type, node.Xoffset, args)
480 481 482 483
		}
	}
}

484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
// markUnsafePoints finds unsafe points and computes lv.unsafePoints.
func (lv *Liveness) markUnsafePoints() {
	if compiling_runtime || lv.f.NoSplit {
		// No complex analysis necessary. Do this on the fly
		// in issafepoint.
		return
	}

	lv.unsafePoints = bvalloc(int32(lv.f.NumValues()))

	// Mark write barrier unsafe points.
	for _, wbBlock := range lv.f.WBLoads {
		// Check that we have the expected diamond shape.
		if len(wbBlock.Succs) != 2 {
			lv.f.Fatalf("expected branch at write barrier block %v", wbBlock)
		}
		s0, s1 := wbBlock.Succs[0].Block(), wbBlock.Succs[1].Block()
		if s0.Kind != ssa.BlockPlain || s1.Kind != ssa.BlockPlain {
			lv.f.Fatalf("expected successors of write barrier block %v to be plain", wbBlock)
		}
		if s0.Succs[0].Block() != s1.Succs[0].Block() {
			lv.f.Fatalf("expected successors of write barrier block %v to converge", wbBlock)
		}

		// Flow backwards from the control value to find the
		// flag load. We don't know what lowered ops we're
		// looking for, but all current arches produce a
		// single op that does the memory load from the flag
		// address, so we look for that.
		var load *ssa.Value
		v := wbBlock.Control
		for {
			if sym, ok := v.Aux.(*obj.LSym); ok && sym == writeBarrier {
				load = v
				break
			}
			switch v.Op {
			case ssa.Op386TESTL:
				// 386 lowers Neq32 to (TESTL cond cond),
				if v.Args[0] == v.Args[1] {
					v = v.Args[0]
					continue
				}
			case ssa.OpPPC64MOVWZload, ssa.Op386MOVLload:
				// Args[0] is the address of the write
				// barrier control. Ignore Args[1],
				// which is the mem operand.
				v = v.Args[0]
				continue
			}
			// Common case: just flow backwards.
			if len(v.Args) != 1 {
				v.Fatalf("write barrier control value has more than one argument: %s", v.LongString())
			}
			v = v.Args[0]
		}

		// Mark everything after the load unsafe.
		found := false
		for _, v := range wbBlock.Values {
			found = found || v == load
			if found {
				lv.unsafePoints.Set(int32(v.ID))
			}
		}

		// Mark the two successor blocks unsafe. These come
		// back together immediately after the direct write in
		// one successor and the last write barrier call in
		// the other, so there's no need to be more precise.
		for _, succ := range wbBlock.Succs {
			for _, v := range succ.Block().Values {
				lv.unsafePoints.Set(int32(v.ID))
			}
		}
	}

	// Find uintptr -> unsafe.Pointer conversions and flood
	// unsafeness back to a call (which is always a safe point).
	//
	// Looking for the uintptr -> unsafe.Pointer conversion has a
	// few advantages over looking for unsafe.Pointer -> uintptr
	// conversions:
	//
	// 1. We avoid needlessly blocking safe-points for
	// unsafe.Pointer -> uintptr conversions that never go back to
	// a Pointer.
	//
	// 2. We don't have to detect calls to reflect.Value.Pointer,
	// reflect.Value.UnsafeAddr, and reflect.Value.InterfaceData,
	// which are implicit unsafe.Pointer -> uintptr conversions.
	// We can't even reliably detect this if there's an indirect
	// call to one of these methods.
	//
	// TODO: For trivial unsafe.Pointer arithmetic, it would be
	// nice to only flood as far as the unsafe.Pointer -> uintptr
	// conversion, but it's hard to know which argument of an Add
	// or Sub to follow.
	var flooded bvec
	var flood func(b *ssa.Block, vi int)
	flood = func(b *ssa.Block, vi int) {
		if flooded.n == 0 {
			flooded = bvalloc(int32(lv.f.NumBlocks()))
		}
		if flooded.Get(int32(b.ID)) {
			return
		}
		for i := vi - 1; i >= 0; i-- {
			v := b.Values[i]
			if v.Op.IsCall() {
				// Uintptrs must not contain live
				// pointers across calls, so stop
				// flooding.
				return
			}
			lv.unsafePoints.Set(int32(v.ID))
		}
		if vi == len(b.Values) {
			// We marked all values in this block, so no
			// need to flood this block again.
			flooded.Set(int32(b.ID))
		}
		for _, pred := range b.Preds {
			flood(pred.Block(), len(pred.Block().Values))
		}
	}
	for _, b := range lv.f.Blocks {
		for i, v := range b.Values {
			if !(v.Op == ssa.OpConvert && v.Type.IsPtrShaped()) {
				continue
			}
			// Flood the unsafe-ness of this backwards
			// until we hit a call.
			flood(b, i+1)
		}
	}
}

622 623
// Returns true for instructions that are safe points that must be annotated
// with liveness information.
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
func (lv *Liveness) issafepoint(v *ssa.Value) bool {
	// The runtime was written with the assumption that
	// safe-points only appear at call sites (because that's how
	// it used to be). We could and should improve that, but for
	// now keep the old safe-point rules in the runtime.
	//
	// go:nosplit functions are similar. Since safe points used to
	// be coupled with stack checks, go:nosplit often actually
	// means "no safe points in this function".
	if compiling_runtime || lv.f.NoSplit {
		return v.Op.IsCall()
	}
	switch v.Op {
	case ssa.OpInitMem, ssa.OpArg, ssa.OpSP, ssa.OpSB,
		ssa.OpSelect0, ssa.OpSelect1, ssa.OpGetG,
		ssa.OpVarDef, ssa.OpVarLive, ssa.OpKeepAlive,
		ssa.OpPhi:
		// These don't produce code (see genssa).
		return false
	}
	return !lv.unsafePoints.Get(int32(v.ID))
645 646
}

647
// Initializes the sets for solving the live variables. Visits all the
648 649
// instructions in each basic block to summarizes the information at each basic
// block
650
func (lv *Liveness) prologue() {
651 652
	lv.initcache()

653 654 655
	for _, b := range lv.f.Blocks {
		be := lv.blockEffects(b)

656 657
		// Walk the block instructions backward and update the block
		// effects with the each prog effects.
658 659 660 661 662
		for j := len(b.Values) - 1; j >= 0; j-- {
			pos, e := lv.valueEffects(b.Values[j])
			if e&varkill != 0 {
				be.varkill.Set(pos)
				be.uevar.Unset(pos)
663
			}
664 665
			if e&uevar != 0 {
				be.uevar.Set(pos)
666 667 668 669 670
			}
		}

		// Walk the block instructions forward to update avarinit bits.
		// avarinit describes the effect at the end of the block, not the beginning.
671 672
		for _, val := range b.Values {
			pos, e := lv.valueEffects(val)
673 674
			if e&varkill != 0 {
				be.avarinit.Unset(pos)
675
			}
676 677
			if e&avarinit != 0 {
				be.avarinit.Set(pos)
678 679 680 681 682 683
			}
		}
	}
}

// Solve the liveness dataflow equations.
684
func (lv *Liveness) solve() {
685 686
	// These temporary bitvectors exist to avoid successive allocations and
	// frees within the loop.
687 688 689 690
	newlivein := bvalloc(int32(len(lv.vars)))
	newliveout := bvalloc(int32(len(lv.vars)))
	any := bvalloc(int32(len(lv.vars)))
	all := bvalloc(int32(len(lv.vars)))
691 692 693 694

	// Push avarinitall, avarinitany forward.
	// avarinitall says the addressed var is initialized along all paths reaching the block exit.
	// avarinitany says the addressed var is initialized along some path reaching the block exit.
695 696 697 698
	for _, b := range lv.f.Blocks {
		be := lv.blockEffects(b)
		if b == lv.f.Entry {
			be.avarinitall.Copy(be.avarinit)
699
		} else {
700 701
			be.avarinitall.Clear()
			be.avarinitall.Not()
702
		}
703
		be.avarinitany.Copy(be.avarinit)
704 705
	}

706 707 708 709 710
	// Walk blocks in the general direction of propagation (RPO
	// for avarinit{any,all}, and PO for live{in,out}). This
	// improves convergence.
	po := lv.f.Postorder()

711 712
	for change := true; change; {
		change = false
713 714 715 716 717 718 719 720 721 722
		for i := len(po) - 1; i >= 0; i-- {
			b := po[i]
			be := lv.blockEffects(b)
			lv.avarinitanyall(b, any, all)

			any.AndNot(any, be.varkill)
			all.AndNot(all, be.varkill)
			any.Or(any, be.avarinit)
			all.Or(all, be.avarinit)
			if !any.Eq(be.avarinitany) {
723
				change = true
724
				be.avarinitany.Copy(any)
725 726
			}

727
			if !all.Eq(be.avarinitall) {
728
				change = true
729
				be.avarinitall.Copy(all)
730 731 732 733
			}
		}
	}

734 735
	// Iterate through the blocks in reverse round-robin fashion. A work
	// queue might be slightly faster. As is, the number of iterations is
736 737
	// so low that it hardly seems to be worth the complexity.

738 739
	for change := true; change; {
		change = false
740 741
		for _, b := range po {
			be := lv.blockEffects(b)
742

743
			newliveout.Clear()
744 745 746 747
			switch b.Kind {
			case ssa.BlockRet:
				for _, pos := range lv.cache.retuevar {
					newliveout.Set(pos)
748
				}
749 750 751 752 753 754 755
			case ssa.BlockRetJmp:
				for _, pos := range lv.cache.tailuevar {
					newliveout.Set(pos)
				}
			case ssa.BlockExit:
				// nothing to do
			default:
756 757 758 759
				// A variable is live on output from this block
				// if it is live on input to some successor.
				//
				// out[b] = \bigcup_{s \in succ[b]} in[s]
760 761 762
				newliveout.Copy(lv.blockEffects(b.Succs[0].Block()).livein)
				for _, succ := range b.Succs[1:] {
					newliveout.Or(newliveout, lv.blockEffects(succ.Block()).livein)
763
				}
764 765
			}

766
			if !be.liveout.Eq(newliveout) {
767
				change = true
768
				be.liveout.Copy(newliveout)
769 770 771 772 773 774 775
			}

			// A variable is live on input to this block
			// if it is live on output from this block and
			// not set by the code in this block.
			//
			// in[b] = uevar[b] \cup (out[b] \setminus varkill[b])
776 777
			newlivein.AndNot(be.liveout, be.varkill)
			be.livein.Or(newlivein, be.uevar)
778 779 780 781 782 783
		}
	}
}

// Visits all instructions in a basic block and computes a bit vector of live
// variables at each safe point locations.
784
func (lv *Liveness) epilogue() {
785 786 787 788
	nvars := int32(len(lv.vars))
	liveout := bvalloc(nvars)
	any := bvalloc(nvars)
	all := bvalloc(nvars)
789
	livedefer := bvalloc(nvars) // always-live variables
790 791 792 793 794 795 796 797

	// If there is a defer (that could recover), then all output
	// parameters are live all the time.  In addition, any locals
	// that are pointers to heap-allocated output parameters are
	// also always live (post-deferreturn code needs these
	// pointers to copy values back to the stack).
	// TODO: if the output parameter is heap-allocated, then we
	// don't need to keep the stack copy live?
798
	if lv.fn.Func.HasDefer() {
799
		for i, n := range lv.vars {
800
			if n.Class() == PPARAMOUT {
801
				if n.IsOutputParamHeapAddr() {
802
					// Just to be paranoid.  Heap addresses are PAUTOs.
803 804
					Fatalf("variable %v both output param and heap output param", n)
				}
805 806 807 808 809 810
				if n.Name.Param.Heapaddr != nil {
					// If this variable moved to the heap, then
					// its stack copy is not live.
					continue
				}
				// Note: zeroing is handled by zeroResults in walk.go.
811
				livedefer.Set(int32(i))
812
			}
813
			if n.IsOutputParamHeapAddr() {
814
				n.Name.SetNeedzero(true)
815
				livedefer.Set(int32(i))
816 817 818 819
			}
		}
	}

820 821 822 823 824 825 826 827 828 829 830 831
	{
		// Reserve an entry for function entry.
		live := bvalloc(nvars)
		for _, pos := range lv.cache.textavarinit {
			live.Set(pos)
		}
		lv.livevars = append(lv.livevars, live)
	}

	for _, b := range lv.f.Blocks {
		be := lv.blockEffects(b)

832
		// Compute avarinitany and avarinitall for entry to block.
833
		// This duplicates information known during Liveness.solve
834
		// but avoids storing two more vectors for each block.
835
		lv.avarinitanyall(b, any, all)
836 837 838 839

		// Walk forward through the basic block instructions and
		// allocate liveness maps for those instructions that need them.
		// Seed the maps with information about the addrtaken variables.
840 841 842
		for _, v := range b.Values {
			pos, e := lv.valueEffects(v)
			if e&varkill != 0 {
843 844 845
				any.Unset(pos)
				all.Unset(pos)
			}
846
			if e&avarinit != 0 {
847 848 849
				any.Set(pos)
				all.Set(pos)
			}
850

851
			if !lv.issafepoint(v) {
852 853
				continue
			}
854

855
			// Annotate ambiguously live variables so that they can
856
			// be zeroed at function entry and at VARKILL points.
857
			// liveout is dead here and used as a temporary.
858 859 860 861 862 863 864 865 866 867 868
			liveout.AndNot(any, all)
			if !liveout.IsEmpty() {
				for pos := int32(0); pos < liveout.n; pos++ {
					if !liveout.Get(pos) {
						continue
					}
					all.Set(pos) // silence future warnings in this block
					n := lv.vars[pos]
					if !n.Name.Needzero() {
						n.Name.SetNeedzero(true)
						if debuglive >= 1 {
869
							Warnl(v.Pos, "%v: %L is ambiguously live", lv.fn.Func.Nname, n)
870 871
						}
					}
872 873 874
				}
			}

875 876 877 878
			// Live stuff first.
			live := bvalloc(nvars)
			live.Copy(any)
			lv.livevars = append(lv.livevars, live)
879 880
		}

881
		be.lastbitmapindex = len(lv.livevars) - 1
882 883
	}

884 885
	for _, b := range lv.f.Blocks {
		be := lv.blockEffects(b)
886

887
		// walk backward, construct maps at each safe point
888 889
		index := int32(be.lastbitmapindex)
		if index < 0 {
890 891
			// the first block we encounter should have the ATEXT so
			// at no point should pos ever be less than zero.
892
			Fatalf("livenessepilogue")
893 894
		}

895
		liveout.Copy(be.liveout)
896 897
		for i := len(b.Values) - 1; i >= 0; i-- {
			v := b.Values[i]
898

899
			if lv.issafepoint(v) {
900 901
				// Found an interesting instruction, record the
				// corresponding liveness information.
902

903 904 905 906
				live := lv.livevars[index]
				live.Or(live, liveout)
				live.Or(live, livedefer) // only for non-entry safe points
				index--
907
			}
908

909 910 911 912 913 914 915 916
			// Update liveness information.
			pos, e := lv.valueEffects(v)
			if e&varkill != 0 {
				liveout.Unset(pos)
			}
			if e&uevar != 0 {
				liveout.Set(pos)
			}
917 918
		}

919
		if b == lv.f.Entry {
920 921
			if index != 0 {
				Fatalf("bad index for entry point: %v", index)
922 923
			}

924
			// Record live variables.
925
			live := lv.livevars[index]
926
			live.Or(live, liveout)
927 928 929
		}
	}

930 931 932 933
	// Useful sanity check: on entry to the function,
	// the only things that can possibly be live are the
	// input parameters.
	for j, n := range lv.vars {
934
		if n.Class() != PPARAM && lv.livevars[0].Get(int32(j)) {
935
			Fatalf("internal error: %v %L recorded as live on entry", lv.fn.Func.Nname, n)
936 937 938 939
		}
	}
}

940 941 942 943 944 945 946 947 948
func (lv *Liveness) clobber() {
	// The clobberdead experiment inserts code to clobber all the dead variables (locals and args)
	// before and after every safepoint. This experiment is useful for debugging the generation
	// of live pointer bitmaps.
	if objabi.Clobberdead_enabled == 0 {
		return
	}
	var varSize int64
	for _, n := range lv.vars {
949
		varSize += n.Type.Size()
950
	}
951
	if len(lv.stackMaps) > 1000 || varSize > 10000 {
952 953 954 955 956 957 958 959 960
		// Be careful to avoid doing too much work.
		// Bail if >1000 safepoints or >10000 bytes of variables.
		// Otherwise, giant functions make this experiment generate too much code.
		return
	}
	if h := os.Getenv("GOCLOBBERDEADHASH"); h != "" {
		// Clobber only functions where the hash of the function name matches a pattern.
		// Useful for binary searching for a miscompiled function.
		hstr := ""
961
		for _, b := range sha1.Sum([]byte(lv.fn.funcname())) {
962 963 964 965 966
			hstr += fmt.Sprintf("%08b", b)
		}
		if !strings.HasSuffix(hstr, h) {
			return
		}
967
		fmt.Printf("\t\t\tCLOBBERDEAD %s\n", lv.fn.funcname())
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
	}
	if lv.f.Name == "forkAndExecInChild" {
		// forkAndExecInChild calls vfork (on linux/amd64, anyway).
		// The code we add here clobbers parts of the stack in the child.
		// When the parent resumes, it is using the same stack frame. But the
		// child has clobbered stack variables that the parent needs. Boom!
		// In particular, the sys argument gets clobbered.
		// Note to self: GOCLOBBERDEADHASH=011100101110
		return
	}

	var oldSched []*ssa.Value
	for _, b := range lv.f.Blocks {
		// Copy block's values to a temporary.
		oldSched = append(oldSched[:0], b.Values...)
		b.Values = b.Values[:0]

		// Clobber all dead variables at entry.
		if b == lv.f.Entry {
			for len(oldSched) > 0 && len(oldSched[0].Args) == 0 {
				// Skip argless ops. We need to skip at least
				// the lowered ClosurePtr op, because it
				// really wants to be first. This will also
				// skip ops like InitMem and SP, which are ok.
				b.Values = append(b.Values, oldSched[0])
				oldSched = oldSched[1:]
			}
995
			clobber(lv, b, lv.stackMaps[0])
996 997 998 999
		}

		// Copy values into schedule, adding clobbering around safepoints.
		for _, v := range oldSched {
1000
			if !lv.issafepoint(v) {
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
				b.Values = append(b.Values, v)
				continue
			}
			before := true
			if v.Op.IsCall() && v.Aux != nil && v.Aux.(*obj.LSym) == typedmemmove {
				// Can't put clobber code before the call to typedmemmove.
				// The variable to-be-copied is marked as dead
				// at the callsite. That is ok, though, as typedmemmove
				// is marked as nosplit, and the first thing it does
				// is to call memmove (also nosplit), after which
				// the source value is dead.
				// See issue 16026.
				before = false
			}
			if before {
1016
				clobber(lv, b, lv.stackMaps[lv.livenessMap.Get(v).stackMapIndex])
1017 1018
			}
			b.Values = append(b.Values, v)
1019
			clobber(lv, b, lv.stackMaps[lv.livenessMap.Get(v).stackMapIndex])
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
		}
	}
}

// clobber generates code to clobber all dead variables (those not marked in live).
// Clobbering instructions are added to the end of b.Values.
func clobber(lv *Liveness, b *ssa.Block, live bvec) {
	for i, n := range lv.vars {
		if !live.Get(int32(i)) {
			clobberVar(b, n)
		}
	}
}

// clobberVar generates code to trash the pointers in v.
// Clobbering instructions are added to the end of b.Values.
func clobberVar(b *ssa.Block, v *Node) {
	clobberWalk(b, v, 0, v.Type)
}

// b = block to which we append instructions
// v = variable
// offset = offset of (sub-portion of) variable to clobber (in bytes)
// t = type of sub-portion of v.
func clobberWalk(b *ssa.Block, v *Node, offset int64, t *types.Type) {
	if !types.Haspointers(t) {
		return
	}
	switch t.Etype {
	case TPTR32,
		TPTR64,
		TUNSAFEPTR,
		TFUNC,
		TCHAN,
		TMAP:
		clobberPtr(b, v, offset)

	case TSTRING:
		// struct { byte *str; int len; }
		clobberPtr(b, v, offset)

	case TINTER:
		// struct { Itab *tab; void *data; }
		// or, when isnilinter(t)==true:
		// struct { Type *type; void *data; }
1065
		// Note: the first word isn't a pointer. See comment in plive.go:onebitwalktype1.
1066 1067 1068 1069 1070 1071 1072 1073
		clobberPtr(b, v, offset+int64(Widthptr))

	case TSLICE:
		// struct { byte *array; int len; int cap; }
		clobberPtr(b, v, offset)

	case TARRAY:
		for i := int64(0); i < t.NumElem(); i++ {
1074
			clobberWalk(b, v, offset+i*t.Elem().Size(), t.Elem())
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
		}

	case TSTRUCT:
		for _, t1 := range t.Fields().Slice() {
			clobberWalk(b, v, offset+t1.Offset, t1.Type)
		}

	default:
		Fatalf("clobberWalk: unexpected type, %v", t)
	}
}

// clobberPtr generates a clobber of the pointer at offset offset in v.
// The clobber instruction is added at the end of b.
func clobberPtr(b *ssa.Block, v *Node, offset int64) {
1090
	b.NewValue0IA(src.NoXPos, ssa.OpClobber, types.TypeVoid, offset, v)
1091 1092
}

1093 1094
func (lv *Liveness) avarinitanyall(b *ssa.Block, any, all bvec) {
	if len(b.Preds) == 0 {
1095 1096 1097 1098 1099 1100 1101 1102 1103
		any.Clear()
		all.Clear()
		for _, pos := range lv.cache.textavarinit {
			any.Set(pos)
			all.Set(pos)
		}
		return
	}

1104 1105 1106 1107 1108 1109 1110 1111
	be := lv.blockEffects(b.Preds[0].Block())
	any.Copy(be.avarinitany)
	all.Copy(be.avarinitall)

	for _, pred := range b.Preds[1:] {
		be := lv.blockEffects(pred.Block())
		any.Or(any, be.avarinitany)
		all.And(all, be.avarinitall)
1112
	}
1113 1114 1115 1116 1117 1118 1119 1120
}

// FNV-1 hash function constants.
const (
	H0 = 2166136261
	Hp = 16777619
)

1121
func hashbitmap(h uint32, bv bvec) uint32 {
1122 1123
	n := int((bv.n + 31) / 32)
	for i := 0; i < n; i++ {
1124
		w := bv.b[i]
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
		h = (h * Hp) ^ (w & 0xff)
		h = (h * Hp) ^ ((w >> 8) & 0xff)
		h = (h * Hp) ^ ((w >> 16) & 0xff)
		h = (h * Hp) ^ ((w >> 24) & 0xff)
	}

	return h
}

// Compact liveness information by coalescing identical per-call-site bitmaps.
// The merging only happens for a single function, not across the entire binary.
//
// There are actually two lists of bitmaps, one list for the local variables and one
// list for the function arguments. Both lists are indexed by the same PCDATA
// index, so the corresponding pairs must be considered together when
// merging duplicates. The argument bitmaps change much less often during
// function execution than the local variable bitmaps, so it is possible that
// we could introduce a separate PCDATA index for arguments vs locals and
// then compact the set of argument bitmaps separately from the set of
// local variable bitmaps. As of 2014-04-02, doing this to the godoc binary
// is actually a net loss: we save about 50k of argument bitmaps but the new
// PCDATA tables cost about 100k. So for now we keep using a single index for
// both bitmap lists.
1148
func (lv *Liveness) compact() {
1149 1150 1151
	// Linear probing hash table of bitmaps seen so far.
	// The hash table has 4n entries to keep the linear
	// scan short. An entry of -1 indicates an empty slot.
1152
	n := len(lv.livevars)
1153

1154 1155
	tablesize := 4 * n
	table := make([]int, tablesize)
1156 1157 1158 1159 1160
	for i := range table {
		table[i] = -1
	}

	// remap[i] = the new index of the old bit vector #i.
1161
	remap := make([]int, n)
1162 1163 1164 1165 1166 1167
	for i := range remap {
		remap[i] = -1
	}

	// Consider bit vectors in turn.
	// If new, assign next number using uniq,
1168
	// record in remap, record in lv.livevars
1169
	// under the new index, and add entry to hash table.
1170 1171 1172 1173
	// If already seen, record earlier index in remap.
Outer:
	for i, live := range lv.livevars {
		h := hashbitmap(H0, live) % uint32(tablesize)
1174 1175

		for {
1176
			j := table[h]
1177 1178 1179
			if j < 0 {
				break
			}
1180
			jlive := lv.stackMaps[j]
1181
			if live.Eq(jlive) {
1182
				remap[i] = j
1183
				continue Outer
1184 1185 1186 1187 1188 1189 1190 1191
			}

			h++
			if h == uint32(tablesize) {
				h = 0
			}
		}

1192 1193 1194
		table[h] = len(lv.stackMaps)
		remap[i] = len(lv.stackMaps)
		lv.stackMaps = append(lv.stackMaps, live)
1195 1196
	}

1197 1198 1199
	// Clear lv.livevars to allow GC of duplicate maps and to
	// prevent accidental use.
	lv.livevars = nil
1200

1201 1202
	// Record compacted stack map indexes for each value.
	// These will later become PCDATA instructions.
1203
	lv.showlive(nil, lv.stackMaps[0])
1204
	pos := 1
1205
	lv.livenessMap = LivenessMap{make(map[*ssa.Value]LivenessIndex)}
1206 1207
	for _, b := range lv.f.Blocks {
		for _, v := range b.Values {
1208
			if lv.issafepoint(v) {
1209
				lv.showlive(v, lv.stackMaps[remap[pos]])
1210
				lv.livenessMap.m[v] = LivenessIndex{remap[pos]}
1211
				pos++
1212 1213 1214 1215 1216
			}
		}
	}
}

1217
func (lv *Liveness) showlive(v *ssa.Value, live bvec) {
1218
	if debuglive == 0 || lv.fn.funcname() == "init" || strings.HasPrefix(lv.fn.funcname(), ".") {
1219 1220
		return
	}
1221 1222 1223 1224 1225
	if !(v == nil || v.Op.IsCall()) {
		// Historically we only printed this information at
		// calls. Keep doing so.
		return
	}
1226 1227 1228 1229
	if live.IsEmpty() {
		return
	}

1230
	pos := lv.fn.Func.Nname.Pos
1231 1232 1233 1234 1235 1236
	if v != nil {
		pos = v.Pos
	}

	s := "live at "
	if v == nil {
1237
		s += fmt.Sprintf("entry to %s:", lv.fn.funcname())
1238 1239
	} else if sym, ok := v.Aux.(*obj.LSym); ok {
		fn := sym.Name
1240
		if pos := strings.Index(fn, "."); pos >= 0 {
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
			fn = fn[pos+1:]
		}
		s += fmt.Sprintf("call to %s:", fn)
	} else {
		s += "indirect call:"
	}

	for j, n := range lv.vars {
		if live.Get(int32(j)) {
			s += fmt.Sprintf(" %v", n)
		}
	}

	Warnl(pos, s)
}

func (lv *Liveness) printbvec(printed bool, name string, live bvec) bool {
1258
	started := false
1259 1260
	for i, n := range lv.vars {
		if !live.Get(int32(i)) {
1261 1262
			continue
		}
1263 1264
		if !started {
			if !printed {
1265 1266 1267 1268
				fmt.Printf("\t")
			} else {
				fmt.Printf(" ")
			}
1269 1270
			started = true
			printed = true
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
			fmt.Printf("%s=", name)
		} else {
			fmt.Printf(",")
		}

		fmt.Printf("%s", n.Sym.Name)
	}
	return printed
}

1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
// printeffect is like printbvec, but for a single variable.
func (lv *Liveness) printeffect(printed bool, name string, pos int32, x bool) bool {
	if !x {
		return printed
	}
	if !printed {
		fmt.Printf("\t")
	} else {
		fmt.Printf(" ")
	}
	fmt.Printf("%s=%s", name, lv.vars[pos].Sym.Name)
	return true
}

1295 1296 1297
// Prints the computed liveness information and inputs, for debugging.
// This format synthesizes the information used during the multiple passes
// into a single presentation.
1298
func (lv *Liveness) printDebug() {
1299
	fmt.Printf("liveness: %s\n", lv.fn.funcname())
1300

1301
	pcdata := 0
1302
	for i, b := range lv.f.Blocks {
1303 1304 1305 1306 1307
		if i > 0 {
			fmt.Printf("\n")
		}

		// bb#0 pred=1,2 succ=3,4
1308 1309
		fmt.Printf("bb#%d pred=", b.ID)
		for j, pred := range b.Preds {
1310 1311 1312
			if j > 0 {
				fmt.Printf(",")
			}
1313
			fmt.Printf("%d", pred.Block().ID)
1314 1315
		}
		fmt.Printf(" succ=")
1316
		for j, succ := range b.Succs {
1317 1318 1319
			if j > 0 {
				fmt.Printf(",")
			}
1320
			fmt.Printf("%d", succ.Block().ID)
1321 1322 1323
		}
		fmt.Printf("\n")

1324
		be := lv.blockEffects(b)
1325

1326 1327 1328 1329
		// initial settings
		printed := false
		printed = lv.printbvec(printed, "uevar", be.uevar)
		printed = lv.printbvec(printed, "livein", be.livein)
1330
		if printed {
1331 1332 1333 1334
			fmt.Printf("\n")
		}

		// program listing, with individual effects listed
1335 1336

		if b == lv.f.Entry {
1337
			live := lv.stackMaps[pcdata]
1338
			fmt.Printf("(%s) function entry\n", linestr(lv.fn.Func.Nname.Pos))
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
			fmt.Printf("\tlive=")
			printed = false
			for j, n := range lv.vars {
				if !live.Get(int32(j)) {
					continue
				}
				if printed {
					fmt.Printf(",")
				}
				fmt.Printf("%v", n)
				printed = true
			}
			fmt.Printf("\n")
		}

		for _, v := range b.Values {
			fmt.Printf("(%s) %v\n", linestr(v.Pos), v.LongString())

1357 1358
			if pos := lv.livenessMap.Get(v); pos.Valid() {
				pcdata = pos.stackMapIndex
1359
			}
1360 1361

			pos, effect := lv.valueEffects(v)
1362
			printed = false
1363 1364 1365
			printed = lv.printeffect(printed, "uevar", pos, effect&uevar != 0)
			printed = lv.printeffect(printed, "varkill", pos, effect&varkill != 0)
			printed = lv.printeffect(printed, "avarinit", pos, effect&avarinit != 0)
1366
			if printed {
1367 1368
				fmt.Printf("\n")
			}
1369

1370
			if !lv.issafepoint(v) {
1371
				continue
1372 1373
			}

1374
			live := lv.stackMaps[pcdata]
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
			fmt.Printf("\tlive=")
			printed = false
			for j, n := range lv.vars {
				if !live.Get(int32(j)) {
					continue
				}
				if printed {
					fmt.Printf(",")
				}
				fmt.Printf("%v", n)
				printed = true
1386
			}
1387
			fmt.Printf("\n")
1388 1389 1390 1391
		}

		// bb bitsets
		fmt.Printf("end\n")
1392 1393 1394 1395 1396 1397
		printed = false
		printed = lv.printbvec(printed, "varkill", be.varkill)
		printed = lv.printbvec(printed, "liveout", be.liveout)
		printed = lv.printbvec(printed, "avarinit", be.avarinit)
		printed = lv.printbvec(printed, "avarinitany", be.avarinitany)
		printed = lv.printbvec(printed, "avarinitall", be.avarinitall)
1398
		if printed {
1399 1400 1401 1402 1403 1404 1405
			fmt.Printf("\n")
		}
	}

	fmt.Printf("\n")
}

1406 1407 1408 1409
// Dumps a slice of bitmaps to a symbol as a sequence of uint32 values. The
// first word dumped is the total number of bitmaps. The second word is the
// length of the bitmaps. All bitmaps are assumed to be of equal length. The
// remaining bytes are the raw bitmaps.
1410
func (lv *Liveness) emit(argssym, livesym *obj.LSym) {
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
	// Size args bitmaps to be just large enough to hold the largest pointer.
	// First, find the largest Xoffset node we care about.
	// (Nodes without pointers aren't in lv.vars; see livenessShouldTrack.)
	var maxArgNode *Node
	for _, n := range lv.vars {
		switch n.Class() {
		case PPARAM, PPARAMOUT:
			if maxArgNode == nil || n.Xoffset > maxArgNode.Xoffset {
				maxArgNode = n
			}
		}
	}
	// Next, find the offset of the largest pointer in the largest node.
	var maxArgs int64
	if maxArgNode != nil {
		maxArgs = maxArgNode.Xoffset + typeptrdata(maxArgNode.Type)
	}

	// Size locals bitmaps to be stkptrsize sized.
	// We cannot shrink them to only hold the largest pointer,
	// because their size is used to calculate the beginning
	// of the local variables frame.
	// Further discussion in https://golang.org/cl/104175.
	// TODO: consider trimming leading zeros.
	// This would require shifting all bitmaps.
	maxLocals := lv.stkptrsize

	args := bvalloc(int32(maxArgs / int64(Widthptr)))
1439 1440
	aoff := duint32(argssym, 0, uint32(len(lv.stackMaps))) // number of bitmaps
	aoff = duint32(argssym, aoff, uint32(args.n))          // number of bits in each bitmap
1441

1442
	locals := bvalloc(int32(maxLocals / int64(Widthptr)))
1443 1444
	loff := duint32(livesym, 0, uint32(len(lv.stackMaps))) // number of bitmaps
	loff = duint32(livesym, loff, uint32(locals.n))        // number of bits in each bitmap
1445

1446
	for _, live := range lv.stackMaps {
1447 1448 1449
		args.Clear()
		locals.Clear()

1450
		lv.pointerMap(live, lv.vars, args, locals)
1451

1452 1453
		aoff = dbvec(argssym, aoff, args)
		loff = dbvec(livesym, loff, locals)
1454
	}
1455

1456 1457 1458 1459
	// Give these LSyms content-addressable names,
	// so that they can be de-duplicated.
	// This provides significant binary size savings.
	// It is safe to rename these LSyms because
1460
	// they are tracked separately from ctxt.hash.
1461 1462
	argssym.Name = fmt.Sprintf("gclocals·%x", md5.Sum(argssym.P))
	livesym.Name = fmt.Sprintf("gclocals·%x", md5.Sum(livesym.P))
1463 1464
}

1465 1466
// Entry pointer for liveness analysis. Solves for the liveness of
// pointer variables in the function and emits a runtime data
1467
// structure read by the garbage collector.
1468
// Returns a map from GC safe points to their corresponding stack map index.
1469
func liveness(e *ssafn, f *ssa.Func) LivenessMap {
1470
	// Construct the global liveness state.
1471 1472
	vars, idx := getvariables(e.curfn)
	lv := newliveness(e.curfn, f, vars, idx, e.stkptrsize)
1473 1474

	// Run the dataflow framework.
1475 1476 1477 1478
	lv.prologue()
	lv.solve()
	lv.epilogue()
	lv.compact()
1479
	lv.clobber()
1480
	if debuglive >= 2 {
1481
		lv.printDebug()
1482 1483 1484
	}

	// Emit the live pointer map data structures
1485
	if ls := e.curfn.Func.lsym; ls != nil {
1486
		lv.emit(&ls.Func.GCArgs, &ls.Func.GCLocals)
1487
	}
1488
	return lv.livenessMap
1489
}