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