...
Run Format

Source file src/cmd/compile/internal/gc/pgen.go

Documentation: cmd/compile/internal/gc

     1  // Copyright 2011 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  package gc
     6  
     7  import (
     8  	"cmd/compile/internal/ssa"
     9  	"cmd/compile/internal/types"
    10  	"cmd/internal/dwarf"
    11  	"cmd/internal/obj"
    12  	"cmd/internal/objabi"
    13  	"cmd/internal/src"
    14  	"cmd/internal/sys"
    15  	"fmt"
    16  	"math/rand"
    17  	"sort"
    18  	"strings"
    19  	"sync"
    20  	"time"
    21  )
    22  
    23  // "Portable" code generation.
    24  
    25  var (
    26  	nBackendWorkers int     // number of concurrent backend workers, set by a compiler flag
    27  	compilequeue    []*Node // functions waiting to be compiled
    28  )
    29  
    30  func emitptrargsmap(fn *Node) {
    31  	if fn.funcname() == "_" {
    32  		return
    33  	}
    34  	sym := lookup(fmt.Sprintf("%s.args_stackmap", fn.funcname()))
    35  	lsym := sym.Linksym()
    36  
    37  	nptr := int(fn.Type.ArgWidth() / int64(Widthptr))
    38  	bv := bvalloc(int32(nptr) * 2)
    39  	nbitmap := 1
    40  	if fn.Type.NumResults() > 0 {
    41  		nbitmap = 2
    42  	}
    43  	off := duint32(lsym, 0, uint32(nbitmap))
    44  	off = duint32(lsym, off, uint32(bv.n))
    45  
    46  	if fn.IsMethod() {
    47  		onebitwalktype1(fn.Type.Recvs(), 0, bv)
    48  	}
    49  	if fn.Type.NumParams() > 0 {
    50  		onebitwalktype1(fn.Type.Params(), 0, bv)
    51  	}
    52  	off = dbvec(lsym, off, bv)
    53  
    54  	if fn.Type.NumResults() > 0 {
    55  		onebitwalktype1(fn.Type.Results(), 0, bv)
    56  		off = dbvec(lsym, off, bv)
    57  	}
    58  
    59  	ggloblsym(lsym, int32(off), obj.RODATA|obj.LOCAL)
    60  }
    61  
    62  // cmpstackvarlt reports whether the stack variable a sorts before b.
    63  //
    64  // Sort the list of stack variables. Autos after anything else,
    65  // within autos, unused after used, within used, things with
    66  // pointers first, zeroed things first, and then decreasing size.
    67  // Because autos are laid out in decreasing addresses
    68  // on the stack, pointers first, zeroed things first and decreasing size
    69  // really means, in memory, things with pointers needing zeroing at
    70  // the top of the stack and increasing in size.
    71  // Non-autos sort on offset.
    72  func cmpstackvarlt(a, b *Node) bool {
    73  	if (a.Class() == PAUTO) != (b.Class() == PAUTO) {
    74  		return b.Class() == PAUTO
    75  	}
    76  
    77  	if a.Class() != PAUTO {
    78  		return a.Xoffset < b.Xoffset
    79  	}
    80  
    81  	if a.Name.Used() != b.Name.Used() {
    82  		return a.Name.Used()
    83  	}
    84  
    85  	ap := types.Haspointers(a.Type)
    86  	bp := types.Haspointers(b.Type)
    87  	if ap != bp {
    88  		return ap
    89  	}
    90  
    91  	ap = a.Name.Needzero()
    92  	bp = b.Name.Needzero()
    93  	if ap != bp {
    94  		return ap
    95  	}
    96  
    97  	if a.Type.Width != b.Type.Width {
    98  		return a.Type.Width > b.Type.Width
    99  	}
   100  
   101  	return a.Sym.Name < b.Sym.Name
   102  }
   103  
   104  // byStackvar implements sort.Interface for []*Node using cmpstackvarlt.
   105  type byStackVar []*Node
   106  
   107  func (s byStackVar) Len() int           { return len(s) }
   108  func (s byStackVar) Less(i, j int) bool { return cmpstackvarlt(s[i], s[j]) }
   109  func (s byStackVar) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
   110  
   111  func (s *ssafn) AllocFrame(f *ssa.Func) {
   112  	s.stksize = 0
   113  	s.stkptrsize = 0
   114  	fn := s.curfn.Func
   115  
   116  	// Mark the PAUTO's unused.
   117  	for _, ln := range fn.Dcl {
   118  		if ln.Class() == PAUTO {
   119  			ln.Name.SetUsed(false)
   120  		}
   121  	}
   122  
   123  	for _, l := range f.RegAlloc {
   124  		if ls, ok := l.(ssa.LocalSlot); ok {
   125  			ls.N.(*Node).Name.SetUsed(true)
   126  		}
   127  	}
   128  
   129  	scratchUsed := false
   130  	for _, b := range f.Blocks {
   131  		for _, v := range b.Values {
   132  			if n, ok := v.Aux.(*Node); ok {
   133  				switch n.Class() {
   134  				case PPARAM, PPARAMOUT:
   135  					// Don't modify nodfp; it is a global.
   136  					if n != nodfp {
   137  						n.Name.SetUsed(true)
   138  					}
   139  				case PAUTO:
   140  					n.Name.SetUsed(true)
   141  				}
   142  			}
   143  			if !scratchUsed {
   144  				scratchUsed = v.Op.UsesScratch()
   145  			}
   146  
   147  		}
   148  	}
   149  
   150  	if f.Config.NeedsFpScratch && scratchUsed {
   151  		s.scratchFpMem = tempAt(src.NoXPos, s.curfn, types.Types[TUINT64])
   152  	}
   153  
   154  	sort.Sort(byStackVar(fn.Dcl))
   155  
   156  	// Reassign stack offsets of the locals that are used.
   157  	for i, n := range fn.Dcl {
   158  		if n.Op != ONAME || n.Class() != PAUTO {
   159  			continue
   160  		}
   161  		if !n.Name.Used() {
   162  			fn.Dcl = fn.Dcl[:i]
   163  			break
   164  		}
   165  
   166  		dowidth(n.Type)
   167  		w := n.Type.Width
   168  		if w >= thearch.MAXWIDTH || w < 0 {
   169  			Fatalf("bad width")
   170  		}
   171  		s.stksize += w
   172  		s.stksize = Rnd(s.stksize, int64(n.Type.Align))
   173  		if types.Haspointers(n.Type) {
   174  			s.stkptrsize = s.stksize
   175  		}
   176  		if thearch.LinkArch.InFamily(sys.MIPS, sys.MIPS64, sys.ARM, sys.ARM64, sys.PPC64, sys.S390X) {
   177  			s.stksize = Rnd(s.stksize, int64(Widthptr))
   178  		}
   179  		n.Xoffset = -s.stksize
   180  	}
   181  
   182  	s.stksize = Rnd(s.stksize, int64(Widthreg))
   183  	s.stkptrsize = Rnd(s.stkptrsize, int64(Widthreg))
   184  }
   185  
   186  func funccompile(fn *Node) {
   187  	if Curfn != nil {
   188  		Fatalf("funccompile %v inside %v", fn.Func.Nname.Sym, Curfn.Func.Nname.Sym)
   189  	}
   190  
   191  	if fn.Type == nil {
   192  		if nerrors == 0 {
   193  			Fatalf("funccompile missing type")
   194  		}
   195  		return
   196  	}
   197  
   198  	// assign parameter offsets
   199  	dowidth(fn.Type)
   200  
   201  	if fn.Nbody.Len() == 0 {
   202  		emitptrargsmap(fn)
   203  		return
   204  	}
   205  
   206  	dclcontext = PAUTO
   207  	Curfn = fn
   208  
   209  	compile(fn)
   210  
   211  	Curfn = nil
   212  	dclcontext = PEXTERN
   213  }
   214  
   215  func compile(fn *Node) {
   216  	saveerrors()
   217  
   218  	order(fn)
   219  	if nerrors != 0 {
   220  		return
   221  	}
   222  
   223  	walk(fn)
   224  	if nerrors != 0 {
   225  		return
   226  	}
   227  	if instrumenting {
   228  		instrument(fn)
   229  	}
   230  
   231  	// From this point, there should be no uses of Curfn. Enforce that.
   232  	Curfn = nil
   233  
   234  	// Set up the function's LSym early to avoid data races with the assemblers.
   235  	fn.Func.initLSym()
   236  
   237  	if compilenow() {
   238  		compileSSA(fn, 0)
   239  	} else {
   240  		compilequeue = append(compilequeue, fn)
   241  	}
   242  }
   243  
   244  // compilenow reports whether to compile immediately.
   245  // If functions are not compiled immediately,
   246  // they are enqueued in compilequeue,
   247  // which is drained by compileFunctions.
   248  func compilenow() bool {
   249  	return nBackendWorkers == 1 && Debug_compilelater == 0
   250  }
   251  
   252  const maxStackSize = 1 << 30
   253  
   254  // compileSSA builds an SSA backend function,
   255  // uses it to generate a plist,
   256  // and flushes that plist to machine code.
   257  // worker indicates which of the backend workers is doing the processing.
   258  func compileSSA(fn *Node, worker int) {
   259  	f := buildssa(fn, worker)
   260  	// Note: check arg size to fix issue 25507.
   261  	if f.Frontend().(*ssafn).stksize >= maxStackSize || fn.Type.ArgWidth() >= maxStackSize {
   262  		largeStackFramesMu.Lock()
   263  		largeStackFrames = append(largeStackFrames, fn.Pos)
   264  		largeStackFramesMu.Unlock()
   265  		return
   266  	}
   267  	pp := newProgs(fn, worker)
   268  	defer pp.Free()
   269  	genssa(f, pp)
   270  	// Check frame size again.
   271  	// The check above included only the space needed for local variables.
   272  	// After genssa, the space needed includes local variables and the callee arg region.
   273  	// We must do this check prior to calling pp.Flush.
   274  	// If there are any oversized stack frames,
   275  	// the assembler may emit inscrutable complaints about invalid instructions.
   276  	if pp.Text.To.Offset >= maxStackSize {
   277  		largeStackFramesMu.Lock()
   278  		largeStackFrames = append(largeStackFrames, fn.Pos)
   279  		largeStackFramesMu.Unlock()
   280  		return
   281  	}
   282  
   283  	pp.Flush() // assemble, fill in boilerplate, etc.
   284  	// fieldtrack must be called after pp.Flush. See issue 20014.
   285  	fieldtrack(pp.Text.From.Sym, fn.Func.FieldTrack)
   286  }
   287  
   288  func init() {
   289  	if raceEnabled {
   290  		rand.Seed(time.Now().UnixNano())
   291  	}
   292  }
   293  
   294  // compileFunctions compiles all functions in compilequeue.
   295  // It fans out nBackendWorkers to do the work
   296  // and waits for them to complete.
   297  func compileFunctions() {
   298  	if len(compilequeue) != 0 {
   299  		sizeCalculationDisabled = true // not safe to calculate sizes concurrently
   300  		if raceEnabled {
   301  			// Randomize compilation order to try to shake out races.
   302  			tmp := make([]*Node, len(compilequeue))
   303  			perm := rand.Perm(len(compilequeue))
   304  			for i, v := range perm {
   305  				tmp[v] = compilequeue[i]
   306  			}
   307  			copy(compilequeue, tmp)
   308  		} else {
   309  			// Compile the longest functions first,
   310  			// since they're most likely to be the slowest.
   311  			// This helps avoid stragglers.
   312  			obj.SortSlice(compilequeue, func(i, j int) bool {
   313  				return compilequeue[i].Nbody.Len() > compilequeue[j].Nbody.Len()
   314  			})
   315  		}
   316  		var wg sync.WaitGroup
   317  		Ctxt.InParallel = true
   318  		c := make(chan *Node, nBackendWorkers)
   319  		for i := 0; i < nBackendWorkers; i++ {
   320  			wg.Add(1)
   321  			go func(worker int) {
   322  				for fn := range c {
   323  					compileSSA(fn, worker)
   324  				}
   325  				wg.Done()
   326  			}(i)
   327  		}
   328  		for _, fn := range compilequeue {
   329  			c <- fn
   330  		}
   331  		close(c)
   332  		compilequeue = nil
   333  		wg.Wait()
   334  		Ctxt.InParallel = false
   335  		sizeCalculationDisabled = false
   336  	}
   337  }
   338  
   339  func debuginfo(fnsym *obj.LSym, curfn interface{}) ([]dwarf.Scope, dwarf.InlCalls) {
   340  	fn := curfn.(*Node)
   341  	if fn.Func.Nname != nil {
   342  		if expect := fn.Func.Nname.Sym.Linksym(); fnsym != expect {
   343  			Fatalf("unexpected fnsym: %v != %v", fnsym, expect)
   344  		}
   345  	}
   346  
   347  	var automDecls []*Node
   348  	// Populate Automs for fn.
   349  	for _, n := range fn.Func.Dcl {
   350  		if n.Op != ONAME { // might be OTYPE or OLITERAL
   351  			continue
   352  		}
   353  		var name obj.AddrName
   354  		switch n.Class() {
   355  		case PAUTO:
   356  			if !n.Name.Used() {
   357  				// Text == nil -> generating abstract function
   358  				if fnsym.Func.Text != nil {
   359  					Fatalf("debuginfo unused node (AllocFrame should truncate fn.Func.Dcl)")
   360  				}
   361  				continue
   362  			}
   363  			name = obj.NAME_AUTO
   364  		case PPARAM, PPARAMOUT:
   365  			name = obj.NAME_PARAM
   366  		default:
   367  			continue
   368  		}
   369  		automDecls = append(automDecls, n)
   370  		gotype := ngotype(n).Linksym()
   371  		fnsym.Func.Autom = append(fnsym.Func.Autom, &obj.Auto{
   372  			Asym:    Ctxt.Lookup(n.Sym.Name),
   373  			Aoffset: int32(n.Xoffset),
   374  			Name:    name,
   375  			Gotype:  gotype,
   376  		})
   377  	}
   378  
   379  	decls, dwarfVars := createDwarfVars(fnsym, fn.Func, automDecls)
   380  
   381  	var varScopes []ScopeID
   382  	for _, decl := range decls {
   383  		pos := decl.Pos
   384  		if decl.Name.Defn != nil && (decl.Name.Captured() || decl.Name.Byval()) {
   385  			// It's not clear which position is correct for captured variables here:
   386  			// * decl.Pos is the wrong position for captured variables, in the inner
   387  			//   function, but it is the right position in the outer function.
   388  			// * decl.Name.Defn is nil for captured variables that were arguments
   389  			//   on the outer function, however the decl.Pos for those seems to be
   390  			//   correct.
   391  			// * decl.Name.Defn is the "wrong" thing for variables declared in the
   392  			//   header of a type switch, it's their position in the header, rather
   393  			//   than the position of the case statement. In principle this is the
   394  			//   right thing, but here we prefer the latter because it makes each
   395  			//   instance of the header variable local to the lexical block of its
   396  			//   case statement.
   397  			// This code is probably wrong for type switch variables that are also
   398  			// captured.
   399  			pos = decl.Name.Defn.Pos
   400  		}
   401  		varScopes = append(varScopes, findScope(fn.Func.Marks, pos))
   402  	}
   403  
   404  	scopes := assembleScopes(fnsym, fn, dwarfVars, varScopes)
   405  	var inlcalls dwarf.InlCalls
   406  	if genDwarfInline > 0 {
   407  		inlcalls = assembleInlines(fnsym, dwarfVars)
   408  	}
   409  	return scopes, inlcalls
   410  }
   411  
   412  // createSimpleVars creates a DWARF entry for every variable declared in the
   413  // function, claiming that they are permanently on the stack.
   414  func createSimpleVars(automDecls []*Node) ([]*Node, []*dwarf.Var, map[*Node]bool) {
   415  	var vars []*dwarf.Var
   416  	var decls []*Node
   417  	selected := make(map[*Node]bool)
   418  	for _, n := range automDecls {
   419  		if n.IsAutoTmp() {
   420  			continue
   421  		}
   422  		var abbrev int
   423  		offs := n.Xoffset
   424  
   425  		switch n.Class() {
   426  		case PAUTO:
   427  			abbrev = dwarf.DW_ABRV_AUTO
   428  			if Ctxt.FixedFrameSize() == 0 {
   429  				offs -= int64(Widthptr)
   430  			}
   431  			if objabi.Framepointer_enabled(objabi.GOOS, objabi.GOARCH) {
   432  				offs -= int64(Widthptr)
   433  			}
   434  
   435  		case PPARAM, PPARAMOUT:
   436  			abbrev = dwarf.DW_ABRV_PARAM
   437  			offs += Ctxt.FixedFrameSize()
   438  		default:
   439  			Fatalf("createSimpleVars unexpected type %v for node %v", n.Class(), n)
   440  		}
   441  
   442  		selected[n] = true
   443  		typename := dwarf.InfoPrefix + typesymname(n.Type)
   444  		decls = append(decls, n)
   445  		inlIndex := 0
   446  		if genDwarfInline > 1 {
   447  			if n.InlFormal() || n.InlLocal() {
   448  				inlIndex = posInlIndex(n.Pos) + 1
   449  				if n.InlFormal() {
   450  					abbrev = dwarf.DW_ABRV_PARAM
   451  				}
   452  			}
   453  		}
   454  		declpos := Ctxt.InnermostPos(n.Pos)
   455  		vars = append(vars, &dwarf.Var{
   456  			Name:          n.Sym.Name,
   457  			IsReturnValue: n.Class() == PPARAMOUT,
   458  			IsInlFormal:   n.InlFormal(),
   459  			Abbrev:        abbrev,
   460  			StackOffset:   int32(offs),
   461  			Type:          Ctxt.Lookup(typename),
   462  			DeclFile:      declpos.RelFilename(),
   463  			DeclLine:      declpos.RelLine(),
   464  			DeclCol:       declpos.Col(),
   465  			InlIndex:      int32(inlIndex),
   466  			ChildIndex:    -1,
   467  		})
   468  	}
   469  	return decls, vars, selected
   470  }
   471  
   472  // createComplexVars creates recomposed DWARF vars with location lists,
   473  // suitable for describing optimized code.
   474  func createComplexVars(fn *Func) ([]*Node, []*dwarf.Var, map[*Node]bool) {
   475  	debugInfo := fn.DebugInfo
   476  
   477  	// Produce a DWARF variable entry for each user variable.
   478  	var decls []*Node
   479  	var vars []*dwarf.Var
   480  	ssaVars := make(map[*Node]bool)
   481  
   482  	for varID, dvar := range debugInfo.Vars {
   483  		n := dvar.(*Node)
   484  		ssaVars[n] = true
   485  		for _, slot := range debugInfo.VarSlots[varID] {
   486  			ssaVars[debugInfo.Slots[slot].N.(*Node)] = true
   487  		}
   488  
   489  		if dvar := createComplexVar(fn, ssa.VarID(varID)); dvar != nil {
   490  			decls = append(decls, n)
   491  			vars = append(vars, dvar)
   492  		}
   493  	}
   494  
   495  	return decls, vars, ssaVars
   496  }
   497  
   498  // createDwarfVars process fn, returning a list of DWARF variables and the
   499  // Nodes they represent.
   500  func createDwarfVars(fnsym *obj.LSym, fn *Func, automDecls []*Node) ([]*Node, []*dwarf.Var) {
   501  	// Collect a raw list of DWARF vars.
   502  	var vars []*dwarf.Var
   503  	var decls []*Node
   504  	var selected map[*Node]bool
   505  	if Ctxt.Flag_locationlists && Ctxt.Flag_optimize && fn.DebugInfo != nil {
   506  		decls, vars, selected = createComplexVars(fn)
   507  	} else {
   508  		decls, vars, selected = createSimpleVars(automDecls)
   509  	}
   510  
   511  	var dcl []*Node
   512  	if fnsym.WasInlined() {
   513  		dcl = preInliningDcls(fnsym)
   514  	} else {
   515  		dcl = automDecls
   516  	}
   517  
   518  	// If optimization is enabled, the list above will typically be
   519  	// missing some of the original pre-optimization variables in the
   520  	// function (they may have been promoted to registers, folded into
   521  	// constants, dead-coded away, etc). Here we add back in entries
   522  	// for selected missing vars. Note that the recipe below creates a
   523  	// conservative location. The idea here is that we want to
   524  	// communicate to the user that "yes, there is a variable named X
   525  	// in this function, but no, I don't have enough information to
   526  	// reliably report its contents."
   527  	for _, n := range dcl {
   528  		if _, found := selected[n]; found {
   529  			continue
   530  		}
   531  		c := n.Sym.Name[0]
   532  		if c == '.' || n.Type.IsUntyped() {
   533  			continue
   534  		}
   535  		typename := dwarf.InfoPrefix + typesymname(n.Type)
   536  		decls = append(decls, n)
   537  		abbrev := dwarf.DW_ABRV_AUTO_LOCLIST
   538  		if n.Class() == PPARAM || n.Class() == PPARAMOUT {
   539  			abbrev = dwarf.DW_ABRV_PARAM_LOCLIST
   540  		}
   541  		inlIndex := 0
   542  		if genDwarfInline > 1 {
   543  			if n.InlFormal() || n.InlLocal() {
   544  				inlIndex = posInlIndex(n.Pos) + 1
   545  				if n.InlFormal() {
   546  					abbrev = dwarf.DW_ABRV_PARAM_LOCLIST
   547  				}
   548  			}
   549  		}
   550  		declpos := Ctxt.InnermostPos(n.Pos)
   551  		vars = append(vars, &dwarf.Var{
   552  			Name:          n.Sym.Name,
   553  			IsReturnValue: n.Class() == PPARAMOUT,
   554  			Abbrev:        abbrev,
   555  			StackOffset:   int32(n.Xoffset),
   556  			Type:          Ctxt.Lookup(typename),
   557  			DeclFile:      declpos.RelFilename(),
   558  			DeclLine:      declpos.RelLine(),
   559  			DeclCol:       declpos.Col(),
   560  			InlIndex:      int32(inlIndex),
   561  			ChildIndex:    -1,
   562  		})
   563  		// Append a "deleted auto" entry to the autom list so as to
   564  		// insure that the type in question is picked up by the linker.
   565  		// See issue 22941.
   566  		gotype := ngotype(n).Linksym()
   567  		fnsym.Func.Autom = append(fnsym.Func.Autom, &obj.Auto{
   568  			Asym:    Ctxt.Lookup(n.Sym.Name),
   569  			Aoffset: int32(-1),
   570  			Name:    obj.NAME_DELETED_AUTO,
   571  			Gotype:  gotype,
   572  		})
   573  
   574  	}
   575  
   576  	return decls, vars
   577  }
   578  
   579  // Given a function that was inlined at some point during the
   580  // compilation, return a sorted list of nodes corresponding to the
   581  // autos/locals in that function prior to inlining. If this is a
   582  // function that is not local to the package being compiled, then the
   583  // names of the variables may have been "versioned" to avoid conflicts
   584  // with local vars; disregard this versioning when sorting.
   585  func preInliningDcls(fnsym *obj.LSym) []*Node {
   586  	fn := Ctxt.DwFixups.GetPrecursorFunc(fnsym).(*Node)
   587  	var rdcl []*Node
   588  	for _, n := range fn.Func.Inl.Dcl {
   589  		c := n.Sym.Name[0]
   590  		// Avoid reporting "_" parameters, since if there are more than
   591  		// one, it can result in a collision later on, as in #23179.
   592  		if unversion(n.Sym.Name) == "_" || c == '.' || n.Type.IsUntyped() {
   593  			continue
   594  		}
   595  		rdcl = append(rdcl, n)
   596  	}
   597  	sort.Sort(byNodeName(rdcl))
   598  	return rdcl
   599  }
   600  
   601  func cmpNodeName(a, b *Node) bool {
   602  	aart := 0
   603  	if strings.HasPrefix(a.Sym.Name, "~") {
   604  		aart = 1
   605  	}
   606  	bart := 0
   607  	if strings.HasPrefix(b.Sym.Name, "~") {
   608  		bart = 1
   609  	}
   610  	if aart != bart {
   611  		return aart < bart
   612  	}
   613  
   614  	aname := unversion(a.Sym.Name)
   615  	bname := unversion(b.Sym.Name)
   616  	return aname < bname
   617  }
   618  
   619  // byNodeName implements sort.Interface for []*Node using cmpNodeName.
   620  type byNodeName []*Node
   621  
   622  func (s byNodeName) Len() int           { return len(s) }
   623  func (s byNodeName) Less(i, j int) bool { return cmpNodeName(s[i], s[j]) }
   624  func (s byNodeName) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
   625  
   626  // stackOffset returns the stack location of a LocalSlot relative to the
   627  // stack pointer, suitable for use in a DWARF location entry. This has nothing
   628  // to do with its offset in the user variable.
   629  func stackOffset(slot ssa.LocalSlot) int32 {
   630  	n := slot.N.(*Node)
   631  	var base int64
   632  	switch n.Class() {
   633  	case PAUTO:
   634  		if Ctxt.FixedFrameSize() == 0 {
   635  			base -= int64(Widthptr)
   636  		}
   637  		if objabi.Framepointer_enabled(objabi.GOOS, objabi.GOARCH) {
   638  			base -= int64(Widthptr)
   639  		}
   640  	case PPARAM, PPARAMOUT:
   641  		base += Ctxt.FixedFrameSize()
   642  	}
   643  	return int32(base + n.Xoffset + slot.Off)
   644  }
   645  
   646  // createComplexVar builds a single DWARF variable entry and location list.
   647  func createComplexVar(fn *Func, varID ssa.VarID) *dwarf.Var {
   648  	debug := fn.DebugInfo
   649  	n := debug.Vars[varID].(*Node)
   650  
   651  	var abbrev int
   652  	switch n.Class() {
   653  	case PAUTO:
   654  		abbrev = dwarf.DW_ABRV_AUTO_LOCLIST
   655  	case PPARAM, PPARAMOUT:
   656  		abbrev = dwarf.DW_ABRV_PARAM_LOCLIST
   657  	default:
   658  		return nil
   659  	}
   660  
   661  	gotype := ngotype(n).Linksym()
   662  	typename := dwarf.InfoPrefix + gotype.Name[len("type."):]
   663  	inlIndex := 0
   664  	if genDwarfInline > 1 {
   665  		if n.InlFormal() || n.InlLocal() {
   666  			inlIndex = posInlIndex(n.Pos) + 1
   667  			if n.InlFormal() {
   668  				abbrev = dwarf.DW_ABRV_PARAM_LOCLIST
   669  			}
   670  		}
   671  	}
   672  	declpos := Ctxt.InnermostPos(n.Pos)
   673  	dvar := &dwarf.Var{
   674  		Name:          n.Sym.Name,
   675  		IsReturnValue: n.Class() == PPARAMOUT,
   676  		IsInlFormal:   n.InlFormal(),
   677  		Abbrev:        abbrev,
   678  		Type:          Ctxt.Lookup(typename),
   679  		// The stack offset is used as a sorting key, so for decomposed
   680  		// variables just give it the first one. It's not used otherwise.
   681  		// This won't work well if the first slot hasn't been assigned a stack
   682  		// location, but it's not obvious how to do better.
   683  		StackOffset: stackOffset(debug.Slots[debug.VarSlots[varID][0]]),
   684  		DeclFile:    declpos.RelFilename(),
   685  		DeclLine:    declpos.RelLine(),
   686  		DeclCol:     declpos.Col(),
   687  		InlIndex:    int32(inlIndex),
   688  		ChildIndex:  -1,
   689  	}
   690  	list := debug.LocationLists[varID]
   691  	if len(list) != 0 {
   692  		dvar.PutLocationList = func(listSym, startPC dwarf.Sym) {
   693  			debug.PutLocationList(list, Ctxt, listSym.(*obj.LSym), startPC.(*obj.LSym))
   694  		}
   695  	}
   696  	return dvar
   697  }
   698  
   699  // fieldtrack adds R_USEFIELD relocations to fnsym to record any
   700  // struct fields that it used.
   701  func fieldtrack(fnsym *obj.LSym, tracked map[*types.Sym]struct{}) {
   702  	if fnsym == nil {
   703  		return
   704  	}
   705  	if objabi.Fieldtrack_enabled == 0 || len(tracked) == 0 {
   706  		return
   707  	}
   708  
   709  	trackSyms := make([]*types.Sym, 0, len(tracked))
   710  	for sym := range tracked {
   711  		trackSyms = append(trackSyms, sym)
   712  	}
   713  	sort.Sort(symByName(trackSyms))
   714  	for _, sym := range trackSyms {
   715  		r := obj.Addrel(fnsym)
   716  		r.Sym = sym.Linksym()
   717  		r.Type = objabi.R_USEFIELD
   718  	}
   719  }
   720  
   721  type symByName []*types.Sym
   722  
   723  func (a symByName) Len() int           { return len(a) }
   724  func (a symByName) Less(i, j int) bool { return a[i].Name < a[j].Name }
   725  func (a symByName) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
   726  

View as plain text