github.com/bir3/gocompiler@v0.3.205/src/cmd/internal/obj/link.go (about)

     1  // Derived from Inferno utils/6l/l.h and related files.
     2  // https://bitbucket.org/inferno-os/inferno-os/src/master/utils/6l/l.h
     3  //
     4  //	Copyright © 1994-1999 Lucent Technologies Inc.  All rights reserved.
     5  //	Portions Copyright © 1995-1997 C H Forsyth (forsyth@terzarima.net)
     6  //	Portions Copyright © 1997-1999 Vita Nuova Limited
     7  //	Portions Copyright © 2000-2007 Vita Nuova Holdings Limited (www.vitanuova.com)
     8  //	Portions Copyright © 2004,2006 Bruce Ellis
     9  //	Portions Copyright © 2005-2007 C H Forsyth (forsyth@terzarima.net)
    10  //	Revisions Copyright © 2000-2007 Lucent Technologies Inc. and others
    11  //	Portions Copyright © 2009 The Go Authors. All rights reserved.
    12  //
    13  // Permission is hereby granted, free of charge, to any person obtaining a copy
    14  // of this software and associated documentation files (the "Software"), to deal
    15  // in the Software without restriction, including without limitation the rights
    16  // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    17  // copies of the Software, and to permit persons to whom the Software is
    18  // furnished to do so, subject to the following conditions:
    19  //
    20  // The above copyright notice and this permission notice shall be included in
    21  // all copies or substantial portions of the Software.
    22  //
    23  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    24  // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    25  // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
    26  // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    27  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    28  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    29  // THE SOFTWARE.
    30  
    31  package obj
    32  
    33  import (
    34  	"bufio"
    35  	"github.com/bir3/gocompiler/src/cmd/internal/dwarf"
    36  	"github.com/bir3/gocompiler/src/cmd/internal/goobj"
    37  	"github.com/bir3/gocompiler/src/cmd/internal/objabi"
    38  	"github.com/bir3/gocompiler/src/cmd/internal/src"
    39  	"github.com/bir3/gocompiler/src/cmd/internal/sys"
    40  	"fmt"
    41  	"sync"
    42  	"sync/atomic"
    43  )
    44  
    45  // An Addr is an argument to an instruction.
    46  // The general forms and their encodings are:
    47  //
    48  //	sym±offset(symkind)(reg)(index*scale)
    49  //		Memory reference at address &sym(symkind) + offset + reg + index*scale.
    50  //		Any of sym(symkind), ±offset, (reg), (index*scale), and *scale can be omitted.
    51  //		If (reg) and *scale are both omitted, the resulting expression (index) is parsed as (reg).
    52  //		To force a parsing as index*scale, write (index*1).
    53  //		Encoding:
    54  //			type = TYPE_MEM
    55  //			name = symkind (NAME_AUTO, ...) or 0 (NAME_NONE)
    56  //			sym = sym
    57  //			offset = ±offset
    58  //			reg = reg (REG_*)
    59  //			index = index (REG_*)
    60  //			scale = scale (1, 2, 4, 8)
    61  //
    62  //	$<mem>
    63  //		Effective address of memory reference <mem>, defined above.
    64  //		Encoding: same as memory reference, but type = TYPE_ADDR.
    65  //
    66  //	$<±integer value>
    67  //		This is a special case of $<mem>, in which only ±offset is present.
    68  //		It has a separate type for easy recognition.
    69  //		Encoding:
    70  //			type = TYPE_CONST
    71  //			offset = ±integer value
    72  //
    73  //	*<mem>
    74  //		Indirect reference through memory reference <mem>, defined above.
    75  //		Only used on x86 for CALL/JMP *sym(SB), which calls/jumps to a function
    76  //		pointer stored in the data word sym(SB), not a function named sym(SB).
    77  //		Encoding: same as above, but type = TYPE_INDIR.
    78  //
    79  //	$*$<mem>
    80  //		No longer used.
    81  //		On machines with actual SB registers, $*$<mem> forced the
    82  //		instruction encoding to use a full 32-bit constant, never a
    83  //		reference relative to SB.
    84  //
    85  //	$<floating point literal>
    86  //		Floating point constant value.
    87  //		Encoding:
    88  //			type = TYPE_FCONST
    89  //			val = floating point value
    90  //
    91  //	$<string literal, up to 8 chars>
    92  //		String literal value (raw bytes used for DATA instruction).
    93  //		Encoding:
    94  //			type = TYPE_SCONST
    95  //			val = string
    96  //
    97  //	<symbolic constant name>
    98  //		Special symbolic constants for ARM64, such as conditional flags, tlbi_op and so on.
    99  //		Encoding:
   100  //			type = TYPE_SPECIAL
   101  //			offset = The constant value corresponding to this symbol
   102  //
   103  //	<register name>
   104  //		Any register: integer, floating point, control, segment, and so on.
   105  //		If looking for specific register kind, must check type and reg value range.
   106  //		Encoding:
   107  //			type = TYPE_REG
   108  //			reg = reg (REG_*)
   109  //
   110  //	x(PC)
   111  //		Encoding:
   112  //			type = TYPE_BRANCH
   113  //			val = Prog* reference OR ELSE offset = target pc (branch takes priority)
   114  //
   115  //	$±x-±y
   116  //		Final argument to TEXT, specifying local frame size x and argument size y.
   117  //		In this form, x and y are integer literals only, not arbitrary expressions.
   118  //		This avoids parsing ambiguities due to the use of - as a separator.
   119  //		The ± are optional.
   120  //		If the final argument to TEXT omits the -±y, the encoding should still
   121  //		use TYPE_TEXTSIZE (not TYPE_CONST), with u.argsize = ArgsSizeUnknown.
   122  //		Encoding:
   123  //			type = TYPE_TEXTSIZE
   124  //			offset = x
   125  //			val = int32(y)
   126  //
   127  //	reg<<shift, reg>>shift, reg->shift, reg@>shift
   128  //		Shifted register value, for ARM and ARM64.
   129  //		In this form, reg must be a register and shift can be a register or an integer constant.
   130  //		Encoding:
   131  //			type = TYPE_SHIFT
   132  //		On ARM:
   133  //			offset = (reg&15) | shifttype<<5 | count
   134  //			shifttype = 0, 1, 2, 3 for <<, >>, ->, @>
   135  //			count = (reg&15)<<8 | 1<<4 for a register shift count, (n&31)<<7 for an integer constant.
   136  //		On ARM64:
   137  //			offset = (reg&31)<<16 | shifttype<<22 | (count&63)<<10
   138  //			shifttype = 0, 1, 2 for <<, >>, ->
   139  //
   140  //	(reg, reg)
   141  //		A destination register pair. When used as the last argument of an instruction,
   142  //		this form makes clear that both registers are destinations.
   143  //		Encoding:
   144  //			type = TYPE_REGREG
   145  //			reg = first register
   146  //			offset = second register
   147  //
   148  //	[reg, reg, reg-reg]
   149  //		Register list for ARM, ARM64, 386/AMD64.
   150  //		Encoding:
   151  //			type = TYPE_REGLIST
   152  //		On ARM:
   153  //			offset = bit mask of registers in list; R0 is low bit.
   154  //		On ARM64:
   155  //			offset = register count (Q:size) | arrangement (opcode) | first register
   156  //		On 386/AMD64:
   157  //			reg = range low register
   158  //			offset = 2 packed registers + kind tag (see x86.EncodeRegisterRange)
   159  //
   160  //	reg, reg
   161  //		Register pair for ARM.
   162  //		TYPE_REGREG2
   163  //
   164  //	(reg+reg)
   165  //		Register pair for PPC64.
   166  //		Encoding:
   167  //			type = TYPE_MEM
   168  //			reg = first register
   169  //			index = second register
   170  //			scale = 1
   171  //
   172  //	reg.[US]XT[BHWX]
   173  //		Register extension for ARM64
   174  //		Encoding:
   175  //			type = TYPE_REG
   176  //			reg = REG_[US]XT[BHWX] + register + shift amount
   177  //			offset = ((reg&31) << 16) | (exttype << 13) | (amount<<10)
   178  //
   179  //	reg.<T>
   180  //		Register arrangement for ARM64 SIMD register
   181  //		e.g.: V1.S4, V2.S2, V7.D2, V2.H4, V6.B16
   182  //		Encoding:
   183  //			type = TYPE_REG
   184  //			reg = REG_ARNG + register + arrangement
   185  //
   186  //	reg.<T>[index]
   187  //		Register element for ARM64
   188  //		Encoding:
   189  //			type = TYPE_REG
   190  //			reg = REG_ELEM + register + arrangement
   191  //			index = element index
   192  
   193  type Addr struct {
   194  	Reg    int16
   195  	Index  int16
   196  	Scale  int16 // Sometimes holds a register.
   197  	Type   AddrType
   198  	Name   AddrName
   199  	Class  int8
   200  	Offset int64
   201  	Sym    *LSym
   202  
   203  	// argument value:
   204  	//	for TYPE_SCONST, a string
   205  	//	for TYPE_FCONST, a float64
   206  	//	for TYPE_BRANCH, a *Prog (optional)
   207  	//	for TYPE_TEXTSIZE, an int32 (optional)
   208  	Val interface{}
   209  }
   210  
   211  type AddrName int8
   212  
   213  const (
   214  	NAME_NONE AddrName = iota
   215  	NAME_EXTERN
   216  	NAME_STATIC
   217  	NAME_AUTO
   218  	NAME_PARAM
   219  	// A reference to name@GOT(SB) is a reference to the entry in the global offset
   220  	// table for 'name'.
   221  	NAME_GOTREF
   222  	// Indicates that this is a reference to a TOC anchor.
   223  	NAME_TOCREF
   224  )
   225  
   226  //go:generate stringer -type AddrType
   227  
   228  type AddrType uint8
   229  
   230  const (
   231  	TYPE_NONE AddrType = iota
   232  	TYPE_BRANCH
   233  	TYPE_TEXTSIZE
   234  	TYPE_MEM
   235  	TYPE_CONST
   236  	TYPE_FCONST
   237  	TYPE_SCONST
   238  	TYPE_REG
   239  	TYPE_ADDR
   240  	TYPE_SHIFT
   241  	TYPE_REGREG
   242  	TYPE_REGREG2
   243  	TYPE_INDIR
   244  	TYPE_REGLIST
   245  	TYPE_SPECIAL
   246  )
   247  
   248  func (a *Addr) Target() *Prog {
   249  	if a.Type == TYPE_BRANCH && a.Val != nil {
   250  		return a.Val.(*Prog)
   251  	}
   252  	return nil
   253  }
   254  func (a *Addr) SetTarget(t *Prog) {
   255  	if a.Type != TYPE_BRANCH {
   256  		panic("setting branch target when type is not TYPE_BRANCH")
   257  	}
   258  	a.Val = t
   259  }
   260  
   261  func (a *Addr) SetConst(v int64) {
   262  	a.Sym = nil
   263  	a.Type = TYPE_CONST
   264  	a.Offset = v
   265  }
   266  
   267  // Prog describes a single machine instruction.
   268  //
   269  // The general instruction form is:
   270  //
   271  //	(1) As.Scond From [, ...RestArgs], To
   272  //	(2) As.Scond From, Reg [, ...RestArgs], To, RegTo2
   273  //
   274  // where As is an opcode and the others are arguments:
   275  // From, Reg are sources, and To, RegTo2 are destinations.
   276  // RestArgs can hold additional sources and destinations.
   277  // Usually, not all arguments are present.
   278  // For example, MOVL R1, R2 encodes using only As=MOVL, From=R1, To=R2.
   279  // The Scond field holds additional condition bits for systems (like arm)
   280  // that have generalized conditional execution.
   281  // (2) form is present for compatibility with older code,
   282  // to avoid too much changes in a single swing.
   283  // (1) scheme is enough to express any kind of operand combination.
   284  //
   285  // Jump instructions use the To.Val field to point to the target *Prog,
   286  // which must be in the same linked list as the jump instruction.
   287  //
   288  // The Progs for a given function are arranged in a list linked through the Link field.
   289  //
   290  // Each Prog is charged to a specific source line in the debug information,
   291  // specified by Pos.Line().
   292  // Every Prog has a Ctxt field that defines its context.
   293  // For performance reasons, Progs are usually bulk allocated, cached, and reused;
   294  // those bulk allocators should always be used, rather than new(Prog).
   295  //
   296  // The other fields not yet mentioned are for use by the back ends and should
   297  // be left zeroed by creators of Prog lists.
   298  type Prog struct {
   299  	Ctxt     *Link     // linker context
   300  	Link     *Prog     // next Prog in linked list
   301  	From     Addr      // first source operand
   302  	RestArgs []AddrPos // can pack any operands that not fit into {Prog.From, Prog.To}
   303  	To       Addr      // destination operand (second is RegTo2 below)
   304  	Pool     *Prog     // constant pool entry, for arm,arm64 back ends
   305  	Forwd    *Prog     // for x86 back end
   306  	Rel      *Prog     // for x86, arm back ends
   307  	Pc       int64     // for back ends or assembler: virtual or actual program counter, depending on phase
   308  	Pos      src.XPos  // source position of this instruction
   309  	Spadj    int32     // effect of instruction on stack pointer (increment or decrement amount)
   310  	As       As        // assembler opcode
   311  	Reg      int16     // 2nd source operand
   312  	RegTo2   int16     // 2nd destination operand
   313  	Mark     uint16    // bitmask of arch-specific items
   314  	Optab    uint16    // arch-specific opcode index
   315  	Scond    uint8     // bits that describe instruction suffixes (e.g. ARM conditions)
   316  	Back     uint8     // for x86 back end: backwards branch state
   317  	Ft       uint8     // for x86 back end: type index of Prog.From
   318  	Tt       uint8     // for x86 back end: type index of Prog.To
   319  	Isize    uint8     // for x86 back end: size of the instruction in bytes
   320  }
   321  
   322  // AddrPos indicates whether the operand is the source or the destination.
   323  type AddrPos struct {
   324  	Addr
   325  	Pos OperandPos
   326  }
   327  
   328  type OperandPos int8
   329  
   330  const (
   331  	Source OperandPos = iota
   332  	Destination
   333  )
   334  
   335  // From3Type returns p.GetFrom3().Type, or TYPE_NONE when
   336  // p.GetFrom3() returns nil.
   337  //
   338  // Deprecated: for the same reasons as Prog.GetFrom3.
   339  func (p *Prog) From3Type() AddrType {
   340  	if p.RestArgs == nil {
   341  		return TYPE_NONE
   342  	}
   343  	return p.RestArgs[0].Type
   344  }
   345  
   346  // GetFrom3 returns second source operand (the first is Prog.From).
   347  // In combination with Prog.From and Prog.To it makes common 3 operand
   348  // case easier to use.
   349  //
   350  // Should be used only when RestArgs is set with SetFrom3.
   351  //
   352  // Deprecated: better use RestArgs directly or define backend-specific getters.
   353  // Introduced to simplify transition to []Addr.
   354  // Usage of this is discouraged due to fragility and lack of guarantees.
   355  func (p *Prog) GetFrom3() *Addr {
   356  	if p.RestArgs == nil {
   357  		return nil
   358  	}
   359  	return &p.RestArgs[0].Addr
   360  }
   361  
   362  // SetFrom3 assigns []Args{{a, 0}} to p.RestArgs.
   363  // In pair with Prog.GetFrom3 it can help in emulation of Prog.From3.
   364  //
   365  // Deprecated: for the same reasons as Prog.GetFrom3.
   366  func (p *Prog) SetFrom3(a Addr) {
   367  	p.RestArgs = []AddrPos{{a, Source}}
   368  }
   369  
   370  // SetFrom3Reg calls p.SetFrom3 with a register Addr containing reg.
   371  //
   372  // Deprecated: for the same reasons as Prog.GetFrom3.
   373  func (p *Prog) SetFrom3Reg(reg int16) {
   374  	p.SetFrom3(Addr{Type: TYPE_REG, Reg: reg})
   375  }
   376  
   377  // SetFrom3Const calls p.SetFrom3 with a const Addr containing x.
   378  //
   379  // Deprecated: for the same reasons as Prog.GetFrom3.
   380  func (p *Prog) SetFrom3Const(off int64) {
   381  	p.SetFrom3(Addr{Type: TYPE_CONST, Offset: off})
   382  }
   383  
   384  // SetTo2 assigns []Args{{a, 1}} to p.RestArgs when the second destination
   385  // operand does not fit into prog.RegTo2.
   386  func (p *Prog) SetTo2(a Addr) {
   387  	p.RestArgs = []AddrPos{{a, Destination}}
   388  }
   389  
   390  // GetTo2 returns the second destination operand.
   391  func (p *Prog) GetTo2() *Addr {
   392  	if p.RestArgs == nil {
   393  		return nil
   394  	}
   395  	return &p.RestArgs[0].Addr
   396  }
   397  
   398  // SetRestArgs assigns more than one source operands to p.RestArgs.
   399  func (p *Prog) SetRestArgs(args []Addr) {
   400  	for i := range args {
   401  		p.RestArgs = append(p.RestArgs, AddrPos{args[i], Source})
   402  	}
   403  }
   404  
   405  // An As denotes an assembler opcode.
   406  // There are some portable opcodes, declared here in package obj,
   407  // that are common to all architectures.
   408  // However, the majority of opcodes are arch-specific
   409  // and are declared in their respective architecture's subpackage.
   410  type As int16
   411  
   412  // These are the portable opcodes.
   413  const (
   414  	AXXX As = iota
   415  	ACALL
   416  	ADUFFCOPY
   417  	ADUFFZERO
   418  	AEND
   419  	AFUNCDATA
   420  	AJMP
   421  	ANOP
   422  	APCALIGN
   423  	APCDATA
   424  	ARET
   425  	AGETCALLERPC
   426  	ATEXT
   427  	AUNDEF
   428  	A_ARCHSPECIFIC
   429  )
   430  
   431  // Each architecture is allotted a distinct subspace of opcode values
   432  // for declaring its arch-specific opcodes.
   433  // Within this subspace, the first arch-specific opcode should be
   434  // at offset A_ARCHSPECIFIC.
   435  //
   436  // Subspaces are aligned to a power of two so opcodes can be masked
   437  // with AMask and used as compact array indices.
   438  const (
   439  	ABase386 = (1 + iota) << 11
   440  	ABaseARM
   441  	ABaseAMD64
   442  	ABasePPC64
   443  	ABaseARM64
   444  	ABaseMIPS
   445  	ABaseLoong64
   446  	ABaseRISCV
   447  	ABaseS390X
   448  	ABaseWasm
   449  
   450  	AllowedOpCodes = 1 << 11            // The number of opcodes available for any given architecture.
   451  	AMask          = AllowedOpCodes - 1 // AND with this to use the opcode as an array index.
   452  )
   453  
   454  // An LSym is the sort of symbol that is written to an object file.
   455  // It represents Go symbols in a flat pkg+"."+name namespace.
   456  type LSym struct {
   457  	Name string
   458  	Type objabi.SymKind
   459  	Attribute
   460  
   461  	Size   int64
   462  	Gotype *LSym
   463  	P      []byte
   464  	R      []Reloc
   465  
   466  	Extra *interface{} // *FuncInfo or *FileInfo, if present
   467  
   468  	Pkg    string
   469  	PkgIdx int32
   470  	SymIdx int32
   471  }
   472  
   473  // A FuncInfo contains extra fields for STEXT symbols.
   474  type FuncInfo struct {
   475  	Args      int32
   476  	Locals    int32
   477  	Align     int32
   478  	FuncID    objabi.FuncID
   479  	FuncFlag  objabi.FuncFlag
   480  	StartLine int32
   481  	Text      *Prog
   482  	Autot     map[*LSym]struct{}
   483  	Pcln      Pcln
   484  	InlMarks  []InlMark
   485  	spills    []RegSpill
   486  
   487  	dwarfInfoSym       *LSym
   488  	dwarfLocSym        *LSym
   489  	dwarfRangesSym     *LSym
   490  	dwarfAbsFnSym      *LSym
   491  	dwarfDebugLinesSym *LSym
   492  
   493  	GCArgs             *LSym
   494  	GCLocals           *LSym
   495  	StackObjects       *LSym
   496  	OpenCodedDeferInfo *LSym
   497  	ArgInfo            *LSym // argument info for traceback
   498  	ArgLiveInfo        *LSym // argument liveness info for traceback
   499  	WrapInfo           *LSym // for wrapper, info of wrapped function
   500  	JumpTables         []JumpTable
   501  
   502  	FuncInfoSym *LSym
   503  }
   504  
   505  // JumpTable represents a table used for implementing multi-way
   506  // computed branching, used typically for implementing switches.
   507  // Sym is the table itself, and Targets is a list of target
   508  // instructions to go to for the computed branch index.
   509  type JumpTable struct {
   510  	Sym     *LSym
   511  	Targets []*Prog
   512  }
   513  
   514  // NewFuncInfo allocates and returns a FuncInfo for LSym.
   515  func (s *LSym) NewFuncInfo() *FuncInfo {
   516  	if s.Extra != nil {
   517  		panic(fmt.Sprintf("invalid use of LSym - NewFuncInfo with Extra of type %T", *s.Extra))
   518  	}
   519  	f := new(FuncInfo)
   520  	s.Extra = new(interface{})
   521  	*s.Extra = f
   522  	return f
   523  }
   524  
   525  // Func returns the *FuncInfo associated with s, or else nil.
   526  func (s *LSym) Func() *FuncInfo {
   527  	if s.Extra == nil {
   528  		return nil
   529  	}
   530  	f, _ := (*s.Extra).(*FuncInfo)
   531  	return f
   532  }
   533  
   534  // A FileInfo contains extra fields for SDATA symbols backed by files.
   535  // (If LSym.Extra is a *FileInfo, LSym.P == nil.)
   536  type FileInfo struct {
   537  	Name string // name of file to read into object file
   538  	Size int64  // length of file
   539  }
   540  
   541  // NewFileInfo allocates and returns a FileInfo for LSym.
   542  func (s *LSym) NewFileInfo() *FileInfo {
   543  	if s.Extra != nil {
   544  		panic(fmt.Sprintf("invalid use of LSym - NewFileInfo with Extra of type %T", *s.Extra))
   545  	}
   546  	f := new(FileInfo)
   547  	s.Extra = new(interface{})
   548  	*s.Extra = f
   549  	return f
   550  }
   551  
   552  // File returns the *FileInfo associated with s, or else nil.
   553  func (s *LSym) File() *FileInfo {
   554  	if s.Extra == nil {
   555  		return nil
   556  	}
   557  	f, _ := (*s.Extra).(*FileInfo)
   558  	return f
   559  }
   560  
   561  type InlMark struct {
   562  	// When unwinding from an instruction in an inlined body, mark
   563  	// where we should unwind to.
   564  	// id records the global inlining id of the inlined body.
   565  	// p records the location of an instruction in the parent (inliner) frame.
   566  	p  *Prog
   567  	id int32
   568  }
   569  
   570  // Mark p as the instruction to set as the pc when
   571  // "unwinding" the inlining global frame id. Usually it should be
   572  // instruction with a file:line at the callsite, and occur
   573  // just before the body of the inlined function.
   574  func (fi *FuncInfo) AddInlMark(p *Prog, id int32) {
   575  	fi.InlMarks = append(fi.InlMarks, InlMark{p: p, id: id})
   576  }
   577  
   578  // AddSpill appends a spill record to the list for FuncInfo fi
   579  func (fi *FuncInfo) AddSpill(s RegSpill) {
   580  	fi.spills = append(fi.spills, s)
   581  }
   582  
   583  // Record the type symbol for an auto variable so that the linker
   584  // an emit DWARF type information for the type.
   585  func (fi *FuncInfo) RecordAutoType(gotype *LSym) {
   586  	if fi.Autot == nil {
   587  		fi.Autot = make(map[*LSym]struct{})
   588  	}
   589  	fi.Autot[gotype] = struct{}{}
   590  }
   591  
   592  //go:generate stringer -type ABI
   593  
   594  // ABI is the calling convention of a text symbol.
   595  type ABI uint8
   596  
   597  const (
   598  	// ABI0 is the stable stack-based ABI. It's important that the
   599  	// value of this is "0": we can't distinguish between
   600  	// references to data and ABI0 text symbols in assembly code,
   601  	// and hence this doesn't distinguish between symbols without
   602  	// an ABI and text symbols with ABI0.
   603  	ABI0 ABI = iota
   604  
   605  	// ABIInternal is the internal ABI that may change between Go
   606  	// versions. All Go functions use the internal ABI and the
   607  	// compiler generates wrappers for calls to and from other
   608  	// ABIs.
   609  	ABIInternal
   610  
   611  	ABICount
   612  )
   613  
   614  // ParseABI converts from a string representation in 'abistr' to the
   615  // corresponding ABI value. Second return value is TRUE if the
   616  // abi string is recognized, FALSE otherwise.
   617  func ParseABI(abistr string) (ABI, bool) {
   618  	switch abistr {
   619  	default:
   620  		return ABI0, false
   621  	case "ABI0":
   622  		return ABI0, true
   623  	case "ABIInternal":
   624  		return ABIInternal, true
   625  	}
   626  }
   627  
   628  // ABISet is a bit set of ABI values.
   629  type ABISet uint8
   630  
   631  const (
   632  	// ABISetCallable is the set of all ABIs any function could
   633  	// potentially be called using.
   634  	ABISetCallable ABISet = (1 << ABI0) | (1 << ABIInternal)
   635  )
   636  
   637  // Ensure ABISet is big enough to hold all ABIs.
   638  var _ ABISet = 1 << (ABICount - 1)
   639  
   640  func ABISetOf(abi ABI) ABISet {
   641  	return 1 << abi
   642  }
   643  
   644  func (a *ABISet) Set(abi ABI, value bool) {
   645  	if value {
   646  		*a |= 1 << abi
   647  	} else {
   648  		*a &^= 1 << abi
   649  	}
   650  }
   651  
   652  func (a *ABISet) Get(abi ABI) bool {
   653  	return (*a>>abi)&1 != 0
   654  }
   655  
   656  func (a ABISet) String() string {
   657  	s := "{"
   658  	for i := ABI(0); a != 0; i++ {
   659  		if a&(1<<i) != 0 {
   660  			if s != "{" {
   661  				s += ","
   662  			}
   663  			s += i.String()
   664  			a &^= 1 << i
   665  		}
   666  	}
   667  	return s + "}"
   668  }
   669  
   670  // Attribute is a set of symbol attributes.
   671  type Attribute uint32
   672  
   673  const (
   674  	AttrDuplicateOK Attribute = 1 << iota
   675  	AttrCFunc
   676  	AttrNoSplit
   677  	AttrLeaf
   678  	AttrWrapper
   679  	AttrNeedCtxt
   680  	AttrNoFrame
   681  	AttrOnList
   682  	AttrStatic
   683  
   684  	// MakeTypelink means that the type should have an entry in the typelink table.
   685  	AttrMakeTypelink
   686  
   687  	// ReflectMethod means the function may call reflect.Type.Method or
   688  	// reflect.Type.MethodByName. Matching is imprecise (as reflect.Type
   689  	// can be used through a custom interface), so ReflectMethod may be
   690  	// set in some cases when the reflect package is not called.
   691  	//
   692  	// Used by the linker to determine what methods can be pruned.
   693  	AttrReflectMethod
   694  
   695  	// Local means make the symbol local even when compiling Go code to reference Go
   696  	// symbols in other shared libraries, as in this mode symbols are global by
   697  	// default. "local" here means in the sense of the dynamic linker, i.e. not
   698  	// visible outside of the module (shared library or executable) that contains its
   699  	// definition. (When not compiling to support Go shared libraries, all symbols are
   700  	// local in this sense unless there is a cgo_export_* directive).
   701  	AttrLocal
   702  
   703  	// For function symbols; indicates that the specified function was the
   704  	// target of an inline during compilation
   705  	AttrWasInlined
   706  
   707  	// Indexed indicates this symbol has been assigned with an index (when using the
   708  	// new object file format).
   709  	AttrIndexed
   710  
   711  	// Only applied on type descriptor symbols, UsedInIface indicates this type is
   712  	// converted to an interface.
   713  	//
   714  	// Used by the linker to determine what methods can be pruned.
   715  	AttrUsedInIface
   716  
   717  	// ContentAddressable indicates this is a content-addressable symbol.
   718  	AttrContentAddressable
   719  
   720  	// ABI wrapper is set for compiler-generated text symbols that
   721  	// convert between ABI0 and ABIInternal calling conventions.
   722  	AttrABIWrapper
   723  
   724  	// IsPcdata indicates this is a pcdata symbol.
   725  	AttrPcdata
   726  
   727  	// attrABIBase is the value at which the ABI is encoded in
   728  	// Attribute. This must be last; all bits after this are
   729  	// assumed to be an ABI value.
   730  	//
   731  	// MUST BE LAST since all bits above this comprise the ABI.
   732  	attrABIBase
   733  )
   734  
   735  func (a *Attribute) load() Attribute { return Attribute(atomic.LoadUint32((*uint32)(a))) }
   736  
   737  func (a *Attribute) DuplicateOK() bool        { return a.load()&AttrDuplicateOK != 0 }
   738  func (a *Attribute) MakeTypelink() bool       { return a.load()&AttrMakeTypelink != 0 }
   739  func (a *Attribute) CFunc() bool              { return a.load()&AttrCFunc != 0 }
   740  func (a *Attribute) NoSplit() bool            { return a.load()&AttrNoSplit != 0 }
   741  func (a *Attribute) Leaf() bool               { return a.load()&AttrLeaf != 0 }
   742  func (a *Attribute) OnList() bool             { return a.load()&AttrOnList != 0 }
   743  func (a *Attribute) ReflectMethod() bool      { return a.load()&AttrReflectMethod != 0 }
   744  func (a *Attribute) Local() bool              { return a.load()&AttrLocal != 0 }
   745  func (a *Attribute) Wrapper() bool            { return a.load()&AttrWrapper != 0 }
   746  func (a *Attribute) NeedCtxt() bool           { return a.load()&AttrNeedCtxt != 0 }
   747  func (a *Attribute) NoFrame() bool            { return a.load()&AttrNoFrame != 0 }
   748  func (a *Attribute) Static() bool             { return a.load()&AttrStatic != 0 }
   749  func (a *Attribute) WasInlined() bool         { return a.load()&AttrWasInlined != 0 }
   750  func (a *Attribute) Indexed() bool            { return a.load()&AttrIndexed != 0 }
   751  func (a *Attribute) UsedInIface() bool        { return a.load()&AttrUsedInIface != 0 }
   752  func (a *Attribute) ContentAddressable() bool { return a.load()&AttrContentAddressable != 0 }
   753  func (a *Attribute) ABIWrapper() bool         { return a.load()&AttrABIWrapper != 0 }
   754  func (a *Attribute) IsPcdata() bool           { return a.load()&AttrPcdata != 0 }
   755  
   756  func (a *Attribute) Set(flag Attribute, value bool) {
   757  	for {
   758  		v0 := a.load()
   759  		v := v0
   760  		if value {
   761  			v |= flag
   762  		} else {
   763  			v &^= flag
   764  		}
   765  		if atomic.CompareAndSwapUint32((*uint32)(a), uint32(v0), uint32(v)) {
   766  			break
   767  		}
   768  	}
   769  }
   770  
   771  func (a *Attribute) ABI() ABI { return ABI(a.load() / attrABIBase) }
   772  func (a *Attribute) SetABI(abi ABI) {
   773  	const mask = 1 // Only one ABI bit for now.
   774  	for {
   775  		v0 := a.load()
   776  		v := (v0 &^ (mask * attrABIBase)) | Attribute(abi)*attrABIBase
   777  		if atomic.CompareAndSwapUint32((*uint32)(a), uint32(v0), uint32(v)) {
   778  			break
   779  		}
   780  	}
   781  }
   782  
   783  var textAttrStrings = [...]struct {
   784  	bit Attribute
   785  	s   string
   786  }{
   787  	{bit: AttrDuplicateOK, s: "DUPOK"},
   788  	{bit: AttrMakeTypelink, s: ""},
   789  	{bit: AttrCFunc, s: "CFUNC"},
   790  	{bit: AttrNoSplit, s: "NOSPLIT"},
   791  	{bit: AttrLeaf, s: "LEAF"},
   792  	{bit: AttrOnList, s: ""},
   793  	{bit: AttrReflectMethod, s: "REFLECTMETHOD"},
   794  	{bit: AttrLocal, s: "LOCAL"},
   795  	{bit: AttrWrapper, s: "WRAPPER"},
   796  	{bit: AttrNeedCtxt, s: "NEEDCTXT"},
   797  	{bit: AttrNoFrame, s: "NOFRAME"},
   798  	{bit: AttrStatic, s: "STATIC"},
   799  	{bit: AttrWasInlined, s: ""},
   800  	{bit: AttrIndexed, s: ""},
   801  	{bit: AttrContentAddressable, s: ""},
   802  	{bit: AttrABIWrapper, s: "ABIWRAPPER"},
   803  }
   804  
   805  // String formats a for printing in as part of a TEXT prog.
   806  func (a Attribute) String() string {
   807  	var s string
   808  	for _, x := range textAttrStrings {
   809  		if a&x.bit != 0 {
   810  			if x.s != "" {
   811  				s += x.s + "|"
   812  			}
   813  			a &^= x.bit
   814  		}
   815  	}
   816  	switch a.ABI() {
   817  	case ABI0:
   818  	case ABIInternal:
   819  		s += "ABIInternal|"
   820  		a.SetABI(0) // Clear ABI so we don't print below.
   821  	}
   822  	if a != 0 {
   823  		s += fmt.Sprintf("UnknownAttribute(%d)|", a)
   824  	}
   825  	// Chop off trailing |, if present.
   826  	if len(s) > 0 {
   827  		s = s[:len(s)-1]
   828  	}
   829  	return s
   830  }
   831  
   832  // TextAttrString formats the symbol attributes for printing in as part of a TEXT prog.
   833  func (s *LSym) TextAttrString() string {
   834  	attr := s.Attribute.String()
   835  	if s.Func().FuncFlag&objabi.FuncFlag_TOPFRAME != 0 {
   836  		if attr != "" {
   837  			attr += "|"
   838  		}
   839  		attr += "TOPFRAME"
   840  	}
   841  	return attr
   842  }
   843  
   844  func (s *LSym) String() string {
   845  	return s.Name
   846  }
   847  
   848  // The compiler needs *LSym to be assignable to cmd/compile/internal/ssa.Sym.
   849  func (*LSym) CanBeAnSSASym() {}
   850  func (*LSym) CanBeAnSSAAux() {}
   851  
   852  type Pcln struct {
   853  	// Aux symbols for pcln
   854  	Pcsp      *LSym
   855  	Pcfile    *LSym
   856  	Pcline    *LSym
   857  	Pcinline  *LSym
   858  	Pcdata    []*LSym
   859  	Funcdata  []*LSym
   860  	UsedFiles map[goobj.CUFileIndex]struct{} // file indices used while generating pcfile
   861  	InlTree   InlTree                        // per-function inlining tree extracted from the global tree
   862  }
   863  
   864  type Reloc struct {
   865  	Off  int32
   866  	Siz  uint8
   867  	Type objabi.RelocType
   868  	Add  int64
   869  	Sym  *LSym
   870  }
   871  
   872  type Auto struct {
   873  	Asym    *LSym
   874  	Aoffset int32
   875  	Name    AddrName
   876  	Gotype  *LSym
   877  }
   878  
   879  // RegSpill provides spill/fill information for a register-resident argument
   880  // to a function.  These need spilling/filling in the safepoint/stackgrowth case.
   881  // At the time of fill/spill, the offset must be adjusted by the architecture-dependent
   882  // adjustment to hardware SP that occurs in a call instruction.  E.g., for AMD64,
   883  // at Offset+8 because the return address was pushed.
   884  type RegSpill struct {
   885  	Addr           Addr
   886  	Reg            int16
   887  	Spill, Unspill As
   888  }
   889  
   890  // Link holds the context for writing object code from a compiler
   891  // to be linker input or for reading that input into the linker.
   892  type Link struct {
   893  	Headtype           objabi.HeadType
   894  	Arch               *LinkArch
   895  	Debugasm           int
   896  	Debugvlog          bool
   897  	Debugpcln          string
   898  	Flag_shared        bool
   899  	Flag_dynlink       bool
   900  	Flag_linkshared    bool
   901  	Flag_optimize      bool
   902  	Flag_locationlists bool
   903  	Flag_noRefName     bool   // do not include referenced symbol names in object file
   904  	Retpoline          bool   // emit use of retpoline stubs for indirect jmp/call
   905  	Flag_maymorestack  string // If not "", call this function before stack checks
   906  	Bso                *bufio.Writer
   907  	Pathname           string
   908  	Pkgpath            string           // the current package's import path
   909  	hashmu             sync.Mutex       // protects hash, funchash
   910  	hash               map[string]*LSym // name -> sym mapping
   911  	funchash           map[string]*LSym // name -> sym mapping for ABIInternal syms
   912  	statichash         map[string]*LSym // name -> sym mapping for static syms
   913  	PosTable           src.PosTable
   914  	InlTree            InlTree // global inlining tree used by gc/inl.go
   915  	DwFixups           *DwarfFixupTable
   916  	Imports            []goobj.ImportedPkg
   917  	DiagFunc           func(string, ...interface{})
   918  	DiagFlush          func()
   919  	DebugInfo          func(fn *LSym, info *LSym, curfn interface{}) ([]dwarf.Scope, dwarf.InlCalls) // if non-nil, curfn is a *gc.Node
   920  	GenAbstractFunc    func(fn *LSym)
   921  	Errors             int
   922  
   923  	InParallel    bool // parallel backend phase in effect
   924  	UseBASEntries bool // use Base Address Selection Entries in location lists and PC ranges
   925  	IsAsm         bool // is the source assembly language, which may contain surprising idioms (e.g., call tables)
   926  
   927  	// state for writing objects
   928  	Text []*LSym
   929  	Data []*LSym
   930  
   931  	// Constant symbols (e.g. $i64.*) are data symbols created late
   932  	// in the concurrent phase. To ensure a deterministic order, we
   933  	// add them to a separate list, sort at the end, and append it
   934  	// to Data.
   935  	constSyms []*LSym
   936  
   937  	// pkgIdx maps package path to index. The index is used for
   938  	// symbol reference in the object file.
   939  	pkgIdx map[string]int32
   940  
   941  	defs         []*LSym // list of defined symbols in the current package
   942  	hashed64defs []*LSym // list of defined short (64-bit or less) hashed (content-addressable) symbols
   943  	hasheddefs   []*LSym // list of defined hashed (content-addressable) symbols
   944  	nonpkgdefs   []*LSym // list of defined non-package symbols
   945  	nonpkgrefs   []*LSym // list of referenced non-package symbols
   946  
   947  	Fingerprint goobj.FingerprintType // fingerprint of symbol indices, to catch index mismatch
   948  }
   949  
   950  func (ctxt *Link) Diag(format string, args ...interface{}) {
   951  	ctxt.Errors++
   952  	ctxt.DiagFunc(format, args...)
   953  }
   954  
   955  func (ctxt *Link) Logf(format string, args ...interface{}) {
   956  	fmt.Fprintf(ctxt.Bso, format, args...)
   957  	ctxt.Bso.Flush()
   958  }
   959  
   960  // SpillRegisterArgs emits the code to spill register args into whatever
   961  // locations the spill records specify.
   962  func (fi *FuncInfo) SpillRegisterArgs(last *Prog, pa ProgAlloc) *Prog {
   963  	// Spill register args.
   964  	for _, ra := range fi.spills {
   965  		spill := Appendp(last, pa)
   966  		spill.As = ra.Spill
   967  		spill.From.Type = TYPE_REG
   968  		spill.From.Reg = ra.Reg
   969  		spill.To = ra.Addr
   970  		last = spill
   971  	}
   972  	return last
   973  }
   974  
   975  // UnspillRegisterArgs emits the code to restore register args from whatever
   976  // locations the spill records specify.
   977  func (fi *FuncInfo) UnspillRegisterArgs(last *Prog, pa ProgAlloc) *Prog {
   978  	// Unspill any spilled register args
   979  	for _, ra := range fi.spills {
   980  		unspill := Appendp(last, pa)
   981  		unspill.As = ra.Unspill
   982  		unspill.From = ra.Addr
   983  		unspill.To.Type = TYPE_REG
   984  		unspill.To.Reg = ra.Reg
   985  		last = unspill
   986  	}
   987  	return last
   988  }
   989  
   990  // LinkArch is the definition of a single architecture.
   991  type LinkArch struct {
   992  	*sys.Arch
   993  	Init           func(*Link)
   994  	ErrorCheck     func(*Link, *LSym)
   995  	Preprocess     func(*Link, *LSym, ProgAlloc)
   996  	Assemble       func(*Link, *LSym, ProgAlloc)
   997  	Progedit       func(*Link, *Prog, ProgAlloc)
   998  	UnaryDst       map[As]bool // Instruction takes one operand, a destination.
   999  	DWARFRegisters map[int16]int16
  1000  }