]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/ssagen/ssa.go
cmd/compile/internal/ir: add Func.DeclareParams
[gostls13.git] / src / cmd / compile / internal / ssagen / ssa.go
1 // Copyright 2015 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 ssagen
6
7 import (
8         "bufio"
9         "bytes"
10         "fmt"
11         "go/constant"
12         "html"
13         "internal/buildcfg"
14         "os"
15         "path/filepath"
16         "sort"
17         "strings"
18
19         "cmd/compile/internal/abi"
20         "cmd/compile/internal/base"
21         "cmd/compile/internal/ir"
22         "cmd/compile/internal/liveness"
23         "cmd/compile/internal/objw"
24         "cmd/compile/internal/reflectdata"
25         "cmd/compile/internal/ssa"
26         "cmd/compile/internal/staticdata"
27         "cmd/compile/internal/typecheck"
28         "cmd/compile/internal/types"
29         "cmd/internal/obj"
30         "cmd/internal/src"
31         "cmd/internal/sys"
32
33         rtabi "internal/abi"
34 )
35
36 var ssaConfig *ssa.Config
37 var ssaCaches []ssa.Cache
38
39 var ssaDump string     // early copy of $GOSSAFUNC; the func name to dump output for
40 var ssaDir string      // optional destination for ssa dump file
41 var ssaDumpStdout bool // whether to dump to stdout
42 var ssaDumpCFG string  // generate CFGs for these phases
43 const ssaDumpFile = "ssa.html"
44
45 // ssaDumpInlined holds all inlined functions when ssaDump contains a function name.
46 var ssaDumpInlined []*ir.Func
47
48 func DumpInline(fn *ir.Func) {
49         if ssaDump != "" && ssaDump == ir.FuncName(fn) {
50                 ssaDumpInlined = append(ssaDumpInlined, fn)
51         }
52 }
53
54 func InitEnv() {
55         ssaDump = os.Getenv("GOSSAFUNC")
56         ssaDir = os.Getenv("GOSSADIR")
57         if ssaDump != "" {
58                 if strings.HasSuffix(ssaDump, "+") {
59                         ssaDump = ssaDump[:len(ssaDump)-1]
60                         ssaDumpStdout = true
61                 }
62                 spl := strings.Split(ssaDump, ":")
63                 if len(spl) > 1 {
64                         ssaDump = spl[0]
65                         ssaDumpCFG = spl[1]
66                 }
67         }
68 }
69
70 func InitConfig() {
71         types_ := ssa.NewTypes()
72
73         if Arch.SoftFloat {
74                 softfloatInit()
75         }
76
77         // Generate a few pointer types that are uncommon in the frontend but common in the backend.
78         // Caching is disabled in the backend, so generating these here avoids allocations.
79         _ = types.NewPtr(types.Types[types.TINTER])                             // *interface{}
80         _ = types.NewPtr(types.NewPtr(types.Types[types.TSTRING]))              // **string
81         _ = types.NewPtr(types.NewSlice(types.Types[types.TINTER]))             // *[]interface{}
82         _ = types.NewPtr(types.NewPtr(types.ByteType))                          // **byte
83         _ = types.NewPtr(types.NewSlice(types.ByteType))                        // *[]byte
84         _ = types.NewPtr(types.NewSlice(types.Types[types.TSTRING]))            // *[]string
85         _ = types.NewPtr(types.NewPtr(types.NewPtr(types.Types[types.TUINT8]))) // ***uint8
86         _ = types.NewPtr(types.Types[types.TINT16])                             // *int16
87         _ = types.NewPtr(types.Types[types.TINT64])                             // *int64
88         _ = types.NewPtr(types.ErrorType)                                       // *error
89         _ = types.NewPtr(reflectdata.MapType())                                 // *runtime.hmap
90         _ = types.NewPtr(deferstruct())                                         // *runtime._defer
91         types.NewPtrCacheEnabled = false
92         ssaConfig = ssa.NewConfig(base.Ctxt.Arch.Name, *types_, base.Ctxt, base.Flag.N == 0, Arch.SoftFloat)
93         ssaConfig.Race = base.Flag.Race
94         ssaCaches = make([]ssa.Cache, base.Flag.LowerC)
95
96         // Set up some runtime functions we'll need to call.
97         ir.Syms.AssertE2I = typecheck.LookupRuntimeFunc("assertE2I")
98         ir.Syms.AssertE2I2 = typecheck.LookupRuntimeFunc("assertE2I2")
99         ir.Syms.AssertI2I = typecheck.LookupRuntimeFunc("assertI2I")
100         ir.Syms.AssertI2I2 = typecheck.LookupRuntimeFunc("assertI2I2")
101         ir.Syms.CgoCheckMemmove = typecheck.LookupRuntimeFunc("cgoCheckMemmove")
102         ir.Syms.CgoCheckPtrWrite = typecheck.LookupRuntimeFunc("cgoCheckPtrWrite")
103         ir.Syms.CheckPtrAlignment = typecheck.LookupRuntimeFunc("checkptrAlignment")
104         ir.Syms.Deferproc = typecheck.LookupRuntimeFunc("deferproc")
105         ir.Syms.DeferprocStack = typecheck.LookupRuntimeFunc("deferprocStack")
106         ir.Syms.Deferreturn = typecheck.LookupRuntimeFunc("deferreturn")
107         ir.Syms.Duffcopy = typecheck.LookupRuntimeFunc("duffcopy")
108         ir.Syms.Duffzero = typecheck.LookupRuntimeFunc("duffzero")
109         ir.Syms.GCWriteBarrier[0] = typecheck.LookupRuntimeFunc("gcWriteBarrier1")
110         ir.Syms.GCWriteBarrier[1] = typecheck.LookupRuntimeFunc("gcWriteBarrier2")
111         ir.Syms.GCWriteBarrier[2] = typecheck.LookupRuntimeFunc("gcWriteBarrier3")
112         ir.Syms.GCWriteBarrier[3] = typecheck.LookupRuntimeFunc("gcWriteBarrier4")
113         ir.Syms.GCWriteBarrier[4] = typecheck.LookupRuntimeFunc("gcWriteBarrier5")
114         ir.Syms.GCWriteBarrier[5] = typecheck.LookupRuntimeFunc("gcWriteBarrier6")
115         ir.Syms.GCWriteBarrier[6] = typecheck.LookupRuntimeFunc("gcWriteBarrier7")
116         ir.Syms.GCWriteBarrier[7] = typecheck.LookupRuntimeFunc("gcWriteBarrier8")
117         ir.Syms.Goschedguarded = typecheck.LookupRuntimeFunc("goschedguarded")
118         ir.Syms.Growslice = typecheck.LookupRuntimeFunc("growslice")
119         ir.Syms.Memmove = typecheck.LookupRuntimeFunc("memmove")
120         ir.Syms.Msanread = typecheck.LookupRuntimeFunc("msanread")
121         ir.Syms.Msanwrite = typecheck.LookupRuntimeFunc("msanwrite")
122         ir.Syms.Msanmove = typecheck.LookupRuntimeFunc("msanmove")
123         ir.Syms.Asanread = typecheck.LookupRuntimeFunc("asanread")
124         ir.Syms.Asanwrite = typecheck.LookupRuntimeFunc("asanwrite")
125         ir.Syms.Newobject = typecheck.LookupRuntimeFunc("newobject")
126         ir.Syms.Newproc = typecheck.LookupRuntimeFunc("newproc")
127         ir.Syms.Panicdivide = typecheck.LookupRuntimeFunc("panicdivide")
128         ir.Syms.PanicdottypeE = typecheck.LookupRuntimeFunc("panicdottypeE")
129         ir.Syms.PanicdottypeI = typecheck.LookupRuntimeFunc("panicdottypeI")
130         ir.Syms.Panicnildottype = typecheck.LookupRuntimeFunc("panicnildottype")
131         ir.Syms.Panicoverflow = typecheck.LookupRuntimeFunc("panicoverflow")
132         ir.Syms.Panicshift = typecheck.LookupRuntimeFunc("panicshift")
133         ir.Syms.Raceread = typecheck.LookupRuntimeFunc("raceread")
134         ir.Syms.Racereadrange = typecheck.LookupRuntimeFunc("racereadrange")
135         ir.Syms.Racewrite = typecheck.LookupRuntimeFunc("racewrite")
136         ir.Syms.Racewriterange = typecheck.LookupRuntimeFunc("racewriterange")
137         ir.Syms.WBZero = typecheck.LookupRuntimeFunc("wbZero")
138         ir.Syms.WBMove = typecheck.LookupRuntimeFunc("wbMove")
139         ir.Syms.X86HasPOPCNT = typecheck.LookupRuntimeVar("x86HasPOPCNT")       // bool
140         ir.Syms.X86HasSSE41 = typecheck.LookupRuntimeVar("x86HasSSE41")         // bool
141         ir.Syms.X86HasFMA = typecheck.LookupRuntimeVar("x86HasFMA")             // bool
142         ir.Syms.ARMHasVFPv4 = typecheck.LookupRuntimeVar("armHasVFPv4")         // bool
143         ir.Syms.ARM64HasATOMICS = typecheck.LookupRuntimeVar("arm64HasATOMICS") // bool
144         ir.Syms.Staticuint64s = typecheck.LookupRuntimeVar("staticuint64s")
145         ir.Syms.Typedmemmove = typecheck.LookupRuntimeFunc("typedmemmove")
146         ir.Syms.Udiv = typecheck.LookupRuntimeVar("udiv")                 // asm func with special ABI
147         ir.Syms.WriteBarrier = typecheck.LookupRuntimeVar("writeBarrier") // struct { bool; ... }
148         ir.Syms.Zerobase = typecheck.LookupRuntimeVar("zerobase")
149
150         if Arch.LinkArch.Family == sys.Wasm {
151                 BoundsCheckFunc[ssa.BoundsIndex] = typecheck.LookupRuntimeFunc("goPanicIndex")
152                 BoundsCheckFunc[ssa.BoundsIndexU] = typecheck.LookupRuntimeFunc("goPanicIndexU")
153                 BoundsCheckFunc[ssa.BoundsSliceAlen] = typecheck.LookupRuntimeFunc("goPanicSliceAlen")
154                 BoundsCheckFunc[ssa.BoundsSliceAlenU] = typecheck.LookupRuntimeFunc("goPanicSliceAlenU")
155                 BoundsCheckFunc[ssa.BoundsSliceAcap] = typecheck.LookupRuntimeFunc("goPanicSliceAcap")
156                 BoundsCheckFunc[ssa.BoundsSliceAcapU] = typecheck.LookupRuntimeFunc("goPanicSliceAcapU")
157                 BoundsCheckFunc[ssa.BoundsSliceB] = typecheck.LookupRuntimeFunc("goPanicSliceB")
158                 BoundsCheckFunc[ssa.BoundsSliceBU] = typecheck.LookupRuntimeFunc("goPanicSliceBU")
159                 BoundsCheckFunc[ssa.BoundsSlice3Alen] = typecheck.LookupRuntimeFunc("goPanicSlice3Alen")
160                 BoundsCheckFunc[ssa.BoundsSlice3AlenU] = typecheck.LookupRuntimeFunc("goPanicSlice3AlenU")
161                 BoundsCheckFunc[ssa.BoundsSlice3Acap] = typecheck.LookupRuntimeFunc("goPanicSlice3Acap")
162                 BoundsCheckFunc[ssa.BoundsSlice3AcapU] = typecheck.LookupRuntimeFunc("goPanicSlice3AcapU")
163                 BoundsCheckFunc[ssa.BoundsSlice3B] = typecheck.LookupRuntimeFunc("goPanicSlice3B")
164                 BoundsCheckFunc[ssa.BoundsSlice3BU] = typecheck.LookupRuntimeFunc("goPanicSlice3BU")
165                 BoundsCheckFunc[ssa.BoundsSlice3C] = typecheck.LookupRuntimeFunc("goPanicSlice3C")
166                 BoundsCheckFunc[ssa.BoundsSlice3CU] = typecheck.LookupRuntimeFunc("goPanicSlice3CU")
167                 BoundsCheckFunc[ssa.BoundsConvert] = typecheck.LookupRuntimeFunc("goPanicSliceConvert")
168         } else {
169                 BoundsCheckFunc[ssa.BoundsIndex] = typecheck.LookupRuntimeFunc("panicIndex")
170                 BoundsCheckFunc[ssa.BoundsIndexU] = typecheck.LookupRuntimeFunc("panicIndexU")
171                 BoundsCheckFunc[ssa.BoundsSliceAlen] = typecheck.LookupRuntimeFunc("panicSliceAlen")
172                 BoundsCheckFunc[ssa.BoundsSliceAlenU] = typecheck.LookupRuntimeFunc("panicSliceAlenU")
173                 BoundsCheckFunc[ssa.BoundsSliceAcap] = typecheck.LookupRuntimeFunc("panicSliceAcap")
174                 BoundsCheckFunc[ssa.BoundsSliceAcapU] = typecheck.LookupRuntimeFunc("panicSliceAcapU")
175                 BoundsCheckFunc[ssa.BoundsSliceB] = typecheck.LookupRuntimeFunc("panicSliceB")
176                 BoundsCheckFunc[ssa.BoundsSliceBU] = typecheck.LookupRuntimeFunc("panicSliceBU")
177                 BoundsCheckFunc[ssa.BoundsSlice3Alen] = typecheck.LookupRuntimeFunc("panicSlice3Alen")
178                 BoundsCheckFunc[ssa.BoundsSlice3AlenU] = typecheck.LookupRuntimeFunc("panicSlice3AlenU")
179                 BoundsCheckFunc[ssa.BoundsSlice3Acap] = typecheck.LookupRuntimeFunc("panicSlice3Acap")
180                 BoundsCheckFunc[ssa.BoundsSlice3AcapU] = typecheck.LookupRuntimeFunc("panicSlice3AcapU")
181                 BoundsCheckFunc[ssa.BoundsSlice3B] = typecheck.LookupRuntimeFunc("panicSlice3B")
182                 BoundsCheckFunc[ssa.BoundsSlice3BU] = typecheck.LookupRuntimeFunc("panicSlice3BU")
183                 BoundsCheckFunc[ssa.BoundsSlice3C] = typecheck.LookupRuntimeFunc("panicSlice3C")
184                 BoundsCheckFunc[ssa.BoundsSlice3CU] = typecheck.LookupRuntimeFunc("panicSlice3CU")
185                 BoundsCheckFunc[ssa.BoundsConvert] = typecheck.LookupRuntimeFunc("panicSliceConvert")
186         }
187         if Arch.LinkArch.PtrSize == 4 {
188                 ExtendCheckFunc[ssa.BoundsIndex] = typecheck.LookupRuntimeVar("panicExtendIndex")
189                 ExtendCheckFunc[ssa.BoundsIndexU] = typecheck.LookupRuntimeVar("panicExtendIndexU")
190                 ExtendCheckFunc[ssa.BoundsSliceAlen] = typecheck.LookupRuntimeVar("panicExtendSliceAlen")
191                 ExtendCheckFunc[ssa.BoundsSliceAlenU] = typecheck.LookupRuntimeVar("panicExtendSliceAlenU")
192                 ExtendCheckFunc[ssa.BoundsSliceAcap] = typecheck.LookupRuntimeVar("panicExtendSliceAcap")
193                 ExtendCheckFunc[ssa.BoundsSliceAcapU] = typecheck.LookupRuntimeVar("panicExtendSliceAcapU")
194                 ExtendCheckFunc[ssa.BoundsSliceB] = typecheck.LookupRuntimeVar("panicExtendSliceB")
195                 ExtendCheckFunc[ssa.BoundsSliceBU] = typecheck.LookupRuntimeVar("panicExtendSliceBU")
196                 ExtendCheckFunc[ssa.BoundsSlice3Alen] = typecheck.LookupRuntimeVar("panicExtendSlice3Alen")
197                 ExtendCheckFunc[ssa.BoundsSlice3AlenU] = typecheck.LookupRuntimeVar("panicExtendSlice3AlenU")
198                 ExtendCheckFunc[ssa.BoundsSlice3Acap] = typecheck.LookupRuntimeVar("panicExtendSlice3Acap")
199                 ExtendCheckFunc[ssa.BoundsSlice3AcapU] = typecheck.LookupRuntimeVar("panicExtendSlice3AcapU")
200                 ExtendCheckFunc[ssa.BoundsSlice3B] = typecheck.LookupRuntimeVar("panicExtendSlice3B")
201                 ExtendCheckFunc[ssa.BoundsSlice3BU] = typecheck.LookupRuntimeVar("panicExtendSlice3BU")
202                 ExtendCheckFunc[ssa.BoundsSlice3C] = typecheck.LookupRuntimeVar("panicExtendSlice3C")
203                 ExtendCheckFunc[ssa.BoundsSlice3CU] = typecheck.LookupRuntimeVar("panicExtendSlice3CU")
204         }
205
206         // Wasm (all asm funcs with special ABIs)
207         ir.Syms.WasmDiv = typecheck.LookupRuntimeVar("wasmDiv")
208         ir.Syms.WasmTruncS = typecheck.LookupRuntimeVar("wasmTruncS")
209         ir.Syms.WasmTruncU = typecheck.LookupRuntimeVar("wasmTruncU")
210         ir.Syms.SigPanic = typecheck.LookupRuntimeFunc("sigpanic")
211 }
212
213 // AbiForBodylessFuncStackMap returns the ABI for a bodyless function's stack map.
214 // This is not necessarily the ABI used to call it.
215 // Currently (1.17 dev) such a stack map is always ABI0;
216 // any ABI wrapper that is present is nosplit, hence a precise
217 // stack map is not needed there (the parameters survive only long
218 // enough to call the wrapped assembly function).
219 // This always returns a freshly copied ABI.
220 func AbiForBodylessFuncStackMap(fn *ir.Func) *abi.ABIConfig {
221         return ssaConfig.ABI0.Copy() // No idea what races will result, be safe
222 }
223
224 // abiForFunc implements ABI policy for a function, but does not return a copy of the ABI.
225 // Passing a nil function returns the default ABI based on experiment configuration.
226 func abiForFunc(fn *ir.Func, abi0, abi1 *abi.ABIConfig) *abi.ABIConfig {
227         if buildcfg.Experiment.RegabiArgs {
228                 // Select the ABI based on the function's defining ABI.
229                 if fn == nil {
230                         return abi1
231                 }
232                 switch fn.ABI {
233                 case obj.ABI0:
234                         return abi0
235                 case obj.ABIInternal:
236                         // TODO(austin): Clean up the nomenclature here.
237                         // It's not clear that "abi1" is ABIInternal.
238                         return abi1
239                 }
240                 base.Fatalf("function %v has unknown ABI %v", fn, fn.ABI)
241                 panic("not reachable")
242         }
243
244         a := abi0
245         if fn != nil {
246                 if fn.Pragma&ir.RegisterParams != 0 { // TODO(register args) remove after register abi is working
247                         a = abi1
248                 }
249         }
250         return a
251 }
252
253 // dvarint writes a varint v to the funcdata in symbol x and returns the new offset.
254 func dvarint(x *obj.LSym, off int, v int64) int {
255         if v < 0 || v > 1e9 {
256                 panic(fmt.Sprintf("dvarint: bad offset for funcdata - %v", v))
257         }
258         if v < 1<<7 {
259                 return objw.Uint8(x, off, uint8(v))
260         }
261         off = objw.Uint8(x, off, uint8((v&127)|128))
262         if v < 1<<14 {
263                 return objw.Uint8(x, off, uint8(v>>7))
264         }
265         off = objw.Uint8(x, off, uint8(((v>>7)&127)|128))
266         if v < 1<<21 {
267                 return objw.Uint8(x, off, uint8(v>>14))
268         }
269         off = objw.Uint8(x, off, uint8(((v>>14)&127)|128))
270         if v < 1<<28 {
271                 return objw.Uint8(x, off, uint8(v>>21))
272         }
273         off = objw.Uint8(x, off, uint8(((v>>21)&127)|128))
274         return objw.Uint8(x, off, uint8(v>>28))
275 }
276
277 // emitOpenDeferInfo emits FUNCDATA information about the defers in a function
278 // that is using open-coded defers.  This funcdata is used to determine the active
279 // defers in a function and execute those defers during panic processing.
280 //
281 // The funcdata is all encoded in varints (since values will almost always be less than
282 // 128, but stack offsets could potentially be up to 2Gbyte). All "locations" (offsets)
283 // for stack variables are specified as the number of bytes below varp (pointer to the
284 // top of the local variables) for their starting address. The format is:
285 //
286 //   - Offset of the deferBits variable
287 //   - Offset of the first closure slot (the rest are laid out consecutively).
288 func (s *state) emitOpenDeferInfo() {
289         firstOffset := s.openDefers[0].closureNode.FrameOffset()
290
291         // Verify that cmpstackvarlt laid out the slots in order.
292         for i, r := range s.openDefers {
293                 have := r.closureNode.FrameOffset()
294                 want := firstOffset + int64(i)*int64(types.PtrSize)
295                 if have != want {
296                         base.FatalfAt(s.curfn.Pos(), "unexpected frame offset for open-coded defer slot #%v: have %v, want %v", i, have, want)
297                 }
298         }
299
300         x := base.Ctxt.Lookup(s.curfn.LSym.Name + ".opendefer")
301         x.Set(obj.AttrContentAddressable, true)
302         s.curfn.LSym.Func().OpenCodedDeferInfo = x
303
304         off := 0
305         off = dvarint(x, off, -s.deferBitsTemp.FrameOffset())
306         off = dvarint(x, off, -firstOffset)
307 }
308
309 // buildssa builds an SSA function for fn.
310 // worker indicates which of the backend workers is doing the processing.
311 func buildssa(fn *ir.Func, worker int) *ssa.Func {
312         name := ir.FuncName(fn)
313         printssa := false
314         if ssaDump != "" { // match either a simple name e.g. "(*Reader).Reset", package.name e.g. "compress/gzip.(*Reader).Reset", or subpackage name "gzip.(*Reader).Reset"
315                 pkgDotName := base.Ctxt.Pkgpath + "." + name
316                 printssa = name == ssaDump ||
317                         strings.HasSuffix(pkgDotName, ssaDump) && (pkgDotName == ssaDump || strings.HasSuffix(pkgDotName, "/"+ssaDump))
318         }
319         var astBuf *bytes.Buffer
320         if printssa {
321                 astBuf = &bytes.Buffer{}
322                 ir.FDumpList(astBuf, "buildssa-enter", fn.Enter)
323                 ir.FDumpList(astBuf, "buildssa-body", fn.Body)
324                 ir.FDumpList(astBuf, "buildssa-exit", fn.Exit)
325                 if ssaDumpStdout {
326                         fmt.Println("generating SSA for", name)
327                         fmt.Print(astBuf.String())
328                 }
329         }
330
331         var s state
332         s.pushLine(fn.Pos())
333         defer s.popLine()
334
335         s.hasdefer = fn.HasDefer()
336         if fn.Pragma&ir.CgoUnsafeArgs != 0 {
337                 s.cgoUnsafeArgs = true
338         }
339         s.checkPtrEnabled = ir.ShouldCheckPtr(fn, 1)
340
341         fe := ssafn{
342                 curfn: fn,
343                 log:   printssa && ssaDumpStdout,
344         }
345         s.curfn = fn
346
347         cache := &ssaCaches[worker]
348         cache.Reset()
349
350         s.f = ssaConfig.NewFunc(&fe, cache)
351         s.config = ssaConfig
352         s.f.Type = fn.Type()
353         s.f.Name = name
354         s.f.PrintOrHtmlSSA = printssa
355         if fn.Pragma&ir.Nosplit != 0 {
356                 s.f.NoSplit = true
357         }
358         s.f.ABI0 = ssaConfig.ABI0.Copy() // Make a copy to avoid racy map operations in type-register-width cache.
359         s.f.ABI1 = ssaConfig.ABI1.Copy()
360         s.f.ABIDefault = abiForFunc(nil, s.f.ABI0, s.f.ABI1)
361         s.f.ABISelf = abiForFunc(fn, s.f.ABI0, s.f.ABI1)
362
363         s.panics = map[funcLine]*ssa.Block{}
364         s.softFloat = s.config.SoftFloat
365
366         // Allocate starting block
367         s.f.Entry = s.f.NewBlock(ssa.BlockPlain)
368         s.f.Entry.Pos = fn.Pos()
369
370         if printssa {
371                 ssaDF := ssaDumpFile
372                 if ssaDir != "" {
373                         ssaDF = filepath.Join(ssaDir, base.Ctxt.Pkgpath+"."+name+".html")
374                         ssaD := filepath.Dir(ssaDF)
375                         os.MkdirAll(ssaD, 0755)
376                 }
377                 s.f.HTMLWriter = ssa.NewHTMLWriter(ssaDF, s.f, ssaDumpCFG)
378                 // TODO: generate and print a mapping from nodes to values and blocks
379                 dumpSourcesColumn(s.f.HTMLWriter, fn)
380                 s.f.HTMLWriter.WriteAST("AST", astBuf)
381         }
382
383         // Allocate starting values
384         s.labels = map[string]*ssaLabel{}
385         s.fwdVars = map[ir.Node]*ssa.Value{}
386         s.startmem = s.entryNewValue0(ssa.OpInitMem, types.TypeMem)
387
388         s.hasOpenDefers = base.Flag.N == 0 && s.hasdefer && !s.curfn.OpenCodedDeferDisallowed()
389         switch {
390         case base.Debug.NoOpenDefer != 0:
391                 s.hasOpenDefers = false
392         case s.hasOpenDefers && (base.Ctxt.Flag_shared || base.Ctxt.Flag_dynlink) && base.Ctxt.Arch.Name == "386":
393                 // Don't support open-coded defers for 386 ONLY when using shared
394                 // libraries, because there is extra code (added by rewriteToUseGot())
395                 // preceding the deferreturn/ret code that we don't track correctly.
396                 s.hasOpenDefers = false
397         }
398         if s.hasOpenDefers && len(s.curfn.Exit) > 0 {
399                 // Skip doing open defers if there is any extra exit code (likely
400                 // race detection), since we will not generate that code in the
401                 // case of the extra deferreturn/ret segment.
402                 s.hasOpenDefers = false
403         }
404         if s.hasOpenDefers {
405                 // Similarly, skip if there are any heap-allocated result
406                 // parameters that need to be copied back to their stack slots.
407                 for _, f := range s.curfn.Type().Results() {
408                         if !f.Nname.(*ir.Name).OnStack() {
409                                 s.hasOpenDefers = false
410                                 break
411                         }
412                 }
413         }
414         if s.hasOpenDefers &&
415                 s.curfn.NumReturns*s.curfn.NumDefers > 15 {
416                 // Since we are generating defer calls at every exit for
417                 // open-coded defers, skip doing open-coded defers if there are
418                 // too many returns (especially if there are multiple defers).
419                 // Open-coded defers are most important for improving performance
420                 // for smaller functions (which don't have many returns).
421                 s.hasOpenDefers = false
422         }
423
424         s.sp = s.entryNewValue0(ssa.OpSP, types.Types[types.TUINTPTR]) // TODO: use generic pointer type (unsafe.Pointer?) instead
425         s.sb = s.entryNewValue0(ssa.OpSB, types.Types[types.TUINTPTR])
426
427         s.startBlock(s.f.Entry)
428         s.vars[memVar] = s.startmem
429         if s.hasOpenDefers {
430                 // Create the deferBits variable and stack slot.  deferBits is a
431                 // bitmask showing which of the open-coded defers in this function
432                 // have been activated.
433                 deferBitsTemp := typecheck.TempAt(src.NoXPos, s.curfn, types.Types[types.TUINT8])
434                 deferBitsTemp.SetAddrtaken(true)
435                 s.deferBitsTemp = deferBitsTemp
436                 // For this value, AuxInt is initialized to zero by default
437                 startDeferBits := s.entryNewValue0(ssa.OpConst8, types.Types[types.TUINT8])
438                 s.vars[deferBitsVar] = startDeferBits
439                 s.deferBitsAddr = s.addr(deferBitsTemp)
440                 s.store(types.Types[types.TUINT8], s.deferBitsAddr, startDeferBits)
441                 // Make sure that the deferBits stack slot is kept alive (for use
442                 // by panics) and stores to deferBits are not eliminated, even if
443                 // all checking code on deferBits in the function exit can be
444                 // eliminated, because the defer statements were all
445                 // unconditional.
446                 s.vars[memVar] = s.newValue1Apos(ssa.OpVarLive, types.TypeMem, deferBitsTemp, s.mem(), false)
447         }
448
449         var params *abi.ABIParamResultInfo
450         params = s.f.ABISelf.ABIAnalyze(fn.Type(), true)
451
452         // The backend's stackframe pass prunes away entries from the fn's
453         // Dcl list, including PARAMOUT nodes that correspond to output
454         // params passed in registers. Walk the Dcl list and capture these
455         // nodes to a side list, so that we'll have them available during
456         // DWARF-gen later on. See issue 48573 for more details.
457         var debugInfo ssa.FuncDebug
458         for _, n := range fn.Dcl {
459                 if n.Class == ir.PPARAMOUT && n.IsOutputParamInRegisters() {
460                         debugInfo.RegOutputParams = append(debugInfo.RegOutputParams, n)
461                 }
462         }
463         fn.DebugInfo = &debugInfo
464
465         // Generate addresses of local declarations
466         s.decladdrs = map[*ir.Name]*ssa.Value{}
467         for _, n := range fn.Dcl {
468                 switch n.Class {
469                 case ir.PPARAM:
470                         // Be aware that blank and unnamed input parameters will not appear here, but do appear in the type
471                         s.decladdrs[n] = s.entryNewValue2A(ssa.OpLocalAddr, types.NewPtr(n.Type()), n, s.sp, s.startmem)
472                 case ir.PPARAMOUT:
473                         s.decladdrs[n] = s.entryNewValue2A(ssa.OpLocalAddr, types.NewPtr(n.Type()), n, s.sp, s.startmem)
474                 case ir.PAUTO:
475                         // processed at each use, to prevent Addr coming
476                         // before the decl.
477                 default:
478                         s.Fatalf("local variable with class %v unimplemented", n.Class)
479                 }
480         }
481
482         s.f.OwnAux = ssa.OwnAuxCall(fn.LSym, params)
483
484         // Populate SSAable arguments.
485         for _, n := range fn.Dcl {
486                 if n.Class == ir.PPARAM {
487                         if s.canSSA(n) {
488                                 v := s.newValue0A(ssa.OpArg, n.Type(), n)
489                                 s.vars[n] = v
490                                 s.addNamedValue(n, v) // This helps with debugging information, not needed for compilation itself.
491                         } else { // address was taken AND/OR too large for SSA
492                                 paramAssignment := ssa.ParamAssignmentForArgName(s.f, n)
493                                 if len(paramAssignment.Registers) > 0 {
494                                         if ssa.CanSSA(n.Type()) { // SSA-able type, so address was taken -- receive value in OpArg, DO NOT bind to var, store immediately to memory.
495                                                 v := s.newValue0A(ssa.OpArg, n.Type(), n)
496                                                 s.store(n.Type(), s.decladdrs[n], v)
497                                         } else { // Too big for SSA.
498                                                 // Brute force, and early, do a bunch of stores from registers
499                                                 // TODO fix the nasty storeArgOrLoad recursion in ssa/expand_calls.go so this Just Works with store of a big Arg.
500                                                 s.storeParameterRegsToStack(s.f.ABISelf, paramAssignment, n, s.decladdrs[n], false)
501                                         }
502                                 }
503                         }
504                 }
505         }
506
507         // Populate closure variables.
508         if fn.Needctxt() {
509                 clo := s.entryNewValue0(ssa.OpGetClosurePtr, s.f.Config.Types.BytePtr)
510                 offset := int64(types.PtrSize) // PtrSize to skip past function entry PC field
511                 for _, n := range fn.ClosureVars {
512                         typ := n.Type()
513                         if !n.Byval() {
514                                 typ = types.NewPtr(typ)
515                         }
516
517                         offset = types.RoundUp(offset, typ.Alignment())
518                         ptr := s.newValue1I(ssa.OpOffPtr, types.NewPtr(typ), offset, clo)
519                         offset += typ.Size()
520
521                         // If n is a small variable captured by value, promote
522                         // it to PAUTO so it can be converted to SSA.
523                         //
524                         // Note: While we never capture a variable by value if
525                         // the user took its address, we may have generated
526                         // runtime calls that did (#43701). Since we don't
527                         // convert Addrtaken variables to SSA anyway, no point
528                         // in promoting them either.
529                         if n.Byval() && !n.Addrtaken() && ssa.CanSSA(n.Type()) {
530                                 n.Class = ir.PAUTO
531                                 fn.Dcl = append(fn.Dcl, n)
532                                 s.assign(n, s.load(n.Type(), ptr), false, 0)
533                                 continue
534                         }
535
536                         if !n.Byval() {
537                                 ptr = s.load(typ, ptr)
538                         }
539                         s.setHeapaddr(fn.Pos(), n, ptr)
540                 }
541         }
542
543         // Convert the AST-based IR to the SSA-based IR
544         s.stmtList(fn.Enter)
545         s.zeroResults()
546         s.paramsToHeap()
547         s.stmtList(fn.Body)
548
549         // fallthrough to exit
550         if s.curBlock != nil {
551                 s.pushLine(fn.Endlineno)
552                 s.exit()
553                 s.popLine()
554         }
555
556         for _, b := range s.f.Blocks {
557                 if b.Pos != src.NoXPos {
558                         s.updateUnsetPredPos(b)
559                 }
560         }
561
562         s.f.HTMLWriter.WritePhase("before insert phis", "before insert phis")
563
564         s.insertPhis()
565
566         // Main call to ssa package to compile function
567         ssa.Compile(s.f)
568
569         fe.AllocFrame(s.f)
570
571         if len(s.openDefers) != 0 {
572                 s.emitOpenDeferInfo()
573         }
574
575         // Record incoming parameter spill information for morestack calls emitted in the assembler.
576         // This is done here, using all the parameters (used, partially used, and unused) because
577         // it mimics the behavior of the former ABI (everything stored) and because it's not 100%
578         // clear if naming conventions are respected in autogenerated code.
579         // TODO figure out exactly what's unused, don't spill it. Make liveness fine-grained, also.
580         for _, p := range params.InParams() {
581                 typs, offs := p.RegisterTypesAndOffsets()
582                 for i, t := range typs {
583                         o := offs[i]                // offset within parameter
584                         fo := p.FrameOffset(params) // offset of parameter in frame
585                         reg := ssa.ObjRegForAbiReg(p.Registers[i], s.f.Config)
586                         s.f.RegArgs = append(s.f.RegArgs, ssa.Spill{Reg: reg, Offset: fo + o, Type: t})
587                 }
588         }
589
590         return s.f
591 }
592
593 func (s *state) storeParameterRegsToStack(abi *abi.ABIConfig, paramAssignment *abi.ABIParamAssignment, n *ir.Name, addr *ssa.Value, pointersOnly bool) {
594         typs, offs := paramAssignment.RegisterTypesAndOffsets()
595         for i, t := range typs {
596                 if pointersOnly && !t.IsPtrShaped() {
597                         continue
598                 }
599                 r := paramAssignment.Registers[i]
600                 o := offs[i]
601                 op, reg := ssa.ArgOpAndRegisterFor(r, abi)
602                 aux := &ssa.AuxNameOffset{Name: n, Offset: o}
603                 v := s.newValue0I(op, t, reg)
604                 v.Aux = aux
605                 p := s.newValue1I(ssa.OpOffPtr, types.NewPtr(t), o, addr)
606                 s.store(t, p, v)
607         }
608 }
609
610 // zeroResults zeros the return values at the start of the function.
611 // We need to do this very early in the function.  Defer might stop a
612 // panic and show the return values as they exist at the time of
613 // panic.  For precise stacks, the garbage collector assumes results
614 // are always live, so we need to zero them before any allocations,
615 // even allocations to move params/results to the heap.
616 func (s *state) zeroResults() {
617         for _, f := range s.curfn.Type().Results() {
618                 n := f.Nname.(*ir.Name)
619                 if !n.OnStack() {
620                         // The local which points to the return value is the
621                         // thing that needs zeroing. This is already handled
622                         // by a Needzero annotation in plive.go:(*liveness).epilogue.
623                         continue
624                 }
625                 // Zero the stack location containing f.
626                 if typ := n.Type(); ssa.CanSSA(typ) {
627                         s.assign(n, s.zeroVal(typ), false, 0)
628                 } else {
629                         if typ.HasPointers() {
630                                 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, n, s.mem())
631                         }
632                         s.zero(n.Type(), s.decladdrs[n])
633                 }
634         }
635 }
636
637 // paramsToHeap produces code to allocate memory for heap-escaped parameters
638 // and to copy non-result parameters' values from the stack.
639 func (s *state) paramsToHeap() {
640         do := func(params []*types.Field) {
641                 for _, f := range params {
642                         if f.Nname == nil {
643                                 continue // anonymous or blank parameter
644                         }
645                         n := f.Nname.(*ir.Name)
646                         if ir.IsBlank(n) || n.OnStack() {
647                                 continue
648                         }
649                         s.newHeapaddr(n)
650                         if n.Class == ir.PPARAM {
651                                 s.move(n.Type(), s.expr(n.Heapaddr), s.decladdrs[n])
652                         }
653                 }
654         }
655
656         typ := s.curfn.Type()
657         do(typ.Recvs())
658         do(typ.Params())
659         do(typ.Results())
660 }
661
662 // newHeapaddr allocates heap memory for n and sets its heap address.
663 func (s *state) newHeapaddr(n *ir.Name) {
664         s.setHeapaddr(n.Pos(), n, s.newObject(n.Type(), nil))
665 }
666
667 // setHeapaddr allocates a new PAUTO variable to store ptr (which must be non-nil)
668 // and then sets it as n's heap address.
669 func (s *state) setHeapaddr(pos src.XPos, n *ir.Name, ptr *ssa.Value) {
670         if !ptr.Type.IsPtr() || !types.Identical(n.Type(), ptr.Type.Elem()) {
671                 base.FatalfAt(n.Pos(), "setHeapaddr %L with type %v", n, ptr.Type)
672         }
673
674         // Declare variable to hold address.
675         sym := &types.Sym{Name: "&" + n.Sym().Name, Pkg: types.LocalPkg}
676         addr := s.curfn.NewLocal(pos, sym, types.NewPtr(n.Type()))
677         addr.SetUsed(true)
678         types.CalcSize(addr.Type())
679
680         if n.Class == ir.PPARAMOUT {
681                 addr.SetIsOutputParamHeapAddr(true)
682         }
683
684         n.Heapaddr = addr
685         s.assign(addr, ptr, false, 0)
686 }
687
688 // newObject returns an SSA value denoting new(typ).
689 func (s *state) newObject(typ *types.Type, rtype *ssa.Value) *ssa.Value {
690         if typ.Size() == 0 {
691                 return s.newValue1A(ssa.OpAddr, types.NewPtr(typ), ir.Syms.Zerobase, s.sb)
692         }
693         if rtype == nil {
694                 rtype = s.reflectType(typ)
695         }
696         return s.rtcall(ir.Syms.Newobject, true, []*types.Type{types.NewPtr(typ)}, rtype)[0]
697 }
698
699 func (s *state) checkPtrAlignment(n *ir.ConvExpr, v *ssa.Value, count *ssa.Value) {
700         if !n.Type().IsPtr() {
701                 s.Fatalf("expected pointer type: %v", n.Type())
702         }
703         elem, rtypeExpr := n.Type().Elem(), n.ElemRType
704         if count != nil {
705                 if !elem.IsArray() {
706                         s.Fatalf("expected array type: %v", elem)
707                 }
708                 elem, rtypeExpr = elem.Elem(), n.ElemElemRType
709         }
710         size := elem.Size()
711         // Casting from larger type to smaller one is ok, so for smallest type, do nothing.
712         if elem.Alignment() == 1 && (size == 0 || size == 1 || count == nil) {
713                 return
714         }
715         if count == nil {
716                 count = s.constInt(types.Types[types.TUINTPTR], 1)
717         }
718         if count.Type.Size() != s.config.PtrSize {
719                 s.Fatalf("expected count fit to a uintptr size, have: %d, want: %d", count.Type.Size(), s.config.PtrSize)
720         }
721         var rtype *ssa.Value
722         if rtypeExpr != nil {
723                 rtype = s.expr(rtypeExpr)
724         } else {
725                 rtype = s.reflectType(elem)
726         }
727         s.rtcall(ir.Syms.CheckPtrAlignment, true, nil, v, rtype, count)
728 }
729
730 // reflectType returns an SSA value representing a pointer to typ's
731 // reflection type descriptor.
732 func (s *state) reflectType(typ *types.Type) *ssa.Value {
733         // TODO(mdempsky): Make this Fatalf under Unified IR; frontend needs
734         // to supply RType expressions.
735         lsym := reflectdata.TypeLinksym(typ)
736         return s.entryNewValue1A(ssa.OpAddr, types.NewPtr(types.Types[types.TUINT8]), lsym, s.sb)
737 }
738
739 func dumpSourcesColumn(writer *ssa.HTMLWriter, fn *ir.Func) {
740         // Read sources of target function fn.
741         fname := base.Ctxt.PosTable.Pos(fn.Pos()).Filename()
742         targetFn, err := readFuncLines(fname, fn.Pos().Line(), fn.Endlineno.Line())
743         if err != nil {
744                 writer.Logf("cannot read sources for function %v: %v", fn, err)
745         }
746
747         // Read sources of inlined functions.
748         var inlFns []*ssa.FuncLines
749         for _, fi := range ssaDumpInlined {
750                 elno := fi.Endlineno
751                 fname := base.Ctxt.PosTable.Pos(fi.Pos()).Filename()
752                 fnLines, err := readFuncLines(fname, fi.Pos().Line(), elno.Line())
753                 if err != nil {
754                         writer.Logf("cannot read sources for inlined function %v: %v", fi, err)
755                         continue
756                 }
757                 inlFns = append(inlFns, fnLines)
758         }
759
760         sort.Sort(ssa.ByTopo(inlFns))
761         if targetFn != nil {
762                 inlFns = append([]*ssa.FuncLines{targetFn}, inlFns...)
763         }
764
765         writer.WriteSources("sources", inlFns)
766 }
767
768 func readFuncLines(file string, start, end uint) (*ssa.FuncLines, error) {
769         f, err := os.Open(os.ExpandEnv(file))
770         if err != nil {
771                 return nil, err
772         }
773         defer f.Close()
774         var lines []string
775         ln := uint(1)
776         scanner := bufio.NewScanner(f)
777         for scanner.Scan() && ln <= end {
778                 if ln >= start {
779                         lines = append(lines, scanner.Text())
780                 }
781                 ln++
782         }
783         return &ssa.FuncLines{Filename: file, StartLineno: start, Lines: lines}, nil
784 }
785
786 // updateUnsetPredPos propagates the earliest-value position information for b
787 // towards all of b's predecessors that need a position, and recurs on that
788 // predecessor if its position is updated. B should have a non-empty position.
789 func (s *state) updateUnsetPredPos(b *ssa.Block) {
790         if b.Pos == src.NoXPos {
791                 s.Fatalf("Block %s should have a position", b)
792         }
793         bestPos := src.NoXPos
794         for _, e := range b.Preds {
795                 p := e.Block()
796                 if !p.LackingPos() {
797                         continue
798                 }
799                 if bestPos == src.NoXPos {
800                         bestPos = b.Pos
801                         for _, v := range b.Values {
802                                 if v.LackingPos() {
803                                         continue
804                                 }
805                                 if v.Pos != src.NoXPos {
806                                         // Assume values are still in roughly textual order;
807                                         // TODO: could also seek minimum position?
808                                         bestPos = v.Pos
809                                         break
810                                 }
811                         }
812                 }
813                 p.Pos = bestPos
814                 s.updateUnsetPredPos(p) // We do not expect long chains of these, thus recursion is okay.
815         }
816 }
817
818 // Information about each open-coded defer.
819 type openDeferInfo struct {
820         // The node representing the call of the defer
821         n *ir.CallExpr
822         // If defer call is closure call, the address of the argtmp where the
823         // closure is stored.
824         closure *ssa.Value
825         // The node representing the argtmp where the closure is stored - used for
826         // function, method, or interface call, to store a closure that panic
827         // processing can use for this defer.
828         closureNode *ir.Name
829 }
830
831 type state struct {
832         // configuration (arch) information
833         config *ssa.Config
834
835         // function we're building
836         f *ssa.Func
837
838         // Node for function
839         curfn *ir.Func
840
841         // labels in f
842         labels map[string]*ssaLabel
843
844         // unlabeled break and continue statement tracking
845         breakTo    *ssa.Block // current target for plain break statement
846         continueTo *ssa.Block // current target for plain continue statement
847
848         // current location where we're interpreting the AST
849         curBlock *ssa.Block
850
851         // variable assignments in the current block (map from variable symbol to ssa value)
852         // *Node is the unique identifier (an ONAME Node) for the variable.
853         // TODO: keep a single varnum map, then make all of these maps slices instead?
854         vars map[ir.Node]*ssa.Value
855
856         // fwdVars are variables that are used before they are defined in the current block.
857         // This map exists just to coalesce multiple references into a single FwdRef op.
858         // *Node is the unique identifier (an ONAME Node) for the variable.
859         fwdVars map[ir.Node]*ssa.Value
860
861         // all defined variables at the end of each block. Indexed by block ID.
862         defvars []map[ir.Node]*ssa.Value
863
864         // addresses of PPARAM and PPARAMOUT variables on the stack.
865         decladdrs map[*ir.Name]*ssa.Value
866
867         // starting values. Memory, stack pointer, and globals pointer
868         startmem *ssa.Value
869         sp       *ssa.Value
870         sb       *ssa.Value
871         // value representing address of where deferBits autotmp is stored
872         deferBitsAddr *ssa.Value
873         deferBitsTemp *ir.Name
874
875         // line number stack. The current line number is top of stack
876         line []src.XPos
877         // the last line number processed; it may have been popped
878         lastPos src.XPos
879
880         // list of panic calls by function name and line number.
881         // Used to deduplicate panic calls.
882         panics map[funcLine]*ssa.Block
883
884         cgoUnsafeArgs   bool
885         hasdefer        bool // whether the function contains a defer statement
886         softFloat       bool
887         hasOpenDefers   bool // whether we are doing open-coded defers
888         checkPtrEnabled bool // whether to insert checkptr instrumentation
889
890         // If doing open-coded defers, list of info about the defer calls in
891         // scanning order. Hence, at exit we should run these defers in reverse
892         // order of this list
893         openDefers []*openDeferInfo
894         // For open-coded defers, this is the beginning and end blocks of the last
895         // defer exit code that we have generated so far. We use these to share
896         // code between exits if the shareDeferExits option (disabled by default)
897         // is on.
898         lastDeferExit       *ssa.Block // Entry block of last defer exit code we generated
899         lastDeferFinalBlock *ssa.Block // Final block of last defer exit code we generated
900         lastDeferCount      int        // Number of defers encountered at that point
901
902         prevCall *ssa.Value // the previous call; use this to tie results to the call op.
903 }
904
905 type funcLine struct {
906         f    *obj.LSym
907         base *src.PosBase
908         line uint
909 }
910
911 type ssaLabel struct {
912         target         *ssa.Block // block identified by this label
913         breakTarget    *ssa.Block // block to break to in control flow node identified by this label
914         continueTarget *ssa.Block // block to continue to in control flow node identified by this label
915 }
916
917 // label returns the label associated with sym, creating it if necessary.
918 func (s *state) label(sym *types.Sym) *ssaLabel {
919         lab := s.labels[sym.Name]
920         if lab == nil {
921                 lab = new(ssaLabel)
922                 s.labels[sym.Name] = lab
923         }
924         return lab
925 }
926
927 func (s *state) Logf(msg string, args ...interface{}) { s.f.Logf(msg, args...) }
928 func (s *state) Log() bool                            { return s.f.Log() }
929 func (s *state) Fatalf(msg string, args ...interface{}) {
930         s.f.Frontend().Fatalf(s.peekPos(), msg, args...)
931 }
932 func (s *state) Warnl(pos src.XPos, msg string, args ...interface{}) { s.f.Warnl(pos, msg, args...) }
933 func (s *state) Debug_checknil() bool                                { return s.f.Frontend().Debug_checknil() }
934
935 func ssaMarker(name string) *ir.Name {
936         return ir.NewNameAt(base.Pos, &types.Sym{Name: name}, nil)
937 }
938
939 var (
940         // marker node for the memory variable
941         memVar = ssaMarker("mem")
942
943         // marker nodes for temporary variables
944         ptrVar       = ssaMarker("ptr")
945         lenVar       = ssaMarker("len")
946         capVar       = ssaMarker("cap")
947         typVar       = ssaMarker("typ")
948         okVar        = ssaMarker("ok")
949         deferBitsVar = ssaMarker("deferBits")
950 )
951
952 // startBlock sets the current block we're generating code in to b.
953 func (s *state) startBlock(b *ssa.Block) {
954         if s.curBlock != nil {
955                 s.Fatalf("starting block %v when block %v has not ended", b, s.curBlock)
956         }
957         s.curBlock = b
958         s.vars = map[ir.Node]*ssa.Value{}
959         for n := range s.fwdVars {
960                 delete(s.fwdVars, n)
961         }
962 }
963
964 // endBlock marks the end of generating code for the current block.
965 // Returns the (former) current block. Returns nil if there is no current
966 // block, i.e. if no code flows to the current execution point.
967 func (s *state) endBlock() *ssa.Block {
968         b := s.curBlock
969         if b == nil {
970                 return nil
971         }
972         for len(s.defvars) <= int(b.ID) {
973                 s.defvars = append(s.defvars, nil)
974         }
975         s.defvars[b.ID] = s.vars
976         s.curBlock = nil
977         s.vars = nil
978         if b.LackingPos() {
979                 // Empty plain blocks get the line of their successor (handled after all blocks created),
980                 // except for increment blocks in For statements (handled in ssa conversion of OFOR),
981                 // and for blocks ending in GOTO/BREAK/CONTINUE.
982                 b.Pos = src.NoXPos
983         } else {
984                 b.Pos = s.lastPos
985         }
986         return b
987 }
988
989 // pushLine pushes a line number on the line number stack.
990 func (s *state) pushLine(line src.XPos) {
991         if !line.IsKnown() {
992                 // the frontend may emit node with line number missing,
993                 // use the parent line number in this case.
994                 line = s.peekPos()
995                 if base.Flag.K != 0 {
996                         base.Warn("buildssa: unknown position (line 0)")
997                 }
998         } else {
999                 s.lastPos = line
1000         }
1001
1002         s.line = append(s.line, line)
1003 }
1004
1005 // popLine pops the top of the line number stack.
1006 func (s *state) popLine() {
1007         s.line = s.line[:len(s.line)-1]
1008 }
1009
1010 // peekPos peeks the top of the line number stack.
1011 func (s *state) peekPos() src.XPos {
1012         return s.line[len(s.line)-1]
1013 }
1014
1015 // newValue0 adds a new value with no arguments to the current block.
1016 func (s *state) newValue0(op ssa.Op, t *types.Type) *ssa.Value {
1017         return s.curBlock.NewValue0(s.peekPos(), op, t)
1018 }
1019
1020 // newValue0A adds a new value with no arguments and an aux value to the current block.
1021 func (s *state) newValue0A(op ssa.Op, t *types.Type, aux ssa.Aux) *ssa.Value {
1022         return s.curBlock.NewValue0A(s.peekPos(), op, t, aux)
1023 }
1024
1025 // newValue0I adds a new value with no arguments and an auxint value to the current block.
1026 func (s *state) newValue0I(op ssa.Op, t *types.Type, auxint int64) *ssa.Value {
1027         return s.curBlock.NewValue0I(s.peekPos(), op, t, auxint)
1028 }
1029
1030 // newValue1 adds a new value with one argument to the current block.
1031 func (s *state) newValue1(op ssa.Op, t *types.Type, arg *ssa.Value) *ssa.Value {
1032         return s.curBlock.NewValue1(s.peekPos(), op, t, arg)
1033 }
1034
1035 // newValue1A adds a new value with one argument and an aux value to the current block.
1036 func (s *state) newValue1A(op ssa.Op, t *types.Type, aux ssa.Aux, arg *ssa.Value) *ssa.Value {
1037         return s.curBlock.NewValue1A(s.peekPos(), op, t, aux, arg)
1038 }
1039
1040 // newValue1Apos adds a new value with one argument and an aux value to the current block.
1041 // isStmt determines whether the created values may be a statement or not
1042 // (i.e., false means never, yes means maybe).
1043 func (s *state) newValue1Apos(op ssa.Op, t *types.Type, aux ssa.Aux, arg *ssa.Value, isStmt bool) *ssa.Value {
1044         if isStmt {
1045                 return s.curBlock.NewValue1A(s.peekPos(), op, t, aux, arg)
1046         }
1047         return s.curBlock.NewValue1A(s.peekPos().WithNotStmt(), op, t, aux, arg)
1048 }
1049
1050 // newValue1I adds a new value with one argument and an auxint value to the current block.
1051 func (s *state) newValue1I(op ssa.Op, t *types.Type, aux int64, arg *ssa.Value) *ssa.Value {
1052         return s.curBlock.NewValue1I(s.peekPos(), op, t, aux, arg)
1053 }
1054
1055 // newValue2 adds a new value with two arguments to the current block.
1056 func (s *state) newValue2(op ssa.Op, t *types.Type, arg0, arg1 *ssa.Value) *ssa.Value {
1057         return s.curBlock.NewValue2(s.peekPos(), op, t, arg0, arg1)
1058 }
1059
1060 // newValue2A adds a new value with two arguments and an aux value to the current block.
1061 func (s *state) newValue2A(op ssa.Op, t *types.Type, aux ssa.Aux, arg0, arg1 *ssa.Value) *ssa.Value {
1062         return s.curBlock.NewValue2A(s.peekPos(), op, t, aux, arg0, arg1)
1063 }
1064
1065 // newValue2Apos adds a new value with two arguments and an aux value to the current block.
1066 // isStmt determines whether the created values may be a statement or not
1067 // (i.e., false means never, yes means maybe).
1068 func (s *state) newValue2Apos(op ssa.Op, t *types.Type, aux ssa.Aux, arg0, arg1 *ssa.Value, isStmt bool) *ssa.Value {
1069         if isStmt {
1070                 return s.curBlock.NewValue2A(s.peekPos(), op, t, aux, arg0, arg1)
1071         }
1072         return s.curBlock.NewValue2A(s.peekPos().WithNotStmt(), op, t, aux, arg0, arg1)
1073 }
1074
1075 // newValue2I adds a new value with two arguments and an auxint value to the current block.
1076 func (s *state) newValue2I(op ssa.Op, t *types.Type, aux int64, arg0, arg1 *ssa.Value) *ssa.Value {
1077         return s.curBlock.NewValue2I(s.peekPos(), op, t, aux, arg0, arg1)
1078 }
1079
1080 // newValue3 adds a new value with three arguments to the current block.
1081 func (s *state) newValue3(op ssa.Op, t *types.Type, arg0, arg1, arg2 *ssa.Value) *ssa.Value {
1082         return s.curBlock.NewValue3(s.peekPos(), op, t, arg0, arg1, arg2)
1083 }
1084
1085 // newValue3I adds a new value with three arguments and an auxint value to the current block.
1086 func (s *state) newValue3I(op ssa.Op, t *types.Type, aux int64, arg0, arg1, arg2 *ssa.Value) *ssa.Value {
1087         return s.curBlock.NewValue3I(s.peekPos(), op, t, aux, arg0, arg1, arg2)
1088 }
1089
1090 // newValue3A adds a new value with three arguments and an aux value to the current block.
1091 func (s *state) newValue3A(op ssa.Op, t *types.Type, aux ssa.Aux, arg0, arg1, arg2 *ssa.Value) *ssa.Value {
1092         return s.curBlock.NewValue3A(s.peekPos(), op, t, aux, arg0, arg1, arg2)
1093 }
1094
1095 // newValue3Apos adds a new value with three arguments and an aux value to the current block.
1096 // isStmt determines whether the created values may be a statement or not
1097 // (i.e., false means never, yes means maybe).
1098 func (s *state) newValue3Apos(op ssa.Op, t *types.Type, aux ssa.Aux, arg0, arg1, arg2 *ssa.Value, isStmt bool) *ssa.Value {
1099         if isStmt {
1100                 return s.curBlock.NewValue3A(s.peekPos(), op, t, aux, arg0, arg1, arg2)
1101         }
1102         return s.curBlock.NewValue3A(s.peekPos().WithNotStmt(), op, t, aux, arg0, arg1, arg2)
1103 }
1104
1105 // newValue4 adds a new value with four arguments to the current block.
1106 func (s *state) newValue4(op ssa.Op, t *types.Type, arg0, arg1, arg2, arg3 *ssa.Value) *ssa.Value {
1107         return s.curBlock.NewValue4(s.peekPos(), op, t, arg0, arg1, arg2, arg3)
1108 }
1109
1110 // newValue4I adds a new value with four arguments and an auxint value to the current block.
1111 func (s *state) newValue4I(op ssa.Op, t *types.Type, aux int64, arg0, arg1, arg2, arg3 *ssa.Value) *ssa.Value {
1112         return s.curBlock.NewValue4I(s.peekPos(), op, t, aux, arg0, arg1, arg2, arg3)
1113 }
1114
1115 func (s *state) entryBlock() *ssa.Block {
1116         b := s.f.Entry
1117         if base.Flag.N > 0 && s.curBlock != nil {
1118                 // If optimizations are off, allocate in current block instead. Since with -N
1119                 // we're not doing the CSE or tighten passes, putting lots of stuff in the
1120                 // entry block leads to O(n^2) entries in the live value map during regalloc.
1121                 // See issue 45897.
1122                 b = s.curBlock
1123         }
1124         return b
1125 }
1126
1127 // entryNewValue0 adds a new value with no arguments to the entry block.
1128 func (s *state) entryNewValue0(op ssa.Op, t *types.Type) *ssa.Value {
1129         return s.entryBlock().NewValue0(src.NoXPos, op, t)
1130 }
1131
1132 // entryNewValue0A adds a new value with no arguments and an aux value to the entry block.
1133 func (s *state) entryNewValue0A(op ssa.Op, t *types.Type, aux ssa.Aux) *ssa.Value {
1134         return s.entryBlock().NewValue0A(src.NoXPos, op, t, aux)
1135 }
1136
1137 // entryNewValue1 adds a new value with one argument to the entry block.
1138 func (s *state) entryNewValue1(op ssa.Op, t *types.Type, arg *ssa.Value) *ssa.Value {
1139         return s.entryBlock().NewValue1(src.NoXPos, op, t, arg)
1140 }
1141
1142 // entryNewValue1I adds a new value with one argument and an auxint value to the entry block.
1143 func (s *state) entryNewValue1I(op ssa.Op, t *types.Type, auxint int64, arg *ssa.Value) *ssa.Value {
1144         return s.entryBlock().NewValue1I(src.NoXPos, op, t, auxint, arg)
1145 }
1146
1147 // entryNewValue1A adds a new value with one argument and an aux value to the entry block.
1148 func (s *state) entryNewValue1A(op ssa.Op, t *types.Type, aux ssa.Aux, arg *ssa.Value) *ssa.Value {
1149         return s.entryBlock().NewValue1A(src.NoXPos, op, t, aux, arg)
1150 }
1151
1152 // entryNewValue2 adds a new value with two arguments to the entry block.
1153 func (s *state) entryNewValue2(op ssa.Op, t *types.Type, arg0, arg1 *ssa.Value) *ssa.Value {
1154         return s.entryBlock().NewValue2(src.NoXPos, op, t, arg0, arg1)
1155 }
1156
1157 // entryNewValue2A adds a new value with two arguments and an aux value to the entry block.
1158 func (s *state) entryNewValue2A(op ssa.Op, t *types.Type, aux ssa.Aux, arg0, arg1 *ssa.Value) *ssa.Value {
1159         return s.entryBlock().NewValue2A(src.NoXPos, op, t, aux, arg0, arg1)
1160 }
1161
1162 // const* routines add a new const value to the entry block.
1163 func (s *state) constSlice(t *types.Type) *ssa.Value {
1164         return s.f.ConstSlice(t)
1165 }
1166 func (s *state) constInterface(t *types.Type) *ssa.Value {
1167         return s.f.ConstInterface(t)
1168 }
1169 func (s *state) constNil(t *types.Type) *ssa.Value { return s.f.ConstNil(t) }
1170 func (s *state) constEmptyString(t *types.Type) *ssa.Value {
1171         return s.f.ConstEmptyString(t)
1172 }
1173 func (s *state) constBool(c bool) *ssa.Value {
1174         return s.f.ConstBool(types.Types[types.TBOOL], c)
1175 }
1176 func (s *state) constInt8(t *types.Type, c int8) *ssa.Value {
1177         return s.f.ConstInt8(t, c)
1178 }
1179 func (s *state) constInt16(t *types.Type, c int16) *ssa.Value {
1180         return s.f.ConstInt16(t, c)
1181 }
1182 func (s *state) constInt32(t *types.Type, c int32) *ssa.Value {
1183         return s.f.ConstInt32(t, c)
1184 }
1185 func (s *state) constInt64(t *types.Type, c int64) *ssa.Value {
1186         return s.f.ConstInt64(t, c)
1187 }
1188 func (s *state) constFloat32(t *types.Type, c float64) *ssa.Value {
1189         return s.f.ConstFloat32(t, c)
1190 }
1191 func (s *state) constFloat64(t *types.Type, c float64) *ssa.Value {
1192         return s.f.ConstFloat64(t, c)
1193 }
1194 func (s *state) constInt(t *types.Type, c int64) *ssa.Value {
1195         if s.config.PtrSize == 8 {
1196                 return s.constInt64(t, c)
1197         }
1198         if int64(int32(c)) != c {
1199                 s.Fatalf("integer constant too big %d", c)
1200         }
1201         return s.constInt32(t, int32(c))
1202 }
1203 func (s *state) constOffPtrSP(t *types.Type, c int64) *ssa.Value {
1204         return s.f.ConstOffPtrSP(t, c, s.sp)
1205 }
1206
1207 // newValueOrSfCall* are wrappers around newValue*, which may create a call to a
1208 // soft-float runtime function instead (when emitting soft-float code).
1209 func (s *state) newValueOrSfCall1(op ssa.Op, t *types.Type, arg *ssa.Value) *ssa.Value {
1210         if s.softFloat {
1211                 if c, ok := s.sfcall(op, arg); ok {
1212                         return c
1213                 }
1214         }
1215         return s.newValue1(op, t, arg)
1216 }
1217 func (s *state) newValueOrSfCall2(op ssa.Op, t *types.Type, arg0, arg1 *ssa.Value) *ssa.Value {
1218         if s.softFloat {
1219                 if c, ok := s.sfcall(op, arg0, arg1); ok {
1220                         return c
1221                 }
1222         }
1223         return s.newValue2(op, t, arg0, arg1)
1224 }
1225
1226 type instrumentKind uint8
1227
1228 const (
1229         instrumentRead = iota
1230         instrumentWrite
1231         instrumentMove
1232 )
1233
1234 func (s *state) instrument(t *types.Type, addr *ssa.Value, kind instrumentKind) {
1235         s.instrument2(t, addr, nil, kind)
1236 }
1237
1238 // instrumentFields instruments a read/write operation on addr.
1239 // If it is instrumenting for MSAN or ASAN and t is a struct type, it instruments
1240 // operation for each field, instead of for the whole struct.
1241 func (s *state) instrumentFields(t *types.Type, addr *ssa.Value, kind instrumentKind) {
1242         if !(base.Flag.MSan || base.Flag.ASan) || !t.IsStruct() {
1243                 s.instrument(t, addr, kind)
1244                 return
1245         }
1246         for _, f := range t.Fields() {
1247                 if f.Sym.IsBlank() {
1248                         continue
1249                 }
1250                 offptr := s.newValue1I(ssa.OpOffPtr, types.NewPtr(f.Type), f.Offset, addr)
1251                 s.instrumentFields(f.Type, offptr, kind)
1252         }
1253 }
1254
1255 func (s *state) instrumentMove(t *types.Type, dst, src *ssa.Value) {
1256         if base.Flag.MSan {
1257                 s.instrument2(t, dst, src, instrumentMove)
1258         } else {
1259                 s.instrument(t, src, instrumentRead)
1260                 s.instrument(t, dst, instrumentWrite)
1261         }
1262 }
1263
1264 func (s *state) instrument2(t *types.Type, addr, addr2 *ssa.Value, kind instrumentKind) {
1265         if !s.curfn.InstrumentBody() {
1266                 return
1267         }
1268
1269         w := t.Size()
1270         if w == 0 {
1271                 return // can't race on zero-sized things
1272         }
1273
1274         if ssa.IsSanitizerSafeAddr(addr) {
1275                 return
1276         }
1277
1278         var fn *obj.LSym
1279         needWidth := false
1280
1281         if addr2 != nil && kind != instrumentMove {
1282                 panic("instrument2: non-nil addr2 for non-move instrumentation")
1283         }
1284
1285         if base.Flag.MSan {
1286                 switch kind {
1287                 case instrumentRead:
1288                         fn = ir.Syms.Msanread
1289                 case instrumentWrite:
1290                         fn = ir.Syms.Msanwrite
1291                 case instrumentMove:
1292                         fn = ir.Syms.Msanmove
1293                 default:
1294                         panic("unreachable")
1295                 }
1296                 needWidth = true
1297         } else if base.Flag.Race && t.NumComponents(types.CountBlankFields) > 1 {
1298                 // for composite objects we have to write every address
1299                 // because a write might happen to any subobject.
1300                 // composites with only one element don't have subobjects, though.
1301                 switch kind {
1302                 case instrumentRead:
1303                         fn = ir.Syms.Racereadrange
1304                 case instrumentWrite:
1305                         fn = ir.Syms.Racewriterange
1306                 default:
1307                         panic("unreachable")
1308                 }
1309                 needWidth = true
1310         } else if base.Flag.Race {
1311                 // for non-composite objects we can write just the start
1312                 // address, as any write must write the first byte.
1313                 switch kind {
1314                 case instrumentRead:
1315                         fn = ir.Syms.Raceread
1316                 case instrumentWrite:
1317                         fn = ir.Syms.Racewrite
1318                 default:
1319                         panic("unreachable")
1320                 }
1321         } else if base.Flag.ASan {
1322                 switch kind {
1323                 case instrumentRead:
1324                         fn = ir.Syms.Asanread
1325                 case instrumentWrite:
1326                         fn = ir.Syms.Asanwrite
1327                 default:
1328                         panic("unreachable")
1329                 }
1330                 needWidth = true
1331         } else {
1332                 panic("unreachable")
1333         }
1334
1335         args := []*ssa.Value{addr}
1336         if addr2 != nil {
1337                 args = append(args, addr2)
1338         }
1339         if needWidth {
1340                 args = append(args, s.constInt(types.Types[types.TUINTPTR], w))
1341         }
1342         s.rtcall(fn, true, nil, args...)
1343 }
1344
1345 func (s *state) load(t *types.Type, src *ssa.Value) *ssa.Value {
1346         s.instrumentFields(t, src, instrumentRead)
1347         return s.rawLoad(t, src)
1348 }
1349
1350 func (s *state) rawLoad(t *types.Type, src *ssa.Value) *ssa.Value {
1351         return s.newValue2(ssa.OpLoad, t, src, s.mem())
1352 }
1353
1354 func (s *state) store(t *types.Type, dst, val *ssa.Value) {
1355         s.vars[memVar] = s.newValue3A(ssa.OpStore, types.TypeMem, t, dst, val, s.mem())
1356 }
1357
1358 func (s *state) zero(t *types.Type, dst *ssa.Value) {
1359         s.instrument(t, dst, instrumentWrite)
1360         store := s.newValue2I(ssa.OpZero, types.TypeMem, t.Size(), dst, s.mem())
1361         store.Aux = t
1362         s.vars[memVar] = store
1363 }
1364
1365 func (s *state) move(t *types.Type, dst, src *ssa.Value) {
1366         s.moveWhichMayOverlap(t, dst, src, false)
1367 }
1368 func (s *state) moveWhichMayOverlap(t *types.Type, dst, src *ssa.Value, mayOverlap bool) {
1369         s.instrumentMove(t, dst, src)
1370         if mayOverlap && t.IsArray() && t.NumElem() > 1 && !ssa.IsInlinableMemmove(dst, src, t.Size(), s.f.Config) {
1371                 // Normally, when moving Go values of type T from one location to another,
1372                 // we don't need to worry about partial overlaps. The two Ts must either be
1373                 // in disjoint (nonoverlapping) memory or in exactly the same location.
1374                 // There are 2 cases where this isn't true:
1375                 //  1) Using unsafe you can arrange partial overlaps.
1376                 //  2) Since Go 1.17, you can use a cast from a slice to a ptr-to-array.
1377                 //     https://go.dev/ref/spec#Conversions_from_slice_to_array_pointer
1378                 //     This feature can be used to construct partial overlaps of array types.
1379                 //       var a [3]int
1380                 //       p := (*[2]int)(a[:])
1381                 //       q := (*[2]int)(a[1:])
1382                 //       *p = *q
1383                 // We don't care about solving 1. Or at least, we haven't historically
1384                 // and no one has complained.
1385                 // For 2, we need to ensure that if there might be partial overlap,
1386                 // then we can't use OpMove; we must use memmove instead.
1387                 // (memmove handles partial overlap by copying in the correct
1388                 // direction. OpMove does not.)
1389                 //
1390                 // Note that we have to be careful here not to introduce a call when
1391                 // we're marshaling arguments to a call or unmarshaling results from a call.
1392                 // Cases where this is happening must pass mayOverlap to false.
1393                 // (Currently this only happens when unmarshaling results of a call.)
1394                 if t.HasPointers() {
1395                         s.rtcall(ir.Syms.Typedmemmove, true, nil, s.reflectType(t), dst, src)
1396                         // We would have otherwise implemented this move with straightline code,
1397                         // including a write barrier. Pretend we issue a write barrier here,
1398                         // so that the write barrier tests work. (Otherwise they'd need to know
1399                         // the details of IsInlineableMemmove.)
1400                         s.curfn.SetWBPos(s.peekPos())
1401                 } else {
1402                         s.rtcall(ir.Syms.Memmove, true, nil, dst, src, s.constInt(types.Types[types.TUINTPTR], t.Size()))
1403                 }
1404                 ssa.LogLargeCopy(s.f.Name, s.peekPos(), t.Size())
1405                 return
1406         }
1407         store := s.newValue3I(ssa.OpMove, types.TypeMem, t.Size(), dst, src, s.mem())
1408         store.Aux = t
1409         s.vars[memVar] = store
1410 }
1411
1412 // stmtList converts the statement list n to SSA and adds it to s.
1413 func (s *state) stmtList(l ir.Nodes) {
1414         for _, n := range l {
1415                 s.stmt(n)
1416         }
1417 }
1418
1419 // stmt converts the statement n to SSA and adds it to s.
1420 func (s *state) stmt(n ir.Node) {
1421         s.pushLine(n.Pos())
1422         defer s.popLine()
1423
1424         // If s.curBlock is nil, and n isn't a label (which might have an associated goto somewhere),
1425         // then this code is dead. Stop here.
1426         if s.curBlock == nil && n.Op() != ir.OLABEL {
1427                 return
1428         }
1429
1430         s.stmtList(n.Init())
1431         switch n.Op() {
1432
1433         case ir.OBLOCK:
1434                 n := n.(*ir.BlockStmt)
1435                 s.stmtList(n.List)
1436
1437         case ir.OFALL: // no-op
1438
1439         // Expression statements
1440         case ir.OCALLFUNC:
1441                 n := n.(*ir.CallExpr)
1442                 if ir.IsIntrinsicCall(n) {
1443                         s.intrinsicCall(n)
1444                         return
1445                 }
1446                 fallthrough
1447
1448         case ir.OCALLINTER:
1449                 n := n.(*ir.CallExpr)
1450                 s.callResult(n, callNormal)
1451                 if n.Op() == ir.OCALLFUNC && n.X.Op() == ir.ONAME && n.X.(*ir.Name).Class == ir.PFUNC {
1452                         if fn := n.X.Sym().Name; base.Flag.CompilingRuntime && fn == "throw" ||
1453                                 n.X.Sym().Pkg == ir.Pkgs.Runtime && (fn == "throwinit" || fn == "gopanic" || fn == "panicwrap" || fn == "block" || fn == "panicmakeslicelen" || fn == "panicmakeslicecap" || fn == "panicunsafeslicelen" || fn == "panicunsafeslicenilptr" || fn == "panicunsafestringlen" || fn == "panicunsafestringnilptr") {
1454                                 m := s.mem()
1455                                 b := s.endBlock()
1456                                 b.Kind = ssa.BlockExit
1457                                 b.SetControl(m)
1458                                 // TODO: never rewrite OPANIC to OCALLFUNC in the
1459                                 // first place. Need to wait until all backends
1460                                 // go through SSA.
1461                         }
1462                 }
1463         case ir.ODEFER:
1464                 n := n.(*ir.GoDeferStmt)
1465                 if base.Debug.Defer > 0 {
1466                         var defertype string
1467                         if s.hasOpenDefers {
1468                                 defertype = "open-coded"
1469                         } else if n.Esc() == ir.EscNever {
1470                                 defertype = "stack-allocated"
1471                         } else {
1472                                 defertype = "heap-allocated"
1473                         }
1474                         base.WarnfAt(n.Pos(), "%s defer", defertype)
1475                 }
1476                 if s.hasOpenDefers {
1477                         s.openDeferRecord(n.Call.(*ir.CallExpr))
1478                 } else {
1479                         d := callDefer
1480                         if n.Esc() == ir.EscNever {
1481                                 d = callDeferStack
1482                         }
1483                         s.callResult(n.Call.(*ir.CallExpr), d)
1484                 }
1485         case ir.OGO:
1486                 n := n.(*ir.GoDeferStmt)
1487                 s.callResult(n.Call.(*ir.CallExpr), callGo)
1488
1489         case ir.OAS2DOTTYPE:
1490                 n := n.(*ir.AssignListStmt)
1491                 var res, resok *ssa.Value
1492                 if n.Rhs[0].Op() == ir.ODOTTYPE2 {
1493                         res, resok = s.dottype(n.Rhs[0].(*ir.TypeAssertExpr), true)
1494                 } else {
1495                         res, resok = s.dynamicDottype(n.Rhs[0].(*ir.DynamicTypeAssertExpr), true)
1496                 }
1497                 deref := false
1498                 if !ssa.CanSSA(n.Rhs[0].Type()) {
1499                         if res.Op != ssa.OpLoad {
1500                                 s.Fatalf("dottype of non-load")
1501                         }
1502                         mem := s.mem()
1503                         if res.Args[1] != mem {
1504                                 s.Fatalf("memory no longer live from 2-result dottype load")
1505                         }
1506                         deref = true
1507                         res = res.Args[0]
1508                 }
1509                 s.assign(n.Lhs[0], res, deref, 0)
1510                 s.assign(n.Lhs[1], resok, false, 0)
1511                 return
1512
1513         case ir.OAS2FUNC:
1514                 // We come here only when it is an intrinsic call returning two values.
1515                 n := n.(*ir.AssignListStmt)
1516                 call := n.Rhs[0].(*ir.CallExpr)
1517                 if !ir.IsIntrinsicCall(call) {
1518                         s.Fatalf("non-intrinsic AS2FUNC not expanded %v", call)
1519                 }
1520                 v := s.intrinsicCall(call)
1521                 v1 := s.newValue1(ssa.OpSelect0, n.Lhs[0].Type(), v)
1522                 v2 := s.newValue1(ssa.OpSelect1, n.Lhs[1].Type(), v)
1523                 s.assign(n.Lhs[0], v1, false, 0)
1524                 s.assign(n.Lhs[1], v2, false, 0)
1525                 return
1526
1527         case ir.ODCL:
1528                 n := n.(*ir.Decl)
1529                 if v := n.X; v.Esc() == ir.EscHeap {
1530                         s.newHeapaddr(v)
1531                 }
1532
1533         case ir.OLABEL:
1534                 n := n.(*ir.LabelStmt)
1535                 sym := n.Label
1536                 if sym.IsBlank() {
1537                         // Nothing to do because the label isn't targetable. See issue 52278.
1538                         break
1539                 }
1540                 lab := s.label(sym)
1541
1542                 // The label might already have a target block via a goto.
1543                 if lab.target == nil {
1544                         lab.target = s.f.NewBlock(ssa.BlockPlain)
1545                 }
1546
1547                 // Go to that label.
1548                 // (We pretend "label:" is preceded by "goto label", unless the predecessor is unreachable.)
1549                 if s.curBlock != nil {
1550                         b := s.endBlock()
1551                         b.AddEdgeTo(lab.target)
1552                 }
1553                 s.startBlock(lab.target)
1554
1555         case ir.OGOTO:
1556                 n := n.(*ir.BranchStmt)
1557                 sym := n.Label
1558
1559                 lab := s.label(sym)
1560                 if lab.target == nil {
1561                         lab.target = s.f.NewBlock(ssa.BlockPlain)
1562                 }
1563
1564                 b := s.endBlock()
1565                 b.Pos = s.lastPos.WithIsStmt() // Do this even if b is an empty block.
1566                 b.AddEdgeTo(lab.target)
1567
1568         case ir.OAS:
1569                 n := n.(*ir.AssignStmt)
1570                 if n.X == n.Y && n.X.Op() == ir.ONAME {
1571                         // An x=x assignment. No point in doing anything
1572                         // here. In addition, skipping this assignment
1573                         // prevents generating:
1574                         //   VARDEF x
1575                         //   COPY x -> x
1576                         // which is bad because x is incorrectly considered
1577                         // dead before the vardef. See issue #14904.
1578                         return
1579                 }
1580
1581                 // mayOverlap keeps track of whether the LHS and RHS might
1582                 // refer to partially overlapping memory. Partial overlapping can
1583                 // only happen for arrays, see the comment in moveWhichMayOverlap.
1584                 //
1585                 // If both sides of the assignment are not dereferences, then partial
1586                 // overlap can't happen. Partial overlap can only occur only when the
1587                 // arrays referenced are strictly smaller parts of the same base array.
1588                 // If one side of the assignment is a full array, then partial overlap
1589                 // can't happen. (The arrays are either disjoint or identical.)
1590                 mayOverlap := n.X.Op() == ir.ODEREF && (n.Y != nil && n.Y.Op() == ir.ODEREF)
1591                 if n.Y != nil && n.Y.Op() == ir.ODEREF {
1592                         p := n.Y.(*ir.StarExpr).X
1593                         for p.Op() == ir.OCONVNOP {
1594                                 p = p.(*ir.ConvExpr).X
1595                         }
1596                         if p.Op() == ir.OSPTR && p.(*ir.UnaryExpr).X.Type().IsString() {
1597                                 // Pointer fields of strings point to unmodifiable memory.
1598                                 // That memory can't overlap with the memory being written.
1599                                 mayOverlap = false
1600                         }
1601                 }
1602
1603                 // Evaluate RHS.
1604                 rhs := n.Y
1605                 if rhs != nil {
1606                         switch rhs.Op() {
1607                         case ir.OSTRUCTLIT, ir.OARRAYLIT, ir.OSLICELIT:
1608                                 // All literals with nonzero fields have already been
1609                                 // rewritten during walk. Any that remain are just T{}
1610                                 // or equivalents. Use the zero value.
1611                                 if !ir.IsZero(rhs) {
1612                                         s.Fatalf("literal with nonzero value in SSA: %v", rhs)
1613                                 }
1614                                 rhs = nil
1615                         case ir.OAPPEND:
1616                                 rhs := rhs.(*ir.CallExpr)
1617                                 // Check whether we're writing the result of an append back to the same slice.
1618                                 // If so, we handle it specially to avoid write barriers on the fast
1619                                 // (non-growth) path.
1620                                 if !ir.SameSafeExpr(n.X, rhs.Args[0]) || base.Flag.N != 0 {
1621                                         break
1622                                 }
1623                                 // If the slice can be SSA'd, it'll be on the stack,
1624                                 // so there will be no write barriers,
1625                                 // so there's no need to attempt to prevent them.
1626                                 if s.canSSA(n.X) {
1627                                         if base.Debug.Append > 0 { // replicating old diagnostic message
1628                                                 base.WarnfAt(n.Pos(), "append: len-only update (in local slice)")
1629                                         }
1630                                         break
1631                                 }
1632                                 if base.Debug.Append > 0 {
1633                                         base.WarnfAt(n.Pos(), "append: len-only update")
1634                                 }
1635                                 s.append(rhs, true)
1636                                 return
1637                         }
1638                 }
1639
1640                 if ir.IsBlank(n.X) {
1641                         // _ = rhs
1642                         // Just evaluate rhs for side-effects.
1643                         if rhs != nil {
1644                                 s.expr(rhs)
1645                         }
1646                         return
1647                 }
1648
1649                 var t *types.Type
1650                 if n.Y != nil {
1651                         t = n.Y.Type()
1652                 } else {
1653                         t = n.X.Type()
1654                 }
1655
1656                 var r *ssa.Value
1657                 deref := !ssa.CanSSA(t)
1658                 if deref {
1659                         if rhs == nil {
1660                                 r = nil // Signal assign to use OpZero.
1661                         } else {
1662                                 r = s.addr(rhs)
1663                         }
1664                 } else {
1665                         if rhs == nil {
1666                                 r = s.zeroVal(t)
1667                         } else {
1668                                 r = s.expr(rhs)
1669                         }
1670                 }
1671
1672                 var skip skipMask
1673                 if rhs != nil && (rhs.Op() == ir.OSLICE || rhs.Op() == ir.OSLICE3 || rhs.Op() == ir.OSLICESTR) && ir.SameSafeExpr(rhs.(*ir.SliceExpr).X, n.X) {
1674                         // We're assigning a slicing operation back to its source.
1675                         // Don't write back fields we aren't changing. See issue #14855.
1676                         rhs := rhs.(*ir.SliceExpr)
1677                         i, j, k := rhs.Low, rhs.High, rhs.Max
1678                         if i != nil && (i.Op() == ir.OLITERAL && i.Val().Kind() == constant.Int && ir.Int64Val(i) == 0) {
1679                                 // [0:...] is the same as [:...]
1680                                 i = nil
1681                         }
1682                         // TODO: detect defaults for len/cap also.
1683                         // Currently doesn't really work because (*p)[:len(*p)] appears here as:
1684                         //    tmp = len(*p)
1685                         //    (*p)[:tmp]
1686                         // if j != nil && (j.Op == OLEN && SameSafeExpr(j.Left, n.Left)) {
1687                         //      j = nil
1688                         // }
1689                         // if k != nil && (k.Op == OCAP && SameSafeExpr(k.Left, n.Left)) {
1690                         //      k = nil
1691                         // }
1692                         if i == nil {
1693                                 skip |= skipPtr
1694                                 if j == nil {
1695                                         skip |= skipLen
1696                                 }
1697                                 if k == nil {
1698                                         skip |= skipCap
1699                                 }
1700                         }
1701                 }
1702
1703                 s.assignWhichMayOverlap(n.X, r, deref, skip, mayOverlap)
1704
1705         case ir.OIF:
1706                 n := n.(*ir.IfStmt)
1707                 if ir.IsConst(n.Cond, constant.Bool) {
1708                         s.stmtList(n.Cond.Init())
1709                         if ir.BoolVal(n.Cond) {
1710                                 s.stmtList(n.Body)
1711                         } else {
1712                                 s.stmtList(n.Else)
1713                         }
1714                         break
1715                 }
1716
1717                 bEnd := s.f.NewBlock(ssa.BlockPlain)
1718                 var likely int8
1719                 if n.Likely {
1720                         likely = 1
1721                 }
1722                 var bThen *ssa.Block
1723                 if len(n.Body) != 0 {
1724                         bThen = s.f.NewBlock(ssa.BlockPlain)
1725                 } else {
1726                         bThen = bEnd
1727                 }
1728                 var bElse *ssa.Block
1729                 if len(n.Else) != 0 {
1730                         bElse = s.f.NewBlock(ssa.BlockPlain)
1731                 } else {
1732                         bElse = bEnd
1733                 }
1734                 s.condBranch(n.Cond, bThen, bElse, likely)
1735
1736                 if len(n.Body) != 0 {
1737                         s.startBlock(bThen)
1738                         s.stmtList(n.Body)
1739                         if b := s.endBlock(); b != nil {
1740                                 b.AddEdgeTo(bEnd)
1741                         }
1742                 }
1743                 if len(n.Else) != 0 {
1744                         s.startBlock(bElse)
1745                         s.stmtList(n.Else)
1746                         if b := s.endBlock(); b != nil {
1747                                 b.AddEdgeTo(bEnd)
1748                         }
1749                 }
1750                 s.startBlock(bEnd)
1751
1752         case ir.ORETURN:
1753                 n := n.(*ir.ReturnStmt)
1754                 s.stmtList(n.Results)
1755                 b := s.exit()
1756                 b.Pos = s.lastPos.WithIsStmt()
1757
1758         case ir.OTAILCALL:
1759                 n := n.(*ir.TailCallStmt)
1760                 s.callResult(n.Call, callTail)
1761                 call := s.mem()
1762                 b := s.endBlock()
1763                 b.Kind = ssa.BlockRetJmp // could use BlockExit. BlockRetJmp is mostly for clarity.
1764                 b.SetControl(call)
1765
1766         case ir.OCONTINUE, ir.OBREAK:
1767                 n := n.(*ir.BranchStmt)
1768                 var to *ssa.Block
1769                 if n.Label == nil {
1770                         // plain break/continue
1771                         switch n.Op() {
1772                         case ir.OCONTINUE:
1773                                 to = s.continueTo
1774                         case ir.OBREAK:
1775                                 to = s.breakTo
1776                         }
1777                 } else {
1778                         // labeled break/continue; look up the target
1779                         sym := n.Label
1780                         lab := s.label(sym)
1781                         switch n.Op() {
1782                         case ir.OCONTINUE:
1783                                 to = lab.continueTarget
1784                         case ir.OBREAK:
1785                                 to = lab.breakTarget
1786                         }
1787                 }
1788
1789                 b := s.endBlock()
1790                 b.Pos = s.lastPos.WithIsStmt() // Do this even if b is an empty block.
1791                 b.AddEdgeTo(to)
1792
1793         case ir.OFOR:
1794                 // OFOR: for Ninit; Left; Right { Nbody }
1795                 // cond (Left); body (Nbody); incr (Right)
1796                 n := n.(*ir.ForStmt)
1797                 base.Assert(!n.DistinctVars) // Should all be rewritten before escape analysis
1798                 bCond := s.f.NewBlock(ssa.BlockPlain)
1799                 bBody := s.f.NewBlock(ssa.BlockPlain)
1800                 bIncr := s.f.NewBlock(ssa.BlockPlain)
1801                 bEnd := s.f.NewBlock(ssa.BlockPlain)
1802
1803                 // ensure empty for loops have correct position; issue #30167
1804                 bBody.Pos = n.Pos()
1805
1806                 // first, jump to condition test
1807                 b := s.endBlock()
1808                 b.AddEdgeTo(bCond)
1809
1810                 // generate code to test condition
1811                 s.startBlock(bCond)
1812                 if n.Cond != nil {
1813                         s.condBranch(n.Cond, bBody, bEnd, 1)
1814                 } else {
1815                         b := s.endBlock()
1816                         b.Kind = ssa.BlockPlain
1817                         b.AddEdgeTo(bBody)
1818                 }
1819
1820                 // set up for continue/break in body
1821                 prevContinue := s.continueTo
1822                 prevBreak := s.breakTo
1823                 s.continueTo = bIncr
1824                 s.breakTo = bEnd
1825                 var lab *ssaLabel
1826                 if sym := n.Label; sym != nil {
1827                         // labeled for loop
1828                         lab = s.label(sym)
1829                         lab.continueTarget = bIncr
1830                         lab.breakTarget = bEnd
1831                 }
1832
1833                 // generate body
1834                 s.startBlock(bBody)
1835                 s.stmtList(n.Body)
1836
1837                 // tear down continue/break
1838                 s.continueTo = prevContinue
1839                 s.breakTo = prevBreak
1840                 if lab != nil {
1841                         lab.continueTarget = nil
1842                         lab.breakTarget = nil
1843                 }
1844
1845                 // done with body, goto incr
1846                 if b := s.endBlock(); b != nil {
1847                         b.AddEdgeTo(bIncr)
1848                 }
1849
1850                 // generate incr
1851                 s.startBlock(bIncr)
1852                 if n.Post != nil {
1853                         s.stmt(n.Post)
1854                 }
1855                 if b := s.endBlock(); b != nil {
1856                         b.AddEdgeTo(bCond)
1857                         // It can happen that bIncr ends in a block containing only VARKILL,
1858                         // and that muddles the debugging experience.
1859                         if b.Pos == src.NoXPos {
1860                                 b.Pos = bCond.Pos
1861                         }
1862                 }
1863
1864                 s.startBlock(bEnd)
1865
1866         case ir.OSWITCH, ir.OSELECT:
1867                 // These have been mostly rewritten by the front end into their Nbody fields.
1868                 // Our main task is to correctly hook up any break statements.
1869                 bEnd := s.f.NewBlock(ssa.BlockPlain)
1870
1871                 prevBreak := s.breakTo
1872                 s.breakTo = bEnd
1873                 var sym *types.Sym
1874                 var body ir.Nodes
1875                 if n.Op() == ir.OSWITCH {
1876                         n := n.(*ir.SwitchStmt)
1877                         sym = n.Label
1878                         body = n.Compiled
1879                 } else {
1880                         n := n.(*ir.SelectStmt)
1881                         sym = n.Label
1882                         body = n.Compiled
1883                 }
1884
1885                 var lab *ssaLabel
1886                 if sym != nil {
1887                         // labeled
1888                         lab = s.label(sym)
1889                         lab.breakTarget = bEnd
1890                 }
1891
1892                 // generate body code
1893                 s.stmtList(body)
1894
1895                 s.breakTo = prevBreak
1896                 if lab != nil {
1897                         lab.breakTarget = nil
1898                 }
1899
1900                 // walk adds explicit OBREAK nodes to the end of all reachable code paths.
1901                 // If we still have a current block here, then mark it unreachable.
1902                 if s.curBlock != nil {
1903                         m := s.mem()
1904                         b := s.endBlock()
1905                         b.Kind = ssa.BlockExit
1906                         b.SetControl(m)
1907                 }
1908                 s.startBlock(bEnd)
1909
1910         case ir.OJUMPTABLE:
1911                 n := n.(*ir.JumpTableStmt)
1912
1913                 // Make blocks we'll need.
1914                 jt := s.f.NewBlock(ssa.BlockJumpTable)
1915                 bEnd := s.f.NewBlock(ssa.BlockPlain)
1916
1917                 // The only thing that needs evaluating is the index we're looking up.
1918                 idx := s.expr(n.Idx)
1919                 unsigned := idx.Type.IsUnsigned()
1920
1921                 // Extend so we can do everything in uintptr arithmetic.
1922                 t := types.Types[types.TUINTPTR]
1923                 idx = s.conv(nil, idx, idx.Type, t)
1924
1925                 // The ending condition for the current block decides whether we'll use
1926                 // the jump table at all.
1927                 // We check that min <= idx <= max and jump around the jump table
1928                 // if that test fails.
1929                 // We implement min <= idx <= max with 0 <= idx-min <= max-min, because
1930                 // we'll need idx-min anyway as the control value for the jump table.
1931                 var min, max uint64
1932                 if unsigned {
1933                         min, _ = constant.Uint64Val(n.Cases[0])
1934                         max, _ = constant.Uint64Val(n.Cases[len(n.Cases)-1])
1935                 } else {
1936                         mn, _ := constant.Int64Val(n.Cases[0])
1937                         mx, _ := constant.Int64Val(n.Cases[len(n.Cases)-1])
1938                         min = uint64(mn)
1939                         max = uint64(mx)
1940                 }
1941                 // Compare idx-min with max-min, to see if we can use the jump table.
1942                 idx = s.newValue2(s.ssaOp(ir.OSUB, t), t, idx, s.uintptrConstant(min))
1943                 width := s.uintptrConstant(max - min)
1944                 cmp := s.newValue2(s.ssaOp(ir.OLE, t), types.Types[types.TBOOL], idx, width)
1945                 b := s.endBlock()
1946                 b.Kind = ssa.BlockIf
1947                 b.SetControl(cmp)
1948                 b.AddEdgeTo(jt)             // in range - use jump table
1949                 b.AddEdgeTo(bEnd)           // out of range - no case in the jump table will trigger
1950                 b.Likely = ssa.BranchLikely // TODO: assumes missing the table entirely is unlikely. True?
1951
1952                 // Build jump table block.
1953                 s.startBlock(jt)
1954                 jt.Pos = n.Pos()
1955                 if base.Flag.Cfg.SpectreIndex {
1956                         idx = s.newValue2(ssa.OpSpectreSliceIndex, t, idx, width)
1957                 }
1958                 jt.SetControl(idx)
1959
1960                 // Figure out where we should go for each index in the table.
1961                 table := make([]*ssa.Block, max-min+1)
1962                 for i := range table {
1963                         table[i] = bEnd // default target
1964                 }
1965                 for i := range n.Targets {
1966                         c := n.Cases[i]
1967                         lab := s.label(n.Targets[i])
1968                         if lab.target == nil {
1969                                 lab.target = s.f.NewBlock(ssa.BlockPlain)
1970                         }
1971                         var val uint64
1972                         if unsigned {
1973                                 val, _ = constant.Uint64Val(c)
1974                         } else {
1975                                 vl, _ := constant.Int64Val(c)
1976                                 val = uint64(vl)
1977                         }
1978                         // Overwrite the default target.
1979                         table[val-min] = lab.target
1980                 }
1981                 for _, t := range table {
1982                         jt.AddEdgeTo(t)
1983                 }
1984                 s.endBlock()
1985
1986                 s.startBlock(bEnd)
1987
1988         case ir.OCHECKNIL:
1989                 n := n.(*ir.UnaryExpr)
1990                 p := s.expr(n.X)
1991                 s.nilCheck(p)
1992
1993         case ir.OINLMARK:
1994                 n := n.(*ir.InlineMarkStmt)
1995                 s.newValue1I(ssa.OpInlMark, types.TypeVoid, n.Index, s.mem())
1996
1997         default:
1998                 s.Fatalf("unhandled stmt %v", n.Op())
1999         }
2000 }
2001
2002 // If true, share as many open-coded defer exits as possible (with the downside of
2003 // worse line-number information)
2004 const shareDeferExits = false
2005
2006 // exit processes any code that needs to be generated just before returning.
2007 // It returns a BlockRet block that ends the control flow. Its control value
2008 // will be set to the final memory state.
2009 func (s *state) exit() *ssa.Block {
2010         if s.hasdefer {
2011                 if s.hasOpenDefers {
2012                         if shareDeferExits && s.lastDeferExit != nil && len(s.openDefers) == s.lastDeferCount {
2013                                 if s.curBlock.Kind != ssa.BlockPlain {
2014                                         panic("Block for an exit should be BlockPlain")
2015                                 }
2016                                 s.curBlock.AddEdgeTo(s.lastDeferExit)
2017                                 s.endBlock()
2018                                 return s.lastDeferFinalBlock
2019                         }
2020                         s.openDeferExit()
2021                 } else {
2022                         s.rtcall(ir.Syms.Deferreturn, true, nil)
2023                 }
2024         }
2025
2026         var b *ssa.Block
2027         var m *ssa.Value
2028         // Do actual return.
2029         // These currently turn into self-copies (in many cases).
2030         resultFields := s.curfn.Type().Results()
2031         results := make([]*ssa.Value, len(resultFields)+1, len(resultFields)+1)
2032         m = s.newValue0(ssa.OpMakeResult, s.f.OwnAux.LateExpansionResultType())
2033         // Store SSAable and heap-escaped PPARAMOUT variables back to stack locations.
2034         for i, f := range resultFields {
2035                 n := f.Nname.(*ir.Name)
2036                 if s.canSSA(n) { // result is in some SSA variable
2037                         if !n.IsOutputParamInRegisters() && n.Type().HasPointers() {
2038                                 // We are about to store to the result slot.
2039                                 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, n, s.mem())
2040                         }
2041                         results[i] = s.variable(n, n.Type())
2042                 } else if !n.OnStack() { // result is actually heap allocated
2043                         // We are about to copy the in-heap result to the result slot.
2044                         if n.Type().HasPointers() {
2045                                 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, n, s.mem())
2046                         }
2047                         ha := s.expr(n.Heapaddr)
2048                         s.instrumentFields(n.Type(), ha, instrumentRead)
2049                         results[i] = s.newValue2(ssa.OpDereference, n.Type(), ha, s.mem())
2050                 } else { // result is not SSA-able; not escaped, so not on heap, but too large for SSA.
2051                         // Before register ABI this ought to be a self-move, home=dest,
2052                         // With register ABI, it's still a self-move if parameter is on stack (i.e., too big or overflowed)
2053                         // No VarDef, as the result slot is already holding live value.
2054                         results[i] = s.newValue2(ssa.OpDereference, n.Type(), s.addr(n), s.mem())
2055                 }
2056         }
2057
2058         // Run exit code. Today, this is just racefuncexit, in -race mode.
2059         // TODO(register args) this seems risky here with a register-ABI, but not clear it is right to do it earlier either.
2060         // Spills in register allocation might just fix it.
2061         s.stmtList(s.curfn.Exit)
2062
2063         results[len(results)-1] = s.mem()
2064         m.AddArgs(results...)
2065
2066         b = s.endBlock()
2067         b.Kind = ssa.BlockRet
2068         b.SetControl(m)
2069         if s.hasdefer && s.hasOpenDefers {
2070                 s.lastDeferFinalBlock = b
2071         }
2072         return b
2073 }
2074
2075 type opAndType struct {
2076         op    ir.Op
2077         etype types.Kind
2078 }
2079
2080 var opToSSA = map[opAndType]ssa.Op{
2081         {ir.OADD, types.TINT8}:    ssa.OpAdd8,
2082         {ir.OADD, types.TUINT8}:   ssa.OpAdd8,
2083         {ir.OADD, types.TINT16}:   ssa.OpAdd16,
2084         {ir.OADD, types.TUINT16}:  ssa.OpAdd16,
2085         {ir.OADD, types.TINT32}:   ssa.OpAdd32,
2086         {ir.OADD, types.TUINT32}:  ssa.OpAdd32,
2087         {ir.OADD, types.TINT64}:   ssa.OpAdd64,
2088         {ir.OADD, types.TUINT64}:  ssa.OpAdd64,
2089         {ir.OADD, types.TFLOAT32}: ssa.OpAdd32F,
2090         {ir.OADD, types.TFLOAT64}: ssa.OpAdd64F,
2091
2092         {ir.OSUB, types.TINT8}:    ssa.OpSub8,
2093         {ir.OSUB, types.TUINT8}:   ssa.OpSub8,
2094         {ir.OSUB, types.TINT16}:   ssa.OpSub16,
2095         {ir.OSUB, types.TUINT16}:  ssa.OpSub16,
2096         {ir.OSUB, types.TINT32}:   ssa.OpSub32,
2097         {ir.OSUB, types.TUINT32}:  ssa.OpSub32,
2098         {ir.OSUB, types.TINT64}:   ssa.OpSub64,
2099         {ir.OSUB, types.TUINT64}:  ssa.OpSub64,
2100         {ir.OSUB, types.TFLOAT32}: ssa.OpSub32F,
2101         {ir.OSUB, types.TFLOAT64}: ssa.OpSub64F,
2102
2103         {ir.ONOT, types.TBOOL}: ssa.OpNot,
2104
2105         {ir.ONEG, types.TINT8}:    ssa.OpNeg8,
2106         {ir.ONEG, types.TUINT8}:   ssa.OpNeg8,
2107         {ir.ONEG, types.TINT16}:   ssa.OpNeg16,
2108         {ir.ONEG, types.TUINT16}:  ssa.OpNeg16,
2109         {ir.ONEG, types.TINT32}:   ssa.OpNeg32,
2110         {ir.ONEG, types.TUINT32}:  ssa.OpNeg32,
2111         {ir.ONEG, types.TINT64}:   ssa.OpNeg64,
2112         {ir.ONEG, types.TUINT64}:  ssa.OpNeg64,
2113         {ir.ONEG, types.TFLOAT32}: ssa.OpNeg32F,
2114         {ir.ONEG, types.TFLOAT64}: ssa.OpNeg64F,
2115
2116         {ir.OBITNOT, types.TINT8}:   ssa.OpCom8,
2117         {ir.OBITNOT, types.TUINT8}:  ssa.OpCom8,
2118         {ir.OBITNOT, types.TINT16}:  ssa.OpCom16,
2119         {ir.OBITNOT, types.TUINT16}: ssa.OpCom16,
2120         {ir.OBITNOT, types.TINT32}:  ssa.OpCom32,
2121         {ir.OBITNOT, types.TUINT32}: ssa.OpCom32,
2122         {ir.OBITNOT, types.TINT64}:  ssa.OpCom64,
2123         {ir.OBITNOT, types.TUINT64}: ssa.OpCom64,
2124
2125         {ir.OIMAG, types.TCOMPLEX64}:  ssa.OpComplexImag,
2126         {ir.OIMAG, types.TCOMPLEX128}: ssa.OpComplexImag,
2127         {ir.OREAL, types.TCOMPLEX64}:  ssa.OpComplexReal,
2128         {ir.OREAL, types.TCOMPLEX128}: ssa.OpComplexReal,
2129
2130         {ir.OMUL, types.TINT8}:    ssa.OpMul8,
2131         {ir.OMUL, types.TUINT8}:   ssa.OpMul8,
2132         {ir.OMUL, types.TINT16}:   ssa.OpMul16,
2133         {ir.OMUL, types.TUINT16}:  ssa.OpMul16,
2134         {ir.OMUL, types.TINT32}:   ssa.OpMul32,
2135         {ir.OMUL, types.TUINT32}:  ssa.OpMul32,
2136         {ir.OMUL, types.TINT64}:   ssa.OpMul64,
2137         {ir.OMUL, types.TUINT64}:  ssa.OpMul64,
2138         {ir.OMUL, types.TFLOAT32}: ssa.OpMul32F,
2139         {ir.OMUL, types.TFLOAT64}: ssa.OpMul64F,
2140
2141         {ir.ODIV, types.TFLOAT32}: ssa.OpDiv32F,
2142         {ir.ODIV, types.TFLOAT64}: ssa.OpDiv64F,
2143
2144         {ir.ODIV, types.TINT8}:   ssa.OpDiv8,
2145         {ir.ODIV, types.TUINT8}:  ssa.OpDiv8u,
2146         {ir.ODIV, types.TINT16}:  ssa.OpDiv16,
2147         {ir.ODIV, types.TUINT16}: ssa.OpDiv16u,
2148         {ir.ODIV, types.TINT32}:  ssa.OpDiv32,
2149         {ir.ODIV, types.TUINT32}: ssa.OpDiv32u,
2150         {ir.ODIV, types.TINT64}:  ssa.OpDiv64,
2151         {ir.ODIV, types.TUINT64}: ssa.OpDiv64u,
2152
2153         {ir.OMOD, types.TINT8}:   ssa.OpMod8,
2154         {ir.OMOD, types.TUINT8}:  ssa.OpMod8u,
2155         {ir.OMOD, types.TINT16}:  ssa.OpMod16,
2156         {ir.OMOD, types.TUINT16}: ssa.OpMod16u,
2157         {ir.OMOD, types.TINT32}:  ssa.OpMod32,
2158         {ir.OMOD, types.TUINT32}: ssa.OpMod32u,
2159         {ir.OMOD, types.TINT64}:  ssa.OpMod64,
2160         {ir.OMOD, types.TUINT64}: ssa.OpMod64u,
2161
2162         {ir.OAND, types.TINT8}:   ssa.OpAnd8,
2163         {ir.OAND, types.TUINT8}:  ssa.OpAnd8,
2164         {ir.OAND, types.TINT16}:  ssa.OpAnd16,
2165         {ir.OAND, types.TUINT16}: ssa.OpAnd16,
2166         {ir.OAND, types.TINT32}:  ssa.OpAnd32,
2167         {ir.OAND, types.TUINT32}: ssa.OpAnd32,
2168         {ir.OAND, types.TINT64}:  ssa.OpAnd64,
2169         {ir.OAND, types.TUINT64}: ssa.OpAnd64,
2170
2171         {ir.OOR, types.TINT8}:   ssa.OpOr8,
2172         {ir.OOR, types.TUINT8}:  ssa.OpOr8,
2173         {ir.OOR, types.TINT16}:  ssa.OpOr16,
2174         {ir.OOR, types.TUINT16}: ssa.OpOr16,
2175         {ir.OOR, types.TINT32}:  ssa.OpOr32,
2176         {ir.OOR, types.TUINT32}: ssa.OpOr32,
2177         {ir.OOR, types.TINT64}:  ssa.OpOr64,
2178         {ir.OOR, types.TUINT64}: ssa.OpOr64,
2179
2180         {ir.OXOR, types.TINT8}:   ssa.OpXor8,
2181         {ir.OXOR, types.TUINT8}:  ssa.OpXor8,
2182         {ir.OXOR, types.TINT16}:  ssa.OpXor16,
2183         {ir.OXOR, types.TUINT16}: ssa.OpXor16,
2184         {ir.OXOR, types.TINT32}:  ssa.OpXor32,
2185         {ir.OXOR, types.TUINT32}: ssa.OpXor32,
2186         {ir.OXOR, types.TINT64}:  ssa.OpXor64,
2187         {ir.OXOR, types.TUINT64}: ssa.OpXor64,
2188
2189         {ir.OEQ, types.TBOOL}:      ssa.OpEqB,
2190         {ir.OEQ, types.TINT8}:      ssa.OpEq8,
2191         {ir.OEQ, types.TUINT8}:     ssa.OpEq8,
2192         {ir.OEQ, types.TINT16}:     ssa.OpEq16,
2193         {ir.OEQ, types.TUINT16}:    ssa.OpEq16,
2194         {ir.OEQ, types.TINT32}:     ssa.OpEq32,
2195         {ir.OEQ, types.TUINT32}:    ssa.OpEq32,
2196         {ir.OEQ, types.TINT64}:     ssa.OpEq64,
2197         {ir.OEQ, types.TUINT64}:    ssa.OpEq64,
2198         {ir.OEQ, types.TINTER}:     ssa.OpEqInter,
2199         {ir.OEQ, types.TSLICE}:     ssa.OpEqSlice,
2200         {ir.OEQ, types.TFUNC}:      ssa.OpEqPtr,
2201         {ir.OEQ, types.TMAP}:       ssa.OpEqPtr,
2202         {ir.OEQ, types.TCHAN}:      ssa.OpEqPtr,
2203         {ir.OEQ, types.TPTR}:       ssa.OpEqPtr,
2204         {ir.OEQ, types.TUINTPTR}:   ssa.OpEqPtr,
2205         {ir.OEQ, types.TUNSAFEPTR}: ssa.OpEqPtr,
2206         {ir.OEQ, types.TFLOAT64}:   ssa.OpEq64F,
2207         {ir.OEQ, types.TFLOAT32}:   ssa.OpEq32F,
2208
2209         {ir.ONE, types.TBOOL}:      ssa.OpNeqB,
2210         {ir.ONE, types.TINT8}:      ssa.OpNeq8,
2211         {ir.ONE, types.TUINT8}:     ssa.OpNeq8,
2212         {ir.ONE, types.TINT16}:     ssa.OpNeq16,
2213         {ir.ONE, types.TUINT16}:    ssa.OpNeq16,
2214         {ir.ONE, types.TINT32}:     ssa.OpNeq32,
2215         {ir.ONE, types.TUINT32}:    ssa.OpNeq32,
2216         {ir.ONE, types.TINT64}:     ssa.OpNeq64,
2217         {ir.ONE, types.TUINT64}:    ssa.OpNeq64,
2218         {ir.ONE, types.TINTER}:     ssa.OpNeqInter,
2219         {ir.ONE, types.TSLICE}:     ssa.OpNeqSlice,
2220         {ir.ONE, types.TFUNC}:      ssa.OpNeqPtr,
2221         {ir.ONE, types.TMAP}:       ssa.OpNeqPtr,
2222         {ir.ONE, types.TCHAN}:      ssa.OpNeqPtr,
2223         {ir.ONE, types.TPTR}:       ssa.OpNeqPtr,
2224         {ir.ONE, types.TUINTPTR}:   ssa.OpNeqPtr,
2225         {ir.ONE, types.TUNSAFEPTR}: ssa.OpNeqPtr,
2226         {ir.ONE, types.TFLOAT64}:   ssa.OpNeq64F,
2227         {ir.ONE, types.TFLOAT32}:   ssa.OpNeq32F,
2228
2229         {ir.OLT, types.TINT8}:    ssa.OpLess8,
2230         {ir.OLT, types.TUINT8}:   ssa.OpLess8U,
2231         {ir.OLT, types.TINT16}:   ssa.OpLess16,
2232         {ir.OLT, types.TUINT16}:  ssa.OpLess16U,
2233         {ir.OLT, types.TINT32}:   ssa.OpLess32,
2234         {ir.OLT, types.TUINT32}:  ssa.OpLess32U,
2235         {ir.OLT, types.TINT64}:   ssa.OpLess64,
2236         {ir.OLT, types.TUINT64}:  ssa.OpLess64U,
2237         {ir.OLT, types.TFLOAT64}: ssa.OpLess64F,
2238         {ir.OLT, types.TFLOAT32}: ssa.OpLess32F,
2239
2240         {ir.OLE, types.TINT8}:    ssa.OpLeq8,
2241         {ir.OLE, types.TUINT8}:   ssa.OpLeq8U,
2242         {ir.OLE, types.TINT16}:   ssa.OpLeq16,
2243         {ir.OLE, types.TUINT16}:  ssa.OpLeq16U,
2244         {ir.OLE, types.TINT32}:   ssa.OpLeq32,
2245         {ir.OLE, types.TUINT32}:  ssa.OpLeq32U,
2246         {ir.OLE, types.TINT64}:   ssa.OpLeq64,
2247         {ir.OLE, types.TUINT64}:  ssa.OpLeq64U,
2248         {ir.OLE, types.TFLOAT64}: ssa.OpLeq64F,
2249         {ir.OLE, types.TFLOAT32}: ssa.OpLeq32F,
2250 }
2251
2252 func (s *state) concreteEtype(t *types.Type) types.Kind {
2253         e := t.Kind()
2254         switch e {
2255         default:
2256                 return e
2257         case types.TINT:
2258                 if s.config.PtrSize == 8 {
2259                         return types.TINT64
2260                 }
2261                 return types.TINT32
2262         case types.TUINT:
2263                 if s.config.PtrSize == 8 {
2264                         return types.TUINT64
2265                 }
2266                 return types.TUINT32
2267         case types.TUINTPTR:
2268                 if s.config.PtrSize == 8 {
2269                         return types.TUINT64
2270                 }
2271                 return types.TUINT32
2272         }
2273 }
2274
2275 func (s *state) ssaOp(op ir.Op, t *types.Type) ssa.Op {
2276         etype := s.concreteEtype(t)
2277         x, ok := opToSSA[opAndType{op, etype}]
2278         if !ok {
2279                 s.Fatalf("unhandled binary op %v %s", op, etype)
2280         }
2281         return x
2282 }
2283
2284 type opAndTwoTypes struct {
2285         op     ir.Op
2286         etype1 types.Kind
2287         etype2 types.Kind
2288 }
2289
2290 type twoTypes struct {
2291         etype1 types.Kind
2292         etype2 types.Kind
2293 }
2294
2295 type twoOpsAndType struct {
2296         op1              ssa.Op
2297         op2              ssa.Op
2298         intermediateType types.Kind
2299 }
2300
2301 var fpConvOpToSSA = map[twoTypes]twoOpsAndType{
2302
2303         {types.TINT8, types.TFLOAT32}:  {ssa.OpSignExt8to32, ssa.OpCvt32to32F, types.TINT32},
2304         {types.TINT16, types.TFLOAT32}: {ssa.OpSignExt16to32, ssa.OpCvt32to32F, types.TINT32},
2305         {types.TINT32, types.TFLOAT32}: {ssa.OpCopy, ssa.OpCvt32to32F, types.TINT32},
2306         {types.TINT64, types.TFLOAT32}: {ssa.OpCopy, ssa.OpCvt64to32F, types.TINT64},
2307
2308         {types.TINT8, types.TFLOAT64}:  {ssa.OpSignExt8to32, ssa.OpCvt32to64F, types.TINT32},
2309         {types.TINT16, types.TFLOAT64}: {ssa.OpSignExt16to32, ssa.OpCvt32to64F, types.TINT32},
2310         {types.TINT32, types.TFLOAT64}: {ssa.OpCopy, ssa.OpCvt32to64F, types.TINT32},
2311         {types.TINT64, types.TFLOAT64}: {ssa.OpCopy, ssa.OpCvt64to64F, types.TINT64},
2312
2313         {types.TFLOAT32, types.TINT8}:  {ssa.OpCvt32Fto32, ssa.OpTrunc32to8, types.TINT32},
2314         {types.TFLOAT32, types.TINT16}: {ssa.OpCvt32Fto32, ssa.OpTrunc32to16, types.TINT32},
2315         {types.TFLOAT32, types.TINT32}: {ssa.OpCvt32Fto32, ssa.OpCopy, types.TINT32},
2316         {types.TFLOAT32, types.TINT64}: {ssa.OpCvt32Fto64, ssa.OpCopy, types.TINT64},
2317
2318         {types.TFLOAT64, types.TINT8}:  {ssa.OpCvt64Fto32, ssa.OpTrunc32to8, types.TINT32},
2319         {types.TFLOAT64, types.TINT16}: {ssa.OpCvt64Fto32, ssa.OpTrunc32to16, types.TINT32},
2320         {types.TFLOAT64, types.TINT32}: {ssa.OpCvt64Fto32, ssa.OpCopy, types.TINT32},
2321         {types.TFLOAT64, types.TINT64}: {ssa.OpCvt64Fto64, ssa.OpCopy, types.TINT64},
2322         // unsigned
2323         {types.TUINT8, types.TFLOAT32}:  {ssa.OpZeroExt8to32, ssa.OpCvt32to32F, types.TINT32},
2324         {types.TUINT16, types.TFLOAT32}: {ssa.OpZeroExt16to32, ssa.OpCvt32to32F, types.TINT32},
2325         {types.TUINT32, types.TFLOAT32}: {ssa.OpZeroExt32to64, ssa.OpCvt64to32F, types.TINT64}, // go wide to dodge unsigned
2326         {types.TUINT64, types.TFLOAT32}: {ssa.OpCopy, ssa.OpInvalid, types.TUINT64},            // Cvt64Uto32F, branchy code expansion instead
2327
2328         {types.TUINT8, types.TFLOAT64}:  {ssa.OpZeroExt8to32, ssa.OpCvt32to64F, types.TINT32},
2329         {types.TUINT16, types.TFLOAT64}: {ssa.OpZeroExt16to32, ssa.OpCvt32to64F, types.TINT32},
2330         {types.TUINT32, types.TFLOAT64}: {ssa.OpZeroExt32to64, ssa.OpCvt64to64F, types.TINT64}, // go wide to dodge unsigned
2331         {types.TUINT64, types.TFLOAT64}: {ssa.OpCopy, ssa.OpInvalid, types.TUINT64},            // Cvt64Uto64F, branchy code expansion instead
2332
2333         {types.TFLOAT32, types.TUINT8}:  {ssa.OpCvt32Fto32, ssa.OpTrunc32to8, types.TINT32},
2334         {types.TFLOAT32, types.TUINT16}: {ssa.OpCvt32Fto32, ssa.OpTrunc32to16, types.TINT32},
2335         {types.TFLOAT32, types.TUINT32}: {ssa.OpCvt32Fto64, ssa.OpTrunc64to32, types.TINT64}, // go wide to dodge unsigned
2336         {types.TFLOAT32, types.TUINT64}: {ssa.OpInvalid, ssa.OpCopy, types.TUINT64},          // Cvt32Fto64U, branchy code expansion instead
2337
2338         {types.TFLOAT64, types.TUINT8}:  {ssa.OpCvt64Fto32, ssa.OpTrunc32to8, types.TINT32},
2339         {types.TFLOAT64, types.TUINT16}: {ssa.OpCvt64Fto32, ssa.OpTrunc32to16, types.TINT32},
2340         {types.TFLOAT64, types.TUINT32}: {ssa.OpCvt64Fto64, ssa.OpTrunc64to32, types.TINT64}, // go wide to dodge unsigned
2341         {types.TFLOAT64, types.TUINT64}: {ssa.OpInvalid, ssa.OpCopy, types.TUINT64},          // Cvt64Fto64U, branchy code expansion instead
2342
2343         // float
2344         {types.TFLOAT64, types.TFLOAT32}: {ssa.OpCvt64Fto32F, ssa.OpCopy, types.TFLOAT32},
2345         {types.TFLOAT64, types.TFLOAT64}: {ssa.OpRound64F, ssa.OpCopy, types.TFLOAT64},
2346         {types.TFLOAT32, types.TFLOAT32}: {ssa.OpRound32F, ssa.OpCopy, types.TFLOAT32},
2347         {types.TFLOAT32, types.TFLOAT64}: {ssa.OpCvt32Fto64F, ssa.OpCopy, types.TFLOAT64},
2348 }
2349
2350 // this map is used only for 32-bit arch, and only includes the difference
2351 // on 32-bit arch, don't use int64<->float conversion for uint32
2352 var fpConvOpToSSA32 = map[twoTypes]twoOpsAndType{
2353         {types.TUINT32, types.TFLOAT32}: {ssa.OpCopy, ssa.OpCvt32Uto32F, types.TUINT32},
2354         {types.TUINT32, types.TFLOAT64}: {ssa.OpCopy, ssa.OpCvt32Uto64F, types.TUINT32},
2355         {types.TFLOAT32, types.TUINT32}: {ssa.OpCvt32Fto32U, ssa.OpCopy, types.TUINT32},
2356         {types.TFLOAT64, types.TUINT32}: {ssa.OpCvt64Fto32U, ssa.OpCopy, types.TUINT32},
2357 }
2358
2359 // uint64<->float conversions, only on machines that have instructions for that
2360 var uint64fpConvOpToSSA = map[twoTypes]twoOpsAndType{
2361         {types.TUINT64, types.TFLOAT32}: {ssa.OpCopy, ssa.OpCvt64Uto32F, types.TUINT64},
2362         {types.TUINT64, types.TFLOAT64}: {ssa.OpCopy, ssa.OpCvt64Uto64F, types.TUINT64},
2363         {types.TFLOAT32, types.TUINT64}: {ssa.OpCvt32Fto64U, ssa.OpCopy, types.TUINT64},
2364         {types.TFLOAT64, types.TUINT64}: {ssa.OpCvt64Fto64U, ssa.OpCopy, types.TUINT64},
2365 }
2366
2367 var shiftOpToSSA = map[opAndTwoTypes]ssa.Op{
2368         {ir.OLSH, types.TINT8, types.TUINT8}:   ssa.OpLsh8x8,
2369         {ir.OLSH, types.TUINT8, types.TUINT8}:  ssa.OpLsh8x8,
2370         {ir.OLSH, types.TINT8, types.TUINT16}:  ssa.OpLsh8x16,
2371         {ir.OLSH, types.TUINT8, types.TUINT16}: ssa.OpLsh8x16,
2372         {ir.OLSH, types.TINT8, types.TUINT32}:  ssa.OpLsh8x32,
2373         {ir.OLSH, types.TUINT8, types.TUINT32}: ssa.OpLsh8x32,
2374         {ir.OLSH, types.TINT8, types.TUINT64}:  ssa.OpLsh8x64,
2375         {ir.OLSH, types.TUINT8, types.TUINT64}: ssa.OpLsh8x64,
2376
2377         {ir.OLSH, types.TINT16, types.TUINT8}:   ssa.OpLsh16x8,
2378         {ir.OLSH, types.TUINT16, types.TUINT8}:  ssa.OpLsh16x8,
2379         {ir.OLSH, types.TINT16, types.TUINT16}:  ssa.OpLsh16x16,
2380         {ir.OLSH, types.TUINT16, types.TUINT16}: ssa.OpLsh16x16,
2381         {ir.OLSH, types.TINT16, types.TUINT32}:  ssa.OpLsh16x32,
2382         {ir.OLSH, types.TUINT16, types.TUINT32}: ssa.OpLsh16x32,
2383         {ir.OLSH, types.TINT16, types.TUINT64}:  ssa.OpLsh16x64,
2384         {ir.OLSH, types.TUINT16, types.TUINT64}: ssa.OpLsh16x64,
2385
2386         {ir.OLSH, types.TINT32, types.TUINT8}:   ssa.OpLsh32x8,
2387         {ir.OLSH, types.TUINT32, types.TUINT8}:  ssa.OpLsh32x8,
2388         {ir.OLSH, types.TINT32, types.TUINT16}:  ssa.OpLsh32x16,
2389         {ir.OLSH, types.TUINT32, types.TUINT16}: ssa.OpLsh32x16,
2390         {ir.OLSH, types.TINT32, types.TUINT32}:  ssa.OpLsh32x32,
2391         {ir.OLSH, types.TUINT32, types.TUINT32}: ssa.OpLsh32x32,
2392         {ir.OLSH, types.TINT32, types.TUINT64}:  ssa.OpLsh32x64,
2393         {ir.OLSH, types.TUINT32, types.TUINT64}: ssa.OpLsh32x64,
2394
2395         {ir.OLSH, types.TINT64, types.TUINT8}:   ssa.OpLsh64x8,
2396         {ir.OLSH, types.TUINT64, types.TUINT8}:  ssa.OpLsh64x8,
2397         {ir.OLSH, types.TINT64, types.TUINT16}:  ssa.OpLsh64x16,
2398         {ir.OLSH, types.TUINT64, types.TUINT16}: ssa.OpLsh64x16,
2399         {ir.OLSH, types.TINT64, types.TUINT32}:  ssa.OpLsh64x32,
2400         {ir.OLSH, types.TUINT64, types.TUINT32}: ssa.OpLsh64x32,
2401         {ir.OLSH, types.TINT64, types.TUINT64}:  ssa.OpLsh64x64,
2402         {ir.OLSH, types.TUINT64, types.TUINT64}: ssa.OpLsh64x64,
2403
2404         {ir.ORSH, types.TINT8, types.TUINT8}:   ssa.OpRsh8x8,
2405         {ir.ORSH, types.TUINT8, types.TUINT8}:  ssa.OpRsh8Ux8,
2406         {ir.ORSH, types.TINT8, types.TUINT16}:  ssa.OpRsh8x16,
2407         {ir.ORSH, types.TUINT8, types.TUINT16}: ssa.OpRsh8Ux16,
2408         {ir.ORSH, types.TINT8, types.TUINT32}:  ssa.OpRsh8x32,
2409         {ir.ORSH, types.TUINT8, types.TUINT32}: ssa.OpRsh8Ux32,
2410         {ir.ORSH, types.TINT8, types.TUINT64}:  ssa.OpRsh8x64,
2411         {ir.ORSH, types.TUINT8, types.TUINT64}: ssa.OpRsh8Ux64,
2412
2413         {ir.ORSH, types.TINT16, types.TUINT8}:   ssa.OpRsh16x8,
2414         {ir.ORSH, types.TUINT16, types.TUINT8}:  ssa.OpRsh16Ux8,
2415         {ir.ORSH, types.TINT16, types.TUINT16}:  ssa.OpRsh16x16,
2416         {ir.ORSH, types.TUINT16, types.TUINT16}: ssa.OpRsh16Ux16,
2417         {ir.ORSH, types.TINT16, types.TUINT32}:  ssa.OpRsh16x32,
2418         {ir.ORSH, types.TUINT16, types.TUINT32}: ssa.OpRsh16Ux32,
2419         {ir.ORSH, types.TINT16, types.TUINT64}:  ssa.OpRsh16x64,
2420         {ir.ORSH, types.TUINT16, types.TUINT64}: ssa.OpRsh16Ux64,
2421
2422         {ir.ORSH, types.TINT32, types.TUINT8}:   ssa.OpRsh32x8,
2423         {ir.ORSH, types.TUINT32, types.TUINT8}:  ssa.OpRsh32Ux8,
2424         {ir.ORSH, types.TINT32, types.TUINT16}:  ssa.OpRsh32x16,
2425         {ir.ORSH, types.TUINT32, types.TUINT16}: ssa.OpRsh32Ux16,
2426         {ir.ORSH, types.TINT32, types.TUINT32}:  ssa.OpRsh32x32,
2427         {ir.ORSH, types.TUINT32, types.TUINT32}: ssa.OpRsh32Ux32,
2428         {ir.ORSH, types.TINT32, types.TUINT64}:  ssa.OpRsh32x64,
2429         {ir.ORSH, types.TUINT32, types.TUINT64}: ssa.OpRsh32Ux64,
2430
2431         {ir.ORSH, types.TINT64, types.TUINT8}:   ssa.OpRsh64x8,
2432         {ir.ORSH, types.TUINT64, types.TUINT8}:  ssa.OpRsh64Ux8,
2433         {ir.ORSH, types.TINT64, types.TUINT16}:  ssa.OpRsh64x16,
2434         {ir.ORSH, types.TUINT64, types.TUINT16}: ssa.OpRsh64Ux16,
2435         {ir.ORSH, types.TINT64, types.TUINT32}:  ssa.OpRsh64x32,
2436         {ir.ORSH, types.TUINT64, types.TUINT32}: ssa.OpRsh64Ux32,
2437         {ir.ORSH, types.TINT64, types.TUINT64}:  ssa.OpRsh64x64,
2438         {ir.ORSH, types.TUINT64, types.TUINT64}: ssa.OpRsh64Ux64,
2439 }
2440
2441 func (s *state) ssaShiftOp(op ir.Op, t *types.Type, u *types.Type) ssa.Op {
2442         etype1 := s.concreteEtype(t)
2443         etype2 := s.concreteEtype(u)
2444         x, ok := shiftOpToSSA[opAndTwoTypes{op, etype1, etype2}]
2445         if !ok {
2446                 s.Fatalf("unhandled shift op %v etype=%s/%s", op, etype1, etype2)
2447         }
2448         return x
2449 }
2450
2451 func (s *state) uintptrConstant(v uint64) *ssa.Value {
2452         if s.config.PtrSize == 4 {
2453                 return s.newValue0I(ssa.OpConst32, types.Types[types.TUINTPTR], int64(v))
2454         }
2455         return s.newValue0I(ssa.OpConst64, types.Types[types.TUINTPTR], int64(v))
2456 }
2457
2458 func (s *state) conv(n ir.Node, v *ssa.Value, ft, tt *types.Type) *ssa.Value {
2459         if ft.IsBoolean() && tt.IsKind(types.TUINT8) {
2460                 // Bool -> uint8 is generated internally when indexing into runtime.staticbyte.
2461                 return s.newValue1(ssa.OpCvtBoolToUint8, tt, v)
2462         }
2463         if ft.IsInteger() && tt.IsInteger() {
2464                 var op ssa.Op
2465                 if tt.Size() == ft.Size() {
2466                         op = ssa.OpCopy
2467                 } else if tt.Size() < ft.Size() {
2468                         // truncation
2469                         switch 10*ft.Size() + tt.Size() {
2470                         case 21:
2471                                 op = ssa.OpTrunc16to8
2472                         case 41:
2473                                 op = ssa.OpTrunc32to8
2474                         case 42:
2475                                 op = ssa.OpTrunc32to16
2476                         case 81:
2477                                 op = ssa.OpTrunc64to8
2478                         case 82:
2479                                 op = ssa.OpTrunc64to16
2480                         case 84:
2481                                 op = ssa.OpTrunc64to32
2482                         default:
2483                                 s.Fatalf("weird integer truncation %v -> %v", ft, tt)
2484                         }
2485                 } else if ft.IsSigned() {
2486                         // sign extension
2487                         switch 10*ft.Size() + tt.Size() {
2488                         case 12:
2489                                 op = ssa.OpSignExt8to16
2490                         case 14:
2491                                 op = ssa.OpSignExt8to32
2492                         case 18:
2493                                 op = ssa.OpSignExt8to64
2494                         case 24:
2495                                 op = ssa.OpSignExt16to32
2496                         case 28:
2497                                 op = ssa.OpSignExt16to64
2498                         case 48:
2499                                 op = ssa.OpSignExt32to64
2500                         default:
2501                                 s.Fatalf("bad integer sign extension %v -> %v", ft, tt)
2502                         }
2503                 } else {
2504                         // zero extension
2505                         switch 10*ft.Size() + tt.Size() {
2506                         case 12:
2507                                 op = ssa.OpZeroExt8to16
2508                         case 14:
2509                                 op = ssa.OpZeroExt8to32
2510                         case 18:
2511                                 op = ssa.OpZeroExt8to64
2512                         case 24:
2513                                 op = ssa.OpZeroExt16to32
2514                         case 28:
2515                                 op = ssa.OpZeroExt16to64
2516                         case 48:
2517                                 op = ssa.OpZeroExt32to64
2518                         default:
2519                                 s.Fatalf("weird integer sign extension %v -> %v", ft, tt)
2520                         }
2521                 }
2522                 return s.newValue1(op, tt, v)
2523         }
2524
2525         if ft.IsComplex() && tt.IsComplex() {
2526                 var op ssa.Op
2527                 if ft.Size() == tt.Size() {
2528                         switch ft.Size() {
2529                         case 8:
2530                                 op = ssa.OpRound32F
2531                         case 16:
2532                                 op = ssa.OpRound64F
2533                         default:
2534                                 s.Fatalf("weird complex conversion %v -> %v", ft, tt)
2535                         }
2536                 } else if ft.Size() == 8 && tt.Size() == 16 {
2537                         op = ssa.OpCvt32Fto64F
2538                 } else if ft.Size() == 16 && tt.Size() == 8 {
2539                         op = ssa.OpCvt64Fto32F
2540                 } else {
2541                         s.Fatalf("weird complex conversion %v -> %v", ft, tt)
2542                 }
2543                 ftp := types.FloatForComplex(ft)
2544                 ttp := types.FloatForComplex(tt)
2545                 return s.newValue2(ssa.OpComplexMake, tt,
2546                         s.newValueOrSfCall1(op, ttp, s.newValue1(ssa.OpComplexReal, ftp, v)),
2547                         s.newValueOrSfCall1(op, ttp, s.newValue1(ssa.OpComplexImag, ftp, v)))
2548         }
2549
2550         if tt.IsComplex() { // and ft is not complex
2551                 // Needed for generics support - can't happen in normal Go code.
2552                 et := types.FloatForComplex(tt)
2553                 v = s.conv(n, v, ft, et)
2554                 return s.newValue2(ssa.OpComplexMake, tt, v, s.zeroVal(et))
2555         }
2556
2557         if ft.IsFloat() || tt.IsFloat() {
2558                 conv, ok := fpConvOpToSSA[twoTypes{s.concreteEtype(ft), s.concreteEtype(tt)}]
2559                 if s.config.RegSize == 4 && Arch.LinkArch.Family != sys.MIPS && !s.softFloat {
2560                         if conv1, ok1 := fpConvOpToSSA32[twoTypes{s.concreteEtype(ft), s.concreteEtype(tt)}]; ok1 {
2561                                 conv = conv1
2562                         }
2563                 }
2564                 if Arch.LinkArch.Family == sys.ARM64 || Arch.LinkArch.Family == sys.Wasm || Arch.LinkArch.Family == sys.S390X || s.softFloat {
2565                         if conv1, ok1 := uint64fpConvOpToSSA[twoTypes{s.concreteEtype(ft), s.concreteEtype(tt)}]; ok1 {
2566                                 conv = conv1
2567                         }
2568                 }
2569
2570                 if Arch.LinkArch.Family == sys.MIPS && !s.softFloat {
2571                         if ft.Size() == 4 && ft.IsInteger() && !ft.IsSigned() {
2572                                 // tt is float32 or float64, and ft is also unsigned
2573                                 if tt.Size() == 4 {
2574                                         return s.uint32Tofloat32(n, v, ft, tt)
2575                                 }
2576                                 if tt.Size() == 8 {
2577                                         return s.uint32Tofloat64(n, v, ft, tt)
2578                                 }
2579                         } else if tt.Size() == 4 && tt.IsInteger() && !tt.IsSigned() {
2580                                 // ft is float32 or float64, and tt is unsigned integer
2581                                 if ft.Size() == 4 {
2582                                         return s.float32ToUint32(n, v, ft, tt)
2583                                 }
2584                                 if ft.Size() == 8 {
2585                                         return s.float64ToUint32(n, v, ft, tt)
2586                                 }
2587                         }
2588                 }
2589
2590                 if !ok {
2591                         s.Fatalf("weird float conversion %v -> %v", ft, tt)
2592                 }
2593                 op1, op2, it := conv.op1, conv.op2, conv.intermediateType
2594
2595                 if op1 != ssa.OpInvalid && op2 != ssa.OpInvalid {
2596                         // normal case, not tripping over unsigned 64
2597                         if op1 == ssa.OpCopy {
2598                                 if op2 == ssa.OpCopy {
2599                                         return v
2600                                 }
2601                                 return s.newValueOrSfCall1(op2, tt, v)
2602                         }
2603                         if op2 == ssa.OpCopy {
2604                                 return s.newValueOrSfCall1(op1, tt, v)
2605                         }
2606                         return s.newValueOrSfCall1(op2, tt, s.newValueOrSfCall1(op1, types.Types[it], v))
2607                 }
2608                 // Tricky 64-bit unsigned cases.
2609                 if ft.IsInteger() {
2610                         // tt is float32 or float64, and ft is also unsigned
2611                         if tt.Size() == 4 {
2612                                 return s.uint64Tofloat32(n, v, ft, tt)
2613                         }
2614                         if tt.Size() == 8 {
2615                                 return s.uint64Tofloat64(n, v, ft, tt)
2616                         }
2617                         s.Fatalf("weird unsigned integer to float conversion %v -> %v", ft, tt)
2618                 }
2619                 // ft is float32 or float64, and tt is unsigned integer
2620                 if ft.Size() == 4 {
2621                         return s.float32ToUint64(n, v, ft, tt)
2622                 }
2623                 if ft.Size() == 8 {
2624                         return s.float64ToUint64(n, v, ft, tt)
2625                 }
2626                 s.Fatalf("weird float to unsigned integer conversion %v -> %v", ft, tt)
2627                 return nil
2628         }
2629
2630         s.Fatalf("unhandled OCONV %s -> %s", ft.Kind(), tt.Kind())
2631         return nil
2632 }
2633
2634 // expr converts the expression n to ssa, adds it to s and returns the ssa result.
2635 func (s *state) expr(n ir.Node) *ssa.Value {
2636         return s.exprCheckPtr(n, true)
2637 }
2638
2639 func (s *state) exprCheckPtr(n ir.Node, checkPtrOK bool) *ssa.Value {
2640         if ir.HasUniquePos(n) {
2641                 // ONAMEs and named OLITERALs have the line number
2642                 // of the decl, not the use. See issue 14742.
2643                 s.pushLine(n.Pos())
2644                 defer s.popLine()
2645         }
2646
2647         s.stmtList(n.Init())
2648         switch n.Op() {
2649         case ir.OBYTES2STRTMP:
2650                 n := n.(*ir.ConvExpr)
2651                 slice := s.expr(n.X)
2652                 ptr := s.newValue1(ssa.OpSlicePtr, s.f.Config.Types.BytePtr, slice)
2653                 len := s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], slice)
2654                 return s.newValue2(ssa.OpStringMake, n.Type(), ptr, len)
2655         case ir.OSTR2BYTESTMP:
2656                 n := n.(*ir.ConvExpr)
2657                 str := s.expr(n.X)
2658                 ptr := s.newValue1(ssa.OpStringPtr, s.f.Config.Types.BytePtr, str)
2659                 if !n.NonNil() {
2660                         // We need to ensure []byte("") evaluates to []byte{}, and not []byte(nil).
2661                         //
2662                         // TODO(mdempsky): Investigate using "len != 0" instead of "ptr != nil".
2663                         cond := s.newValue2(ssa.OpNeqPtr, types.Types[types.TBOOL], ptr, s.constNil(ptr.Type))
2664                         zerobase := s.newValue1A(ssa.OpAddr, ptr.Type, ir.Syms.Zerobase, s.sb)
2665                         ptr = s.ternary(cond, ptr, zerobase)
2666                 }
2667                 len := s.newValue1(ssa.OpStringLen, types.Types[types.TINT], str)
2668                 return s.newValue3(ssa.OpSliceMake, n.Type(), ptr, len, len)
2669         case ir.OCFUNC:
2670                 n := n.(*ir.UnaryExpr)
2671                 aux := n.X.(*ir.Name).Linksym()
2672                 // OCFUNC is used to build function values, which must
2673                 // always reference ABIInternal entry points.
2674                 if aux.ABI() != obj.ABIInternal {
2675                         s.Fatalf("expected ABIInternal: %v", aux.ABI())
2676                 }
2677                 return s.entryNewValue1A(ssa.OpAddr, n.Type(), aux, s.sb)
2678         case ir.ONAME:
2679                 n := n.(*ir.Name)
2680                 if n.Class == ir.PFUNC {
2681                         // "value" of a function is the address of the function's closure
2682                         sym := staticdata.FuncLinksym(n)
2683                         return s.entryNewValue1A(ssa.OpAddr, types.NewPtr(n.Type()), sym, s.sb)
2684                 }
2685                 if s.canSSA(n) {
2686                         return s.variable(n, n.Type())
2687                 }
2688                 return s.load(n.Type(), s.addr(n))
2689         case ir.OLINKSYMOFFSET:
2690                 n := n.(*ir.LinksymOffsetExpr)
2691                 return s.load(n.Type(), s.addr(n))
2692         case ir.ONIL:
2693                 n := n.(*ir.NilExpr)
2694                 t := n.Type()
2695                 switch {
2696                 case t.IsSlice():
2697                         return s.constSlice(t)
2698                 case t.IsInterface():
2699                         return s.constInterface(t)
2700                 default:
2701                         return s.constNil(t)
2702                 }
2703         case ir.OLITERAL:
2704                 switch u := n.Val(); u.Kind() {
2705                 case constant.Int:
2706                         i := ir.IntVal(n.Type(), u)
2707                         switch n.Type().Size() {
2708                         case 1:
2709                                 return s.constInt8(n.Type(), int8(i))
2710                         case 2:
2711                                 return s.constInt16(n.Type(), int16(i))
2712                         case 4:
2713                                 return s.constInt32(n.Type(), int32(i))
2714                         case 8:
2715                                 return s.constInt64(n.Type(), i)
2716                         default:
2717                                 s.Fatalf("bad integer size %d", n.Type().Size())
2718                                 return nil
2719                         }
2720                 case constant.String:
2721                         i := constant.StringVal(u)
2722                         if i == "" {
2723                                 return s.constEmptyString(n.Type())
2724                         }
2725                         return s.entryNewValue0A(ssa.OpConstString, n.Type(), ssa.StringToAux(i))
2726                 case constant.Bool:
2727                         return s.constBool(constant.BoolVal(u))
2728                 case constant.Float:
2729                         f, _ := constant.Float64Val(u)
2730                         switch n.Type().Size() {
2731                         case 4:
2732                                 return s.constFloat32(n.Type(), f)
2733                         case 8:
2734                                 return s.constFloat64(n.Type(), f)
2735                         default:
2736                                 s.Fatalf("bad float size %d", n.Type().Size())
2737                                 return nil
2738                         }
2739                 case constant.Complex:
2740                         re, _ := constant.Float64Val(constant.Real(u))
2741                         im, _ := constant.Float64Val(constant.Imag(u))
2742                         switch n.Type().Size() {
2743                         case 8:
2744                                 pt := types.Types[types.TFLOAT32]
2745                                 return s.newValue2(ssa.OpComplexMake, n.Type(),
2746                                         s.constFloat32(pt, re),
2747                                         s.constFloat32(pt, im))
2748                         case 16:
2749                                 pt := types.Types[types.TFLOAT64]
2750                                 return s.newValue2(ssa.OpComplexMake, n.Type(),
2751                                         s.constFloat64(pt, re),
2752                                         s.constFloat64(pt, im))
2753                         default:
2754                                 s.Fatalf("bad complex size %d", n.Type().Size())
2755                                 return nil
2756                         }
2757                 default:
2758                         s.Fatalf("unhandled OLITERAL %v", u.Kind())
2759                         return nil
2760                 }
2761         case ir.OCONVNOP:
2762                 n := n.(*ir.ConvExpr)
2763                 to := n.Type()
2764                 from := n.X.Type()
2765
2766                 // Assume everything will work out, so set up our return value.
2767                 // Anything interesting that happens from here is a fatal.
2768                 x := s.expr(n.X)
2769                 if to == from {
2770                         return x
2771                 }
2772
2773                 // Special case for not confusing GC and liveness.
2774                 // We don't want pointers accidentally classified
2775                 // as not-pointers or vice-versa because of copy
2776                 // elision.
2777                 if to.IsPtrShaped() != from.IsPtrShaped() {
2778                         return s.newValue2(ssa.OpConvert, to, x, s.mem())
2779                 }
2780
2781                 v := s.newValue1(ssa.OpCopy, to, x) // ensure that v has the right type
2782
2783                 // CONVNOP closure
2784                 if to.Kind() == types.TFUNC && from.IsPtrShaped() {
2785                         return v
2786                 }
2787
2788                 // named <--> unnamed type or typed <--> untyped const
2789                 if from.Kind() == to.Kind() {
2790                         return v
2791                 }
2792
2793                 // unsafe.Pointer <--> *T
2794                 if to.IsUnsafePtr() && from.IsPtrShaped() || from.IsUnsafePtr() && to.IsPtrShaped() {
2795                         if s.checkPtrEnabled && checkPtrOK && to.IsPtr() && from.IsUnsafePtr() {
2796                                 s.checkPtrAlignment(n, v, nil)
2797                         }
2798                         return v
2799                 }
2800
2801                 // map <--> *hmap
2802                 if to.Kind() == types.TMAP && from == types.NewPtr(reflectdata.MapType()) {
2803                         return v
2804                 }
2805
2806                 types.CalcSize(from)
2807                 types.CalcSize(to)
2808                 if from.Size() != to.Size() {
2809                         s.Fatalf("CONVNOP width mismatch %v (%d) -> %v (%d)\n", from, from.Size(), to, to.Size())
2810                         return nil
2811                 }
2812                 if etypesign(from.Kind()) != etypesign(to.Kind()) {
2813                         s.Fatalf("CONVNOP sign mismatch %v (%s) -> %v (%s)\n", from, from.Kind(), to, to.Kind())
2814                         return nil
2815                 }
2816
2817                 if base.Flag.Cfg.Instrumenting {
2818                         // These appear to be fine, but they fail the
2819                         // integer constraint below, so okay them here.
2820                         // Sample non-integer conversion: map[string]string -> *uint8
2821                         return v
2822                 }
2823
2824                 if etypesign(from.Kind()) == 0 {
2825                         s.Fatalf("CONVNOP unrecognized non-integer %v -> %v\n", from, to)
2826                         return nil
2827                 }
2828
2829                 // integer, same width, same sign
2830                 return v
2831
2832         case ir.OCONV:
2833                 n := n.(*ir.ConvExpr)
2834                 x := s.expr(n.X)
2835                 return s.conv(n, x, n.X.Type(), n.Type())
2836
2837         case ir.ODOTTYPE:
2838                 n := n.(*ir.TypeAssertExpr)
2839                 res, _ := s.dottype(n, false)
2840                 return res
2841
2842         case ir.ODYNAMICDOTTYPE:
2843                 n := n.(*ir.DynamicTypeAssertExpr)
2844                 res, _ := s.dynamicDottype(n, false)
2845                 return res
2846
2847         // binary ops
2848         case ir.OLT, ir.OEQ, ir.ONE, ir.OLE, ir.OGE, ir.OGT:
2849                 n := n.(*ir.BinaryExpr)
2850                 a := s.expr(n.X)
2851                 b := s.expr(n.Y)
2852                 if n.X.Type().IsComplex() {
2853                         pt := types.FloatForComplex(n.X.Type())
2854                         op := s.ssaOp(ir.OEQ, pt)
2855                         r := s.newValueOrSfCall2(op, types.Types[types.TBOOL], s.newValue1(ssa.OpComplexReal, pt, a), s.newValue1(ssa.OpComplexReal, pt, b))
2856                         i := s.newValueOrSfCall2(op, types.Types[types.TBOOL], s.newValue1(ssa.OpComplexImag, pt, a), s.newValue1(ssa.OpComplexImag, pt, b))
2857                         c := s.newValue2(ssa.OpAndB, types.Types[types.TBOOL], r, i)
2858                         switch n.Op() {
2859                         case ir.OEQ:
2860                                 return c
2861                         case ir.ONE:
2862                                 return s.newValue1(ssa.OpNot, types.Types[types.TBOOL], c)
2863                         default:
2864                                 s.Fatalf("ordered complex compare %v", n.Op())
2865                         }
2866                 }
2867
2868                 // Convert OGE and OGT into OLE and OLT.
2869                 op := n.Op()
2870                 switch op {
2871                 case ir.OGE:
2872                         op, a, b = ir.OLE, b, a
2873                 case ir.OGT:
2874                         op, a, b = ir.OLT, b, a
2875                 }
2876                 if n.X.Type().IsFloat() {
2877                         // float comparison
2878                         return s.newValueOrSfCall2(s.ssaOp(op, n.X.Type()), types.Types[types.TBOOL], a, b)
2879                 }
2880                 // integer comparison
2881                 return s.newValue2(s.ssaOp(op, n.X.Type()), types.Types[types.TBOOL], a, b)
2882         case ir.OMUL:
2883                 n := n.(*ir.BinaryExpr)
2884                 a := s.expr(n.X)
2885                 b := s.expr(n.Y)
2886                 if n.Type().IsComplex() {
2887                         mulop := ssa.OpMul64F
2888                         addop := ssa.OpAdd64F
2889                         subop := ssa.OpSub64F
2890                         pt := types.FloatForComplex(n.Type()) // Could be Float32 or Float64
2891                         wt := types.Types[types.TFLOAT64]     // Compute in Float64 to minimize cancellation error
2892
2893                         areal := s.newValue1(ssa.OpComplexReal, pt, a)
2894                         breal := s.newValue1(ssa.OpComplexReal, pt, b)
2895                         aimag := s.newValue1(ssa.OpComplexImag, pt, a)
2896                         bimag := s.newValue1(ssa.OpComplexImag, pt, b)
2897
2898                         if pt != wt { // Widen for calculation
2899                                 areal = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, areal)
2900                                 breal = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, breal)
2901                                 aimag = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, aimag)
2902                                 bimag = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, bimag)
2903                         }
2904
2905                         xreal := s.newValueOrSfCall2(subop, wt, s.newValueOrSfCall2(mulop, wt, areal, breal), s.newValueOrSfCall2(mulop, wt, aimag, bimag))
2906                         ximag := s.newValueOrSfCall2(addop, wt, s.newValueOrSfCall2(mulop, wt, areal, bimag), s.newValueOrSfCall2(mulop, wt, aimag, breal))
2907
2908                         if pt != wt { // Narrow to store back
2909                                 xreal = s.newValueOrSfCall1(ssa.OpCvt64Fto32F, pt, xreal)
2910                                 ximag = s.newValueOrSfCall1(ssa.OpCvt64Fto32F, pt, ximag)
2911                         }
2912
2913                         return s.newValue2(ssa.OpComplexMake, n.Type(), xreal, ximag)
2914                 }
2915
2916                 if n.Type().IsFloat() {
2917                         return s.newValueOrSfCall2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
2918                 }
2919
2920                 return s.newValue2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
2921
2922         case ir.ODIV:
2923                 n := n.(*ir.BinaryExpr)
2924                 a := s.expr(n.X)
2925                 b := s.expr(n.Y)
2926                 if n.Type().IsComplex() {
2927                         // TODO this is not executed because the front-end substitutes a runtime call.
2928                         // That probably ought to change; with modest optimization the widen/narrow
2929                         // conversions could all be elided in larger expression trees.
2930                         mulop := ssa.OpMul64F
2931                         addop := ssa.OpAdd64F
2932                         subop := ssa.OpSub64F
2933                         divop := ssa.OpDiv64F
2934                         pt := types.FloatForComplex(n.Type()) // Could be Float32 or Float64
2935                         wt := types.Types[types.TFLOAT64]     // Compute in Float64 to minimize cancellation error
2936
2937                         areal := s.newValue1(ssa.OpComplexReal, pt, a)
2938                         breal := s.newValue1(ssa.OpComplexReal, pt, b)
2939                         aimag := s.newValue1(ssa.OpComplexImag, pt, a)
2940                         bimag := s.newValue1(ssa.OpComplexImag, pt, b)
2941
2942                         if pt != wt { // Widen for calculation
2943                                 areal = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, areal)
2944                                 breal = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, breal)
2945                                 aimag = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, aimag)
2946                                 bimag = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, bimag)
2947                         }
2948
2949                         denom := s.newValueOrSfCall2(addop, wt, s.newValueOrSfCall2(mulop, wt, breal, breal), s.newValueOrSfCall2(mulop, wt, bimag, bimag))
2950                         xreal := s.newValueOrSfCall2(addop, wt, s.newValueOrSfCall2(mulop, wt, areal, breal), s.newValueOrSfCall2(mulop, wt, aimag, bimag))
2951                         ximag := s.newValueOrSfCall2(subop, wt, s.newValueOrSfCall2(mulop, wt, aimag, breal), s.newValueOrSfCall2(mulop, wt, areal, bimag))
2952
2953                         // TODO not sure if this is best done in wide precision or narrow
2954                         // Double-rounding might be an issue.
2955                         // Note that the pre-SSA implementation does the entire calculation
2956                         // in wide format, so wide is compatible.
2957                         xreal = s.newValueOrSfCall2(divop, wt, xreal, denom)
2958                         ximag = s.newValueOrSfCall2(divop, wt, ximag, denom)
2959
2960                         if pt != wt { // Narrow to store back
2961                                 xreal = s.newValueOrSfCall1(ssa.OpCvt64Fto32F, pt, xreal)
2962                                 ximag = s.newValueOrSfCall1(ssa.OpCvt64Fto32F, pt, ximag)
2963                         }
2964                         return s.newValue2(ssa.OpComplexMake, n.Type(), xreal, ximag)
2965                 }
2966                 if n.Type().IsFloat() {
2967                         return s.newValueOrSfCall2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
2968                 }
2969                 return s.intDivide(n, a, b)
2970         case ir.OMOD:
2971                 n := n.(*ir.BinaryExpr)
2972                 a := s.expr(n.X)
2973                 b := s.expr(n.Y)
2974                 return s.intDivide(n, a, b)
2975         case ir.OADD, ir.OSUB:
2976                 n := n.(*ir.BinaryExpr)
2977                 a := s.expr(n.X)
2978                 b := s.expr(n.Y)
2979                 if n.Type().IsComplex() {
2980                         pt := types.FloatForComplex(n.Type())
2981                         op := s.ssaOp(n.Op(), pt)
2982                         return s.newValue2(ssa.OpComplexMake, n.Type(),
2983                                 s.newValueOrSfCall2(op, pt, s.newValue1(ssa.OpComplexReal, pt, a), s.newValue1(ssa.OpComplexReal, pt, b)),
2984                                 s.newValueOrSfCall2(op, pt, s.newValue1(ssa.OpComplexImag, pt, a), s.newValue1(ssa.OpComplexImag, pt, b)))
2985                 }
2986                 if n.Type().IsFloat() {
2987                         return s.newValueOrSfCall2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
2988                 }
2989                 return s.newValue2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
2990         case ir.OAND, ir.OOR, ir.OXOR:
2991                 n := n.(*ir.BinaryExpr)
2992                 a := s.expr(n.X)
2993                 b := s.expr(n.Y)
2994                 return s.newValue2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
2995         case ir.OANDNOT:
2996                 n := n.(*ir.BinaryExpr)
2997                 a := s.expr(n.X)
2998                 b := s.expr(n.Y)
2999                 b = s.newValue1(s.ssaOp(ir.OBITNOT, b.Type), b.Type, b)
3000                 return s.newValue2(s.ssaOp(ir.OAND, n.Type()), a.Type, a, b)
3001         case ir.OLSH, ir.ORSH:
3002                 n := n.(*ir.BinaryExpr)
3003                 a := s.expr(n.X)
3004                 b := s.expr(n.Y)
3005                 bt := b.Type
3006                 if bt.IsSigned() {
3007                         cmp := s.newValue2(s.ssaOp(ir.OLE, bt), types.Types[types.TBOOL], s.zeroVal(bt), b)
3008                         s.check(cmp, ir.Syms.Panicshift)
3009                         bt = bt.ToUnsigned()
3010                 }
3011                 return s.newValue2(s.ssaShiftOp(n.Op(), n.Type(), bt), a.Type, a, b)
3012         case ir.OANDAND, ir.OOROR:
3013                 // To implement OANDAND (and OOROR), we introduce a
3014                 // new temporary variable to hold the result. The
3015                 // variable is associated with the OANDAND node in the
3016                 // s.vars table (normally variables are only
3017                 // associated with ONAME nodes). We convert
3018                 //     A && B
3019                 // to
3020                 //     var = A
3021                 //     if var {
3022                 //         var = B
3023                 //     }
3024                 // Using var in the subsequent block introduces the
3025                 // necessary phi variable.
3026                 n := n.(*ir.LogicalExpr)
3027                 el := s.expr(n.X)
3028                 s.vars[n] = el
3029
3030                 b := s.endBlock()
3031                 b.Kind = ssa.BlockIf
3032                 b.SetControl(el)
3033                 // In theory, we should set b.Likely here based on context.
3034                 // However, gc only gives us likeliness hints
3035                 // in a single place, for plain OIF statements,
3036                 // and passing around context is finnicky, so don't bother for now.
3037
3038                 bRight := s.f.NewBlock(ssa.BlockPlain)
3039                 bResult := s.f.NewBlock(ssa.BlockPlain)
3040                 if n.Op() == ir.OANDAND {
3041                         b.AddEdgeTo(bRight)
3042                         b.AddEdgeTo(bResult)
3043                 } else if n.Op() == ir.OOROR {
3044                         b.AddEdgeTo(bResult)
3045                         b.AddEdgeTo(bRight)
3046                 }
3047
3048                 s.startBlock(bRight)
3049                 er := s.expr(n.Y)
3050                 s.vars[n] = er
3051
3052                 b = s.endBlock()
3053                 b.AddEdgeTo(bResult)
3054
3055                 s.startBlock(bResult)
3056                 return s.variable(n, types.Types[types.TBOOL])
3057         case ir.OCOMPLEX:
3058                 n := n.(*ir.BinaryExpr)
3059                 r := s.expr(n.X)
3060                 i := s.expr(n.Y)
3061                 return s.newValue2(ssa.OpComplexMake, n.Type(), r, i)
3062
3063         // unary ops
3064         case ir.ONEG:
3065                 n := n.(*ir.UnaryExpr)
3066                 a := s.expr(n.X)
3067                 if n.Type().IsComplex() {
3068                         tp := types.FloatForComplex(n.Type())
3069                         negop := s.ssaOp(n.Op(), tp)
3070                         return s.newValue2(ssa.OpComplexMake, n.Type(),
3071                                 s.newValue1(negop, tp, s.newValue1(ssa.OpComplexReal, tp, a)),
3072                                 s.newValue1(negop, tp, s.newValue1(ssa.OpComplexImag, tp, a)))
3073                 }
3074                 return s.newValue1(s.ssaOp(n.Op(), n.Type()), a.Type, a)
3075         case ir.ONOT, ir.OBITNOT:
3076                 n := n.(*ir.UnaryExpr)
3077                 a := s.expr(n.X)
3078                 return s.newValue1(s.ssaOp(n.Op(), n.Type()), a.Type, a)
3079         case ir.OIMAG, ir.OREAL:
3080                 n := n.(*ir.UnaryExpr)
3081                 a := s.expr(n.X)
3082                 return s.newValue1(s.ssaOp(n.Op(), n.X.Type()), n.Type(), a)
3083         case ir.OPLUS:
3084                 n := n.(*ir.UnaryExpr)
3085                 return s.expr(n.X)
3086
3087         case ir.OADDR:
3088                 n := n.(*ir.AddrExpr)
3089                 return s.addr(n.X)
3090
3091         case ir.ORESULT:
3092                 n := n.(*ir.ResultExpr)
3093                 if s.prevCall == nil || s.prevCall.Op != ssa.OpStaticLECall && s.prevCall.Op != ssa.OpInterLECall && s.prevCall.Op != ssa.OpClosureLECall {
3094                         panic("Expected to see a previous call")
3095                 }
3096                 which := n.Index
3097                 if which == -1 {
3098                         panic(fmt.Errorf("ORESULT %v does not match call %s", n, s.prevCall))
3099                 }
3100                 return s.resultOfCall(s.prevCall, which, n.Type())
3101
3102         case ir.ODEREF:
3103                 n := n.(*ir.StarExpr)
3104                 p := s.exprPtr(n.X, n.Bounded(), n.Pos())
3105                 return s.load(n.Type(), p)
3106
3107         case ir.ODOT:
3108                 n := n.(*ir.SelectorExpr)
3109                 if n.X.Op() == ir.OSTRUCTLIT {
3110                         // All literals with nonzero fields have already been
3111                         // rewritten during walk. Any that remain are just T{}
3112                         // or equivalents. Use the zero value.
3113                         if !ir.IsZero(n.X) {
3114                                 s.Fatalf("literal with nonzero value in SSA: %v", n.X)
3115                         }
3116                         return s.zeroVal(n.Type())
3117                 }
3118                 // If n is addressable and can't be represented in
3119                 // SSA, then load just the selected field. This
3120                 // prevents false memory dependencies in race/msan/asan
3121                 // instrumentation.
3122                 if ir.IsAddressable(n) && !s.canSSA(n) {
3123                         p := s.addr(n)
3124                         return s.load(n.Type(), p)
3125                 }
3126                 v := s.expr(n.X)
3127                 return s.newValue1I(ssa.OpStructSelect, n.Type(), int64(fieldIdx(n)), v)
3128
3129         case ir.ODOTPTR:
3130                 n := n.(*ir.SelectorExpr)
3131                 p := s.exprPtr(n.X, n.Bounded(), n.Pos())
3132                 p = s.newValue1I(ssa.OpOffPtr, types.NewPtr(n.Type()), n.Offset(), p)
3133                 return s.load(n.Type(), p)
3134
3135         case ir.OINDEX:
3136                 n := n.(*ir.IndexExpr)
3137                 switch {
3138                 case n.X.Type().IsString():
3139                         if n.Bounded() && ir.IsConst(n.X, constant.String) && ir.IsConst(n.Index, constant.Int) {
3140                                 // Replace "abc"[1] with 'b'.
3141                                 // Delayed until now because "abc"[1] is not an ideal constant.
3142                                 // See test/fixedbugs/issue11370.go.
3143                                 return s.newValue0I(ssa.OpConst8, types.Types[types.TUINT8], int64(int8(ir.StringVal(n.X)[ir.Int64Val(n.Index)])))
3144                         }
3145                         a := s.expr(n.X)
3146                         i := s.expr(n.Index)
3147                         len := s.newValue1(ssa.OpStringLen, types.Types[types.TINT], a)
3148                         i = s.boundsCheck(i, len, ssa.BoundsIndex, n.Bounded())
3149                         ptrtyp := s.f.Config.Types.BytePtr
3150                         ptr := s.newValue1(ssa.OpStringPtr, ptrtyp, a)
3151                         if ir.IsConst(n.Index, constant.Int) {
3152                                 ptr = s.newValue1I(ssa.OpOffPtr, ptrtyp, ir.Int64Val(n.Index), ptr)
3153                         } else {
3154                                 ptr = s.newValue2(ssa.OpAddPtr, ptrtyp, ptr, i)
3155                         }
3156                         return s.load(types.Types[types.TUINT8], ptr)
3157                 case n.X.Type().IsSlice():
3158                         p := s.addr(n)
3159                         return s.load(n.X.Type().Elem(), p)
3160                 case n.X.Type().IsArray():
3161                         if ssa.CanSSA(n.X.Type()) {
3162                                 // SSA can handle arrays of length at most 1.
3163                                 bound := n.X.Type().NumElem()
3164                                 a := s.expr(n.X)
3165                                 i := s.expr(n.Index)
3166                                 if bound == 0 {
3167                                         // Bounds check will never succeed.  Might as well
3168                                         // use constants for the bounds check.
3169                                         z := s.constInt(types.Types[types.TINT], 0)
3170                                         s.boundsCheck(z, z, ssa.BoundsIndex, false)
3171                                         // The return value won't be live, return junk.
3172                                         // But not quite junk, in case bounds checks are turned off. See issue 48092.
3173                                         return s.zeroVal(n.Type())
3174                                 }
3175                                 len := s.constInt(types.Types[types.TINT], bound)
3176                                 s.boundsCheck(i, len, ssa.BoundsIndex, n.Bounded()) // checks i == 0
3177                                 return s.newValue1I(ssa.OpArraySelect, n.Type(), 0, a)
3178                         }
3179                         p := s.addr(n)
3180                         return s.load(n.X.Type().Elem(), p)
3181                 default:
3182                         s.Fatalf("bad type for index %v", n.X.Type())
3183                         return nil
3184                 }
3185
3186         case ir.OLEN, ir.OCAP:
3187                 n := n.(*ir.UnaryExpr)
3188                 switch {
3189                 case n.X.Type().IsSlice():
3190                         op := ssa.OpSliceLen
3191                         if n.Op() == ir.OCAP {
3192                                 op = ssa.OpSliceCap
3193                         }
3194                         return s.newValue1(op, types.Types[types.TINT], s.expr(n.X))
3195                 case n.X.Type().IsString(): // string; not reachable for OCAP
3196                         return s.newValue1(ssa.OpStringLen, types.Types[types.TINT], s.expr(n.X))
3197                 case n.X.Type().IsMap(), n.X.Type().IsChan():
3198                         return s.referenceTypeBuiltin(n, s.expr(n.X))
3199                 default: // array
3200                         return s.constInt(types.Types[types.TINT], n.X.Type().NumElem())
3201                 }
3202
3203         case ir.OSPTR:
3204                 n := n.(*ir.UnaryExpr)
3205                 a := s.expr(n.X)
3206                 if n.X.Type().IsSlice() {
3207                         if n.Bounded() {
3208                                 return s.newValue1(ssa.OpSlicePtr, n.Type(), a)
3209                         }
3210                         return s.newValue1(ssa.OpSlicePtrUnchecked, n.Type(), a)
3211                 } else {
3212                         return s.newValue1(ssa.OpStringPtr, n.Type(), a)
3213                 }
3214
3215         case ir.OITAB:
3216                 n := n.(*ir.UnaryExpr)
3217                 a := s.expr(n.X)
3218                 return s.newValue1(ssa.OpITab, n.Type(), a)
3219
3220         case ir.OIDATA:
3221                 n := n.(*ir.UnaryExpr)
3222                 a := s.expr(n.X)
3223                 return s.newValue1(ssa.OpIData, n.Type(), a)
3224
3225         case ir.OMAKEFACE:
3226                 n := n.(*ir.BinaryExpr)
3227                 tab := s.expr(n.X)
3228                 data := s.expr(n.Y)
3229                 return s.newValue2(ssa.OpIMake, n.Type(), tab, data)
3230
3231         case ir.OSLICEHEADER:
3232                 n := n.(*ir.SliceHeaderExpr)
3233                 p := s.expr(n.Ptr)
3234                 l := s.expr(n.Len)
3235                 c := s.expr(n.Cap)
3236                 return s.newValue3(ssa.OpSliceMake, n.Type(), p, l, c)
3237
3238         case ir.OSTRINGHEADER:
3239                 n := n.(*ir.StringHeaderExpr)
3240                 p := s.expr(n.Ptr)
3241                 l := s.expr(n.Len)
3242                 return s.newValue2(ssa.OpStringMake, n.Type(), p, l)
3243
3244         case ir.OSLICE, ir.OSLICEARR, ir.OSLICE3, ir.OSLICE3ARR:
3245                 n := n.(*ir.SliceExpr)
3246                 check := s.checkPtrEnabled && n.Op() == ir.OSLICE3ARR && n.X.Op() == ir.OCONVNOP && n.X.(*ir.ConvExpr).X.Type().IsUnsafePtr()
3247                 v := s.exprCheckPtr(n.X, !check)
3248                 var i, j, k *ssa.Value
3249                 if n.Low != nil {
3250                         i = s.expr(n.Low)
3251                 }
3252                 if n.High != nil {
3253                         j = s.expr(n.High)
3254                 }
3255                 if n.Max != nil {
3256                         k = s.expr(n.Max)
3257                 }
3258                 p, l, c := s.slice(v, i, j, k, n.Bounded())
3259                 if check {
3260                         // Emit checkptr instrumentation after bound check to prevent false positive, see #46938.
3261                         s.checkPtrAlignment(n.X.(*ir.ConvExpr), v, s.conv(n.Max, k, k.Type, types.Types[types.TUINTPTR]))
3262                 }
3263                 return s.newValue3(ssa.OpSliceMake, n.Type(), p, l, c)
3264
3265         case ir.OSLICESTR:
3266                 n := n.(*ir.SliceExpr)
3267                 v := s.expr(n.X)
3268                 var i, j *ssa.Value
3269                 if n.Low != nil {
3270                         i = s.expr(n.Low)
3271                 }
3272                 if n.High != nil {
3273                         j = s.expr(n.High)
3274                 }
3275                 p, l, _ := s.slice(v, i, j, nil, n.Bounded())
3276                 return s.newValue2(ssa.OpStringMake, n.Type(), p, l)
3277
3278         case ir.OSLICE2ARRPTR:
3279                 // if arrlen > slice.len {
3280                 //   panic(...)
3281                 // }
3282                 // slice.ptr
3283                 n := n.(*ir.ConvExpr)
3284                 v := s.expr(n.X)
3285                 nelem := n.Type().Elem().NumElem()
3286                 arrlen := s.constInt(types.Types[types.TINT], nelem)
3287                 cap := s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], v)
3288                 s.boundsCheck(arrlen, cap, ssa.BoundsConvert, false)
3289                 op := ssa.OpSlicePtr
3290                 if nelem == 0 {
3291                         op = ssa.OpSlicePtrUnchecked
3292                 }
3293                 return s.newValue1(op, n.Type(), v)
3294
3295         case ir.OCALLFUNC:
3296                 n := n.(*ir.CallExpr)
3297                 if ir.IsIntrinsicCall(n) {
3298                         return s.intrinsicCall(n)
3299                 }
3300                 fallthrough
3301
3302         case ir.OCALLINTER:
3303                 n := n.(*ir.CallExpr)
3304                 return s.callResult(n, callNormal)
3305
3306         case ir.OGETG:
3307                 n := n.(*ir.CallExpr)
3308                 return s.newValue1(ssa.OpGetG, n.Type(), s.mem())
3309
3310         case ir.OGETCALLERPC:
3311                 n := n.(*ir.CallExpr)
3312                 return s.newValue0(ssa.OpGetCallerPC, n.Type())
3313
3314         case ir.OGETCALLERSP:
3315                 n := n.(*ir.CallExpr)
3316                 return s.newValue1(ssa.OpGetCallerSP, n.Type(), s.mem())
3317
3318         case ir.OAPPEND:
3319                 return s.append(n.(*ir.CallExpr), false)
3320
3321         case ir.OMIN, ir.OMAX:
3322                 return s.minMax(n.(*ir.CallExpr))
3323
3324         case ir.OSTRUCTLIT, ir.OARRAYLIT:
3325                 // All literals with nonzero fields have already been
3326                 // rewritten during walk. Any that remain are just T{}
3327                 // or equivalents. Use the zero value.
3328                 n := n.(*ir.CompLitExpr)
3329                 if !ir.IsZero(n) {
3330                         s.Fatalf("literal with nonzero value in SSA: %v", n)
3331                 }
3332                 return s.zeroVal(n.Type())
3333
3334         case ir.ONEW:
3335                 n := n.(*ir.UnaryExpr)
3336                 var rtype *ssa.Value
3337                 if x, ok := n.X.(*ir.DynamicType); ok && x.Op() == ir.ODYNAMICTYPE {
3338                         rtype = s.expr(x.RType)
3339                 }
3340                 return s.newObject(n.Type().Elem(), rtype)
3341
3342         case ir.OUNSAFEADD:
3343                 n := n.(*ir.BinaryExpr)
3344                 ptr := s.expr(n.X)
3345                 len := s.expr(n.Y)
3346
3347                 // Force len to uintptr to prevent misuse of garbage bits in the
3348                 // upper part of the register (#48536).
3349                 len = s.conv(n, len, len.Type, types.Types[types.TUINTPTR])
3350
3351                 return s.newValue2(ssa.OpAddPtr, n.Type(), ptr, len)
3352
3353         default:
3354                 s.Fatalf("unhandled expr %v", n.Op())
3355                 return nil
3356         }
3357 }
3358
3359 func (s *state) resultOfCall(c *ssa.Value, which int64, t *types.Type) *ssa.Value {
3360         aux := c.Aux.(*ssa.AuxCall)
3361         pa := aux.ParamAssignmentForResult(which)
3362         // TODO(register args) determine if in-memory TypeOK is better loaded early from SelectNAddr or later when SelectN is expanded.
3363         // SelectN is better for pattern-matching and possible call-aware analysis we might want to do in the future.
3364         if len(pa.Registers) == 0 && !ssa.CanSSA(t) {
3365                 addr := s.newValue1I(ssa.OpSelectNAddr, types.NewPtr(t), which, c)
3366                 return s.rawLoad(t, addr)
3367         }
3368         return s.newValue1I(ssa.OpSelectN, t, which, c)
3369 }
3370
3371 func (s *state) resultAddrOfCall(c *ssa.Value, which int64, t *types.Type) *ssa.Value {
3372         aux := c.Aux.(*ssa.AuxCall)
3373         pa := aux.ParamAssignmentForResult(which)
3374         if len(pa.Registers) == 0 {
3375                 return s.newValue1I(ssa.OpSelectNAddr, types.NewPtr(t), which, c)
3376         }
3377         _, addr := s.temp(c.Pos, t)
3378         rval := s.newValue1I(ssa.OpSelectN, t, which, c)
3379         s.vars[memVar] = s.newValue3Apos(ssa.OpStore, types.TypeMem, t, addr, rval, s.mem(), false)
3380         return addr
3381 }
3382
3383 // append converts an OAPPEND node to SSA.
3384 // If inplace is false, it converts the OAPPEND expression n to an ssa.Value,
3385 // adds it to s, and returns the Value.
3386 // If inplace is true, it writes the result of the OAPPEND expression n
3387 // back to the slice being appended to, and returns nil.
3388 // inplace MUST be set to false if the slice can be SSA'd.
3389 // Note: this code only handles fixed-count appends. Dotdotdot appends
3390 // have already been rewritten at this point (by walk).
3391 func (s *state) append(n *ir.CallExpr, inplace bool) *ssa.Value {
3392         // If inplace is false, process as expression "append(s, e1, e2, e3)":
3393         //
3394         // ptr, len, cap := s
3395         // len += 3
3396         // if uint(len) > uint(cap) {
3397         //     ptr, len, cap = growslice(ptr, len, cap, 3, typ)
3398         //     Note that len is unmodified by growslice.
3399         // }
3400         // // with write barriers, if needed:
3401         // *(ptr+(len-3)) = e1
3402         // *(ptr+(len-2)) = e2
3403         // *(ptr+(len-1)) = e3
3404         // return makeslice(ptr, len, cap)
3405         //
3406         //
3407         // If inplace is true, process as statement "s = append(s, e1, e2, e3)":
3408         //
3409         // a := &s
3410         // ptr, len, cap := s
3411         // len += 3
3412         // if uint(len) > uint(cap) {
3413         //    ptr, len, cap = growslice(ptr, len, cap, 3, typ)
3414         //    vardef(a)    // if necessary, advise liveness we are writing a new a
3415         //    *a.cap = cap // write before ptr to avoid a spill
3416         //    *a.ptr = ptr // with write barrier
3417         // }
3418         // *a.len = len
3419         // // with write barriers, if needed:
3420         // *(ptr+(len-3)) = e1
3421         // *(ptr+(len-2)) = e2
3422         // *(ptr+(len-1)) = e3
3423
3424         et := n.Type().Elem()
3425         pt := types.NewPtr(et)
3426
3427         // Evaluate slice
3428         sn := n.Args[0] // the slice node is the first in the list
3429         var slice, addr *ssa.Value
3430         if inplace {
3431                 addr = s.addr(sn)
3432                 slice = s.load(n.Type(), addr)
3433         } else {
3434                 slice = s.expr(sn)
3435         }
3436
3437         // Allocate new blocks
3438         grow := s.f.NewBlock(ssa.BlockPlain)
3439         assign := s.f.NewBlock(ssa.BlockPlain)
3440
3441         // Decomposse input slice.
3442         p := s.newValue1(ssa.OpSlicePtr, pt, slice)
3443         l := s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], slice)
3444         c := s.newValue1(ssa.OpSliceCap, types.Types[types.TINT], slice)
3445
3446         // Add number of new elements to length.
3447         nargs := s.constInt(types.Types[types.TINT], int64(len(n.Args)-1))
3448         l = s.newValue2(s.ssaOp(ir.OADD, types.Types[types.TINT]), types.Types[types.TINT], l, nargs)
3449
3450         // Decide if we need to grow
3451         cmp := s.newValue2(s.ssaOp(ir.OLT, types.Types[types.TUINT]), types.Types[types.TBOOL], c, l)
3452
3453         // Record values of ptr/len/cap before branch.
3454         s.vars[ptrVar] = p
3455         s.vars[lenVar] = l
3456         if !inplace {
3457                 s.vars[capVar] = c
3458         }
3459
3460         b := s.endBlock()
3461         b.Kind = ssa.BlockIf
3462         b.Likely = ssa.BranchUnlikely
3463         b.SetControl(cmp)
3464         b.AddEdgeTo(grow)
3465         b.AddEdgeTo(assign)
3466
3467         // Call growslice
3468         s.startBlock(grow)
3469         taddr := s.expr(n.X)
3470         r := s.rtcall(ir.Syms.Growslice, true, []*types.Type{n.Type()}, p, l, c, nargs, taddr)
3471
3472         // Decompose output slice
3473         p = s.newValue1(ssa.OpSlicePtr, pt, r[0])
3474         l = s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], r[0])
3475         c = s.newValue1(ssa.OpSliceCap, types.Types[types.TINT], r[0])
3476
3477         s.vars[ptrVar] = p
3478         s.vars[lenVar] = l
3479         s.vars[capVar] = c
3480         if inplace {
3481                 if sn.Op() == ir.ONAME {
3482                         sn := sn.(*ir.Name)
3483                         if sn.Class != ir.PEXTERN {
3484                                 // Tell liveness we're about to build a new slice
3485                                 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, sn, s.mem())
3486                         }
3487                 }
3488                 capaddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, types.SliceCapOffset, addr)
3489                 s.store(types.Types[types.TINT], capaddr, c)
3490                 s.store(pt, addr, p)
3491         }
3492
3493         b = s.endBlock()
3494         b.AddEdgeTo(assign)
3495
3496         // assign new elements to slots
3497         s.startBlock(assign)
3498         p = s.variable(ptrVar, pt)                      // generates phi for ptr
3499         l = s.variable(lenVar, types.Types[types.TINT]) // generates phi for len
3500         if !inplace {
3501                 c = s.variable(capVar, types.Types[types.TINT]) // generates phi for cap
3502         }
3503
3504         if inplace {
3505                 // Update length in place.
3506                 // We have to wait until here to make sure growslice succeeded.
3507                 lenaddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, types.SliceLenOffset, addr)
3508                 s.store(types.Types[types.TINT], lenaddr, l)
3509         }
3510
3511         // Evaluate args
3512         type argRec struct {
3513                 // if store is true, we're appending the value v.  If false, we're appending the
3514                 // value at *v.
3515                 v     *ssa.Value
3516                 store bool
3517         }
3518         args := make([]argRec, 0, len(n.Args[1:]))
3519         for _, n := range n.Args[1:] {
3520                 if ssa.CanSSA(n.Type()) {
3521                         args = append(args, argRec{v: s.expr(n), store: true})
3522                 } else {
3523                         v := s.addr(n)
3524                         args = append(args, argRec{v: v})
3525                 }
3526         }
3527
3528         // Write args into slice.
3529         oldLen := s.newValue2(s.ssaOp(ir.OSUB, types.Types[types.TINT]), types.Types[types.TINT], l, nargs)
3530         p2 := s.newValue2(ssa.OpPtrIndex, pt, p, oldLen)
3531         for i, arg := range args {
3532                 addr := s.newValue2(ssa.OpPtrIndex, pt, p2, s.constInt(types.Types[types.TINT], int64(i)))
3533                 if arg.store {
3534                         s.storeType(et, addr, arg.v, 0, true)
3535                 } else {
3536                         s.move(et, addr, arg.v)
3537                 }
3538         }
3539
3540         // The following deletions have no practical effect at this time
3541         // because state.vars has been reset by the preceding state.startBlock.
3542         // They only enforce the fact that these variables are no longer need in
3543         // the current scope.
3544         delete(s.vars, ptrVar)
3545         delete(s.vars, lenVar)
3546         if !inplace {
3547                 delete(s.vars, capVar)
3548         }
3549
3550         // make result
3551         if inplace {
3552                 return nil
3553         }
3554         return s.newValue3(ssa.OpSliceMake, n.Type(), p, l, c)
3555 }
3556
3557 // minMax converts an OMIN/OMAX builtin call into SSA.
3558 func (s *state) minMax(n *ir.CallExpr) *ssa.Value {
3559         // The OMIN/OMAX builtin is variadic, but its semantics are
3560         // equivalent to left-folding a binary min/max operation across the
3561         // arguments list.
3562         fold := func(op func(x, a *ssa.Value) *ssa.Value) *ssa.Value {
3563                 x := s.expr(n.Args[0])
3564                 for _, arg := range n.Args[1:] {
3565                         x = op(x, s.expr(arg))
3566                 }
3567                 return x
3568         }
3569
3570         typ := n.Type()
3571
3572         if typ.IsFloat() || typ.IsString() {
3573                 // min/max semantics for floats are tricky because of NaNs and
3574                 // negative zero. Some architectures have instructions which
3575                 // we can use to generate the right result. For others we must
3576                 // call into the runtime instead.
3577                 //
3578                 // Strings are conceptually simpler, but we currently desugar
3579                 // string comparisons during walk, not ssagen.
3580
3581                 if typ.IsFloat() {
3582                         switch Arch.LinkArch.Family {
3583                         case sys.AMD64, sys.ARM64:
3584                                 var op ssa.Op
3585                                 switch {
3586                                 case typ.Kind() == types.TFLOAT64 && n.Op() == ir.OMIN:
3587                                         op = ssa.OpMin64F
3588                                 case typ.Kind() == types.TFLOAT64 && n.Op() == ir.OMAX:
3589                                         op = ssa.OpMax64F
3590                                 case typ.Kind() == types.TFLOAT32 && n.Op() == ir.OMIN:
3591                                         op = ssa.OpMin32F
3592                                 case typ.Kind() == types.TFLOAT32 && n.Op() == ir.OMAX:
3593                                         op = ssa.OpMax32F
3594                                 }
3595                                 return fold(func(x, a *ssa.Value) *ssa.Value {
3596                                         return s.newValue2(op, typ, x, a)
3597                                 })
3598                         }
3599                 }
3600                 var name string
3601                 switch typ.Kind() {
3602                 case types.TFLOAT32:
3603                         switch n.Op() {
3604                         case ir.OMIN:
3605                                 name = "fmin32"
3606                         case ir.OMAX:
3607                                 name = "fmax32"
3608                         }
3609                 case types.TFLOAT64:
3610                         switch n.Op() {
3611                         case ir.OMIN:
3612                                 name = "fmin64"
3613                         case ir.OMAX:
3614                                 name = "fmax64"
3615                         }
3616                 case types.TSTRING:
3617                         switch n.Op() {
3618                         case ir.OMIN:
3619                                 name = "strmin"
3620                         case ir.OMAX:
3621                                 name = "strmax"
3622                         }
3623                 }
3624                 fn := typecheck.LookupRuntimeFunc(name)
3625
3626                 return fold(func(x, a *ssa.Value) *ssa.Value {
3627                         return s.rtcall(fn, true, []*types.Type{typ}, x, a)[0]
3628                 })
3629         }
3630
3631         lt := s.ssaOp(ir.OLT, typ)
3632
3633         return fold(func(x, a *ssa.Value) *ssa.Value {
3634                 switch n.Op() {
3635                 case ir.OMIN:
3636                         // a < x ? a : x
3637                         return s.ternary(s.newValue2(lt, types.Types[types.TBOOL], a, x), a, x)
3638                 case ir.OMAX:
3639                         // x < a ? a : x
3640                         return s.ternary(s.newValue2(lt, types.Types[types.TBOOL], x, a), a, x)
3641                 }
3642                 panic("unreachable")
3643         })
3644 }
3645
3646 // ternary emits code to evaluate cond ? x : y.
3647 func (s *state) ternary(cond, x, y *ssa.Value) *ssa.Value {
3648         // Note that we need a new ternaryVar each time (unlike okVar where we can
3649         // reuse the variable) because it might have a different type every time.
3650         ternaryVar := ssaMarker("ternary")
3651
3652         bThen := s.f.NewBlock(ssa.BlockPlain)
3653         bElse := s.f.NewBlock(ssa.BlockPlain)
3654         bEnd := s.f.NewBlock(ssa.BlockPlain)
3655
3656         b := s.endBlock()
3657         b.Kind = ssa.BlockIf
3658         b.SetControl(cond)
3659         b.AddEdgeTo(bThen)
3660         b.AddEdgeTo(bElse)
3661
3662         s.startBlock(bThen)
3663         s.vars[ternaryVar] = x
3664         s.endBlock().AddEdgeTo(bEnd)
3665
3666         s.startBlock(bElse)
3667         s.vars[ternaryVar] = y
3668         s.endBlock().AddEdgeTo(bEnd)
3669
3670         s.startBlock(bEnd)
3671         r := s.variable(ternaryVar, x.Type)
3672         delete(s.vars, ternaryVar)
3673         return r
3674 }
3675
3676 // condBranch evaluates the boolean expression cond and branches to yes
3677 // if cond is true and no if cond is false.
3678 // This function is intended to handle && and || better than just calling
3679 // s.expr(cond) and branching on the result.
3680 func (s *state) condBranch(cond ir.Node, yes, no *ssa.Block, likely int8) {
3681         switch cond.Op() {
3682         case ir.OANDAND:
3683                 cond := cond.(*ir.LogicalExpr)
3684                 mid := s.f.NewBlock(ssa.BlockPlain)
3685                 s.stmtList(cond.Init())
3686                 s.condBranch(cond.X, mid, no, max8(likely, 0))
3687                 s.startBlock(mid)
3688                 s.condBranch(cond.Y, yes, no, likely)
3689                 return
3690                 // Note: if likely==1, then both recursive calls pass 1.
3691                 // If likely==-1, then we don't have enough information to decide
3692                 // whether the first branch is likely or not. So we pass 0 for
3693                 // the likeliness of the first branch.
3694                 // TODO: have the frontend give us branch prediction hints for
3695                 // OANDAND and OOROR nodes (if it ever has such info).
3696         case ir.OOROR:
3697                 cond := cond.(*ir.LogicalExpr)
3698                 mid := s.f.NewBlock(ssa.BlockPlain)
3699                 s.stmtList(cond.Init())
3700                 s.condBranch(cond.X, yes, mid, min8(likely, 0))
3701                 s.startBlock(mid)
3702                 s.condBranch(cond.Y, yes, no, likely)
3703                 return
3704                 // Note: if likely==-1, then both recursive calls pass -1.
3705                 // If likely==1, then we don't have enough info to decide
3706                 // the likelihood of the first branch.
3707         case ir.ONOT:
3708                 cond := cond.(*ir.UnaryExpr)
3709                 s.stmtList(cond.Init())
3710                 s.condBranch(cond.X, no, yes, -likely)
3711                 return
3712         case ir.OCONVNOP:
3713                 cond := cond.(*ir.ConvExpr)
3714                 s.stmtList(cond.Init())
3715                 s.condBranch(cond.X, yes, no, likely)
3716                 return
3717         }
3718         c := s.expr(cond)
3719         b := s.endBlock()
3720         b.Kind = ssa.BlockIf
3721         b.SetControl(c)
3722         b.Likely = ssa.BranchPrediction(likely) // gc and ssa both use -1/0/+1 for likeliness
3723         b.AddEdgeTo(yes)
3724         b.AddEdgeTo(no)
3725 }
3726
3727 type skipMask uint8
3728
3729 const (
3730         skipPtr skipMask = 1 << iota
3731         skipLen
3732         skipCap
3733 )
3734
3735 // assign does left = right.
3736 // Right has already been evaluated to ssa, left has not.
3737 // If deref is true, then we do left = *right instead (and right has already been nil-checked).
3738 // If deref is true and right == nil, just do left = 0.
3739 // skip indicates assignments (at the top level) that can be avoided.
3740 // mayOverlap indicates whether left&right might partially overlap in memory. Default is false.
3741 func (s *state) assign(left ir.Node, right *ssa.Value, deref bool, skip skipMask) {
3742         s.assignWhichMayOverlap(left, right, deref, skip, false)
3743 }
3744 func (s *state) assignWhichMayOverlap(left ir.Node, right *ssa.Value, deref bool, skip skipMask, mayOverlap bool) {
3745         if left.Op() == ir.ONAME && ir.IsBlank(left) {
3746                 return
3747         }
3748         t := left.Type()
3749         types.CalcSize(t)
3750         if s.canSSA(left) {
3751                 if deref {
3752                         s.Fatalf("can SSA LHS %v but not RHS %s", left, right)
3753                 }
3754                 if left.Op() == ir.ODOT {
3755                         // We're assigning to a field of an ssa-able value.
3756                         // We need to build a new structure with the new value for the
3757                         // field we're assigning and the old values for the other fields.
3758                         // For instance:
3759                         //   type T struct {a, b, c int}
3760                         //   var T x
3761                         //   x.b = 5
3762                         // For the x.b = 5 assignment we want to generate x = T{x.a, 5, x.c}
3763
3764                         // Grab information about the structure type.
3765                         left := left.(*ir.SelectorExpr)
3766                         t := left.X.Type()
3767                         nf := t.NumFields()
3768                         idx := fieldIdx(left)
3769
3770                         // Grab old value of structure.
3771                         old := s.expr(left.X)
3772
3773                         // Make new structure.
3774                         new := s.newValue0(ssa.StructMakeOp(t.NumFields()), t)
3775
3776                         // Add fields as args.
3777                         for i := 0; i < nf; i++ {
3778                                 if i == idx {
3779                                         new.AddArg(right)
3780                                 } else {
3781                                         new.AddArg(s.newValue1I(ssa.OpStructSelect, t.FieldType(i), int64(i), old))
3782                                 }
3783                         }
3784
3785                         // Recursively assign the new value we've made to the base of the dot op.
3786                         s.assign(left.X, new, false, 0)
3787                         // TODO: do we need to update named values here?
3788                         return
3789                 }
3790                 if left.Op() == ir.OINDEX && left.(*ir.IndexExpr).X.Type().IsArray() {
3791                         left := left.(*ir.IndexExpr)
3792                         s.pushLine(left.Pos())
3793                         defer s.popLine()
3794                         // We're assigning to an element of an ssa-able array.
3795                         // a[i] = v
3796                         t := left.X.Type()
3797                         n := t.NumElem()
3798
3799                         i := s.expr(left.Index) // index
3800                         if n == 0 {
3801                                 // The bounds check must fail.  Might as well
3802                                 // ignore the actual index and just use zeros.
3803                                 z := s.constInt(types.Types[types.TINT], 0)
3804                                 s.boundsCheck(z, z, ssa.BoundsIndex, false)
3805                                 return
3806                         }
3807                         if n != 1 {
3808                                 s.Fatalf("assigning to non-1-length array")
3809                         }
3810                         // Rewrite to a = [1]{v}
3811                         len := s.constInt(types.Types[types.TINT], 1)
3812                         s.boundsCheck(i, len, ssa.BoundsIndex, false) // checks i == 0
3813                         v := s.newValue1(ssa.OpArrayMake1, t, right)
3814                         s.assign(left.X, v, false, 0)
3815                         return
3816                 }
3817                 left := left.(*ir.Name)
3818                 // Update variable assignment.
3819                 s.vars[left] = right
3820                 s.addNamedValue(left, right)
3821                 return
3822         }
3823
3824         // If this assignment clobbers an entire local variable, then emit
3825         // OpVarDef so liveness analysis knows the variable is redefined.
3826         if base, ok := clobberBase(left).(*ir.Name); ok && base.OnStack() && skip == 0 && t.HasPointers() {
3827                 s.vars[memVar] = s.newValue1Apos(ssa.OpVarDef, types.TypeMem, base, s.mem(), !ir.IsAutoTmp(base))
3828         }
3829
3830         // Left is not ssa-able. Compute its address.
3831         addr := s.addr(left)
3832         if ir.IsReflectHeaderDataField(left) {
3833                 // Package unsafe's documentation says storing pointers into
3834                 // reflect.SliceHeader and reflect.StringHeader's Data fields
3835                 // is valid, even though they have type uintptr (#19168).
3836                 // Mark it pointer type to signal the writebarrier pass to
3837                 // insert a write barrier.
3838                 t = types.Types[types.TUNSAFEPTR]
3839         }
3840         if deref {
3841                 // Treat as a mem->mem move.
3842                 if right == nil {
3843                         s.zero(t, addr)
3844                 } else {
3845                         s.moveWhichMayOverlap(t, addr, right, mayOverlap)
3846                 }
3847                 return
3848         }
3849         // Treat as a store.
3850         s.storeType(t, addr, right, skip, !ir.IsAutoTmp(left))
3851 }
3852
3853 // zeroVal returns the zero value for type t.
3854 func (s *state) zeroVal(t *types.Type) *ssa.Value {
3855         switch {
3856         case t.IsInteger():
3857                 switch t.Size() {
3858                 case 1:
3859                         return s.constInt8(t, 0)
3860                 case 2:
3861                         return s.constInt16(t, 0)
3862                 case 4:
3863                         return s.constInt32(t, 0)
3864                 case 8:
3865                         return s.constInt64(t, 0)
3866                 default:
3867                         s.Fatalf("bad sized integer type %v", t)
3868                 }
3869         case t.IsFloat():
3870                 switch t.Size() {
3871                 case 4:
3872                         return s.constFloat32(t, 0)
3873                 case 8:
3874                         return s.constFloat64(t, 0)
3875                 default:
3876                         s.Fatalf("bad sized float type %v", t)
3877                 }
3878         case t.IsComplex():
3879                 switch t.Size() {
3880                 case 8:
3881                         z := s.constFloat32(types.Types[types.TFLOAT32], 0)
3882                         return s.entryNewValue2(ssa.OpComplexMake, t, z, z)
3883                 case 16:
3884                         z := s.constFloat64(types.Types[types.TFLOAT64], 0)
3885                         return s.entryNewValue2(ssa.OpComplexMake, t, z, z)
3886                 default:
3887                         s.Fatalf("bad sized complex type %v", t)
3888                 }
3889
3890         case t.IsString():
3891                 return s.constEmptyString(t)
3892         case t.IsPtrShaped():
3893                 return s.constNil(t)
3894         case t.IsBoolean():
3895                 return s.constBool(false)
3896         case t.IsInterface():
3897                 return s.constInterface(t)
3898         case t.IsSlice():
3899                 return s.constSlice(t)
3900         case t.IsStruct():
3901                 n := t.NumFields()
3902                 v := s.entryNewValue0(ssa.StructMakeOp(t.NumFields()), t)
3903                 for i := 0; i < n; i++ {
3904                         v.AddArg(s.zeroVal(t.FieldType(i)))
3905                 }
3906                 return v
3907         case t.IsArray():
3908                 switch t.NumElem() {
3909                 case 0:
3910                         return s.entryNewValue0(ssa.OpArrayMake0, t)
3911                 case 1:
3912                         return s.entryNewValue1(ssa.OpArrayMake1, t, s.zeroVal(t.Elem()))
3913                 }
3914         }
3915         s.Fatalf("zero for type %v not implemented", t)
3916         return nil
3917 }
3918
3919 type callKind int8
3920
3921 const (
3922         callNormal callKind = iota
3923         callDefer
3924         callDeferStack
3925         callGo
3926         callTail
3927 )
3928
3929 type sfRtCallDef struct {
3930         rtfn  *obj.LSym
3931         rtype types.Kind
3932 }
3933
3934 var softFloatOps map[ssa.Op]sfRtCallDef
3935
3936 func softfloatInit() {
3937         // Some of these operations get transformed by sfcall.
3938         softFloatOps = map[ssa.Op]sfRtCallDef{
3939                 ssa.OpAdd32F: {typecheck.LookupRuntimeFunc("fadd32"), types.TFLOAT32},
3940                 ssa.OpAdd64F: {typecheck.LookupRuntimeFunc("fadd64"), types.TFLOAT64},
3941                 ssa.OpSub32F: {typecheck.LookupRuntimeFunc("fadd32"), types.TFLOAT32},
3942                 ssa.OpSub64F: {typecheck.LookupRuntimeFunc("fadd64"), types.TFLOAT64},
3943                 ssa.OpMul32F: {typecheck.LookupRuntimeFunc("fmul32"), types.TFLOAT32},
3944                 ssa.OpMul64F: {typecheck.LookupRuntimeFunc("fmul64"), types.TFLOAT64},
3945                 ssa.OpDiv32F: {typecheck.LookupRuntimeFunc("fdiv32"), types.TFLOAT32},
3946                 ssa.OpDiv64F: {typecheck.LookupRuntimeFunc("fdiv64"), types.TFLOAT64},
3947
3948                 ssa.OpEq64F:   {typecheck.LookupRuntimeFunc("feq64"), types.TBOOL},
3949                 ssa.OpEq32F:   {typecheck.LookupRuntimeFunc("feq32"), types.TBOOL},
3950                 ssa.OpNeq64F:  {typecheck.LookupRuntimeFunc("feq64"), types.TBOOL},
3951                 ssa.OpNeq32F:  {typecheck.LookupRuntimeFunc("feq32"), types.TBOOL},
3952                 ssa.OpLess64F: {typecheck.LookupRuntimeFunc("fgt64"), types.TBOOL},
3953                 ssa.OpLess32F: {typecheck.LookupRuntimeFunc("fgt32"), types.TBOOL},
3954                 ssa.OpLeq64F:  {typecheck.LookupRuntimeFunc("fge64"), types.TBOOL},
3955                 ssa.OpLeq32F:  {typecheck.LookupRuntimeFunc("fge32"), types.TBOOL},
3956
3957                 ssa.OpCvt32to32F:  {typecheck.LookupRuntimeFunc("fint32to32"), types.TFLOAT32},
3958                 ssa.OpCvt32Fto32:  {typecheck.LookupRuntimeFunc("f32toint32"), types.TINT32},
3959                 ssa.OpCvt64to32F:  {typecheck.LookupRuntimeFunc("fint64to32"), types.TFLOAT32},
3960                 ssa.OpCvt32Fto64:  {typecheck.LookupRuntimeFunc("f32toint64"), types.TINT64},
3961                 ssa.OpCvt64Uto32F: {typecheck.LookupRuntimeFunc("fuint64to32"), types.TFLOAT32},
3962                 ssa.OpCvt32Fto64U: {typecheck.LookupRuntimeFunc("f32touint64"), types.TUINT64},
3963                 ssa.OpCvt32to64F:  {typecheck.LookupRuntimeFunc("fint32to64"), types.TFLOAT64},
3964                 ssa.OpCvt64Fto32:  {typecheck.LookupRuntimeFunc("f64toint32"), types.TINT32},
3965                 ssa.OpCvt64to64F:  {typecheck.LookupRuntimeFunc("fint64to64"), types.TFLOAT64},
3966                 ssa.OpCvt64Fto64:  {typecheck.LookupRuntimeFunc("f64toint64"), types.TINT64},
3967                 ssa.OpCvt64Uto64F: {typecheck.LookupRuntimeFunc("fuint64to64"), types.TFLOAT64},
3968                 ssa.OpCvt64Fto64U: {typecheck.LookupRuntimeFunc("f64touint64"), types.TUINT64},
3969                 ssa.OpCvt32Fto64F: {typecheck.LookupRuntimeFunc("f32to64"), types.TFLOAT64},
3970                 ssa.OpCvt64Fto32F: {typecheck.LookupRuntimeFunc("f64to32"), types.TFLOAT32},
3971         }
3972 }
3973
3974 // TODO: do not emit sfcall if operation can be optimized to constant in later
3975 // opt phase
3976 func (s *state) sfcall(op ssa.Op, args ...*ssa.Value) (*ssa.Value, bool) {
3977         f2i := func(t *types.Type) *types.Type {
3978                 switch t.Kind() {
3979                 case types.TFLOAT32:
3980                         return types.Types[types.TUINT32]
3981                 case types.TFLOAT64:
3982                         return types.Types[types.TUINT64]
3983                 }
3984                 return t
3985         }
3986
3987         if callDef, ok := softFloatOps[op]; ok {
3988                 switch op {
3989                 case ssa.OpLess32F,
3990                         ssa.OpLess64F,
3991                         ssa.OpLeq32F,
3992                         ssa.OpLeq64F:
3993                         args[0], args[1] = args[1], args[0]
3994                 case ssa.OpSub32F,
3995                         ssa.OpSub64F:
3996                         args[1] = s.newValue1(s.ssaOp(ir.ONEG, types.Types[callDef.rtype]), args[1].Type, args[1])
3997                 }
3998
3999                 // runtime functions take uints for floats and returns uints.
4000                 // Convert to uints so we use the right calling convention.
4001                 for i, a := range args {
4002                         if a.Type.IsFloat() {
4003                                 args[i] = s.newValue1(ssa.OpCopy, f2i(a.Type), a)
4004                         }
4005                 }
4006
4007                 rt := types.Types[callDef.rtype]
4008                 result := s.rtcall(callDef.rtfn, true, []*types.Type{f2i(rt)}, args...)[0]
4009                 if rt.IsFloat() {
4010                         result = s.newValue1(ssa.OpCopy, rt, result)
4011                 }
4012                 if op == ssa.OpNeq32F || op == ssa.OpNeq64F {
4013                         result = s.newValue1(ssa.OpNot, result.Type, result)
4014                 }
4015                 return result, true
4016         }
4017         return nil, false
4018 }
4019
4020 var intrinsics map[intrinsicKey]intrinsicBuilder
4021
4022 // An intrinsicBuilder converts a call node n into an ssa value that
4023 // implements that call as an intrinsic. args is a list of arguments to the func.
4024 type intrinsicBuilder func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value
4025
4026 type intrinsicKey struct {
4027         arch *sys.Arch
4028         pkg  string
4029         fn   string
4030 }
4031
4032 func InitTables() {
4033         intrinsics = map[intrinsicKey]intrinsicBuilder{}
4034
4035         var all []*sys.Arch
4036         var p4 []*sys.Arch
4037         var p8 []*sys.Arch
4038         var lwatomics []*sys.Arch
4039         for _, a := range &sys.Archs {
4040                 all = append(all, a)
4041                 if a.PtrSize == 4 {
4042                         p4 = append(p4, a)
4043                 } else {
4044                         p8 = append(p8, a)
4045                 }
4046                 if a.Family != sys.PPC64 {
4047                         lwatomics = append(lwatomics, a)
4048                 }
4049         }
4050
4051         // add adds the intrinsic b for pkg.fn for the given list of architectures.
4052         add := func(pkg, fn string, b intrinsicBuilder, archs ...*sys.Arch) {
4053                 for _, a := range archs {
4054                         intrinsics[intrinsicKey{a, pkg, fn}] = b
4055                 }
4056         }
4057         // addF does the same as add but operates on architecture families.
4058         addF := func(pkg, fn string, b intrinsicBuilder, archFamilies ...sys.ArchFamily) {
4059                 m := 0
4060                 for _, f := range archFamilies {
4061                         if f >= 32 {
4062                                 panic("too many architecture families")
4063                         }
4064                         m |= 1 << uint(f)
4065                 }
4066                 for _, a := range all {
4067                         if m>>uint(a.Family)&1 != 0 {
4068                                 intrinsics[intrinsicKey{a, pkg, fn}] = b
4069                         }
4070                 }
4071         }
4072         // alias defines pkg.fn = pkg2.fn2 for all architectures in archs for which pkg2.fn2 exists.
4073         alias := func(pkg, fn, pkg2, fn2 string, archs ...*sys.Arch) {
4074                 aliased := false
4075                 for _, a := range archs {
4076                         if b, ok := intrinsics[intrinsicKey{a, pkg2, fn2}]; ok {
4077                                 intrinsics[intrinsicKey{a, pkg, fn}] = b
4078                                 aliased = true
4079                         }
4080                 }
4081                 if !aliased {
4082                         panic(fmt.Sprintf("attempted to alias undefined intrinsic: %s.%s", pkg, fn))
4083                 }
4084         }
4085
4086         /******** runtime ********/
4087         if !base.Flag.Cfg.Instrumenting {
4088                 add("runtime", "slicebytetostringtmp",
4089                         func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4090                                 // Compiler frontend optimizations emit OBYTES2STRTMP nodes
4091                                 // for the backend instead of slicebytetostringtmp calls
4092                                 // when not instrumenting.
4093                                 return s.newValue2(ssa.OpStringMake, n.Type(), args[0], args[1])
4094                         },
4095                         all...)
4096         }
4097         addF("runtime/internal/math", "MulUintptr",
4098                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4099                         if s.config.PtrSize == 4 {
4100                                 return s.newValue2(ssa.OpMul32uover, types.NewTuple(types.Types[types.TUINT], types.Types[types.TUINT]), args[0], args[1])
4101                         }
4102                         return s.newValue2(ssa.OpMul64uover, types.NewTuple(types.Types[types.TUINT], types.Types[types.TUINT]), args[0], args[1])
4103                 },
4104                 sys.AMD64, sys.I386, sys.Loong64, sys.MIPS64, sys.RISCV64, sys.ARM64)
4105         alias("runtime", "mulUintptr", "runtime/internal/math", "MulUintptr", all...)
4106         add("runtime", "KeepAlive",
4107                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4108                         data := s.newValue1(ssa.OpIData, s.f.Config.Types.BytePtr, args[0])
4109                         s.vars[memVar] = s.newValue2(ssa.OpKeepAlive, types.TypeMem, data, s.mem())
4110                         return nil
4111                 },
4112                 all...)
4113         add("runtime", "getclosureptr",
4114                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4115                         return s.newValue0(ssa.OpGetClosurePtr, s.f.Config.Types.Uintptr)
4116                 },
4117                 all...)
4118
4119         add("runtime", "getcallerpc",
4120                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4121                         return s.newValue0(ssa.OpGetCallerPC, s.f.Config.Types.Uintptr)
4122                 },
4123                 all...)
4124
4125         add("runtime", "getcallersp",
4126                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4127                         return s.newValue1(ssa.OpGetCallerSP, s.f.Config.Types.Uintptr, s.mem())
4128                 },
4129                 all...)
4130
4131         addF("runtime", "publicationBarrier",
4132                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4133                         s.vars[memVar] = s.newValue1(ssa.OpPubBarrier, types.TypeMem, s.mem())
4134                         return nil
4135                 },
4136                 sys.ARM64, sys.PPC64)
4137
4138         brev_arch := []sys.ArchFamily{sys.AMD64, sys.I386, sys.ARM64, sys.ARM, sys.S390X}
4139         if buildcfg.GOPPC64 >= 10 {
4140                 // Use only on Power10 as the new byte reverse instructions that Power10 provide
4141                 // make it worthwhile as an intrinsic
4142                 brev_arch = append(brev_arch, sys.PPC64)
4143         }
4144         /******** runtime/internal/sys ********/
4145         addF("runtime/internal/sys", "Bswap32",
4146                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4147                         return s.newValue1(ssa.OpBswap32, types.Types[types.TUINT32], args[0])
4148                 },
4149                 brev_arch...)
4150         addF("runtime/internal/sys", "Bswap64",
4151                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4152                         return s.newValue1(ssa.OpBswap64, types.Types[types.TUINT64], args[0])
4153                 },
4154                 brev_arch...)
4155
4156         /****** Prefetch ******/
4157         makePrefetchFunc := func(op ssa.Op) func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4158                 return func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4159                         s.vars[memVar] = s.newValue2(op, types.TypeMem, args[0], s.mem())
4160                         return nil
4161                 }
4162         }
4163
4164         // Make Prefetch intrinsics for supported platforms
4165         // On the unsupported platforms stub function will be eliminated
4166         addF("runtime/internal/sys", "Prefetch", makePrefetchFunc(ssa.OpPrefetchCache),
4167                 sys.AMD64, sys.ARM64, sys.PPC64)
4168         addF("runtime/internal/sys", "PrefetchStreamed", makePrefetchFunc(ssa.OpPrefetchCacheStreamed),
4169                 sys.AMD64, sys.ARM64, sys.PPC64)
4170
4171         /******** runtime/internal/atomic ********/
4172         addF("runtime/internal/atomic", "Load",
4173                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4174                         v := s.newValue2(ssa.OpAtomicLoad32, types.NewTuple(types.Types[types.TUINT32], types.TypeMem), args[0], s.mem())
4175                         s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4176                         return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT32], v)
4177                 },
4178                 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4179         addF("runtime/internal/atomic", "Load8",
4180                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4181                         v := s.newValue2(ssa.OpAtomicLoad8, types.NewTuple(types.Types[types.TUINT8], types.TypeMem), args[0], s.mem())
4182                         s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4183                         return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT8], v)
4184                 },
4185                 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4186         addF("runtime/internal/atomic", "Load64",
4187                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4188                         v := s.newValue2(ssa.OpAtomicLoad64, types.NewTuple(types.Types[types.TUINT64], types.TypeMem), args[0], s.mem())
4189                         s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4190                         return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT64], v)
4191                 },
4192                 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4193         addF("runtime/internal/atomic", "LoadAcq",
4194                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4195                         v := s.newValue2(ssa.OpAtomicLoadAcq32, types.NewTuple(types.Types[types.TUINT32], types.TypeMem), args[0], s.mem())
4196                         s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4197                         return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT32], v)
4198                 },
4199                 sys.PPC64, sys.S390X)
4200         addF("runtime/internal/atomic", "LoadAcq64",
4201                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4202                         v := s.newValue2(ssa.OpAtomicLoadAcq64, types.NewTuple(types.Types[types.TUINT64], types.TypeMem), args[0], s.mem())
4203                         s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4204                         return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT64], v)
4205                 },
4206                 sys.PPC64)
4207         addF("runtime/internal/atomic", "Loadp",
4208                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4209                         v := s.newValue2(ssa.OpAtomicLoadPtr, types.NewTuple(s.f.Config.Types.BytePtr, types.TypeMem), args[0], s.mem())
4210                         s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4211                         return s.newValue1(ssa.OpSelect0, s.f.Config.Types.BytePtr, v)
4212                 },
4213                 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4214
4215         addF("runtime/internal/atomic", "Store",
4216                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4217                         s.vars[memVar] = s.newValue3(ssa.OpAtomicStore32, types.TypeMem, args[0], args[1], s.mem())
4218                         return nil
4219                 },
4220                 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4221         addF("runtime/internal/atomic", "Store8",
4222                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4223                         s.vars[memVar] = s.newValue3(ssa.OpAtomicStore8, types.TypeMem, args[0], args[1], s.mem())
4224                         return nil
4225                 },
4226                 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4227         addF("runtime/internal/atomic", "Store64",
4228                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4229                         s.vars[memVar] = s.newValue3(ssa.OpAtomicStore64, types.TypeMem, args[0], args[1], s.mem())
4230                         return nil
4231                 },
4232                 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4233         addF("runtime/internal/atomic", "StorepNoWB",
4234                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4235                         s.vars[memVar] = s.newValue3(ssa.OpAtomicStorePtrNoWB, types.TypeMem, args[0], args[1], s.mem())
4236                         return nil
4237                 },
4238                 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.RISCV64, sys.S390X)
4239         addF("runtime/internal/atomic", "StoreRel",
4240                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4241                         s.vars[memVar] = s.newValue3(ssa.OpAtomicStoreRel32, types.TypeMem, args[0], args[1], s.mem())
4242                         return nil
4243                 },
4244                 sys.PPC64, sys.S390X)
4245         addF("runtime/internal/atomic", "StoreRel64",
4246                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4247                         s.vars[memVar] = s.newValue3(ssa.OpAtomicStoreRel64, types.TypeMem, args[0], args[1], s.mem())
4248                         return nil
4249                 },
4250                 sys.PPC64)
4251
4252         addF("runtime/internal/atomic", "Xchg",
4253                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4254                         v := s.newValue3(ssa.OpAtomicExchange32, types.NewTuple(types.Types[types.TUINT32], types.TypeMem), args[0], args[1], s.mem())
4255                         s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4256                         return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT32], v)
4257                 },
4258                 sys.AMD64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4259         addF("runtime/internal/atomic", "Xchg64",
4260                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4261                         v := s.newValue3(ssa.OpAtomicExchange64, types.NewTuple(types.Types[types.TUINT64], types.TypeMem), args[0], args[1], s.mem())
4262                         s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4263                         return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT64], v)
4264                 },
4265                 sys.AMD64, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4266
4267         type atomicOpEmitter func(s *state, n *ir.CallExpr, args []*ssa.Value, op ssa.Op, typ types.Kind)
4268
4269         makeAtomicGuardedIntrinsicARM64 := func(op0, op1 ssa.Op, typ, rtyp types.Kind, emit atomicOpEmitter) intrinsicBuilder {
4270
4271                 return func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4272                         // Target Atomic feature is identified by dynamic detection
4273                         addr := s.entryNewValue1A(ssa.OpAddr, types.Types[types.TBOOL].PtrTo(), ir.Syms.ARM64HasATOMICS, s.sb)
4274                         v := s.load(types.Types[types.TBOOL], addr)
4275                         b := s.endBlock()
4276                         b.Kind = ssa.BlockIf
4277                         b.SetControl(v)
4278                         bTrue := s.f.NewBlock(ssa.BlockPlain)
4279                         bFalse := s.f.NewBlock(ssa.BlockPlain)
4280                         bEnd := s.f.NewBlock(ssa.BlockPlain)
4281                         b.AddEdgeTo(bTrue)
4282                         b.AddEdgeTo(bFalse)
4283                         b.Likely = ssa.BranchLikely
4284
4285                         // We have atomic instructions - use it directly.
4286                         s.startBlock(bTrue)
4287                         emit(s, n, args, op1, typ)
4288                         s.endBlock().AddEdgeTo(bEnd)
4289
4290                         // Use original instruction sequence.
4291                         s.startBlock(bFalse)
4292                         emit(s, n, args, op0, typ)
4293                         s.endBlock().AddEdgeTo(bEnd)
4294
4295                         // Merge results.
4296                         s.startBlock(bEnd)
4297                         if rtyp == types.TNIL {
4298                                 return nil
4299                         } else {
4300                                 return s.variable(n, types.Types[rtyp])
4301                         }
4302                 }
4303         }
4304
4305         atomicXchgXaddEmitterARM64 := func(s *state, n *ir.CallExpr, args []*ssa.Value, op ssa.Op, typ types.Kind) {
4306                 v := s.newValue3(op, types.NewTuple(types.Types[typ], types.TypeMem), args[0], args[1], s.mem())
4307                 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4308                 s.vars[n] = s.newValue1(ssa.OpSelect0, types.Types[typ], v)
4309         }
4310         addF("runtime/internal/atomic", "Xchg",
4311                 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicExchange32, ssa.OpAtomicExchange32Variant, types.TUINT32, types.TUINT32, atomicXchgXaddEmitterARM64),
4312                 sys.ARM64)
4313         addF("runtime/internal/atomic", "Xchg64",
4314                 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicExchange64, ssa.OpAtomicExchange64Variant, types.TUINT64, types.TUINT64, atomicXchgXaddEmitterARM64),
4315                 sys.ARM64)
4316
4317         addF("runtime/internal/atomic", "Xadd",
4318                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4319                         v := s.newValue3(ssa.OpAtomicAdd32, types.NewTuple(types.Types[types.TUINT32], types.TypeMem), args[0], args[1], s.mem())
4320                         s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4321                         return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT32], v)
4322                 },
4323                 sys.AMD64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4324         addF("runtime/internal/atomic", "Xadd64",
4325                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4326                         v := s.newValue3(ssa.OpAtomicAdd64, types.NewTuple(types.Types[types.TUINT64], types.TypeMem), args[0], args[1], s.mem())
4327                         s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4328                         return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT64], v)
4329                 },
4330                 sys.AMD64, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4331
4332         addF("runtime/internal/atomic", "Xadd",
4333                 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicAdd32, ssa.OpAtomicAdd32Variant, types.TUINT32, types.TUINT32, atomicXchgXaddEmitterARM64),
4334                 sys.ARM64)
4335         addF("runtime/internal/atomic", "Xadd64",
4336                 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicAdd64, ssa.OpAtomicAdd64Variant, types.TUINT64, types.TUINT64, atomicXchgXaddEmitterARM64),
4337                 sys.ARM64)
4338
4339         addF("runtime/internal/atomic", "Cas",
4340                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4341                         v := s.newValue4(ssa.OpAtomicCompareAndSwap32, types.NewTuple(types.Types[types.TBOOL], types.TypeMem), args[0], args[1], args[2], s.mem())
4342                         s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4343                         return s.newValue1(ssa.OpSelect0, types.Types[types.TBOOL], v)
4344                 },
4345                 sys.AMD64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4346         addF("runtime/internal/atomic", "Cas64",
4347                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4348                         v := s.newValue4(ssa.OpAtomicCompareAndSwap64, types.NewTuple(types.Types[types.TBOOL], types.TypeMem), args[0], args[1], args[2], s.mem())
4349                         s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4350                         return s.newValue1(ssa.OpSelect0, types.Types[types.TBOOL], v)
4351                 },
4352                 sys.AMD64, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4353         addF("runtime/internal/atomic", "CasRel",
4354                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4355                         v := s.newValue4(ssa.OpAtomicCompareAndSwap32, types.NewTuple(types.Types[types.TBOOL], types.TypeMem), args[0], args[1], args[2], s.mem())
4356                         s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4357                         return s.newValue1(ssa.OpSelect0, types.Types[types.TBOOL], v)
4358                 },
4359                 sys.PPC64)
4360
4361         atomicCasEmitterARM64 := func(s *state, n *ir.CallExpr, args []*ssa.Value, op ssa.Op, typ types.Kind) {
4362                 v := s.newValue4(op, types.NewTuple(types.Types[types.TBOOL], types.TypeMem), args[0], args[1], args[2], s.mem())
4363                 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4364                 s.vars[n] = s.newValue1(ssa.OpSelect0, types.Types[typ], v)
4365         }
4366
4367         addF("runtime/internal/atomic", "Cas",
4368                 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicCompareAndSwap32, ssa.OpAtomicCompareAndSwap32Variant, types.TUINT32, types.TBOOL, atomicCasEmitterARM64),
4369                 sys.ARM64)
4370         addF("runtime/internal/atomic", "Cas64",
4371                 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicCompareAndSwap64, ssa.OpAtomicCompareAndSwap64Variant, types.TUINT64, types.TBOOL, atomicCasEmitterARM64),
4372                 sys.ARM64)
4373
4374         addF("runtime/internal/atomic", "And8",
4375                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4376                         s.vars[memVar] = s.newValue3(ssa.OpAtomicAnd8, types.TypeMem, args[0], args[1], s.mem())
4377                         return nil
4378                 },
4379                 sys.AMD64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4380         addF("runtime/internal/atomic", "And",
4381                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4382                         s.vars[memVar] = s.newValue3(ssa.OpAtomicAnd32, types.TypeMem, args[0], args[1], s.mem())
4383                         return nil
4384                 },
4385                 sys.AMD64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4386         addF("runtime/internal/atomic", "Or8",
4387                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4388                         s.vars[memVar] = s.newValue3(ssa.OpAtomicOr8, types.TypeMem, args[0], args[1], s.mem())
4389                         return nil
4390                 },
4391                 sys.AMD64, sys.ARM64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4392         addF("runtime/internal/atomic", "Or",
4393                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4394                         s.vars[memVar] = s.newValue3(ssa.OpAtomicOr32, types.TypeMem, args[0], args[1], s.mem())
4395                         return nil
4396                 },
4397                 sys.AMD64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4398
4399         atomicAndOrEmitterARM64 := func(s *state, n *ir.CallExpr, args []*ssa.Value, op ssa.Op, typ types.Kind) {
4400                 s.vars[memVar] = s.newValue3(op, types.TypeMem, args[0], args[1], s.mem())
4401         }
4402
4403         addF("runtime/internal/atomic", "And8",
4404                 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicAnd8, ssa.OpAtomicAnd8Variant, types.TNIL, types.TNIL, atomicAndOrEmitterARM64),
4405                 sys.ARM64)
4406         addF("runtime/internal/atomic", "And",
4407                 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicAnd32, ssa.OpAtomicAnd32Variant, types.TNIL, types.TNIL, atomicAndOrEmitterARM64),
4408                 sys.ARM64)
4409         addF("runtime/internal/atomic", "Or8",
4410                 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicOr8, ssa.OpAtomicOr8Variant, types.TNIL, types.TNIL, atomicAndOrEmitterARM64),
4411                 sys.ARM64)
4412         addF("runtime/internal/atomic", "Or",
4413                 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicOr32, ssa.OpAtomicOr32Variant, types.TNIL, types.TNIL, atomicAndOrEmitterARM64),
4414                 sys.ARM64)
4415
4416         // Aliases for atomic load operations
4417         alias("runtime/internal/atomic", "Loadint32", "runtime/internal/atomic", "Load", all...)
4418         alias("runtime/internal/atomic", "Loadint64", "runtime/internal/atomic", "Load64", all...)
4419         alias("runtime/internal/atomic", "Loaduintptr", "runtime/internal/atomic", "Load", p4...)
4420         alias("runtime/internal/atomic", "Loaduintptr", "runtime/internal/atomic", "Load64", p8...)
4421         alias("runtime/internal/atomic", "Loaduint", "runtime/internal/atomic", "Load", p4...)
4422         alias("runtime/internal/atomic", "Loaduint", "runtime/internal/atomic", "Load64", p8...)
4423         alias("runtime/internal/atomic", "LoadAcq", "runtime/internal/atomic", "Load", lwatomics...)
4424         alias("runtime/internal/atomic", "LoadAcq64", "runtime/internal/atomic", "Load64", lwatomics...)
4425         alias("runtime/internal/atomic", "LoadAcquintptr", "runtime/internal/atomic", "LoadAcq", p4...)
4426         alias("sync", "runtime_LoadAcquintptr", "runtime/internal/atomic", "LoadAcq", p4...) // linknamed
4427         alias("runtime/internal/atomic", "LoadAcquintptr", "runtime/internal/atomic", "LoadAcq64", p8...)
4428         alias("sync", "runtime_LoadAcquintptr", "runtime/internal/atomic", "LoadAcq64", p8...) // linknamed
4429
4430         // Aliases for atomic store operations
4431         alias("runtime/internal/atomic", "Storeint32", "runtime/internal/atomic", "Store", all...)
4432         alias("runtime/internal/atomic", "Storeint64", "runtime/internal/atomic", "Store64", all...)
4433         alias("runtime/internal/atomic", "Storeuintptr", "runtime/internal/atomic", "Store", p4...)
4434         alias("runtime/internal/atomic", "Storeuintptr", "runtime/internal/atomic", "Store64", p8...)
4435         alias("runtime/internal/atomic", "StoreRel", "runtime/internal/atomic", "Store", lwatomics...)
4436         alias("runtime/internal/atomic", "StoreRel64", "runtime/internal/atomic", "Store64", lwatomics...)
4437         alias("runtime/internal/atomic", "StoreReluintptr", "runtime/internal/atomic", "StoreRel", p4...)
4438         alias("sync", "runtime_StoreReluintptr", "runtime/internal/atomic", "StoreRel", p4...) // linknamed
4439         alias("runtime/internal/atomic", "StoreReluintptr", "runtime/internal/atomic", "StoreRel64", p8...)
4440         alias("sync", "runtime_StoreReluintptr", "runtime/internal/atomic", "StoreRel64", p8...) // linknamed
4441
4442         // Aliases for atomic swap operations
4443         alias("runtime/internal/atomic", "Xchgint32", "runtime/internal/atomic", "Xchg", all...)
4444         alias("runtime/internal/atomic", "Xchgint64", "runtime/internal/atomic", "Xchg64", all...)
4445         alias("runtime/internal/atomic", "Xchguintptr", "runtime/internal/atomic", "Xchg", p4...)
4446         alias("runtime/internal/atomic", "Xchguintptr", "runtime/internal/atomic", "Xchg64", p8...)
4447
4448         // Aliases for atomic add operations
4449         alias("runtime/internal/atomic", "Xaddint32", "runtime/internal/atomic", "Xadd", all...)
4450         alias("runtime/internal/atomic", "Xaddint64", "runtime/internal/atomic", "Xadd64", all...)
4451         alias("runtime/internal/atomic", "Xadduintptr", "runtime/internal/atomic", "Xadd", p4...)
4452         alias("runtime/internal/atomic", "Xadduintptr", "runtime/internal/atomic", "Xadd64", p8...)
4453
4454         // Aliases for atomic CAS operations
4455         alias("runtime/internal/atomic", "Casint32", "runtime/internal/atomic", "Cas", all...)
4456         alias("runtime/internal/atomic", "Casint64", "runtime/internal/atomic", "Cas64", all...)
4457         alias("runtime/internal/atomic", "Casuintptr", "runtime/internal/atomic", "Cas", p4...)
4458         alias("runtime/internal/atomic", "Casuintptr", "runtime/internal/atomic", "Cas64", p8...)
4459         alias("runtime/internal/atomic", "Casp1", "runtime/internal/atomic", "Cas", p4...)
4460         alias("runtime/internal/atomic", "Casp1", "runtime/internal/atomic", "Cas64", p8...)
4461         alias("runtime/internal/atomic", "CasRel", "runtime/internal/atomic", "Cas", lwatomics...)
4462
4463         /******** math ********/
4464         addF("math", "sqrt",
4465                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4466                         return s.newValue1(ssa.OpSqrt, types.Types[types.TFLOAT64], args[0])
4467                 },
4468                 sys.I386, sys.AMD64, sys.ARM, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X, sys.Wasm)
4469         addF("math", "Trunc",
4470                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4471                         return s.newValue1(ssa.OpTrunc, types.Types[types.TFLOAT64], args[0])
4472                 },
4473                 sys.ARM64, sys.PPC64, sys.S390X, sys.Wasm)
4474         addF("math", "Ceil",
4475                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4476                         return s.newValue1(ssa.OpCeil, types.Types[types.TFLOAT64], args[0])
4477                 },
4478                 sys.ARM64, sys.PPC64, sys.S390X, sys.Wasm)
4479         addF("math", "Floor",
4480                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4481                         return s.newValue1(ssa.OpFloor, types.Types[types.TFLOAT64], args[0])
4482                 },
4483                 sys.ARM64, sys.PPC64, sys.S390X, sys.Wasm)
4484         addF("math", "Round",
4485                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4486                         return s.newValue1(ssa.OpRound, types.Types[types.TFLOAT64], args[0])
4487                 },
4488                 sys.ARM64, sys.PPC64, sys.S390X)
4489         addF("math", "RoundToEven",
4490                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4491                         return s.newValue1(ssa.OpRoundToEven, types.Types[types.TFLOAT64], args[0])
4492                 },
4493                 sys.ARM64, sys.S390X, sys.Wasm)
4494         addF("math", "Abs",
4495                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4496                         return s.newValue1(ssa.OpAbs, types.Types[types.TFLOAT64], args[0])
4497                 },
4498                 sys.ARM64, sys.ARM, sys.PPC64, sys.RISCV64, sys.Wasm, sys.MIPS, sys.MIPS64)
4499         addF("math", "Copysign",
4500                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4501                         return s.newValue2(ssa.OpCopysign, types.Types[types.TFLOAT64], args[0], args[1])
4502                 },
4503                 sys.PPC64, sys.RISCV64, sys.Wasm)
4504         addF("math", "FMA",
4505                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4506                         return s.newValue3(ssa.OpFMA, types.Types[types.TFLOAT64], args[0], args[1], args[2])
4507                 },
4508                 sys.ARM64, sys.PPC64, sys.RISCV64, sys.S390X)
4509         addF("math", "FMA",
4510                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4511                         if !s.config.UseFMA {
4512                                 s.vars[n] = s.callResult(n, callNormal) // types.Types[TFLOAT64]
4513                                 return s.variable(n, types.Types[types.TFLOAT64])
4514                         }
4515
4516                         if buildcfg.GOAMD64 >= 3 {
4517                                 return s.newValue3(ssa.OpFMA, types.Types[types.TFLOAT64], args[0], args[1], args[2])
4518                         }
4519
4520                         v := s.entryNewValue0A(ssa.OpHasCPUFeature, types.Types[types.TBOOL], ir.Syms.X86HasFMA)
4521                         b := s.endBlock()
4522                         b.Kind = ssa.BlockIf
4523                         b.SetControl(v)
4524                         bTrue := s.f.NewBlock(ssa.BlockPlain)
4525                         bFalse := s.f.NewBlock(ssa.BlockPlain)
4526                         bEnd := s.f.NewBlock(ssa.BlockPlain)
4527                         b.AddEdgeTo(bTrue)
4528                         b.AddEdgeTo(bFalse)
4529                         b.Likely = ssa.BranchLikely // >= haswell cpus are common
4530
4531                         // We have the intrinsic - use it directly.
4532                         s.startBlock(bTrue)
4533                         s.vars[n] = s.newValue3(ssa.OpFMA, types.Types[types.TFLOAT64], args[0], args[1], args[2])
4534                         s.endBlock().AddEdgeTo(bEnd)
4535
4536                         // Call the pure Go version.
4537                         s.startBlock(bFalse)
4538                         s.vars[n] = s.callResult(n, callNormal) // types.Types[TFLOAT64]
4539                         s.endBlock().AddEdgeTo(bEnd)
4540
4541                         // Merge results.
4542                         s.startBlock(bEnd)
4543                         return s.variable(n, types.Types[types.TFLOAT64])
4544                 },
4545                 sys.AMD64)
4546         addF("math", "FMA",
4547                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4548                         if !s.config.UseFMA {
4549                                 s.vars[n] = s.callResult(n, callNormal) // types.Types[TFLOAT64]
4550                                 return s.variable(n, types.Types[types.TFLOAT64])
4551                         }
4552                         addr := s.entryNewValue1A(ssa.OpAddr, types.Types[types.TBOOL].PtrTo(), ir.Syms.ARMHasVFPv4, s.sb)
4553                         v := s.load(types.Types[types.TBOOL], addr)
4554                         b := s.endBlock()
4555                         b.Kind = ssa.BlockIf
4556                         b.SetControl(v)
4557                         bTrue := s.f.NewBlock(ssa.BlockPlain)
4558                         bFalse := s.f.NewBlock(ssa.BlockPlain)
4559                         bEnd := s.f.NewBlock(ssa.BlockPlain)
4560                         b.AddEdgeTo(bTrue)
4561                         b.AddEdgeTo(bFalse)
4562                         b.Likely = ssa.BranchLikely
4563
4564                         // We have the intrinsic - use it directly.
4565                         s.startBlock(bTrue)
4566                         s.vars[n] = s.newValue3(ssa.OpFMA, types.Types[types.TFLOAT64], args[0], args[1], args[2])
4567                         s.endBlock().AddEdgeTo(bEnd)
4568
4569                         // Call the pure Go version.
4570                         s.startBlock(bFalse)
4571                         s.vars[n] = s.callResult(n, callNormal) // types.Types[TFLOAT64]
4572                         s.endBlock().AddEdgeTo(bEnd)
4573
4574                         // Merge results.
4575                         s.startBlock(bEnd)
4576                         return s.variable(n, types.Types[types.TFLOAT64])
4577                 },
4578                 sys.ARM)
4579
4580         makeRoundAMD64 := func(op ssa.Op) func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4581                 return func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4582                         if buildcfg.GOAMD64 >= 2 {
4583                                 return s.newValue1(op, types.Types[types.TFLOAT64], args[0])
4584                         }
4585
4586                         v := s.entryNewValue0A(ssa.OpHasCPUFeature, types.Types[types.TBOOL], ir.Syms.X86HasSSE41)
4587                         b := s.endBlock()
4588                         b.Kind = ssa.BlockIf
4589                         b.SetControl(v)
4590                         bTrue := s.f.NewBlock(ssa.BlockPlain)
4591                         bFalse := s.f.NewBlock(ssa.BlockPlain)
4592                         bEnd := s.f.NewBlock(ssa.BlockPlain)
4593                         b.AddEdgeTo(bTrue)
4594                         b.AddEdgeTo(bFalse)
4595                         b.Likely = ssa.BranchLikely // most machines have sse4.1 nowadays
4596
4597                         // We have the intrinsic - use it directly.
4598                         s.startBlock(bTrue)
4599                         s.vars[n] = s.newValue1(op, types.Types[types.TFLOAT64], args[0])
4600                         s.endBlock().AddEdgeTo(bEnd)
4601
4602                         // Call the pure Go version.
4603                         s.startBlock(bFalse)
4604                         s.vars[n] = s.callResult(n, callNormal) // types.Types[TFLOAT64]
4605                         s.endBlock().AddEdgeTo(bEnd)
4606
4607                         // Merge results.
4608                         s.startBlock(bEnd)
4609                         return s.variable(n, types.Types[types.TFLOAT64])
4610                 }
4611         }
4612         addF("math", "RoundToEven",
4613                 makeRoundAMD64(ssa.OpRoundToEven),
4614                 sys.AMD64)
4615         addF("math", "Floor",
4616                 makeRoundAMD64(ssa.OpFloor),
4617                 sys.AMD64)
4618         addF("math", "Ceil",
4619                 makeRoundAMD64(ssa.OpCeil),
4620                 sys.AMD64)
4621         addF("math", "Trunc",
4622                 makeRoundAMD64(ssa.OpTrunc),
4623                 sys.AMD64)
4624
4625         /******** math/bits ********/
4626         addF("math/bits", "TrailingZeros64",
4627                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4628                         return s.newValue1(ssa.OpCtz64, types.Types[types.TINT], args[0])
4629                 },
4630                 sys.AMD64, sys.I386, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4631         addF("math/bits", "TrailingZeros32",
4632                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4633                         return s.newValue1(ssa.OpCtz32, types.Types[types.TINT], args[0])
4634                 },
4635                 sys.AMD64, sys.I386, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4636         addF("math/bits", "TrailingZeros16",
4637                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4638                         x := s.newValue1(ssa.OpZeroExt16to32, types.Types[types.TUINT32], args[0])
4639                         c := s.constInt32(types.Types[types.TUINT32], 1<<16)
4640                         y := s.newValue2(ssa.OpOr32, types.Types[types.TUINT32], x, c)
4641                         return s.newValue1(ssa.OpCtz32, types.Types[types.TINT], y)
4642                 },
4643                 sys.MIPS)
4644         addF("math/bits", "TrailingZeros16",
4645                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4646                         return s.newValue1(ssa.OpCtz16, types.Types[types.TINT], args[0])
4647                 },
4648                 sys.AMD64, sys.I386, sys.ARM, sys.ARM64, sys.Wasm)
4649         addF("math/bits", "TrailingZeros16",
4650                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4651                         x := s.newValue1(ssa.OpZeroExt16to64, types.Types[types.TUINT64], args[0])
4652                         c := s.constInt64(types.Types[types.TUINT64], 1<<16)
4653                         y := s.newValue2(ssa.OpOr64, types.Types[types.TUINT64], x, c)
4654                         return s.newValue1(ssa.OpCtz64, types.Types[types.TINT], y)
4655                 },
4656                 sys.S390X, sys.PPC64)
4657         addF("math/bits", "TrailingZeros8",
4658                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4659                         x := s.newValue1(ssa.OpZeroExt8to32, types.Types[types.TUINT32], args[0])
4660                         c := s.constInt32(types.Types[types.TUINT32], 1<<8)
4661                         y := s.newValue2(ssa.OpOr32, types.Types[types.TUINT32], x, c)
4662                         return s.newValue1(ssa.OpCtz32, types.Types[types.TINT], y)
4663                 },
4664                 sys.MIPS)
4665         addF("math/bits", "TrailingZeros8",
4666                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4667                         return s.newValue1(ssa.OpCtz8, types.Types[types.TINT], args[0])
4668                 },
4669                 sys.AMD64, sys.I386, sys.ARM, sys.ARM64, sys.Wasm)
4670         addF("math/bits", "TrailingZeros8",
4671                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4672                         x := s.newValue1(ssa.OpZeroExt8to64, types.Types[types.TUINT64], args[0])
4673                         c := s.constInt64(types.Types[types.TUINT64], 1<<8)
4674                         y := s.newValue2(ssa.OpOr64, types.Types[types.TUINT64], x, c)
4675                         return s.newValue1(ssa.OpCtz64, types.Types[types.TINT], y)
4676                 },
4677                 sys.S390X)
4678         alias("math/bits", "ReverseBytes64", "runtime/internal/sys", "Bswap64", all...)
4679         alias("math/bits", "ReverseBytes32", "runtime/internal/sys", "Bswap32", all...)
4680         // ReverseBytes inlines correctly, no need to intrinsify it.
4681         // Nothing special is needed for targets where ReverseBytes16 lowers to a rotate
4682         // On Power10, 16-bit rotate is not available so use BRH instruction
4683         if buildcfg.GOPPC64 >= 10 {
4684                 addF("math/bits", "ReverseBytes16",
4685                         func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4686                                 return s.newValue1(ssa.OpBswap16, types.Types[types.TUINT], args[0])
4687                         },
4688                         sys.PPC64)
4689         }
4690
4691         addF("math/bits", "Len64",
4692                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4693                         return s.newValue1(ssa.OpBitLen64, types.Types[types.TINT], args[0])
4694                 },
4695                 sys.AMD64, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4696         addF("math/bits", "Len32",
4697                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4698                         return s.newValue1(ssa.OpBitLen32, types.Types[types.TINT], args[0])
4699                 },
4700                 sys.AMD64, sys.ARM64, sys.PPC64)
4701         addF("math/bits", "Len32",
4702                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4703                         if s.config.PtrSize == 4 {
4704                                 return s.newValue1(ssa.OpBitLen32, types.Types[types.TINT], args[0])
4705                         }
4706                         x := s.newValue1(ssa.OpZeroExt32to64, types.Types[types.TUINT64], args[0])
4707                         return s.newValue1(ssa.OpBitLen64, types.Types[types.TINT], x)
4708                 },
4709                 sys.ARM, sys.S390X, sys.MIPS, sys.Wasm)
4710         addF("math/bits", "Len16",
4711                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4712                         if s.config.PtrSize == 4 {
4713                                 x := s.newValue1(ssa.OpZeroExt16to32, types.Types[types.TUINT32], args[0])
4714                                 return s.newValue1(ssa.OpBitLen32, types.Types[types.TINT], x)
4715                         }
4716                         x := s.newValue1(ssa.OpZeroExt16to64, types.Types[types.TUINT64], args[0])
4717                         return s.newValue1(ssa.OpBitLen64, types.Types[types.TINT], x)
4718                 },
4719                 sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4720         addF("math/bits", "Len16",
4721                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4722                         return s.newValue1(ssa.OpBitLen16, types.Types[types.TINT], args[0])
4723                 },
4724                 sys.AMD64)
4725         addF("math/bits", "Len8",
4726                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4727                         if s.config.PtrSize == 4 {
4728                                 x := s.newValue1(ssa.OpZeroExt8to32, types.Types[types.TUINT32], args[0])
4729                                 return s.newValue1(ssa.OpBitLen32, types.Types[types.TINT], x)
4730                         }
4731                         x := s.newValue1(ssa.OpZeroExt8to64, types.Types[types.TUINT64], args[0])
4732                         return s.newValue1(ssa.OpBitLen64, types.Types[types.TINT], x)
4733                 },
4734                 sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4735         addF("math/bits", "Len8",
4736                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4737                         return s.newValue1(ssa.OpBitLen8, types.Types[types.TINT], args[0])
4738                 },
4739                 sys.AMD64)
4740         addF("math/bits", "Len",
4741                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4742                         if s.config.PtrSize == 4 {
4743                                 return s.newValue1(ssa.OpBitLen32, types.Types[types.TINT], args[0])
4744                         }
4745                         return s.newValue1(ssa.OpBitLen64, types.Types[types.TINT], args[0])
4746                 },
4747                 sys.AMD64, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4748         // LeadingZeros is handled because it trivially calls Len.
4749         addF("math/bits", "Reverse64",
4750                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4751                         return s.newValue1(ssa.OpBitRev64, types.Types[types.TINT], args[0])
4752                 },
4753                 sys.ARM64)
4754         addF("math/bits", "Reverse32",
4755                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4756                         return s.newValue1(ssa.OpBitRev32, types.Types[types.TINT], args[0])
4757                 },
4758                 sys.ARM64)
4759         addF("math/bits", "Reverse16",
4760                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4761                         return s.newValue1(ssa.OpBitRev16, types.Types[types.TINT], args[0])
4762                 },
4763                 sys.ARM64)
4764         addF("math/bits", "Reverse8",
4765                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4766                         return s.newValue1(ssa.OpBitRev8, types.Types[types.TINT], args[0])
4767                 },
4768                 sys.ARM64)
4769         addF("math/bits", "Reverse",
4770                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4771                         return s.newValue1(ssa.OpBitRev64, types.Types[types.TINT], args[0])
4772                 },
4773                 sys.ARM64)
4774         addF("math/bits", "RotateLeft8",
4775                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4776                         return s.newValue2(ssa.OpRotateLeft8, types.Types[types.TUINT8], args[0], args[1])
4777                 },
4778                 sys.AMD64)
4779         addF("math/bits", "RotateLeft16",
4780                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4781                         return s.newValue2(ssa.OpRotateLeft16, types.Types[types.TUINT16], args[0], args[1])
4782                 },
4783                 sys.AMD64)
4784         addF("math/bits", "RotateLeft32",
4785                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4786                         return s.newValue2(ssa.OpRotateLeft32, types.Types[types.TUINT32], args[0], args[1])
4787                 },
4788                 sys.AMD64, sys.ARM, sys.ARM64, sys.S390X, sys.PPC64, sys.Wasm, sys.Loong64)
4789         addF("math/bits", "RotateLeft64",
4790                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4791                         return s.newValue2(ssa.OpRotateLeft64, types.Types[types.TUINT64], args[0], args[1])
4792                 },
4793                 sys.AMD64, sys.ARM64, sys.S390X, sys.PPC64, sys.Wasm, sys.Loong64)
4794         alias("math/bits", "RotateLeft", "math/bits", "RotateLeft64", p8...)
4795
4796         makeOnesCountAMD64 := func(op ssa.Op) func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4797                 return func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4798                         if buildcfg.GOAMD64 >= 2 {
4799                                 return s.newValue1(op, types.Types[types.TINT], args[0])
4800                         }
4801
4802                         v := s.entryNewValue0A(ssa.OpHasCPUFeature, types.Types[types.TBOOL], ir.Syms.X86HasPOPCNT)
4803                         b := s.endBlock()
4804                         b.Kind = ssa.BlockIf
4805                         b.SetControl(v)
4806                         bTrue := s.f.NewBlock(ssa.BlockPlain)
4807                         bFalse := s.f.NewBlock(ssa.BlockPlain)
4808                         bEnd := s.f.NewBlock(ssa.BlockPlain)
4809                         b.AddEdgeTo(bTrue)
4810                         b.AddEdgeTo(bFalse)
4811                         b.Likely = ssa.BranchLikely // most machines have popcnt nowadays
4812
4813                         // We have the intrinsic - use it directly.
4814                         s.startBlock(bTrue)
4815                         s.vars[n] = s.newValue1(op, types.Types[types.TINT], args[0])
4816                         s.endBlock().AddEdgeTo(bEnd)
4817
4818                         // Call the pure Go version.
4819                         s.startBlock(bFalse)
4820                         s.vars[n] = s.callResult(n, callNormal) // types.Types[TINT]
4821                         s.endBlock().AddEdgeTo(bEnd)
4822
4823                         // Merge results.
4824                         s.startBlock(bEnd)
4825                         return s.variable(n, types.Types[types.TINT])
4826                 }
4827         }
4828         addF("math/bits", "OnesCount64",
4829                 makeOnesCountAMD64(ssa.OpPopCount64),
4830                 sys.AMD64)
4831         addF("math/bits", "OnesCount64",
4832                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4833                         return s.newValue1(ssa.OpPopCount64, types.Types[types.TINT], args[0])
4834                 },
4835                 sys.PPC64, sys.ARM64, sys.S390X, sys.Wasm)
4836         addF("math/bits", "OnesCount32",
4837                 makeOnesCountAMD64(ssa.OpPopCount32),
4838                 sys.AMD64)
4839         addF("math/bits", "OnesCount32",
4840                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4841                         return s.newValue1(ssa.OpPopCount32, types.Types[types.TINT], args[0])
4842                 },
4843                 sys.PPC64, sys.ARM64, sys.S390X, sys.Wasm)
4844         addF("math/bits", "OnesCount16",
4845                 makeOnesCountAMD64(ssa.OpPopCount16),
4846                 sys.AMD64)
4847         addF("math/bits", "OnesCount16",
4848                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4849                         return s.newValue1(ssa.OpPopCount16, types.Types[types.TINT], args[0])
4850                 },
4851                 sys.ARM64, sys.S390X, sys.PPC64, sys.Wasm)
4852         addF("math/bits", "OnesCount8",
4853                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4854                         return s.newValue1(ssa.OpPopCount8, types.Types[types.TINT], args[0])
4855                 },
4856                 sys.S390X, sys.PPC64, sys.Wasm)
4857         addF("math/bits", "OnesCount",
4858                 makeOnesCountAMD64(ssa.OpPopCount64),
4859                 sys.AMD64)
4860         addF("math/bits", "Mul64",
4861                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4862                         return s.newValue2(ssa.OpMul64uhilo, types.NewTuple(types.Types[types.TUINT64], types.Types[types.TUINT64]), args[0], args[1])
4863                 },
4864                 sys.AMD64, sys.ARM64, sys.PPC64, sys.S390X, sys.MIPS64, sys.RISCV64, sys.Loong64)
4865         alias("math/bits", "Mul", "math/bits", "Mul64", p8...)
4866         alias("runtime/internal/math", "Mul64", "math/bits", "Mul64", p8...)
4867         addF("math/bits", "Add64",
4868                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4869                         return s.newValue3(ssa.OpAdd64carry, types.NewTuple(types.Types[types.TUINT64], types.Types[types.TUINT64]), args[0], args[1], args[2])
4870                 },
4871                 sys.AMD64, sys.ARM64, sys.PPC64, sys.S390X, sys.RISCV64, sys.Loong64, sys.MIPS64)
4872         alias("math/bits", "Add", "math/bits", "Add64", p8...)
4873         alias("runtime/internal/math", "Add64", "math/bits", "Add64", all...)
4874         addF("math/bits", "Sub64",
4875                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4876                         return s.newValue3(ssa.OpSub64borrow, types.NewTuple(types.Types[types.TUINT64], types.Types[types.TUINT64]), args[0], args[1], args[2])
4877                 },
4878                 sys.AMD64, sys.ARM64, sys.PPC64, sys.S390X, sys.RISCV64, sys.Loong64, sys.MIPS64)
4879         alias("math/bits", "Sub", "math/bits", "Sub64", p8...)
4880         addF("math/bits", "Div64",
4881                 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4882                         // check for divide-by-zero/overflow and panic with appropriate message
4883                         cmpZero := s.newValue2(s.ssaOp(ir.ONE, types.Types[types.TUINT64]), types.Types[types.TBOOL], args[2], s.zeroVal(types.Types[types.TUINT64]))
4884                         s.check(cmpZero, ir.Syms.Panicdivide)
4885                         cmpOverflow := s.newValue2(s.ssaOp(ir.OLT, types.Types[types.TUINT64]), types.Types[types.TBOOL], args[0], args[2])
4886                         s.check(cmpOverflow, ir.Syms.Panicoverflow)
4887                         return s.newValue3(ssa.OpDiv128u, types.NewTuple(types.Types[types.TUINT64], types.Types[types.TUINT64]), args[0], args[1], args[2])
4888                 },
4889                 sys.AMD64)
4890         alias("math/bits", "Div", "math/bits", "Div64", sys.ArchAMD64)
4891
4892         alias("runtime/internal/sys", "TrailingZeros8", "math/bits", "TrailingZeros8", all...)
4893         alias("runtime/internal/sys", "TrailingZeros32", "math/bits", "TrailingZeros32", all...)
4894         alias("runtime/internal/sys", "TrailingZeros64", "math/bits", "TrailingZeros64", all...)
4895         alias("runtime/internal/sys", "Len8", "math/bits", "Len8", all...)
4896         alias("runtime/internal/sys", "Len64", "math/bits", "Len64", all...)
4897         alias("runtime/internal/sys", "OnesCount64", "math/bits", "OnesCount64", all...)
4898
4899         /******** sync/atomic ********/
4900
4901         // Note: these are disabled by flag_race in findIntrinsic below.
4902         alias("sync/atomic", "LoadInt32", "runtime/internal/atomic", "Load", all...)
4903         alias("sync/atomic", "LoadInt64", "runtime/internal/atomic", "Load64", all...)
4904         alias("sync/atomic", "LoadPointer", "runtime/internal/atomic", "Loadp", all...)
4905         alias("sync/atomic", "LoadUint32", "runtime/internal/atomic", "Load", all...)
4906         alias("sync/atomic", "LoadUint64", "runtime/internal/atomic", "Load64", all...)
4907         alias("sync/atomic", "LoadUintptr", "runtime/internal/atomic", "Load", p4...)
4908         alias("sync/atomic", "LoadUintptr", "runtime/internal/atomic", "Load64", p8...)
4909
4910         alias("sync/atomic", "StoreInt32", "runtime/internal/atomic", "Store", all...)
4911         alias("sync/atomic", "StoreInt64", "runtime/internal/atomic", "Store64", all...)
4912         // Note: not StorePointer, that needs a write barrier.  Same below for {CompareAnd}Swap.
4913         alias("sync/atomic", "StoreUint32", "runtime/internal/atomic", "Store", all...)
4914         alias("sync/atomic", "StoreUint64", "runtime/internal/atomic", "Store64", all...)
4915         alias("sync/atomic", "StoreUintptr", "runtime/internal/atomic", "Store", p4...)
4916         alias("sync/atomic", "StoreUintptr", "runtime/internal/atomic", "Store64", p8...)
4917
4918         alias("sync/atomic", "SwapInt32", "runtime/internal/atomic", "Xchg", all...)
4919         alias("sync/atomic", "SwapInt64", "runtime/internal/atomic", "Xchg64", all...)
4920         alias("sync/atomic", "SwapUint32", "runtime/internal/atomic", "Xchg", all...)
4921         alias("sync/atomic", "SwapUint64", "runtime/internal/atomic", "Xchg64", all...)
4922         alias("sync/atomic", "SwapUintptr", "runtime/internal/atomic", "Xchg", p4...)
4923         alias("sync/atomic", "SwapUintptr", "runtime/internal/atomic", "Xchg64", p8...)
4924
4925         alias("sync/atomic", "CompareAndSwapInt32", "runtime/internal/atomic", "Cas", all...)
4926         alias("sync/atomic", "CompareAndSwapInt64", "runtime/internal/atomic", "Cas64", all...)
4927         alias("sync/atomic", "CompareAndSwapUint32", "runtime/internal/atomic", "Cas", all...)
4928         alias("sync/atomic", "CompareAndSwapUint64", "runtime/internal/atomic", "Cas64", all...)
4929         alias("sync/atomic", "CompareAndSwapUintptr", "runtime/internal/atomic", "Cas", p4...)
4930         alias("sync/atomic", "CompareAndSwapUintptr", "runtime/internal/atomic", "Cas64", p8...)
4931
4932         alias("sync/atomic", "AddInt32", "runtime/internal/atomic", "Xadd", all...)
4933         alias("sync/atomic", "AddInt64", "runtime/internal/atomic", "Xadd64", all...)
4934         alias("sync/atomic", "AddUint32", "runtime/internal/atomic", "Xadd", all...)
4935         alias("sync/atomic", "AddUint64", "runtime/internal/atomic", "Xadd64", all...)
4936         alias("sync/atomic", "AddUintptr", "runtime/internal/atomic", "Xadd", p4...)
4937         alias("sync/atomic", "AddUintptr", "runtime/internal/atomic", "Xadd64", p8...)
4938
4939         /******** math/big ********/
4940         alias("math/big", "mulWW", "math/bits", "Mul64", p8...)
4941 }
4942
4943 // findIntrinsic returns a function which builds the SSA equivalent of the
4944 // function identified by the symbol sym.  If sym is not an intrinsic call, returns nil.
4945 func findIntrinsic(sym *types.Sym) intrinsicBuilder {
4946         if sym == nil || sym.Pkg == nil {
4947                 return nil
4948         }
4949         pkg := sym.Pkg.Path
4950         if sym.Pkg == ir.Pkgs.Runtime {
4951                 pkg = "runtime"
4952         }
4953         if base.Flag.Race && pkg == "sync/atomic" {
4954                 // The race detector needs to be able to intercept these calls.
4955                 // We can't intrinsify them.
4956                 return nil
4957         }
4958         // Skip intrinsifying math functions (which may contain hard-float
4959         // instructions) when soft-float
4960         if Arch.SoftFloat && pkg == "math" {
4961                 return nil
4962         }
4963
4964         fn := sym.Name
4965         if ssa.IntrinsicsDisable {
4966                 if pkg == "runtime" && (fn == "getcallerpc" || fn == "getcallersp" || fn == "getclosureptr") {
4967                         // These runtime functions don't have definitions, must be intrinsics.
4968                 } else {
4969                         return nil
4970                 }
4971         }
4972         return intrinsics[intrinsicKey{Arch.LinkArch.Arch, pkg, fn}]
4973 }
4974
4975 func IsIntrinsicCall(n *ir.CallExpr) bool {
4976         if n == nil {
4977                 return false
4978         }
4979         name, ok := n.X.(*ir.Name)
4980         if !ok {
4981                 return false
4982         }
4983         return findIntrinsic(name.Sym()) != nil
4984 }
4985
4986 // intrinsicCall converts a call to a recognized intrinsic function into the intrinsic SSA operation.
4987 func (s *state) intrinsicCall(n *ir.CallExpr) *ssa.Value {
4988         v := findIntrinsic(n.X.Sym())(s, n, s.intrinsicArgs(n))
4989         if ssa.IntrinsicsDebug > 0 {
4990                 x := v
4991                 if x == nil {
4992                         x = s.mem()
4993                 }
4994                 if x.Op == ssa.OpSelect0 || x.Op == ssa.OpSelect1 {
4995                         x = x.Args[0]
4996                 }
4997                 base.WarnfAt(n.Pos(), "intrinsic substitution for %v with %s", n.X.Sym().Name, x.LongString())
4998         }
4999         return v
5000 }
5001
5002 // intrinsicArgs extracts args from n, evaluates them to SSA values, and returns them.
5003 func (s *state) intrinsicArgs(n *ir.CallExpr) []*ssa.Value {
5004         args := make([]*ssa.Value, len(n.Args))
5005         for i, n := range n.Args {
5006                 args[i] = s.expr(n)
5007         }
5008         return args
5009 }
5010
5011 // openDeferRecord adds code to evaluate and store the function for an open-code defer
5012 // call, and records info about the defer, so we can generate proper code on the
5013 // exit paths. n is the sub-node of the defer node that is the actual function
5014 // call. We will also record funcdata information on where the function is stored
5015 // (as well as the deferBits variable), and this will enable us to run the proper
5016 // defer calls during panics.
5017 func (s *state) openDeferRecord(n *ir.CallExpr) {
5018         if len(n.Args) != 0 || n.Op() != ir.OCALLFUNC || n.X.Type().NumResults() != 0 {
5019                 s.Fatalf("defer call with arguments or results: %v", n)
5020         }
5021
5022         opendefer := &openDeferInfo{
5023                 n: n,
5024         }
5025         fn := n.X
5026         // We must always store the function value in a stack slot for the
5027         // runtime panic code to use. But in the defer exit code, we will
5028         // call the function directly if it is a static function.
5029         closureVal := s.expr(fn)
5030         closure := s.openDeferSave(fn.Type(), closureVal)
5031         opendefer.closureNode = closure.Aux.(*ir.Name)
5032         if !(fn.Op() == ir.ONAME && fn.(*ir.Name).Class == ir.PFUNC) {
5033                 opendefer.closure = closure
5034         }
5035         index := len(s.openDefers)
5036         s.openDefers = append(s.openDefers, opendefer)
5037
5038         // Update deferBits only after evaluation and storage to stack of
5039         // the function is successful.
5040         bitvalue := s.constInt8(types.Types[types.TUINT8], 1<<uint(index))
5041         newDeferBits := s.newValue2(ssa.OpOr8, types.Types[types.TUINT8], s.variable(deferBitsVar, types.Types[types.TUINT8]), bitvalue)
5042         s.vars[deferBitsVar] = newDeferBits
5043         s.store(types.Types[types.TUINT8], s.deferBitsAddr, newDeferBits)
5044 }
5045
5046 // openDeferSave generates SSA nodes to store a value (with type t) for an
5047 // open-coded defer at an explicit autotmp location on the stack, so it can be
5048 // reloaded and used for the appropriate call on exit. Type t must be a function type
5049 // (therefore SSAable). val is the value to be stored. The function returns an SSA
5050 // value representing a pointer to the autotmp location.
5051 func (s *state) openDeferSave(t *types.Type, val *ssa.Value) *ssa.Value {
5052         if !ssa.CanSSA(t) {
5053                 s.Fatalf("openDeferSave of non-SSA-able type %v val=%v", t, val)
5054         }
5055         if !t.HasPointers() {
5056                 s.Fatalf("openDeferSave of pointerless type %v val=%v", t, val)
5057         }
5058         pos := val.Pos
5059         temp := typecheck.TempAt(pos.WithNotStmt(), s.curfn, t)
5060         temp.SetOpenDeferSlot(true)
5061         temp.SetFrameOffset(int64(len(s.openDefers))) // so cmpstackvarlt can order them
5062         var addrTemp *ssa.Value
5063         // Use OpVarLive to make sure stack slot for the closure is not removed by
5064         // dead-store elimination
5065         if s.curBlock.ID != s.f.Entry.ID {
5066                 // Force the tmp storing this defer function to be declared in the entry
5067                 // block, so that it will be live for the defer exit code (which will
5068                 // actually access it only if the associated defer call has been activated).
5069                 if t.HasPointers() {
5070                         s.defvars[s.f.Entry.ID][memVar] = s.f.Entry.NewValue1A(src.NoXPos, ssa.OpVarDef, types.TypeMem, temp, s.defvars[s.f.Entry.ID][memVar])
5071                 }
5072                 s.defvars[s.f.Entry.ID][memVar] = s.f.Entry.NewValue1A(src.NoXPos, ssa.OpVarLive, types.TypeMem, temp, s.defvars[s.f.Entry.ID][memVar])
5073                 addrTemp = s.f.Entry.NewValue2A(src.NoXPos, ssa.OpLocalAddr, types.NewPtr(temp.Type()), temp, s.sp, s.defvars[s.f.Entry.ID][memVar])
5074         } else {
5075                 // Special case if we're still in the entry block. We can't use
5076                 // the above code, since s.defvars[s.f.Entry.ID] isn't defined
5077                 // until we end the entry block with s.endBlock().
5078                 if t.HasPointers() {
5079                         s.vars[memVar] = s.newValue1Apos(ssa.OpVarDef, types.TypeMem, temp, s.mem(), false)
5080                 }
5081                 s.vars[memVar] = s.newValue1Apos(ssa.OpVarLive, types.TypeMem, temp, s.mem(), false)
5082                 addrTemp = s.newValue2Apos(ssa.OpLocalAddr, types.NewPtr(temp.Type()), temp, s.sp, s.mem(), false)
5083         }
5084         // Since we may use this temp during exit depending on the
5085         // deferBits, we must define it unconditionally on entry.
5086         // Therefore, we must make sure it is zeroed out in the entry
5087         // block if it contains pointers, else GC may wrongly follow an
5088         // uninitialized pointer value.
5089         temp.SetNeedzero(true)
5090         // We are storing to the stack, hence we can avoid the full checks in
5091         // storeType() (no write barrier) and do a simple store().
5092         s.store(t, addrTemp, val)
5093         return addrTemp
5094 }
5095
5096 // openDeferExit generates SSA for processing all the open coded defers at exit.
5097 // The code involves loading deferBits, and checking each of the bits to see if
5098 // the corresponding defer statement was executed. For each bit that is turned
5099 // on, the associated defer call is made.
5100 func (s *state) openDeferExit() {
5101         deferExit := s.f.NewBlock(ssa.BlockPlain)
5102         s.endBlock().AddEdgeTo(deferExit)
5103         s.startBlock(deferExit)
5104         s.lastDeferExit = deferExit
5105         s.lastDeferCount = len(s.openDefers)
5106         zeroval := s.constInt8(types.Types[types.TUINT8], 0)
5107         // Test for and run defers in reverse order
5108         for i := len(s.openDefers) - 1; i >= 0; i-- {
5109                 r := s.openDefers[i]
5110                 bCond := s.f.NewBlock(ssa.BlockPlain)
5111                 bEnd := s.f.NewBlock(ssa.BlockPlain)
5112
5113                 deferBits := s.variable(deferBitsVar, types.Types[types.TUINT8])
5114                 // Generate code to check if the bit associated with the current
5115                 // defer is set.
5116                 bitval := s.constInt8(types.Types[types.TUINT8], 1<<uint(i))
5117                 andval := s.newValue2(ssa.OpAnd8, types.Types[types.TUINT8], deferBits, bitval)
5118                 eqVal := s.newValue2(ssa.OpEq8, types.Types[types.TBOOL], andval, zeroval)
5119                 b := s.endBlock()
5120                 b.Kind = ssa.BlockIf
5121                 b.SetControl(eqVal)
5122                 b.AddEdgeTo(bEnd)
5123                 b.AddEdgeTo(bCond)
5124                 bCond.AddEdgeTo(bEnd)
5125                 s.startBlock(bCond)
5126
5127                 // Clear this bit in deferBits and force store back to stack, so
5128                 // we will not try to re-run this defer call if this defer call panics.
5129                 nbitval := s.newValue1(ssa.OpCom8, types.Types[types.TUINT8], bitval)
5130                 maskedval := s.newValue2(ssa.OpAnd8, types.Types[types.TUINT8], deferBits, nbitval)
5131                 s.store(types.Types[types.TUINT8], s.deferBitsAddr, maskedval)
5132                 // Use this value for following tests, so we keep previous
5133                 // bits cleared.
5134                 s.vars[deferBitsVar] = maskedval
5135
5136                 // Generate code to call the function call of the defer, using the
5137                 // closure that were stored in argtmps at the point of the defer
5138                 // statement.
5139                 fn := r.n.X
5140                 stksize := fn.Type().ArgWidth()
5141                 var callArgs []*ssa.Value
5142                 var call *ssa.Value
5143                 if r.closure != nil {
5144                         v := s.load(r.closure.Type.Elem(), r.closure)
5145                         s.maybeNilCheckClosure(v, callDefer)
5146                         codeptr := s.rawLoad(types.Types[types.TUINTPTR], v)
5147                         aux := ssa.ClosureAuxCall(s.f.ABIDefault.ABIAnalyzeTypes(nil, nil))
5148                         call = s.newValue2A(ssa.OpClosureLECall, aux.LateExpansionResultType(), aux, codeptr, v)
5149                 } else {
5150                         aux := ssa.StaticAuxCall(fn.(*ir.Name).Linksym(), s.f.ABIDefault.ABIAnalyzeTypes(nil, nil))
5151                         call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux)
5152                 }
5153                 callArgs = append(callArgs, s.mem())
5154                 call.AddArgs(callArgs...)
5155                 call.AuxInt = stksize
5156                 s.vars[memVar] = s.newValue1I(ssa.OpSelectN, types.TypeMem, 0, call)
5157                 // Make sure that the stack slots with pointers are kept live
5158                 // through the call (which is a pre-emption point). Also, we will
5159                 // use the first call of the last defer exit to compute liveness
5160                 // for the deferreturn, so we want all stack slots to be live.
5161                 if r.closureNode != nil {
5162                         s.vars[memVar] = s.newValue1Apos(ssa.OpVarLive, types.TypeMem, r.closureNode, s.mem(), false)
5163                 }
5164
5165                 s.endBlock()
5166                 s.startBlock(bEnd)
5167         }
5168 }
5169
5170 func (s *state) callResult(n *ir.CallExpr, k callKind) *ssa.Value {
5171         return s.call(n, k, false)
5172 }
5173
5174 func (s *state) callAddr(n *ir.CallExpr, k callKind) *ssa.Value {
5175         return s.call(n, k, true)
5176 }
5177
5178 // Calls the function n using the specified call type.
5179 // Returns the address of the return value (or nil if none).
5180 func (s *state) call(n *ir.CallExpr, k callKind, returnResultAddr bool) *ssa.Value {
5181         s.prevCall = nil
5182         var callee *ir.Name    // target function (if static)
5183         var closure *ssa.Value // ptr to closure to run (if dynamic)
5184         var codeptr *ssa.Value // ptr to target code (if dynamic)
5185         var rcvr *ssa.Value    // receiver to set
5186         fn := n.X
5187         var ACArgs []*types.Type    // AuxCall args
5188         var ACResults []*types.Type // AuxCall results
5189         var callArgs []*ssa.Value   // For late-expansion, the args themselves (not stored, args to the call instead).
5190
5191         callABI := s.f.ABIDefault
5192
5193         if k != callNormal && k != callTail && (len(n.Args) != 0 || n.Op() == ir.OCALLINTER || n.X.Type().NumResults() != 0) {
5194                 s.Fatalf("go/defer call with arguments: %v", n)
5195         }
5196
5197         switch n.Op() {
5198         case ir.OCALLFUNC:
5199                 if (k == callNormal || k == callTail) && fn.Op() == ir.ONAME && fn.(*ir.Name).Class == ir.PFUNC {
5200                         fn := fn.(*ir.Name)
5201                         callee = fn
5202                         if buildcfg.Experiment.RegabiArgs {
5203                                 // This is a static call, so it may be
5204                                 // a direct call to a non-ABIInternal
5205                                 // function. fn.Func may be nil for
5206                                 // some compiler-generated functions,
5207                                 // but those are all ABIInternal.
5208                                 if fn.Func != nil {
5209                                         callABI = abiForFunc(fn.Func, s.f.ABI0, s.f.ABI1)
5210                                 }
5211                         } else {
5212                                 // TODO(register args) remove after register abi is working
5213                                 inRegistersImported := fn.Pragma()&ir.RegisterParams != 0
5214                                 inRegistersSamePackage := fn.Func != nil && fn.Func.Pragma&ir.RegisterParams != 0
5215                                 if inRegistersImported || inRegistersSamePackage {
5216                                         callABI = s.f.ABI1
5217                                 }
5218                         }
5219                         break
5220                 }
5221                 closure = s.expr(fn)
5222                 if k != callDefer && k != callDeferStack {
5223                         // Deferred nil function needs to panic when the function is invoked,
5224                         // not the point of defer statement.
5225                         s.maybeNilCheckClosure(closure, k)
5226                 }
5227         case ir.OCALLINTER:
5228                 if fn.Op() != ir.ODOTINTER {
5229                         s.Fatalf("OCALLINTER: n.Left not an ODOTINTER: %v", fn.Op())
5230                 }
5231                 fn := fn.(*ir.SelectorExpr)
5232                 var iclosure *ssa.Value
5233                 iclosure, rcvr = s.getClosureAndRcvr(fn)
5234                 if k == callNormal {
5235                         codeptr = s.load(types.Types[types.TUINTPTR], iclosure)
5236                 } else {
5237                         closure = iclosure
5238                 }
5239         }
5240
5241         params := callABI.ABIAnalyze(n.X.Type(), false /* Do not set (register) nNames from caller side -- can cause races. */)
5242         types.CalcSize(fn.Type())
5243         stksize := params.ArgWidth() // includes receiver, args, and results
5244
5245         res := n.X.Type().Results()
5246         if k == callNormal || k == callTail {
5247                 for _, p := range params.OutParams() {
5248                         ACResults = append(ACResults, p.Type)
5249                 }
5250         }
5251
5252         var call *ssa.Value
5253         if k == callDeferStack {
5254                 if stksize != 0 {
5255                         s.Fatalf("deferprocStack with non-zero stack size %d: %v", stksize, n)
5256                 }
5257                 // Make a defer struct on the stack.
5258                 t := deferstruct()
5259                 _, addr := s.temp(n.Pos(), t)
5260                 s.store(closure.Type,
5261                         s.newValue1I(ssa.OpOffPtr, closure.Type.PtrTo(), t.FieldOff(deferStructFnField), addr),
5262                         closure)
5263
5264                 // Call runtime.deferprocStack with pointer to _defer record.
5265                 ACArgs = append(ACArgs, types.Types[types.TUINTPTR])
5266                 aux := ssa.StaticAuxCall(ir.Syms.DeferprocStack, s.f.ABIDefault.ABIAnalyzeTypes(ACArgs, ACResults))
5267                 callArgs = append(callArgs, addr, s.mem())
5268                 call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux)
5269                 call.AddArgs(callArgs...)
5270                 call.AuxInt = int64(types.PtrSize) // deferprocStack takes a *_defer arg
5271         } else {
5272                 // Store arguments to stack, including defer/go arguments and receiver for method calls.
5273                 // These are written in SP-offset order.
5274                 argStart := base.Ctxt.Arch.FixedFrameSize
5275                 // Defer/go args.
5276                 if k != callNormal && k != callTail {
5277                         // Write closure (arg to newproc/deferproc).
5278                         ACArgs = append(ACArgs, types.Types[types.TUINTPTR]) // not argExtra
5279                         callArgs = append(callArgs, closure)
5280                         stksize += int64(types.PtrSize)
5281                         argStart += int64(types.PtrSize)
5282                 }
5283
5284                 // Set receiver (for interface calls).
5285                 if rcvr != nil {
5286                         callArgs = append(callArgs, rcvr)
5287                 }
5288
5289                 // Write args.
5290                 t := n.X.Type()
5291                 args := n.Args
5292
5293                 for _, p := range params.InParams() { // includes receiver for interface calls
5294                         ACArgs = append(ACArgs, p.Type)
5295                 }
5296
5297                 // Split the entry block if there are open defers, because later calls to
5298                 // openDeferSave may cause a mismatch between the mem for an OpDereference
5299                 // and the call site which uses it. See #49282.
5300                 if s.curBlock.ID == s.f.Entry.ID && s.hasOpenDefers {
5301                         b := s.endBlock()
5302                         b.Kind = ssa.BlockPlain
5303                         curb := s.f.NewBlock(ssa.BlockPlain)
5304                         b.AddEdgeTo(curb)
5305                         s.startBlock(curb)
5306                 }
5307
5308                 for i, n := range args {
5309                         callArgs = append(callArgs, s.putArg(n, t.Param(i).Type))
5310                 }
5311
5312                 callArgs = append(callArgs, s.mem())
5313
5314                 // call target
5315                 switch {
5316                 case k == callDefer:
5317                         aux := ssa.StaticAuxCall(ir.Syms.Deferproc, s.f.ABIDefault.ABIAnalyzeTypes(ACArgs, ACResults)) // TODO paramResultInfo for DeferProc
5318                         call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux)
5319                 case k == callGo:
5320                         aux := ssa.StaticAuxCall(ir.Syms.Newproc, s.f.ABIDefault.ABIAnalyzeTypes(ACArgs, ACResults))
5321                         call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux) // TODO paramResultInfo for NewProc
5322                 case closure != nil:
5323                         // rawLoad because loading the code pointer from a
5324                         // closure is always safe, but IsSanitizerSafeAddr
5325                         // can't always figure that out currently, and it's
5326                         // critical that we not clobber any arguments already
5327                         // stored onto the stack.
5328                         codeptr = s.rawLoad(types.Types[types.TUINTPTR], closure)
5329                         aux := ssa.ClosureAuxCall(callABI.ABIAnalyzeTypes(ACArgs, ACResults))
5330                         call = s.newValue2A(ssa.OpClosureLECall, aux.LateExpansionResultType(), aux, codeptr, closure)
5331                 case codeptr != nil:
5332                         // Note that the "receiver" parameter is nil because the actual receiver is the first input parameter.
5333                         aux := ssa.InterfaceAuxCall(params)
5334                         call = s.newValue1A(ssa.OpInterLECall, aux.LateExpansionResultType(), aux, codeptr)
5335                 case callee != nil:
5336                         aux := ssa.StaticAuxCall(callTargetLSym(callee), params)
5337                         call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux)
5338                         if k == callTail {
5339                                 call.Op = ssa.OpTailLECall
5340                                 stksize = 0 // Tail call does not use stack. We reuse caller's frame.
5341                         }
5342                 default:
5343                         s.Fatalf("bad call type %v %v", n.Op(), n)
5344                 }
5345                 call.AddArgs(callArgs...)
5346                 call.AuxInt = stksize // Call operations carry the argsize of the callee along with them
5347         }
5348         s.prevCall = call
5349         s.vars[memVar] = s.newValue1I(ssa.OpSelectN, types.TypeMem, int64(len(ACResults)), call)
5350         // Insert VarLive opcodes.
5351         for _, v := range n.KeepAlive {
5352                 if !v.Addrtaken() {
5353                         s.Fatalf("KeepAlive variable %v must have Addrtaken set", v)
5354                 }
5355                 switch v.Class {
5356                 case ir.PAUTO, ir.PPARAM, ir.PPARAMOUT:
5357                 default:
5358                         s.Fatalf("KeepAlive variable %v must be Auto or Arg", v)
5359                 }
5360                 s.vars[memVar] = s.newValue1A(ssa.OpVarLive, types.TypeMem, v, s.mem())
5361         }
5362
5363         // Finish block for defers
5364         if k == callDefer || k == callDeferStack {
5365                 b := s.endBlock()
5366                 b.Kind = ssa.BlockDefer
5367                 b.SetControl(call)
5368                 bNext := s.f.NewBlock(ssa.BlockPlain)
5369                 b.AddEdgeTo(bNext)
5370                 // Add recover edge to exit code.
5371                 r := s.f.NewBlock(ssa.BlockPlain)
5372                 s.startBlock(r)
5373                 s.exit()
5374                 b.AddEdgeTo(r)
5375                 b.Likely = ssa.BranchLikely
5376                 s.startBlock(bNext)
5377         }
5378
5379         if len(res) == 0 || k != callNormal {
5380                 // call has no return value. Continue with the next statement.
5381                 return nil
5382         }
5383         fp := res[0]
5384         if returnResultAddr {
5385                 return s.resultAddrOfCall(call, 0, fp.Type)
5386         }
5387         return s.newValue1I(ssa.OpSelectN, fp.Type, 0, call)
5388 }
5389
5390 // maybeNilCheckClosure checks if a nil check of a closure is needed in some
5391 // architecture-dependent situations and, if so, emits the nil check.
5392 func (s *state) maybeNilCheckClosure(closure *ssa.Value, k callKind) {
5393         if Arch.LinkArch.Family == sys.Wasm || buildcfg.GOOS == "aix" && k != callGo {
5394                 // On AIX, the closure needs to be verified as fn can be nil, except if it's a call go. This needs to be handled by the runtime to have the "go of nil func value" error.
5395                 // TODO(neelance): On other architectures this should be eliminated by the optimization steps
5396                 s.nilCheck(closure)
5397         }
5398 }
5399
5400 // getClosureAndRcvr returns values for the appropriate closure and receiver of an
5401 // interface call
5402 func (s *state) getClosureAndRcvr(fn *ir.SelectorExpr) (*ssa.Value, *ssa.Value) {
5403         i := s.expr(fn.X)
5404         itab := s.newValue1(ssa.OpITab, types.Types[types.TUINTPTR], i)
5405         s.nilCheck(itab)
5406         itabidx := fn.Offset() + 2*int64(types.PtrSize) + 8 // offset of fun field in runtime.itab
5407         closure := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.UintptrPtr, itabidx, itab)
5408         rcvr := s.newValue1(ssa.OpIData, s.f.Config.Types.BytePtr, i)
5409         return closure, rcvr
5410 }
5411
5412 // etypesign returns the signed-ness of e, for integer/pointer etypes.
5413 // -1 means signed, +1 means unsigned, 0 means non-integer/non-pointer.
5414 func etypesign(e types.Kind) int8 {
5415         switch e {
5416         case types.TINT8, types.TINT16, types.TINT32, types.TINT64, types.TINT:
5417                 return -1
5418         case types.TUINT8, types.TUINT16, types.TUINT32, types.TUINT64, types.TUINT, types.TUINTPTR, types.TUNSAFEPTR:
5419                 return +1
5420         }
5421         return 0
5422 }
5423
5424 // addr converts the address of the expression n to SSA, adds it to s and returns the SSA result.
5425 // The value that the returned Value represents is guaranteed to be non-nil.
5426 func (s *state) addr(n ir.Node) *ssa.Value {
5427         if n.Op() != ir.ONAME {
5428                 s.pushLine(n.Pos())
5429                 defer s.popLine()
5430         }
5431
5432         if s.canSSA(n) {
5433                 s.Fatalf("addr of canSSA expression: %+v", n)
5434         }
5435
5436         t := types.NewPtr(n.Type())
5437         linksymOffset := func(lsym *obj.LSym, offset int64) *ssa.Value {
5438                 v := s.entryNewValue1A(ssa.OpAddr, t, lsym, s.sb)
5439                 // TODO: Make OpAddr use AuxInt as well as Aux.
5440                 if offset != 0 {
5441                         v = s.entryNewValue1I(ssa.OpOffPtr, v.Type, offset, v)
5442                 }
5443                 return v
5444         }
5445         switch n.Op() {
5446         case ir.OLINKSYMOFFSET:
5447                 no := n.(*ir.LinksymOffsetExpr)
5448                 return linksymOffset(no.Linksym, no.Offset_)
5449         case ir.ONAME:
5450                 n := n.(*ir.Name)
5451                 if n.Heapaddr != nil {
5452                         return s.expr(n.Heapaddr)
5453                 }
5454                 switch n.Class {
5455                 case ir.PEXTERN:
5456                         // global variable
5457                         return linksymOffset(n.Linksym(), 0)
5458                 case ir.PPARAM:
5459                         // parameter slot
5460                         v := s.decladdrs[n]
5461                         if v != nil {
5462                                 return v
5463                         }
5464                         s.Fatalf("addr of undeclared ONAME %v. declared: %v", n, s.decladdrs)
5465                         return nil
5466                 case ir.PAUTO:
5467                         return s.newValue2Apos(ssa.OpLocalAddr, t, n, s.sp, s.mem(), !ir.IsAutoTmp(n))
5468
5469                 case ir.PPARAMOUT: // Same as PAUTO -- cannot generate LEA early.
5470                         // ensure that we reuse symbols for out parameters so
5471                         // that cse works on their addresses
5472                         return s.newValue2Apos(ssa.OpLocalAddr, t, n, s.sp, s.mem(), true)
5473                 default:
5474                         s.Fatalf("variable address class %v not implemented", n.Class)
5475                         return nil
5476                 }
5477         case ir.ORESULT:
5478                 // load return from callee
5479                 n := n.(*ir.ResultExpr)
5480                 return s.resultAddrOfCall(s.prevCall, n.Index, n.Type())
5481         case ir.OINDEX:
5482                 n := n.(*ir.IndexExpr)
5483                 if n.X.Type().IsSlice() {
5484                         a := s.expr(n.X)
5485                         i := s.expr(n.Index)
5486                         len := s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], a)
5487                         i = s.boundsCheck(i, len, ssa.BoundsIndex, n.Bounded())
5488                         p := s.newValue1(ssa.OpSlicePtr, t, a)
5489                         return s.newValue2(ssa.OpPtrIndex, t, p, i)
5490                 } else { // array
5491                         a := s.addr(n.X)
5492                         i := s.expr(n.Index)
5493                         len := s.constInt(types.Types[types.TINT], n.X.Type().NumElem())
5494                         i = s.boundsCheck(i, len, ssa.BoundsIndex, n.Bounded())
5495                         return s.newValue2(ssa.OpPtrIndex, types.NewPtr(n.X.Type().Elem()), a, i)
5496                 }
5497         case ir.ODEREF:
5498                 n := n.(*ir.StarExpr)
5499                 return s.exprPtr(n.X, n.Bounded(), n.Pos())
5500         case ir.ODOT:
5501                 n := n.(*ir.SelectorExpr)
5502                 p := s.addr(n.X)
5503                 return s.newValue1I(ssa.OpOffPtr, t, n.Offset(), p)
5504         case ir.ODOTPTR:
5505                 n := n.(*ir.SelectorExpr)
5506                 p := s.exprPtr(n.X, n.Bounded(), n.Pos())
5507                 return s.newValue1I(ssa.OpOffPtr, t, n.Offset(), p)
5508         case ir.OCONVNOP:
5509                 n := n.(*ir.ConvExpr)
5510                 if n.Type() == n.X.Type() {
5511                         return s.addr(n.X)
5512                 }
5513                 addr := s.addr(n.X)
5514                 return s.newValue1(ssa.OpCopy, t, addr) // ensure that addr has the right type
5515         case ir.OCALLFUNC, ir.OCALLINTER:
5516                 n := n.(*ir.CallExpr)
5517                 return s.callAddr(n, callNormal)
5518         case ir.ODOTTYPE, ir.ODYNAMICDOTTYPE:
5519                 var v *ssa.Value
5520                 if n.Op() == ir.ODOTTYPE {
5521                         v, _ = s.dottype(n.(*ir.TypeAssertExpr), false)
5522                 } else {
5523                         v, _ = s.dynamicDottype(n.(*ir.DynamicTypeAssertExpr), false)
5524                 }
5525                 if v.Op != ssa.OpLoad {
5526                         s.Fatalf("dottype of non-load")
5527                 }
5528                 if v.Args[1] != s.mem() {
5529                         s.Fatalf("memory no longer live from dottype load")
5530                 }
5531                 return v.Args[0]
5532         default:
5533                 s.Fatalf("unhandled addr %v", n.Op())
5534                 return nil
5535         }
5536 }
5537
5538 // canSSA reports whether n is SSA-able.
5539 // n must be an ONAME (or an ODOT sequence with an ONAME base).
5540 func (s *state) canSSA(n ir.Node) bool {
5541         if base.Flag.N != 0 {
5542                 return false
5543         }
5544         for {
5545                 nn := n
5546                 if nn.Op() == ir.ODOT {
5547                         nn := nn.(*ir.SelectorExpr)
5548                         n = nn.X
5549                         continue
5550                 }
5551                 if nn.Op() == ir.OINDEX {
5552                         nn := nn.(*ir.IndexExpr)
5553                         if nn.X.Type().IsArray() {
5554                                 n = nn.X
5555                                 continue
5556                         }
5557                 }
5558                 break
5559         }
5560         if n.Op() != ir.ONAME {
5561                 return false
5562         }
5563         return s.canSSAName(n.(*ir.Name)) && ssa.CanSSA(n.Type())
5564 }
5565
5566 func (s *state) canSSAName(name *ir.Name) bool {
5567         if name.Addrtaken() || !name.OnStack() {
5568                 return false
5569         }
5570         switch name.Class {
5571         case ir.PPARAMOUT:
5572                 if s.hasdefer {
5573                         // TODO: handle this case? Named return values must be
5574                         // in memory so that the deferred function can see them.
5575                         // Maybe do: if !strings.HasPrefix(n.String(), "~") { return false }
5576                         // Or maybe not, see issue 18860.  Even unnamed return values
5577                         // must be written back so if a defer recovers, the caller can see them.
5578                         return false
5579                 }
5580                 if s.cgoUnsafeArgs {
5581                         // Cgo effectively takes the address of all result args,
5582                         // but the compiler can't see that.
5583                         return false
5584                 }
5585         }
5586         return true
5587         // TODO: try to make more variables SSAable?
5588 }
5589
5590 // exprPtr evaluates n to a pointer and nil-checks it.
5591 func (s *state) exprPtr(n ir.Node, bounded bool, lineno src.XPos) *ssa.Value {
5592         p := s.expr(n)
5593         if bounded || n.NonNil() {
5594                 if s.f.Frontend().Debug_checknil() && lineno.Line() > 1 {
5595                         s.f.Warnl(lineno, "removed nil check")
5596                 }
5597                 return p
5598         }
5599         s.nilCheck(p)
5600         return p
5601 }
5602
5603 // nilCheck generates nil pointer checking code.
5604 // Used only for automatically inserted nil checks,
5605 // not for user code like 'x != nil'.
5606 func (s *state) nilCheck(ptr *ssa.Value) {
5607         if base.Debug.DisableNil != 0 || s.curfn.NilCheckDisabled() {
5608                 return
5609         }
5610         s.newValue2(ssa.OpNilCheck, types.TypeVoid, ptr, s.mem())
5611 }
5612
5613 // boundsCheck generates bounds checking code. Checks if 0 <= idx <[=] len, branches to exit if not.
5614 // Starts a new block on return.
5615 // On input, len must be converted to full int width and be nonnegative.
5616 // Returns idx converted to full int width.
5617 // If bounded is true then caller guarantees the index is not out of bounds
5618 // (but boundsCheck will still extend the index to full int width).
5619 func (s *state) boundsCheck(idx, len *ssa.Value, kind ssa.BoundsKind, bounded bool) *ssa.Value {
5620         idx = s.extendIndex(idx, len, kind, bounded)
5621
5622         if bounded || base.Flag.B != 0 {
5623                 // If bounded or bounds checking is flag-disabled, then no check necessary,
5624                 // just return the extended index.
5625                 //
5626                 // Here, bounded == true if the compiler generated the index itself,
5627                 // such as in the expansion of a slice initializer. These indexes are
5628                 // compiler-generated, not Go program variables, so they cannot be
5629                 // attacker-controlled, so we can omit Spectre masking as well.
5630                 //
5631                 // Note that we do not want to omit Spectre masking in code like:
5632                 //
5633                 //      if 0 <= i && i < len(x) {
5634                 //              use(x[i])
5635                 //      }
5636                 //
5637                 // Lucky for us, bounded==false for that code.
5638                 // In that case (handled below), we emit a bound check (and Spectre mask)
5639                 // and then the prove pass will remove the bounds check.
5640                 // In theory the prove pass could potentially remove certain
5641                 // Spectre masks, but it's very delicate and probably better
5642                 // to be conservative and leave them all in.
5643                 return idx
5644         }
5645
5646         bNext := s.f.NewBlock(ssa.BlockPlain)
5647         bPanic := s.f.NewBlock(ssa.BlockExit)
5648
5649         if !idx.Type.IsSigned() {
5650                 switch kind {
5651                 case ssa.BoundsIndex:
5652                         kind = ssa.BoundsIndexU
5653                 case ssa.BoundsSliceAlen:
5654                         kind = ssa.BoundsSliceAlenU
5655                 case ssa.BoundsSliceAcap:
5656                         kind = ssa.BoundsSliceAcapU
5657                 case ssa.BoundsSliceB:
5658                         kind = ssa.BoundsSliceBU
5659                 case ssa.BoundsSlice3Alen:
5660                         kind = ssa.BoundsSlice3AlenU
5661                 case ssa.BoundsSlice3Acap:
5662                         kind = ssa.BoundsSlice3AcapU
5663                 case ssa.BoundsSlice3B:
5664                         kind = ssa.BoundsSlice3BU
5665                 case ssa.BoundsSlice3C:
5666                         kind = ssa.BoundsSlice3CU
5667                 }
5668         }
5669
5670         var cmp *ssa.Value
5671         if kind == ssa.BoundsIndex || kind == ssa.BoundsIndexU {
5672                 cmp = s.newValue2(ssa.OpIsInBounds, types.Types[types.TBOOL], idx, len)
5673         } else {
5674                 cmp = s.newValue2(ssa.OpIsSliceInBounds, types.Types[types.TBOOL], idx, len)
5675         }
5676         b := s.endBlock()
5677         b.Kind = ssa.BlockIf
5678         b.SetControl(cmp)
5679         b.Likely = ssa.BranchLikely
5680         b.AddEdgeTo(bNext)
5681         b.AddEdgeTo(bPanic)
5682
5683         s.startBlock(bPanic)
5684         if Arch.LinkArch.Family == sys.Wasm {
5685                 // TODO(khr): figure out how to do "register" based calling convention for bounds checks.
5686                 // Should be similar to gcWriteBarrier, but I can't make it work.
5687                 s.rtcall(BoundsCheckFunc[kind], false, nil, idx, len)
5688         } else {
5689                 mem := s.newValue3I(ssa.OpPanicBounds, types.TypeMem, int64(kind), idx, len, s.mem())
5690                 s.endBlock().SetControl(mem)
5691         }
5692         s.startBlock(bNext)
5693
5694         // In Spectre index mode, apply an appropriate mask to avoid speculative out-of-bounds accesses.
5695         if base.Flag.Cfg.SpectreIndex {
5696                 op := ssa.OpSpectreIndex
5697                 if kind != ssa.BoundsIndex && kind != ssa.BoundsIndexU {
5698                         op = ssa.OpSpectreSliceIndex
5699                 }
5700                 idx = s.newValue2(op, types.Types[types.TINT], idx, len)
5701         }
5702
5703         return idx
5704 }
5705
5706 // If cmp (a bool) is false, panic using the given function.
5707 func (s *state) check(cmp *ssa.Value, fn *obj.LSym) {
5708         b := s.endBlock()
5709         b.Kind = ssa.BlockIf
5710         b.SetControl(cmp)
5711         b.Likely = ssa.BranchLikely
5712         bNext := s.f.NewBlock(ssa.BlockPlain)
5713         line := s.peekPos()
5714         pos := base.Ctxt.PosTable.Pos(line)
5715         fl := funcLine{f: fn, base: pos.Base(), line: pos.Line()}
5716         bPanic := s.panics[fl]
5717         if bPanic == nil {
5718                 bPanic = s.f.NewBlock(ssa.BlockPlain)
5719                 s.panics[fl] = bPanic
5720                 s.startBlock(bPanic)
5721                 // The panic call takes/returns memory to ensure that the right
5722                 // memory state is observed if the panic happens.
5723                 s.rtcall(fn, false, nil)
5724         }
5725         b.AddEdgeTo(bNext)
5726         b.AddEdgeTo(bPanic)
5727         s.startBlock(bNext)
5728 }
5729
5730 func (s *state) intDivide(n ir.Node, a, b *ssa.Value) *ssa.Value {
5731         needcheck := true
5732         switch b.Op {
5733         case ssa.OpConst8, ssa.OpConst16, ssa.OpConst32, ssa.OpConst64:
5734                 if b.AuxInt != 0 {
5735                         needcheck = false
5736                 }
5737         }
5738         if needcheck {
5739                 // do a size-appropriate check for zero
5740                 cmp := s.newValue2(s.ssaOp(ir.ONE, n.Type()), types.Types[types.TBOOL], b, s.zeroVal(n.Type()))
5741                 s.check(cmp, ir.Syms.Panicdivide)
5742         }
5743         return s.newValue2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
5744 }
5745
5746 // rtcall issues a call to the given runtime function fn with the listed args.
5747 // Returns a slice of results of the given result types.
5748 // The call is added to the end of the current block.
5749 // If returns is false, the block is marked as an exit block.
5750 func (s *state) rtcall(fn *obj.LSym, returns bool, results []*types.Type, args ...*ssa.Value) []*ssa.Value {
5751         s.prevCall = nil
5752         // Write args to the stack
5753         off := base.Ctxt.Arch.FixedFrameSize
5754         var callArgs []*ssa.Value
5755         var callArgTypes []*types.Type
5756
5757         for _, arg := range args {
5758                 t := arg.Type
5759                 off = types.RoundUp(off, t.Alignment())
5760                 size := t.Size()
5761                 callArgs = append(callArgs, arg)
5762                 callArgTypes = append(callArgTypes, t)
5763                 off += size
5764         }
5765         off = types.RoundUp(off, int64(types.RegSize))
5766
5767         // Issue call
5768         var call *ssa.Value
5769         aux := ssa.StaticAuxCall(fn, s.f.ABIDefault.ABIAnalyzeTypes(callArgTypes, results))
5770         callArgs = append(callArgs, s.mem())
5771         call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux)
5772         call.AddArgs(callArgs...)
5773         s.vars[memVar] = s.newValue1I(ssa.OpSelectN, types.TypeMem, int64(len(results)), call)
5774
5775         if !returns {
5776                 // Finish block
5777                 b := s.endBlock()
5778                 b.Kind = ssa.BlockExit
5779                 b.SetControl(call)
5780                 call.AuxInt = off - base.Ctxt.Arch.FixedFrameSize
5781                 if len(results) > 0 {
5782                         s.Fatalf("panic call can't have results")
5783                 }
5784                 return nil
5785         }
5786
5787         // Load results
5788         res := make([]*ssa.Value, len(results))
5789         for i, t := range results {
5790                 off = types.RoundUp(off, t.Alignment())
5791                 res[i] = s.resultOfCall(call, int64(i), t)
5792                 off += t.Size()
5793         }
5794         off = types.RoundUp(off, int64(types.PtrSize))
5795
5796         // Remember how much callee stack space we needed.
5797         call.AuxInt = off
5798
5799         return res
5800 }
5801
5802 // do *left = right for type t.
5803 func (s *state) storeType(t *types.Type, left, right *ssa.Value, skip skipMask, leftIsStmt bool) {
5804         s.instrument(t, left, instrumentWrite)
5805
5806         if skip == 0 && (!t.HasPointers() || ssa.IsStackAddr(left)) {
5807                 // Known to not have write barrier. Store the whole type.
5808                 s.vars[memVar] = s.newValue3Apos(ssa.OpStore, types.TypeMem, t, left, right, s.mem(), leftIsStmt)
5809                 return
5810         }
5811
5812         // store scalar fields first, so write barrier stores for
5813         // pointer fields can be grouped together, and scalar values
5814         // don't need to be live across the write barrier call.
5815         // TODO: if the writebarrier pass knows how to reorder stores,
5816         // we can do a single store here as long as skip==0.
5817         s.storeTypeScalars(t, left, right, skip)
5818         if skip&skipPtr == 0 && t.HasPointers() {
5819                 s.storeTypePtrs(t, left, right)
5820         }
5821 }
5822
5823 // do *left = right for all scalar (non-pointer) parts of t.
5824 func (s *state) storeTypeScalars(t *types.Type, left, right *ssa.Value, skip skipMask) {
5825         switch {
5826         case t.IsBoolean() || t.IsInteger() || t.IsFloat() || t.IsComplex():
5827                 s.store(t, left, right)
5828         case t.IsPtrShaped():
5829                 if t.IsPtr() && t.Elem().NotInHeap() {
5830                         s.store(t, left, right) // see issue 42032
5831                 }
5832                 // otherwise, no scalar fields.
5833         case t.IsString():
5834                 if skip&skipLen != 0 {
5835                         return
5836                 }
5837                 len := s.newValue1(ssa.OpStringLen, types.Types[types.TINT], right)
5838                 lenAddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, s.config.PtrSize, left)
5839                 s.store(types.Types[types.TINT], lenAddr, len)
5840         case t.IsSlice():
5841                 if skip&skipLen == 0 {
5842                         len := s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], right)
5843                         lenAddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, s.config.PtrSize, left)
5844                         s.store(types.Types[types.TINT], lenAddr, len)
5845                 }
5846                 if skip&skipCap == 0 {
5847                         cap := s.newValue1(ssa.OpSliceCap, types.Types[types.TINT], right)
5848                         capAddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, 2*s.config.PtrSize, left)
5849                         s.store(types.Types[types.TINT], capAddr, cap)
5850                 }
5851         case t.IsInterface():
5852                 // itab field doesn't need a write barrier (even though it is a pointer).
5853                 itab := s.newValue1(ssa.OpITab, s.f.Config.Types.BytePtr, right)
5854                 s.store(types.Types[types.TUINTPTR], left, itab)
5855         case t.IsStruct():
5856                 n := t.NumFields()
5857                 for i := 0; i < n; i++ {
5858                         ft := t.FieldType(i)
5859                         addr := s.newValue1I(ssa.OpOffPtr, ft.PtrTo(), t.FieldOff(i), left)
5860                         val := s.newValue1I(ssa.OpStructSelect, ft, int64(i), right)
5861                         s.storeTypeScalars(ft, addr, val, 0)
5862                 }
5863         case t.IsArray() && t.NumElem() == 0:
5864                 // nothing
5865         case t.IsArray() && t.NumElem() == 1:
5866                 s.storeTypeScalars(t.Elem(), left, s.newValue1I(ssa.OpArraySelect, t.Elem(), 0, right), 0)
5867         default:
5868                 s.Fatalf("bad write barrier type %v", t)
5869         }
5870 }
5871
5872 // do *left = right for all pointer parts of t.
5873 func (s *state) storeTypePtrs(t *types.Type, left, right *ssa.Value) {
5874         switch {
5875         case t.IsPtrShaped():
5876                 if t.IsPtr() && t.Elem().NotInHeap() {
5877                         break // see issue 42032
5878                 }
5879                 s.store(t, left, right)
5880         case t.IsString():
5881                 ptr := s.newValue1(ssa.OpStringPtr, s.f.Config.Types.BytePtr, right)
5882                 s.store(s.f.Config.Types.BytePtr, left, ptr)
5883         case t.IsSlice():
5884                 elType := types.NewPtr(t.Elem())
5885                 ptr := s.newValue1(ssa.OpSlicePtr, elType, right)
5886                 s.store(elType, left, ptr)
5887         case t.IsInterface():
5888                 // itab field is treated as a scalar.
5889                 idata := s.newValue1(ssa.OpIData, s.f.Config.Types.BytePtr, right)
5890                 idataAddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.BytePtrPtr, s.config.PtrSize, left)
5891                 s.store(s.f.Config.Types.BytePtr, idataAddr, idata)
5892         case t.IsStruct():
5893                 n := t.NumFields()
5894                 for i := 0; i < n; i++ {
5895                         ft := t.FieldType(i)
5896                         if !ft.HasPointers() {
5897                                 continue
5898                         }
5899                         addr := s.newValue1I(ssa.OpOffPtr, ft.PtrTo(), t.FieldOff(i), left)
5900                         val := s.newValue1I(ssa.OpStructSelect, ft, int64(i), right)
5901                         s.storeTypePtrs(ft, addr, val)
5902                 }
5903         case t.IsArray() && t.NumElem() == 0:
5904                 // nothing
5905         case t.IsArray() && t.NumElem() == 1:
5906                 s.storeTypePtrs(t.Elem(), left, s.newValue1I(ssa.OpArraySelect, t.Elem(), 0, right))
5907         default:
5908                 s.Fatalf("bad write barrier type %v", t)
5909         }
5910 }
5911
5912 // putArg evaluates n for the purpose of passing it as an argument to a function and returns the value for the call.
5913 func (s *state) putArg(n ir.Node, t *types.Type) *ssa.Value {
5914         var a *ssa.Value
5915         if !ssa.CanSSA(t) {
5916                 a = s.newValue2(ssa.OpDereference, t, s.addr(n), s.mem())
5917         } else {
5918                 a = s.expr(n)
5919         }
5920         return a
5921 }
5922
5923 func (s *state) storeArgWithBase(n ir.Node, t *types.Type, base *ssa.Value, off int64) {
5924         pt := types.NewPtr(t)
5925         var addr *ssa.Value
5926         if base == s.sp {
5927                 // Use special routine that avoids allocation on duplicate offsets.
5928                 addr = s.constOffPtrSP(pt, off)
5929         } else {
5930                 addr = s.newValue1I(ssa.OpOffPtr, pt, off, base)
5931         }
5932
5933         if !ssa.CanSSA(t) {
5934                 a := s.addr(n)
5935                 s.move(t, addr, a)
5936                 return
5937         }
5938
5939         a := s.expr(n)
5940         s.storeType(t, addr, a, 0, false)
5941 }
5942
5943 // slice computes the slice v[i:j:k] and returns ptr, len, and cap of result.
5944 // i,j,k may be nil, in which case they are set to their default value.
5945 // v may be a slice, string or pointer to an array.
5946 func (s *state) slice(v, i, j, k *ssa.Value, bounded bool) (p, l, c *ssa.Value) {
5947         t := v.Type
5948         var ptr, len, cap *ssa.Value
5949         switch {
5950         case t.IsSlice():
5951                 ptr = s.newValue1(ssa.OpSlicePtr, types.NewPtr(t.Elem()), v)
5952                 len = s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], v)
5953                 cap = s.newValue1(ssa.OpSliceCap, types.Types[types.TINT], v)
5954         case t.IsString():
5955                 ptr = s.newValue1(ssa.OpStringPtr, types.NewPtr(types.Types[types.TUINT8]), v)
5956                 len = s.newValue1(ssa.OpStringLen, types.Types[types.TINT], v)
5957                 cap = len
5958         case t.IsPtr():
5959                 if !t.Elem().IsArray() {
5960                         s.Fatalf("bad ptr to array in slice %v\n", t)
5961                 }
5962                 s.nilCheck(v)
5963                 ptr = s.newValue1(ssa.OpCopy, types.NewPtr(t.Elem().Elem()), v)
5964                 len = s.constInt(types.Types[types.TINT], t.Elem().NumElem())
5965                 cap = len
5966         default:
5967                 s.Fatalf("bad type in slice %v\n", t)
5968         }
5969
5970         // Set default values
5971         if i == nil {
5972                 i = s.constInt(types.Types[types.TINT], 0)
5973         }
5974         if j == nil {
5975                 j = len
5976         }
5977         three := true
5978         if k == nil {
5979                 three = false
5980                 k = cap
5981         }
5982
5983         // Panic if slice indices are not in bounds.
5984         // Make sure we check these in reverse order so that we're always
5985         // comparing against a value known to be nonnegative. See issue 28797.
5986         if three {
5987                 if k != cap {
5988                         kind := ssa.BoundsSlice3Alen
5989                         if t.IsSlice() {
5990                                 kind = ssa.BoundsSlice3Acap
5991                         }
5992                         k = s.boundsCheck(k, cap, kind, bounded)
5993                 }
5994                 if j != k {
5995                         j = s.boundsCheck(j, k, ssa.BoundsSlice3B, bounded)
5996                 }
5997                 i = s.boundsCheck(i, j, ssa.BoundsSlice3C, bounded)
5998         } else {
5999                 if j != k {
6000                         kind := ssa.BoundsSliceAlen
6001                         if t.IsSlice() {
6002                                 kind = ssa.BoundsSliceAcap
6003                         }
6004                         j = s.boundsCheck(j, k, kind, bounded)
6005                 }
6006                 i = s.boundsCheck(i, j, ssa.BoundsSliceB, bounded)
6007         }
6008
6009         // Word-sized integer operations.
6010         subOp := s.ssaOp(ir.OSUB, types.Types[types.TINT])
6011         mulOp := s.ssaOp(ir.OMUL, types.Types[types.TINT])
6012         andOp := s.ssaOp(ir.OAND, types.Types[types.TINT])
6013
6014         // Calculate the length (rlen) and capacity (rcap) of the new slice.
6015         // For strings the capacity of the result is unimportant. However,
6016         // we use rcap to test if we've generated a zero-length slice.
6017         // Use length of strings for that.
6018         rlen := s.newValue2(subOp, types.Types[types.TINT], j, i)
6019         rcap := rlen
6020         if j != k && !t.IsString() {
6021                 rcap = s.newValue2(subOp, types.Types[types.TINT], k, i)
6022         }
6023
6024         if (i.Op == ssa.OpConst64 || i.Op == ssa.OpConst32) && i.AuxInt == 0 {
6025                 // No pointer arithmetic necessary.
6026                 return ptr, rlen, rcap
6027         }
6028
6029         // Calculate the base pointer (rptr) for the new slice.
6030         //
6031         // Generate the following code assuming that indexes are in bounds.
6032         // The masking is to make sure that we don't generate a slice
6033         // that points to the next object in memory. We cannot just set
6034         // the pointer to nil because then we would create a nil slice or
6035         // string.
6036         //
6037         //     rcap = k - i
6038         //     rlen = j - i
6039         //     rptr = ptr + (mask(rcap) & (i * stride))
6040         //
6041         // Where mask(x) is 0 if x==0 and -1 if x>0 and stride is the width
6042         // of the element type.
6043         stride := s.constInt(types.Types[types.TINT], ptr.Type.Elem().Size())
6044
6045         // The delta is the number of bytes to offset ptr by.
6046         delta := s.newValue2(mulOp, types.Types[types.TINT], i, stride)
6047
6048         // If we're slicing to the point where the capacity is zero,
6049         // zero out the delta.
6050         mask := s.newValue1(ssa.OpSlicemask, types.Types[types.TINT], rcap)
6051         delta = s.newValue2(andOp, types.Types[types.TINT], delta, mask)
6052
6053         // Compute rptr = ptr + delta.
6054         rptr := s.newValue2(ssa.OpAddPtr, ptr.Type, ptr, delta)
6055
6056         return rptr, rlen, rcap
6057 }
6058
6059 type u642fcvtTab struct {
6060         leq, cvt2F, and, rsh, or, add ssa.Op
6061         one                           func(*state, *types.Type, int64) *ssa.Value
6062 }
6063
6064 var u64_f64 = u642fcvtTab{
6065         leq:   ssa.OpLeq64,
6066         cvt2F: ssa.OpCvt64to64F,
6067         and:   ssa.OpAnd64,
6068         rsh:   ssa.OpRsh64Ux64,
6069         or:    ssa.OpOr64,
6070         add:   ssa.OpAdd64F,
6071         one:   (*state).constInt64,
6072 }
6073
6074 var u64_f32 = u642fcvtTab{
6075         leq:   ssa.OpLeq64,
6076         cvt2F: ssa.OpCvt64to32F,
6077         and:   ssa.OpAnd64,
6078         rsh:   ssa.OpRsh64Ux64,
6079         or:    ssa.OpOr64,
6080         add:   ssa.OpAdd32F,
6081         one:   (*state).constInt64,
6082 }
6083
6084 func (s *state) uint64Tofloat64(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6085         return s.uint64Tofloat(&u64_f64, n, x, ft, tt)
6086 }
6087
6088 func (s *state) uint64Tofloat32(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6089         return s.uint64Tofloat(&u64_f32, n, x, ft, tt)
6090 }
6091
6092 func (s *state) uint64Tofloat(cvttab *u642fcvtTab, n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6093         // if x >= 0 {
6094         //    result = (floatY) x
6095         // } else {
6096         //        y = uintX(x) ; y = x & 1
6097         //        z = uintX(x) ; z = z >> 1
6098         //        z = z | y
6099         //        result = floatY(z)
6100         //        result = result + result
6101         // }
6102         //
6103         // Code borrowed from old code generator.
6104         // What's going on: large 64-bit "unsigned" looks like
6105         // negative number to hardware's integer-to-float
6106         // conversion. However, because the mantissa is only
6107         // 63 bits, we don't need the LSB, so instead we do an
6108         // unsigned right shift (divide by two), convert, and
6109         // double. However, before we do that, we need to be
6110         // sure that we do not lose a "1" if that made the
6111         // difference in the resulting rounding. Therefore, we
6112         // preserve it, and OR (not ADD) it back in. The case
6113         // that matters is when the eleven discarded bits are
6114         // equal to 10000000001; that rounds up, and the 1 cannot
6115         // be lost else it would round down if the LSB of the
6116         // candidate mantissa is 0.
6117         cmp := s.newValue2(cvttab.leq, types.Types[types.TBOOL], s.zeroVal(ft), x)
6118         b := s.endBlock()
6119         b.Kind = ssa.BlockIf
6120         b.SetControl(cmp)
6121         b.Likely = ssa.BranchLikely
6122
6123         bThen := s.f.NewBlock(ssa.BlockPlain)
6124         bElse := s.f.NewBlock(ssa.BlockPlain)
6125         bAfter := s.f.NewBlock(ssa.BlockPlain)
6126
6127         b.AddEdgeTo(bThen)
6128         s.startBlock(bThen)
6129         a0 := s.newValue1(cvttab.cvt2F, tt, x)
6130         s.vars[n] = a0
6131         s.endBlock()
6132         bThen.AddEdgeTo(bAfter)
6133
6134         b.AddEdgeTo(bElse)
6135         s.startBlock(bElse)
6136         one := cvttab.one(s, ft, 1)
6137         y := s.newValue2(cvttab.and, ft, x, one)
6138         z := s.newValue2(cvttab.rsh, ft, x, one)
6139         z = s.newValue2(cvttab.or, ft, z, y)
6140         a := s.newValue1(cvttab.cvt2F, tt, z)
6141         a1 := s.newValue2(cvttab.add, tt, a, a)
6142         s.vars[n] = a1
6143         s.endBlock()
6144         bElse.AddEdgeTo(bAfter)
6145
6146         s.startBlock(bAfter)
6147         return s.variable(n, n.Type())
6148 }
6149
6150 type u322fcvtTab struct {
6151         cvtI2F, cvtF2F ssa.Op
6152 }
6153
6154 var u32_f64 = u322fcvtTab{
6155         cvtI2F: ssa.OpCvt32to64F,
6156         cvtF2F: ssa.OpCopy,
6157 }
6158
6159 var u32_f32 = u322fcvtTab{
6160         cvtI2F: ssa.OpCvt32to32F,
6161         cvtF2F: ssa.OpCvt64Fto32F,
6162 }
6163
6164 func (s *state) uint32Tofloat64(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6165         return s.uint32Tofloat(&u32_f64, n, x, ft, tt)
6166 }
6167
6168 func (s *state) uint32Tofloat32(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6169         return s.uint32Tofloat(&u32_f32, n, x, ft, tt)
6170 }
6171
6172 func (s *state) uint32Tofloat(cvttab *u322fcvtTab, n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6173         // if x >= 0 {
6174         //      result = floatY(x)
6175         // } else {
6176         //      result = floatY(float64(x) + (1<<32))
6177         // }
6178         cmp := s.newValue2(ssa.OpLeq32, types.Types[types.TBOOL], s.zeroVal(ft), x)
6179         b := s.endBlock()
6180         b.Kind = ssa.BlockIf
6181         b.SetControl(cmp)
6182         b.Likely = ssa.BranchLikely
6183
6184         bThen := s.f.NewBlock(ssa.BlockPlain)
6185         bElse := s.f.NewBlock(ssa.BlockPlain)
6186         bAfter := s.f.NewBlock(ssa.BlockPlain)
6187
6188         b.AddEdgeTo(bThen)
6189         s.startBlock(bThen)
6190         a0 := s.newValue1(cvttab.cvtI2F, tt, x)
6191         s.vars[n] = a0
6192         s.endBlock()
6193         bThen.AddEdgeTo(bAfter)
6194
6195         b.AddEdgeTo(bElse)
6196         s.startBlock(bElse)
6197         a1 := s.newValue1(ssa.OpCvt32to64F, types.Types[types.TFLOAT64], x)
6198         twoToThe32 := s.constFloat64(types.Types[types.TFLOAT64], float64(1<<32))
6199         a2 := s.newValue2(ssa.OpAdd64F, types.Types[types.TFLOAT64], a1, twoToThe32)
6200         a3 := s.newValue1(cvttab.cvtF2F, tt, a2)
6201
6202         s.vars[n] = a3
6203         s.endBlock()
6204         bElse.AddEdgeTo(bAfter)
6205
6206         s.startBlock(bAfter)
6207         return s.variable(n, n.Type())
6208 }
6209
6210 // referenceTypeBuiltin generates code for the len/cap builtins for maps and channels.
6211 func (s *state) referenceTypeBuiltin(n *ir.UnaryExpr, x *ssa.Value) *ssa.Value {
6212         if !n.X.Type().IsMap() && !n.X.Type().IsChan() {
6213                 s.Fatalf("node must be a map or a channel")
6214         }
6215         // if n == nil {
6216         //   return 0
6217         // } else {
6218         //   // len
6219         //   return *((*int)n)
6220         //   // cap
6221         //   return *(((*int)n)+1)
6222         // }
6223         lenType := n.Type()
6224         nilValue := s.constNil(types.Types[types.TUINTPTR])
6225         cmp := s.newValue2(ssa.OpEqPtr, types.Types[types.TBOOL], x, nilValue)
6226         b := s.endBlock()
6227         b.Kind = ssa.BlockIf
6228         b.SetControl(cmp)
6229         b.Likely = ssa.BranchUnlikely
6230
6231         bThen := s.f.NewBlock(ssa.BlockPlain)
6232         bElse := s.f.NewBlock(ssa.BlockPlain)
6233         bAfter := s.f.NewBlock(ssa.BlockPlain)
6234
6235         // length/capacity of a nil map/chan is zero
6236         b.AddEdgeTo(bThen)
6237         s.startBlock(bThen)
6238         s.vars[n] = s.zeroVal(lenType)
6239         s.endBlock()
6240         bThen.AddEdgeTo(bAfter)
6241
6242         b.AddEdgeTo(bElse)
6243         s.startBlock(bElse)
6244         switch n.Op() {
6245         case ir.OLEN:
6246                 // length is stored in the first word for map/chan
6247                 s.vars[n] = s.load(lenType, x)
6248         case ir.OCAP:
6249                 // capacity is stored in the second word for chan
6250                 sw := s.newValue1I(ssa.OpOffPtr, lenType.PtrTo(), lenType.Size(), x)
6251                 s.vars[n] = s.load(lenType, sw)
6252         default:
6253                 s.Fatalf("op must be OLEN or OCAP")
6254         }
6255         s.endBlock()
6256         bElse.AddEdgeTo(bAfter)
6257
6258         s.startBlock(bAfter)
6259         return s.variable(n, lenType)
6260 }
6261
6262 type f2uCvtTab struct {
6263         ltf, cvt2U, subf, or ssa.Op
6264         floatValue           func(*state, *types.Type, float64) *ssa.Value
6265         intValue             func(*state, *types.Type, int64) *ssa.Value
6266         cutoff               uint64
6267 }
6268
6269 var f32_u64 = f2uCvtTab{
6270         ltf:        ssa.OpLess32F,
6271         cvt2U:      ssa.OpCvt32Fto64,
6272         subf:       ssa.OpSub32F,
6273         or:         ssa.OpOr64,
6274         floatValue: (*state).constFloat32,
6275         intValue:   (*state).constInt64,
6276         cutoff:     1 << 63,
6277 }
6278
6279 var f64_u64 = f2uCvtTab{
6280         ltf:        ssa.OpLess64F,
6281         cvt2U:      ssa.OpCvt64Fto64,
6282         subf:       ssa.OpSub64F,
6283         or:         ssa.OpOr64,
6284         floatValue: (*state).constFloat64,
6285         intValue:   (*state).constInt64,
6286         cutoff:     1 << 63,
6287 }
6288
6289 var f32_u32 = f2uCvtTab{
6290         ltf:        ssa.OpLess32F,
6291         cvt2U:      ssa.OpCvt32Fto32,
6292         subf:       ssa.OpSub32F,
6293         or:         ssa.OpOr32,
6294         floatValue: (*state).constFloat32,
6295         intValue:   func(s *state, t *types.Type, v int64) *ssa.Value { return s.constInt32(t, int32(v)) },
6296         cutoff:     1 << 31,
6297 }
6298
6299 var f64_u32 = f2uCvtTab{
6300         ltf:        ssa.OpLess64F,
6301         cvt2U:      ssa.OpCvt64Fto32,
6302         subf:       ssa.OpSub64F,
6303         or:         ssa.OpOr32,
6304         floatValue: (*state).constFloat64,
6305         intValue:   func(s *state, t *types.Type, v int64) *ssa.Value { return s.constInt32(t, int32(v)) },
6306         cutoff:     1 << 31,
6307 }
6308
6309 func (s *state) float32ToUint64(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6310         return s.floatToUint(&f32_u64, n, x, ft, tt)
6311 }
6312 func (s *state) float64ToUint64(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6313         return s.floatToUint(&f64_u64, n, x, ft, tt)
6314 }
6315
6316 func (s *state) float32ToUint32(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6317         return s.floatToUint(&f32_u32, n, x, ft, tt)
6318 }
6319
6320 func (s *state) float64ToUint32(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6321         return s.floatToUint(&f64_u32, n, x, ft, tt)
6322 }
6323
6324 func (s *state) floatToUint(cvttab *f2uCvtTab, n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6325         // cutoff:=1<<(intY_Size-1)
6326         // if x < floatX(cutoff) {
6327         //      result = uintY(x)
6328         // } else {
6329         //      y = x - floatX(cutoff)
6330         //      z = uintY(y)
6331         //      result = z | -(cutoff)
6332         // }
6333         cutoff := cvttab.floatValue(s, ft, float64(cvttab.cutoff))
6334         cmp := s.newValue2(cvttab.ltf, types.Types[types.TBOOL], x, cutoff)
6335         b := s.endBlock()
6336         b.Kind = ssa.BlockIf
6337         b.SetControl(cmp)
6338         b.Likely = ssa.BranchLikely
6339
6340         bThen := s.f.NewBlock(ssa.BlockPlain)
6341         bElse := s.f.NewBlock(ssa.BlockPlain)
6342         bAfter := s.f.NewBlock(ssa.BlockPlain)
6343
6344         b.AddEdgeTo(bThen)
6345         s.startBlock(bThen)
6346         a0 := s.newValue1(cvttab.cvt2U, tt, x)
6347         s.vars[n] = a0
6348         s.endBlock()
6349         bThen.AddEdgeTo(bAfter)
6350
6351         b.AddEdgeTo(bElse)
6352         s.startBlock(bElse)
6353         y := s.newValue2(cvttab.subf, ft, x, cutoff)
6354         y = s.newValue1(cvttab.cvt2U, tt, y)
6355         z := cvttab.intValue(s, tt, int64(-cvttab.cutoff))
6356         a1 := s.newValue2(cvttab.or, tt, y, z)
6357         s.vars[n] = a1
6358         s.endBlock()
6359         bElse.AddEdgeTo(bAfter)
6360
6361         s.startBlock(bAfter)
6362         return s.variable(n, n.Type())
6363 }
6364
6365 // dottype generates SSA for a type assertion node.
6366 // commaok indicates whether to panic or return a bool.
6367 // If commaok is false, resok will be nil.
6368 func (s *state) dottype(n *ir.TypeAssertExpr, commaok bool) (res, resok *ssa.Value) {
6369         iface := s.expr(n.X)              // input interface
6370         target := s.reflectType(n.Type()) // target type
6371         var targetItab *ssa.Value
6372         if n.ITab != nil {
6373                 targetItab = s.expr(n.ITab)
6374         }
6375         return s.dottype1(n.Pos(), n.X.Type(), n.Type(), iface, nil, target, targetItab, commaok)
6376 }
6377
6378 func (s *state) dynamicDottype(n *ir.DynamicTypeAssertExpr, commaok bool) (res, resok *ssa.Value) {
6379         iface := s.expr(n.X)
6380         var source, target, targetItab *ssa.Value
6381         if n.SrcRType != nil {
6382                 source = s.expr(n.SrcRType)
6383         }
6384         if !n.X.Type().IsEmptyInterface() && !n.Type().IsInterface() {
6385                 byteptr := s.f.Config.Types.BytePtr
6386                 targetItab = s.expr(n.ITab)
6387                 // TODO(mdempsky): Investigate whether compiling n.RType could be
6388                 // better than loading itab.typ.
6389                 target = s.load(byteptr, s.newValue1I(ssa.OpOffPtr, byteptr, int64(types.PtrSize), targetItab)) // itab.typ
6390         } else {
6391                 target = s.expr(n.RType)
6392         }
6393         return s.dottype1(n.Pos(), n.X.Type(), n.Type(), iface, source, target, targetItab, commaok)
6394 }
6395
6396 // dottype1 implements a x.(T) operation. iface is the argument (x), dst is the type we're asserting to (T)
6397 // and src is the type we're asserting from.
6398 // source is the *runtime._type of src
6399 // target is the *runtime._type of dst.
6400 // If src is a nonempty interface and dst is not an interface, targetItab is an itab representing (dst, src). Otherwise it is nil.
6401 // commaok is true if the caller wants a boolean success value. Otherwise, the generated code panics if the conversion fails.
6402 func (s *state) dottype1(pos src.XPos, src, dst *types.Type, iface, source, target, targetItab *ssa.Value, commaok bool) (res, resok *ssa.Value) {
6403         byteptr := s.f.Config.Types.BytePtr
6404         if dst.IsInterface() {
6405                 if dst.IsEmptyInterface() {
6406                         // Converting to an empty interface.
6407                         // Input could be an empty or nonempty interface.
6408                         if base.Debug.TypeAssert > 0 {
6409                                 base.WarnfAt(pos, "type assertion inlined")
6410                         }
6411
6412                         // Get itab/type field from input.
6413                         itab := s.newValue1(ssa.OpITab, byteptr, iface)
6414                         // Conversion succeeds iff that field is not nil.
6415                         cond := s.newValue2(ssa.OpNeqPtr, types.Types[types.TBOOL], itab, s.constNil(byteptr))
6416
6417                         if src.IsEmptyInterface() && commaok {
6418                                 // Converting empty interface to empty interface with ,ok is just a nil check.
6419                                 return iface, cond
6420                         }
6421
6422                         // Branch on nilness.
6423                         b := s.endBlock()
6424                         b.Kind = ssa.BlockIf
6425                         b.SetControl(cond)
6426                         b.Likely = ssa.BranchLikely
6427                         bOk := s.f.NewBlock(ssa.BlockPlain)
6428                         bFail := s.f.NewBlock(ssa.BlockPlain)
6429                         b.AddEdgeTo(bOk)
6430                         b.AddEdgeTo(bFail)
6431
6432                         if !commaok {
6433                                 // On failure, panic by calling panicnildottype.
6434                                 s.startBlock(bFail)
6435                                 s.rtcall(ir.Syms.Panicnildottype, false, nil, target)
6436
6437                                 // On success, return (perhaps modified) input interface.
6438                                 s.startBlock(bOk)
6439                                 if src.IsEmptyInterface() {
6440                                         res = iface // Use input interface unchanged.
6441                                         return
6442                                 }
6443                                 // Load type out of itab, build interface with existing idata.
6444                                 off := s.newValue1I(ssa.OpOffPtr, byteptr, int64(types.PtrSize), itab)
6445                                 typ := s.load(byteptr, off)
6446                                 idata := s.newValue1(ssa.OpIData, byteptr, iface)
6447                                 res = s.newValue2(ssa.OpIMake, dst, typ, idata)
6448                                 return
6449                         }
6450
6451                         s.startBlock(bOk)
6452                         // nonempty -> empty
6453                         // Need to load type from itab
6454                         off := s.newValue1I(ssa.OpOffPtr, byteptr, int64(types.PtrSize), itab)
6455                         s.vars[typVar] = s.load(byteptr, off)
6456                         s.endBlock()
6457
6458                         // itab is nil, might as well use that as the nil result.
6459                         s.startBlock(bFail)
6460                         s.vars[typVar] = itab
6461                         s.endBlock()
6462
6463                         // Merge point.
6464                         bEnd := s.f.NewBlock(ssa.BlockPlain)
6465                         bOk.AddEdgeTo(bEnd)
6466                         bFail.AddEdgeTo(bEnd)
6467                         s.startBlock(bEnd)
6468                         idata := s.newValue1(ssa.OpIData, byteptr, iface)
6469                         res = s.newValue2(ssa.OpIMake, dst, s.variable(typVar, byteptr), idata)
6470                         resok = cond
6471                         delete(s.vars, typVar) // no practical effect, just to indicate typVar is no longer live.
6472                         return
6473                 }
6474                 // converting to a nonempty interface needs a runtime call.
6475                 if base.Debug.TypeAssert > 0 {
6476                         base.WarnfAt(pos, "type assertion not inlined")
6477                 }
6478                 if !commaok {
6479                         fn := ir.Syms.AssertI2I
6480                         if src.IsEmptyInterface() {
6481                                 fn = ir.Syms.AssertE2I
6482                         }
6483                         data := s.newValue1(ssa.OpIData, types.Types[types.TUNSAFEPTR], iface)
6484                         tab := s.newValue1(ssa.OpITab, byteptr, iface)
6485                         tab = s.rtcall(fn, true, []*types.Type{byteptr}, target, tab)[0]
6486                         return s.newValue2(ssa.OpIMake, dst, tab, data), nil
6487                 }
6488                 fn := ir.Syms.AssertI2I2
6489                 if src.IsEmptyInterface() {
6490                         fn = ir.Syms.AssertE2I2
6491                 }
6492                 res = s.rtcall(fn, true, []*types.Type{dst}, target, iface)[0]
6493                 resok = s.newValue2(ssa.OpNeqInter, types.Types[types.TBOOL], res, s.constInterface(dst))
6494                 return
6495         }
6496
6497         if base.Debug.TypeAssert > 0 {
6498                 base.WarnfAt(pos, "type assertion inlined")
6499         }
6500
6501         // Converting to a concrete type.
6502         direct := types.IsDirectIface(dst)
6503         itab := s.newValue1(ssa.OpITab, byteptr, iface) // type word of interface
6504         if base.Debug.TypeAssert > 0 {
6505                 base.WarnfAt(pos, "type assertion inlined")
6506         }
6507         var wantedFirstWord *ssa.Value
6508         if src.IsEmptyInterface() {
6509                 // Looking for pointer to target type.
6510                 wantedFirstWord = target
6511         } else {
6512                 // Looking for pointer to itab for target type and source interface.
6513                 wantedFirstWord = targetItab
6514         }
6515
6516         var tmp ir.Node     // temporary for use with large types
6517         var addr *ssa.Value // address of tmp
6518         if commaok && !ssa.CanSSA(dst) {
6519                 // unSSAable type, use temporary.
6520                 // TODO: get rid of some of these temporaries.
6521                 tmp, addr = s.temp(pos, dst)
6522         }
6523
6524         cond := s.newValue2(ssa.OpEqPtr, types.Types[types.TBOOL], itab, wantedFirstWord)
6525         b := s.endBlock()
6526         b.Kind = ssa.BlockIf
6527         b.SetControl(cond)
6528         b.Likely = ssa.BranchLikely
6529
6530         bOk := s.f.NewBlock(ssa.BlockPlain)
6531         bFail := s.f.NewBlock(ssa.BlockPlain)
6532         b.AddEdgeTo(bOk)
6533         b.AddEdgeTo(bFail)
6534
6535         if !commaok {
6536                 // on failure, panic by calling panicdottype
6537                 s.startBlock(bFail)
6538                 taddr := source
6539                 if taddr == nil {
6540                         taddr = s.reflectType(src)
6541                 }
6542                 if src.IsEmptyInterface() {
6543                         s.rtcall(ir.Syms.PanicdottypeE, false, nil, itab, target, taddr)
6544                 } else {
6545                         s.rtcall(ir.Syms.PanicdottypeI, false, nil, itab, target, taddr)
6546                 }
6547
6548                 // on success, return data from interface
6549                 s.startBlock(bOk)
6550                 if direct {
6551                         return s.newValue1(ssa.OpIData, dst, iface), nil
6552                 }
6553                 p := s.newValue1(ssa.OpIData, types.NewPtr(dst), iface)
6554                 return s.load(dst, p), nil
6555         }
6556
6557         // commaok is the more complicated case because we have
6558         // a control flow merge point.
6559         bEnd := s.f.NewBlock(ssa.BlockPlain)
6560         // Note that we need a new valVar each time (unlike okVar where we can
6561         // reuse the variable) because it might have a different type every time.
6562         valVar := ssaMarker("val")
6563
6564         // type assertion succeeded
6565         s.startBlock(bOk)
6566         if tmp == nil {
6567                 if direct {
6568                         s.vars[valVar] = s.newValue1(ssa.OpIData, dst, iface)
6569                 } else {
6570                         p := s.newValue1(ssa.OpIData, types.NewPtr(dst), iface)
6571                         s.vars[valVar] = s.load(dst, p)
6572                 }
6573         } else {
6574                 p := s.newValue1(ssa.OpIData, types.NewPtr(dst), iface)
6575                 s.move(dst, addr, p)
6576         }
6577         s.vars[okVar] = s.constBool(true)
6578         s.endBlock()
6579         bOk.AddEdgeTo(bEnd)
6580
6581         // type assertion failed
6582         s.startBlock(bFail)
6583         if tmp == nil {
6584                 s.vars[valVar] = s.zeroVal(dst)
6585         } else {
6586                 s.zero(dst, addr)
6587         }
6588         s.vars[okVar] = s.constBool(false)
6589         s.endBlock()
6590         bFail.AddEdgeTo(bEnd)
6591
6592         // merge point
6593         s.startBlock(bEnd)
6594         if tmp == nil {
6595                 res = s.variable(valVar, dst)
6596                 delete(s.vars, valVar) // no practical effect, just to indicate typVar is no longer live.
6597         } else {
6598                 res = s.load(dst, addr)
6599         }
6600         resok = s.variable(okVar, types.Types[types.TBOOL])
6601         delete(s.vars, okVar) // ditto
6602         return res, resok
6603 }
6604
6605 // temp allocates a temp of type t at position pos
6606 func (s *state) temp(pos src.XPos, t *types.Type) (*ir.Name, *ssa.Value) {
6607         tmp := typecheck.TempAt(pos, s.curfn, t)
6608         if t.HasPointers() {
6609                 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, tmp, s.mem())
6610         }
6611         addr := s.addr(tmp)
6612         return tmp, addr
6613 }
6614
6615 // variable returns the value of a variable at the current location.
6616 func (s *state) variable(n ir.Node, t *types.Type) *ssa.Value {
6617         v := s.vars[n]
6618         if v != nil {
6619                 return v
6620         }
6621         v = s.fwdVars[n]
6622         if v != nil {
6623                 return v
6624         }
6625
6626         if s.curBlock == s.f.Entry {
6627                 // No variable should be live at entry.
6628                 s.f.Fatalf("value %v (%v) incorrectly live at entry", n, v)
6629         }
6630         // Make a FwdRef, which records a value that's live on block input.
6631         // We'll find the matching definition as part of insertPhis.
6632         v = s.newValue0A(ssa.OpFwdRef, t, fwdRefAux{N: n})
6633         s.fwdVars[n] = v
6634         if n.Op() == ir.ONAME {
6635                 s.addNamedValue(n.(*ir.Name), v)
6636         }
6637         return v
6638 }
6639
6640 func (s *state) mem() *ssa.Value {
6641         return s.variable(memVar, types.TypeMem)
6642 }
6643
6644 func (s *state) addNamedValue(n *ir.Name, v *ssa.Value) {
6645         if n.Class == ir.Pxxx {
6646                 // Don't track our marker nodes (memVar etc.).
6647                 return
6648         }
6649         if ir.IsAutoTmp(n) {
6650                 // Don't track temporary variables.
6651                 return
6652         }
6653         if n.Class == ir.PPARAMOUT {
6654                 // Don't track named output values.  This prevents return values
6655                 // from being assigned too early. See #14591 and #14762. TODO: allow this.
6656                 return
6657         }
6658         loc := ssa.LocalSlot{N: n, Type: n.Type(), Off: 0}
6659         values, ok := s.f.NamedValues[loc]
6660         if !ok {
6661                 s.f.Names = append(s.f.Names, &loc)
6662                 s.f.CanonicalLocalSlots[loc] = &loc
6663         }
6664         s.f.NamedValues[loc] = append(values, v)
6665 }
6666
6667 // Branch is an unresolved branch.
6668 type Branch struct {
6669         P *obj.Prog  // branch instruction
6670         B *ssa.Block // target
6671 }
6672
6673 // State contains state needed during Prog generation.
6674 type State struct {
6675         ABI obj.ABI
6676
6677         pp *objw.Progs
6678
6679         // Branches remembers all the branch instructions we've seen
6680         // and where they would like to go.
6681         Branches []Branch
6682
6683         // JumpTables remembers all the jump tables we've seen.
6684         JumpTables []*ssa.Block
6685
6686         // bstart remembers where each block starts (indexed by block ID)
6687         bstart []*obj.Prog
6688
6689         maxarg int64 // largest frame size for arguments to calls made by the function
6690
6691         // Map from GC safe points to liveness index, generated by
6692         // liveness analysis.
6693         livenessMap liveness.Map
6694
6695         // partLiveArgs includes arguments that may be partially live, for which we
6696         // need to generate instructions that spill the argument registers.
6697         partLiveArgs map[*ir.Name]bool
6698
6699         // lineRunStart records the beginning of the current run of instructions
6700         // within a single block sharing the same line number
6701         // Used to move statement marks to the beginning of such runs.
6702         lineRunStart *obj.Prog
6703
6704         // wasm: The number of values on the WebAssembly stack. This is only used as a safeguard.
6705         OnWasmStackSkipped int
6706 }
6707
6708 func (s *State) FuncInfo() *obj.FuncInfo {
6709         return s.pp.CurFunc.LSym.Func()
6710 }
6711
6712 // Prog appends a new Prog.
6713 func (s *State) Prog(as obj.As) *obj.Prog {
6714         p := s.pp.Prog(as)
6715         if objw.LosesStmtMark(as) {
6716                 return p
6717         }
6718         // Float a statement start to the beginning of any same-line run.
6719         // lineRunStart is reset at block boundaries, which appears to work well.
6720         if s.lineRunStart == nil || s.lineRunStart.Pos.Line() != p.Pos.Line() {
6721                 s.lineRunStart = p
6722         } else if p.Pos.IsStmt() == src.PosIsStmt {
6723                 s.lineRunStart.Pos = s.lineRunStart.Pos.WithIsStmt()
6724                 p.Pos = p.Pos.WithNotStmt()
6725         }
6726         return p
6727 }
6728
6729 // Pc returns the current Prog.
6730 func (s *State) Pc() *obj.Prog {
6731         return s.pp.Next
6732 }
6733
6734 // SetPos sets the current source position.
6735 func (s *State) SetPos(pos src.XPos) {
6736         s.pp.Pos = pos
6737 }
6738
6739 // Br emits a single branch instruction and returns the instruction.
6740 // Not all architectures need the returned instruction, but otherwise
6741 // the boilerplate is common to all.
6742 func (s *State) Br(op obj.As, target *ssa.Block) *obj.Prog {
6743         p := s.Prog(op)
6744         p.To.Type = obj.TYPE_BRANCH
6745         s.Branches = append(s.Branches, Branch{P: p, B: target})
6746         return p
6747 }
6748
6749 // DebugFriendlySetPosFrom adjusts Pos.IsStmt subject to heuristics
6750 // that reduce "jumpy" line number churn when debugging.
6751 // Spill/fill/copy instructions from the register allocator,
6752 // phi functions, and instructions with a no-pos position
6753 // are examples of instructions that can cause churn.
6754 func (s *State) DebugFriendlySetPosFrom(v *ssa.Value) {
6755         switch v.Op {
6756         case ssa.OpPhi, ssa.OpCopy, ssa.OpLoadReg, ssa.OpStoreReg:
6757                 // These are not statements
6758                 s.SetPos(v.Pos.WithNotStmt())
6759         default:
6760                 p := v.Pos
6761                 if p != src.NoXPos {
6762                         // If the position is defined, update the position.
6763                         // Also convert default IsStmt to NotStmt; only
6764                         // explicit statement boundaries should appear
6765                         // in the generated code.
6766                         if p.IsStmt() != src.PosIsStmt {
6767                                 if s.pp.Pos.IsStmt() == src.PosIsStmt && s.pp.Pos.SameFileAndLine(p) {
6768                                         // If s.pp.Pos already has a statement mark, then it was set here (below) for
6769                                         // the previous value.  If an actual instruction had been emitted for that
6770                                         // value, then the statement mark would have been reset.  Since the statement
6771                                         // mark of s.pp.Pos was not reset, this position (file/line) still needs a
6772                                         // statement mark on an instruction.  If file and line for this value are
6773                                         // the same as the previous value, then the first instruction for this
6774                                         // value will work to take the statement mark.  Return early to avoid
6775                                         // resetting the statement mark.
6776                                         //
6777                                         // The reset of s.pp.Pos occurs in (*Progs).Prog() -- if it emits
6778                                         // an instruction, and the instruction's statement mark was set,
6779                                         // and it is not one of the LosesStmtMark instructions,
6780                                         // then Prog() resets the statement mark on the (*Progs).Pos.
6781                                         return
6782                                 }
6783                                 p = p.WithNotStmt()
6784                                 // Calls use the pos attached to v, but copy the statement mark from State
6785                         }
6786                         s.SetPos(p)
6787                 } else {
6788                         s.SetPos(s.pp.Pos.WithNotStmt())
6789                 }
6790         }
6791 }
6792
6793 // emit argument info (locations on stack) for traceback.
6794 func emitArgInfo(e *ssafn, f *ssa.Func, pp *objw.Progs) {
6795         ft := e.curfn.Type()
6796         if ft.NumRecvs() == 0 && ft.NumParams() == 0 {
6797                 return
6798         }
6799
6800         x := EmitArgInfo(e.curfn, f.OwnAux.ABIInfo())
6801         x.Set(obj.AttrContentAddressable, true)
6802         e.curfn.LSym.Func().ArgInfo = x
6803
6804         // Emit a funcdata pointing at the arg info data.
6805         p := pp.Prog(obj.AFUNCDATA)
6806         p.From.SetConst(rtabi.FUNCDATA_ArgInfo)
6807         p.To.Type = obj.TYPE_MEM
6808         p.To.Name = obj.NAME_EXTERN
6809         p.To.Sym = x
6810 }
6811
6812 // emit argument info (locations on stack) of f for traceback.
6813 func EmitArgInfo(f *ir.Func, abiInfo *abi.ABIParamResultInfo) *obj.LSym {
6814         x := base.Ctxt.Lookup(fmt.Sprintf("%s.arginfo%d", f.LSym.Name, f.ABI))
6815         // NOTE: do not set ContentAddressable here. This may be referenced from
6816         // assembly code by name (in this case f is a declaration).
6817         // Instead, set it in emitArgInfo above.
6818
6819         PtrSize := int64(types.PtrSize)
6820         uintptrTyp := types.Types[types.TUINTPTR]
6821
6822         isAggregate := func(t *types.Type) bool {
6823                 return t.IsStruct() || t.IsArray() || t.IsComplex() || t.IsInterface() || t.IsString() || t.IsSlice()
6824         }
6825
6826         // Populate the data.
6827         // The data is a stream of bytes, which contains the offsets and sizes of the
6828         // non-aggregate arguments or non-aggregate fields/elements of aggregate-typed
6829         // arguments, along with special "operators". Specifically,
6830         // - for each non-aggrgate arg/field/element, its offset from FP (1 byte) and
6831         //   size (1 byte)
6832         // - special operators:
6833         //   - 0xff - end of sequence
6834         //   - 0xfe - print { (at the start of an aggregate-typed argument)
6835         //   - 0xfd - print } (at the end of an aggregate-typed argument)
6836         //   - 0xfc - print ... (more args/fields/elements)
6837         //   - 0xfb - print _ (offset too large)
6838         // These constants need to be in sync with runtime.traceback.go:printArgs.
6839         const (
6840                 _endSeq         = 0xff
6841                 _startAgg       = 0xfe
6842                 _endAgg         = 0xfd
6843                 _dotdotdot      = 0xfc
6844                 _offsetTooLarge = 0xfb
6845                 _special        = 0xf0 // above this are operators, below this are ordinary offsets
6846         )
6847
6848         const (
6849                 limit    = 10 // print no more than 10 args/components
6850                 maxDepth = 5  // no more than 5 layers of nesting
6851
6852                 // maxLen is a (conservative) upper bound of the byte stream length. For
6853                 // each arg/component, it has no more than 2 bytes of data (size, offset),
6854                 // and no more than one {, }, ... at each level (it cannot have both the
6855                 // data and ... unless it is the last one, just be conservative). Plus 1
6856                 // for _endSeq.
6857                 maxLen = (maxDepth*3+2)*limit + 1
6858         )
6859
6860         wOff := 0
6861         n := 0
6862         writebyte := func(o uint8) { wOff = objw.Uint8(x, wOff, o) }
6863
6864         // Write one non-aggrgate arg/field/element.
6865         write1 := func(sz, offset int64) {
6866                 if offset >= _special {
6867                         writebyte(_offsetTooLarge)
6868                 } else {
6869                         writebyte(uint8(offset))
6870                         writebyte(uint8(sz))
6871                 }
6872                 n++
6873         }
6874
6875         // Visit t recursively and write it out.
6876         // Returns whether to continue visiting.
6877         var visitType func(baseOffset int64, t *types.Type, depth int) bool
6878         visitType = func(baseOffset int64, t *types.Type, depth int) bool {
6879                 if n >= limit {
6880                         writebyte(_dotdotdot)
6881                         return false
6882                 }
6883                 if !isAggregate(t) {
6884                         write1(t.Size(), baseOffset)
6885                         return true
6886                 }
6887                 writebyte(_startAgg)
6888                 depth++
6889                 if depth >= maxDepth {
6890                         writebyte(_dotdotdot)
6891                         writebyte(_endAgg)
6892                         n++
6893                         return true
6894                 }
6895                 switch {
6896                 case t.IsInterface(), t.IsString():
6897                         _ = visitType(baseOffset, uintptrTyp, depth) &&
6898                                 visitType(baseOffset+PtrSize, uintptrTyp, depth)
6899                 case t.IsSlice():
6900                         _ = visitType(baseOffset, uintptrTyp, depth) &&
6901                                 visitType(baseOffset+PtrSize, uintptrTyp, depth) &&
6902                                 visitType(baseOffset+PtrSize*2, uintptrTyp, depth)
6903                 case t.IsComplex():
6904                         _ = visitType(baseOffset, types.FloatForComplex(t), depth) &&
6905                                 visitType(baseOffset+t.Size()/2, types.FloatForComplex(t), depth)
6906                 case t.IsArray():
6907                         if t.NumElem() == 0 {
6908                                 n++ // {} counts as a component
6909                                 break
6910                         }
6911                         for i := int64(0); i < t.NumElem(); i++ {
6912                                 if !visitType(baseOffset, t.Elem(), depth) {
6913                                         break
6914                                 }
6915                                 baseOffset += t.Elem().Size()
6916                         }
6917                 case t.IsStruct():
6918                         if t.NumFields() == 0 {
6919                                 n++ // {} counts as a component
6920                                 break
6921                         }
6922                         for _, field := range t.Fields() {
6923                                 if !visitType(baseOffset+field.Offset, field.Type, depth) {
6924                                         break
6925                                 }
6926                         }
6927                 }
6928                 writebyte(_endAgg)
6929                 return true
6930         }
6931
6932         start := 0
6933         if strings.Contains(f.LSym.Name, "[") {
6934                 // Skip the dictionary argument - it is implicit and the user doesn't need to see it.
6935                 start = 1
6936         }
6937
6938         for _, a := range abiInfo.InParams()[start:] {
6939                 if !visitType(a.FrameOffset(abiInfo), a.Type, 0) {
6940                         break
6941                 }
6942         }
6943         writebyte(_endSeq)
6944         if wOff > maxLen {
6945                 base.Fatalf("ArgInfo too large")
6946         }
6947
6948         return x
6949 }
6950
6951 // for wrapper, emit info of wrapped function.
6952 func emitWrappedFuncInfo(e *ssafn, pp *objw.Progs) {
6953         if base.Ctxt.Flag_linkshared {
6954                 // Relative reference (SymPtrOff) to another shared object doesn't work.
6955                 // Unfortunate.
6956                 return
6957         }
6958
6959         wfn := e.curfn.WrappedFunc
6960         if wfn == nil {
6961                 return
6962         }
6963
6964         wsym := wfn.Linksym()
6965         x := base.Ctxt.LookupInit(fmt.Sprintf("%s.wrapinfo", wsym.Name), func(x *obj.LSym) {
6966                 objw.SymPtrOff(x, 0, wsym)
6967                 x.Set(obj.AttrContentAddressable, true)
6968         })
6969         e.curfn.LSym.Func().WrapInfo = x
6970
6971         // Emit a funcdata pointing at the wrap info data.
6972         p := pp.Prog(obj.AFUNCDATA)
6973         p.From.SetConst(rtabi.FUNCDATA_WrapInfo)
6974         p.To.Type = obj.TYPE_MEM
6975         p.To.Name = obj.NAME_EXTERN
6976         p.To.Sym = x
6977 }
6978
6979 // genssa appends entries to pp for each instruction in f.
6980 func genssa(f *ssa.Func, pp *objw.Progs) {
6981         var s State
6982         s.ABI = f.OwnAux.Fn.ABI()
6983
6984         e := f.Frontend().(*ssafn)
6985
6986         s.livenessMap, s.partLiveArgs = liveness.Compute(e.curfn, f, e.stkptrsize, pp)
6987         emitArgInfo(e, f, pp)
6988         argLiveBlockMap, argLiveValueMap := liveness.ArgLiveness(e.curfn, f, pp)
6989
6990         openDeferInfo := e.curfn.LSym.Func().OpenCodedDeferInfo
6991         if openDeferInfo != nil {
6992                 // This function uses open-coded defers -- write out the funcdata
6993                 // info that we computed at the end of genssa.
6994                 p := pp.Prog(obj.AFUNCDATA)
6995                 p.From.SetConst(rtabi.FUNCDATA_OpenCodedDeferInfo)
6996                 p.To.Type = obj.TYPE_MEM
6997                 p.To.Name = obj.NAME_EXTERN
6998                 p.To.Sym = openDeferInfo
6999         }
7000
7001         emitWrappedFuncInfo(e, pp)
7002
7003         // Remember where each block starts.
7004         s.bstart = make([]*obj.Prog, f.NumBlocks())
7005         s.pp = pp
7006         var progToValue map[*obj.Prog]*ssa.Value
7007         var progToBlock map[*obj.Prog]*ssa.Block
7008         var valueToProgAfter []*obj.Prog // The first Prog following computation of a value v; v is visible at this point.
7009         gatherPrintInfo := f.PrintOrHtmlSSA || ssa.GenssaDump[f.Name]
7010         if gatherPrintInfo {
7011                 progToValue = make(map[*obj.Prog]*ssa.Value, f.NumValues())
7012                 progToBlock = make(map[*obj.Prog]*ssa.Block, f.NumBlocks())
7013                 f.Logf("genssa %s\n", f.Name)
7014                 progToBlock[s.pp.Next] = f.Blocks[0]
7015         }
7016
7017         if base.Ctxt.Flag_locationlists {
7018                 if cap(f.Cache.ValueToProgAfter) < f.NumValues() {
7019                         f.Cache.ValueToProgAfter = make([]*obj.Prog, f.NumValues())
7020                 }
7021                 valueToProgAfter = f.Cache.ValueToProgAfter[:f.NumValues()]
7022                 for i := range valueToProgAfter {
7023                         valueToProgAfter[i] = nil
7024                 }
7025         }
7026
7027         // If the very first instruction is not tagged as a statement,
7028         // debuggers may attribute it to previous function in program.
7029         firstPos := src.NoXPos
7030         for _, v := range f.Entry.Values {
7031                 if v.Pos.IsStmt() == src.PosIsStmt && v.Op != ssa.OpArg && v.Op != ssa.OpArgIntReg && v.Op != ssa.OpArgFloatReg && v.Op != ssa.OpLoadReg && v.Op != ssa.OpStoreReg {
7032                         firstPos = v.Pos
7033                         v.Pos = firstPos.WithDefaultStmt()
7034                         break
7035                 }
7036         }
7037
7038         // inlMarks has an entry for each Prog that implements an inline mark.
7039         // It maps from that Prog to the global inlining id of the inlined body
7040         // which should unwind to this Prog's location.
7041         var inlMarks map[*obj.Prog]int32
7042         var inlMarkList []*obj.Prog
7043
7044         // inlMarksByPos maps from a (column 1) source position to the set of
7045         // Progs that are in the set above and have that source position.
7046         var inlMarksByPos map[src.XPos][]*obj.Prog
7047
7048         var argLiveIdx int = -1 // argument liveness info index
7049
7050         // Emit basic blocks
7051         for i, b := range f.Blocks {
7052                 s.bstart[b.ID] = s.pp.Next
7053                 s.lineRunStart = nil
7054                 s.SetPos(s.pp.Pos.WithNotStmt()) // It needs a non-empty Pos, but cannot be a statement boundary (yet).
7055
7056                 if idx, ok := argLiveBlockMap[b.ID]; ok && idx != argLiveIdx {
7057                         argLiveIdx = idx
7058                         p := s.pp.Prog(obj.APCDATA)
7059                         p.From.SetConst(rtabi.PCDATA_ArgLiveIndex)
7060                         p.To.SetConst(int64(idx))
7061                 }
7062
7063                 // Emit values in block
7064                 Arch.SSAMarkMoves(&s, b)
7065                 for _, v := range b.Values {
7066                         x := s.pp.Next
7067                         s.DebugFriendlySetPosFrom(v)
7068
7069                         if v.Op.ResultInArg0() && v.ResultReg() != v.Args[0].Reg() {
7070                                 v.Fatalf("input[0] and output not in same register %s", v.LongString())
7071                         }
7072
7073                         switch v.Op {
7074                         case ssa.OpInitMem:
7075                                 // memory arg needs no code
7076                         case ssa.OpArg:
7077                                 // input args need no code
7078                         case ssa.OpSP, ssa.OpSB:
7079                                 // nothing to do
7080                         case ssa.OpSelect0, ssa.OpSelect1, ssa.OpSelectN, ssa.OpMakeResult:
7081                                 // nothing to do
7082                         case ssa.OpGetG:
7083                                 // nothing to do when there's a g register,
7084                                 // and checkLower complains if there's not
7085                         case ssa.OpVarDef, ssa.OpVarLive, ssa.OpKeepAlive, ssa.OpWBend:
7086                                 // nothing to do; already used by liveness
7087                         case ssa.OpPhi:
7088                                 CheckLoweredPhi(v)
7089                         case ssa.OpConvert:
7090                                 // nothing to do; no-op conversion for liveness
7091                                 if v.Args[0].Reg() != v.Reg() {
7092                                         v.Fatalf("OpConvert should be a no-op: %s; %s", v.Args[0].LongString(), v.LongString())
7093                                 }
7094                         case ssa.OpInlMark:
7095                                 p := Arch.Ginsnop(s.pp)
7096                                 if inlMarks == nil {
7097                                         inlMarks = map[*obj.Prog]int32{}
7098                                         inlMarksByPos = map[src.XPos][]*obj.Prog{}
7099                                 }
7100                                 inlMarks[p] = v.AuxInt32()
7101                                 inlMarkList = append(inlMarkList, p)
7102                                 pos := v.Pos.AtColumn1()
7103                                 inlMarksByPos[pos] = append(inlMarksByPos[pos], p)
7104                                 firstPos = src.NoXPos
7105
7106                         default:
7107                                 // Special case for first line in function; move it to the start (which cannot be a register-valued instruction)
7108                                 if firstPos != src.NoXPos && v.Op != ssa.OpArgIntReg && v.Op != ssa.OpArgFloatReg && v.Op != ssa.OpLoadReg && v.Op != ssa.OpStoreReg {
7109                                         s.SetPos(firstPos)
7110                                         firstPos = src.NoXPos
7111                                 }
7112                                 // Attach this safe point to the next
7113                                 // instruction.
7114                                 s.pp.NextLive = s.livenessMap.Get(v)
7115                                 s.pp.NextUnsafe = s.livenessMap.GetUnsafe(v)
7116
7117                                 // let the backend handle it
7118                                 Arch.SSAGenValue(&s, v)
7119                         }
7120
7121                         if idx, ok := argLiveValueMap[v.ID]; ok && idx != argLiveIdx {
7122                                 argLiveIdx = idx
7123                                 p := s.pp.Prog(obj.APCDATA)
7124                                 p.From.SetConst(rtabi.PCDATA_ArgLiveIndex)
7125                                 p.To.SetConst(int64(idx))
7126                         }
7127
7128                         if base.Ctxt.Flag_locationlists {
7129                                 valueToProgAfter[v.ID] = s.pp.Next
7130                         }
7131
7132                         if gatherPrintInfo {
7133                                 for ; x != s.pp.Next; x = x.Link {
7134                                         progToValue[x] = v
7135                                 }
7136                         }
7137                 }
7138                 // If this is an empty infinite loop, stick a hardware NOP in there so that debuggers are less confused.
7139                 if s.bstart[b.ID] == s.pp.Next && len(b.Succs) == 1 && b.Succs[0].Block() == b {
7140                         p := Arch.Ginsnop(s.pp)
7141                         p.Pos = p.Pos.WithIsStmt()
7142                         if b.Pos == src.NoXPos {
7143                                 b.Pos = p.Pos // It needs a file, otherwise a no-file non-zero line causes confusion.  See #35652.
7144                                 if b.Pos == src.NoXPos {
7145                                         b.Pos = pp.Text.Pos // Sometimes p.Pos is empty.  See #35695.
7146                                 }
7147                         }
7148                         b.Pos = b.Pos.WithBogusLine() // Debuggers are not good about infinite loops, force a change in line number
7149                 }
7150
7151                 // Set unsafe mark for any end-of-block generated instructions
7152                 // (normally, conditional or unconditional branches).
7153                 // This is particularly important for empty blocks, as there
7154                 // are no values to inherit the unsafe mark from.
7155                 s.pp.NextUnsafe = s.livenessMap.GetUnsafeBlock(b)
7156
7157                 // Emit control flow instructions for block
7158                 var next *ssa.Block
7159                 if i < len(f.Blocks)-1 && base.Flag.N == 0 {
7160                         // If -N, leave next==nil so every block with successors
7161                         // ends in a JMP (except call blocks - plive doesn't like
7162                         // select{send,recv} followed by a JMP call).  Helps keep
7163                         // line numbers for otherwise empty blocks.
7164                         next = f.Blocks[i+1]
7165                 }
7166                 x := s.pp.Next
7167                 s.SetPos(b.Pos)
7168                 Arch.SSAGenBlock(&s, b, next)
7169                 if gatherPrintInfo {
7170                         for ; x != s.pp.Next; x = x.Link {
7171                                 progToBlock[x] = b
7172                         }
7173                 }
7174         }
7175         if f.Blocks[len(f.Blocks)-1].Kind == ssa.BlockExit {
7176                 // We need the return address of a panic call to
7177                 // still be inside the function in question. So if
7178                 // it ends in a call which doesn't return, add a
7179                 // nop (which will never execute) after the call.
7180                 Arch.Ginsnop(pp)
7181         }
7182         if openDeferInfo != nil {
7183                 // When doing open-coded defers, generate a disconnected call to
7184                 // deferreturn and a return. This will be used to during panic
7185                 // recovery to unwind the stack and return back to the runtime.
7186                 s.pp.NextLive = s.livenessMap.DeferReturn
7187                 p := pp.Prog(obj.ACALL)
7188                 p.To.Type = obj.TYPE_MEM
7189                 p.To.Name = obj.NAME_EXTERN
7190                 p.To.Sym = ir.Syms.Deferreturn
7191
7192                 // Load results into registers. So when a deferred function
7193                 // recovers a panic, it will return to caller with right results.
7194                 // The results are already in memory, because they are not SSA'd
7195                 // when the function has defers (see canSSAName).
7196                 for _, o := range f.OwnAux.ABIInfo().OutParams() {
7197                         n := o.Name
7198                         rts, offs := o.RegisterTypesAndOffsets()
7199                         for i := range o.Registers {
7200                                 Arch.LoadRegResult(&s, f, rts[i], ssa.ObjRegForAbiReg(o.Registers[i], f.Config), n, offs[i])
7201                         }
7202                 }
7203
7204                 pp.Prog(obj.ARET)
7205         }
7206
7207         if inlMarks != nil {
7208                 hasCall := false
7209
7210                 // We have some inline marks. Try to find other instructions we're
7211                 // going to emit anyway, and use those instructions instead of the
7212                 // inline marks.
7213                 for p := pp.Text; p != nil; p = p.Link {
7214                         if p.As == obj.ANOP || p.As == obj.AFUNCDATA || p.As == obj.APCDATA || p.As == obj.ATEXT || p.As == obj.APCALIGN || Arch.LinkArch.Family == sys.Wasm {
7215                                 // Don't use 0-sized instructions as inline marks, because we need
7216                                 // to identify inline mark instructions by pc offset.
7217                                 // (Some of these instructions are sometimes zero-sized, sometimes not.
7218                                 // We must not use anything that even might be zero-sized.)
7219                                 // TODO: are there others?
7220                                 continue
7221                         }
7222                         if _, ok := inlMarks[p]; ok {
7223                                 // Don't use inline marks themselves. We don't know
7224                                 // whether they will be zero-sized or not yet.
7225                                 continue
7226                         }
7227                         if p.As == obj.ACALL || p.As == obj.ADUFFCOPY || p.As == obj.ADUFFZERO {
7228                                 hasCall = true
7229                         }
7230                         pos := p.Pos.AtColumn1()
7231                         s := inlMarksByPos[pos]
7232                         if len(s) == 0 {
7233                                 continue
7234                         }
7235                         for _, m := range s {
7236                                 // We found an instruction with the same source position as
7237                                 // some of the inline marks.
7238                                 // Use this instruction instead.
7239                                 p.Pos = p.Pos.WithIsStmt() // promote position to a statement
7240                                 pp.CurFunc.LSym.Func().AddInlMark(p, inlMarks[m])
7241                                 // Make the inline mark a real nop, so it doesn't generate any code.
7242                                 m.As = obj.ANOP
7243                                 m.Pos = src.NoXPos
7244                                 m.From = obj.Addr{}
7245                                 m.To = obj.Addr{}
7246                         }
7247                         delete(inlMarksByPos, pos)
7248                 }
7249                 // Any unmatched inline marks now need to be added to the inlining tree (and will generate a nop instruction).
7250                 for _, p := range inlMarkList {
7251                         if p.As != obj.ANOP {
7252                                 pp.CurFunc.LSym.Func().AddInlMark(p, inlMarks[p])
7253                         }
7254                 }
7255
7256                 if e.stksize == 0 && !hasCall {
7257                         // Frameless leaf function. It doesn't need any preamble,
7258                         // so make sure its first instruction isn't from an inlined callee.
7259                         // If it is, add a nop at the start of the function with a position
7260                         // equal to the start of the function.
7261                         // This ensures that runtime.FuncForPC(uintptr(reflect.ValueOf(fn).Pointer())).Name()
7262                         // returns the right answer. See issue 58300.
7263                         for p := pp.Text; p != nil; p = p.Link {
7264                                 if p.As == obj.AFUNCDATA || p.As == obj.APCDATA || p.As == obj.ATEXT || p.As == obj.ANOP {
7265                                         continue
7266                                 }
7267                                 if base.Ctxt.PosTable.Pos(p.Pos).Base().InliningIndex() >= 0 {
7268                                         // Make a real (not 0-sized) nop.
7269                                         nop := Arch.Ginsnop(pp)
7270                                         nop.Pos = e.curfn.Pos().WithIsStmt()
7271
7272                                         // Unfortunately, Ginsnop puts the instruction at the
7273                                         // end of the list. Move it up to just before p.
7274
7275                                         // Unlink from the current list.
7276                                         for x := pp.Text; x != nil; x = x.Link {
7277                                                 if x.Link == nop {
7278                                                         x.Link = nop.Link
7279                                                         break
7280                                                 }
7281                                         }
7282                                         // Splice in right before p.
7283                                         for x := pp.Text; x != nil; x = x.Link {
7284                                                 if x.Link == p {
7285                                                         nop.Link = p
7286                                                         x.Link = nop
7287                                                         break
7288                                                 }
7289                                         }
7290                                 }
7291                                 break
7292                         }
7293                 }
7294         }
7295
7296         if base.Ctxt.Flag_locationlists {
7297                 var debugInfo *ssa.FuncDebug
7298                 debugInfo = e.curfn.DebugInfo.(*ssa.FuncDebug)
7299                 if e.curfn.ABI == obj.ABIInternal && base.Flag.N != 0 {
7300                         ssa.BuildFuncDebugNoOptimized(base.Ctxt, f, base.Debug.LocationLists > 1, StackOffset, debugInfo)
7301                 } else {
7302                         ssa.BuildFuncDebug(base.Ctxt, f, base.Debug.LocationLists, StackOffset, debugInfo)
7303                 }
7304                 bstart := s.bstart
7305                 idToIdx := make([]int, f.NumBlocks())
7306                 for i, b := range f.Blocks {
7307                         idToIdx[b.ID] = i
7308                 }
7309                 // Note that at this moment, Prog.Pc is a sequence number; it's
7310                 // not a real PC until after assembly, so this mapping has to
7311                 // be done later.
7312                 debugInfo.GetPC = func(b, v ssa.ID) int64 {
7313                         switch v {
7314                         case ssa.BlockStart.ID:
7315                                 if b == f.Entry.ID {
7316                                         return 0 // Start at the very beginning, at the assembler-generated prologue.
7317                                         // this should only happen for function args (ssa.OpArg)
7318                                 }
7319                                 return bstart[b].Pc
7320                         case ssa.BlockEnd.ID:
7321                                 blk := f.Blocks[idToIdx[b]]
7322                                 nv := len(blk.Values)
7323                                 return valueToProgAfter[blk.Values[nv-1].ID].Pc
7324                         case ssa.FuncEnd.ID:
7325                                 return e.curfn.LSym.Size
7326                         default:
7327                                 return valueToProgAfter[v].Pc
7328                         }
7329                 }
7330         }
7331
7332         // Resolve branches, and relax DefaultStmt into NotStmt
7333         for _, br := range s.Branches {
7334                 br.P.To.SetTarget(s.bstart[br.B.ID])
7335                 if br.P.Pos.IsStmt() != src.PosIsStmt {
7336                         br.P.Pos = br.P.Pos.WithNotStmt()
7337                 } else if v0 := br.B.FirstPossibleStmtValue(); v0 != nil && v0.Pos.Line() == br.P.Pos.Line() && v0.Pos.IsStmt() == src.PosIsStmt {
7338                         br.P.Pos = br.P.Pos.WithNotStmt()
7339                 }
7340
7341         }
7342
7343         // Resolve jump table destinations.
7344         for _, jt := range s.JumpTables {
7345                 // Convert from *Block targets to *Prog targets.
7346                 targets := make([]*obj.Prog, len(jt.Succs))
7347                 for i, e := range jt.Succs {
7348                         targets[i] = s.bstart[e.Block().ID]
7349                 }
7350                 // Add to list of jump tables to be resolved at assembly time.
7351                 // The assembler converts from *Prog entries to absolute addresses
7352                 // once it knows instruction byte offsets.
7353                 fi := pp.CurFunc.LSym.Func()
7354                 fi.JumpTables = append(fi.JumpTables, obj.JumpTable{Sym: jt.Aux.(*obj.LSym), Targets: targets})
7355         }
7356
7357         if e.log { // spew to stdout
7358                 filename := ""
7359                 for p := pp.Text; p != nil; p = p.Link {
7360                         if p.Pos.IsKnown() && p.InnermostFilename() != filename {
7361                                 filename = p.InnermostFilename()
7362                                 f.Logf("# %s\n", filename)
7363                         }
7364
7365                         var s string
7366                         if v, ok := progToValue[p]; ok {
7367                                 s = v.String()
7368                         } else if b, ok := progToBlock[p]; ok {
7369                                 s = b.String()
7370                         } else {
7371                                 s = "   " // most value and branch strings are 2-3 characters long
7372                         }
7373                         f.Logf(" %-6s\t%.5d (%s)\t%s\n", s, p.Pc, p.InnermostLineNumber(), p.InstructionString())
7374                 }
7375         }
7376         if f.HTMLWriter != nil { // spew to ssa.html
7377                 var buf strings.Builder
7378                 buf.WriteString("<code>")
7379                 buf.WriteString("<dl class=\"ssa-gen\">")
7380                 filename := ""
7381                 for p := pp.Text; p != nil; p = p.Link {
7382                         // Don't spam every line with the file name, which is often huge.
7383                         // Only print changes, and "unknown" is not a change.
7384                         if p.Pos.IsKnown() && p.InnermostFilename() != filename {
7385                                 filename = p.InnermostFilename()
7386                                 buf.WriteString("<dt class=\"ssa-prog-src\"></dt><dd class=\"ssa-prog\">")
7387                                 buf.WriteString(html.EscapeString("# " + filename))
7388                                 buf.WriteString("</dd>")
7389                         }
7390
7391                         buf.WriteString("<dt class=\"ssa-prog-src\">")
7392                         if v, ok := progToValue[p]; ok {
7393                                 buf.WriteString(v.HTML())
7394                         } else if b, ok := progToBlock[p]; ok {
7395                                 buf.WriteString("<b>" + b.HTML() + "</b>")
7396                         }
7397                         buf.WriteString("</dt>")
7398                         buf.WriteString("<dd class=\"ssa-prog\">")
7399                         fmt.Fprintf(&buf, "%.5d <span class=\"l%v line-number\">(%s)</span> %s", p.Pc, p.InnermostLineNumber(), p.InnermostLineNumberHTML(), html.EscapeString(p.InstructionString()))
7400                         buf.WriteString("</dd>")
7401                 }
7402                 buf.WriteString("</dl>")
7403                 buf.WriteString("</code>")
7404                 f.HTMLWriter.WriteColumn("genssa", "genssa", "ssa-prog", buf.String())
7405         }
7406         if ssa.GenssaDump[f.Name] {
7407                 fi := f.DumpFileForPhase("genssa")
7408                 if fi != nil {
7409
7410                         // inliningDiffers if any filename changes or if any line number except the innermost (last index) changes.
7411                         inliningDiffers := func(a, b []src.Pos) bool {
7412                                 if len(a) != len(b) {
7413                                         return true
7414                                 }
7415                                 for i := range a {
7416                                         if a[i].Filename() != b[i].Filename() {
7417                                                 return true
7418                                         }
7419                                         if i != len(a)-1 && a[i].Line() != b[i].Line() {
7420                                                 return true
7421                                         }
7422                                 }
7423                                 return false
7424                         }
7425
7426                         var allPosOld []src.Pos
7427                         var allPos []src.Pos
7428
7429                         for p := pp.Text; p != nil; p = p.Link {
7430                                 if p.Pos.IsKnown() {
7431                                         allPos = allPos[:0]
7432                                         p.Ctxt.AllPos(p.Pos, func(pos src.Pos) { allPos = append(allPos, pos) })
7433                                         if inliningDiffers(allPos, allPosOld) {
7434                                                 for _, pos := range allPos {
7435                                                         fmt.Fprintf(fi, "# %s:%d\n", pos.Filename(), pos.Line())
7436                                                 }
7437                                                 allPos, allPosOld = allPosOld, allPos // swap, not copy, so that they do not share slice storage.
7438                                         }
7439                                 }
7440
7441                                 var s string
7442                                 if v, ok := progToValue[p]; ok {
7443                                         s = v.String()
7444                                 } else if b, ok := progToBlock[p]; ok {
7445                                         s = b.String()
7446                                 } else {
7447                                         s = "   " // most value and branch strings are 2-3 characters long
7448                                 }
7449                                 fmt.Fprintf(fi, " %-6s\t%.5d %s\t%s\n", s, p.Pc, ssa.StmtString(p.Pos), p.InstructionString())
7450                         }
7451                         fi.Close()
7452                 }
7453         }
7454
7455         defframe(&s, e, f)
7456
7457         f.HTMLWriter.Close()
7458         f.HTMLWriter = nil
7459 }
7460
7461 func defframe(s *State, e *ssafn, f *ssa.Func) {
7462         pp := s.pp
7463
7464         s.maxarg = types.RoundUp(s.maxarg, e.stkalign)
7465         frame := s.maxarg + e.stksize
7466         if Arch.PadFrame != nil {
7467                 frame = Arch.PadFrame(frame)
7468         }
7469
7470         // Fill in argument and frame size.
7471         pp.Text.To.Type = obj.TYPE_TEXTSIZE
7472         pp.Text.To.Val = int32(types.RoundUp(f.OwnAux.ArgWidth(), int64(types.RegSize)))
7473         pp.Text.To.Offset = frame
7474
7475         p := pp.Text
7476
7477         // Insert code to spill argument registers if the named slot may be partially
7478         // live. That is, the named slot is considered live by liveness analysis,
7479         // (because a part of it is live), but we may not spill all parts into the
7480         // slot. This can only happen with aggregate-typed arguments that are SSA-able
7481         // and not address-taken (for non-SSA-able or address-taken arguments we always
7482         // spill upfront).
7483         // Note: spilling is unnecessary in the -N/no-optimize case, since all values
7484         // will be considered non-SSAable and spilled up front.
7485         // TODO(register args) Make liveness more fine-grained to that partial spilling is okay.
7486         if f.OwnAux.ABIInfo().InRegistersUsed() != 0 && base.Flag.N == 0 {
7487                 // First, see if it is already spilled before it may be live. Look for a spill
7488                 // in the entry block up to the first safepoint.
7489                 type nameOff struct {
7490                         n   *ir.Name
7491                         off int64
7492                 }
7493                 partLiveArgsSpilled := make(map[nameOff]bool)
7494                 for _, v := range f.Entry.Values {
7495                         if v.Op.IsCall() {
7496                                 break
7497                         }
7498                         if v.Op != ssa.OpStoreReg || v.Args[0].Op != ssa.OpArgIntReg {
7499                                 continue
7500                         }
7501                         n, off := ssa.AutoVar(v)
7502                         if n.Class != ir.PPARAM || n.Addrtaken() || !ssa.CanSSA(n.Type()) || !s.partLiveArgs[n] {
7503                                 continue
7504                         }
7505                         partLiveArgsSpilled[nameOff{n, off}] = true
7506                 }
7507
7508                 // Then, insert code to spill registers if not already.
7509                 for _, a := range f.OwnAux.ABIInfo().InParams() {
7510                         n := a.Name
7511                         if n == nil || n.Addrtaken() || !ssa.CanSSA(n.Type()) || !s.partLiveArgs[n] || len(a.Registers) <= 1 {
7512                                 continue
7513                         }
7514                         rts, offs := a.RegisterTypesAndOffsets()
7515                         for i := range a.Registers {
7516                                 if !rts[i].HasPointers() {
7517                                         continue
7518                                 }
7519                                 if partLiveArgsSpilled[nameOff{n, offs[i]}] {
7520                                         continue // already spilled
7521                                 }
7522                                 reg := ssa.ObjRegForAbiReg(a.Registers[i], f.Config)
7523                                 p = Arch.SpillArgReg(pp, p, f, rts[i], reg, n, offs[i])
7524                         }
7525                 }
7526         }
7527
7528         // Insert code to zero ambiguously live variables so that the
7529         // garbage collector only sees initialized values when it
7530         // looks for pointers.
7531         var lo, hi int64
7532
7533         // Opaque state for backend to use. Current backends use it to
7534         // keep track of which helper registers have been zeroed.
7535         var state uint32
7536
7537         // Iterate through declarations. Autos are sorted in decreasing
7538         // frame offset order.
7539         for _, n := range e.curfn.Dcl {
7540                 if !n.Needzero() {
7541                         continue
7542                 }
7543                 if n.Class != ir.PAUTO {
7544                         e.Fatalf(n.Pos(), "needzero class %d", n.Class)
7545                 }
7546                 if n.Type().Size()%int64(types.PtrSize) != 0 || n.FrameOffset()%int64(types.PtrSize) != 0 || n.Type().Size() == 0 {
7547                         e.Fatalf(n.Pos(), "var %L has size %d offset %d", n, n.Type().Size(), n.Offset_)
7548                 }
7549
7550                 if lo != hi && n.FrameOffset()+n.Type().Size() >= lo-int64(2*types.RegSize) {
7551                         // Merge with range we already have.
7552                         lo = n.FrameOffset()
7553                         continue
7554                 }
7555
7556                 // Zero old range
7557                 p = Arch.ZeroRange(pp, p, frame+lo, hi-lo, &state)
7558
7559                 // Set new range.
7560                 lo = n.FrameOffset()
7561                 hi = lo + n.Type().Size()
7562         }
7563
7564         // Zero final range.
7565         Arch.ZeroRange(pp, p, frame+lo, hi-lo, &state)
7566 }
7567
7568 // For generating consecutive jump instructions to model a specific branching
7569 type IndexJump struct {
7570         Jump  obj.As
7571         Index int
7572 }
7573
7574 func (s *State) oneJump(b *ssa.Block, jump *IndexJump) {
7575         p := s.Br(jump.Jump, b.Succs[jump.Index].Block())
7576         p.Pos = b.Pos
7577 }
7578
7579 // CombJump generates combinational instructions (2 at present) for a block jump,
7580 // thereby the behaviour of non-standard condition codes could be simulated
7581 func (s *State) CombJump(b, next *ssa.Block, jumps *[2][2]IndexJump) {
7582         switch next {
7583         case b.Succs[0].Block():
7584                 s.oneJump(b, &jumps[0][0])
7585                 s.oneJump(b, &jumps[0][1])
7586         case b.Succs[1].Block():
7587                 s.oneJump(b, &jumps[1][0])
7588                 s.oneJump(b, &jumps[1][1])
7589         default:
7590                 var q *obj.Prog
7591                 if b.Likely != ssa.BranchUnlikely {
7592                         s.oneJump(b, &jumps[1][0])
7593                         s.oneJump(b, &jumps[1][1])
7594                         q = s.Br(obj.AJMP, b.Succs[1].Block())
7595                 } else {
7596                         s.oneJump(b, &jumps[0][0])
7597                         s.oneJump(b, &jumps[0][1])
7598                         q = s.Br(obj.AJMP, b.Succs[0].Block())
7599                 }
7600                 q.Pos = b.Pos
7601         }
7602 }
7603
7604 // AddAux adds the offset in the aux fields (AuxInt and Aux) of v to a.
7605 func AddAux(a *obj.Addr, v *ssa.Value) {
7606         AddAux2(a, v, v.AuxInt)
7607 }
7608 func AddAux2(a *obj.Addr, v *ssa.Value, offset int64) {
7609         if a.Type != obj.TYPE_MEM && a.Type != obj.TYPE_ADDR {
7610                 v.Fatalf("bad AddAux addr %v", a)
7611         }
7612         // add integer offset
7613         a.Offset += offset
7614
7615         // If no additional symbol offset, we're done.
7616         if v.Aux == nil {
7617                 return
7618         }
7619         // Add symbol's offset from its base register.
7620         switch n := v.Aux.(type) {
7621         case *ssa.AuxCall:
7622                 a.Name = obj.NAME_EXTERN
7623                 a.Sym = n.Fn
7624         case *obj.LSym:
7625                 a.Name = obj.NAME_EXTERN
7626                 a.Sym = n
7627         case *ir.Name:
7628                 if n.Class == ir.PPARAM || (n.Class == ir.PPARAMOUT && !n.IsOutputParamInRegisters()) {
7629                         a.Name = obj.NAME_PARAM
7630                 } else {
7631                         a.Name = obj.NAME_AUTO
7632                 }
7633                 a.Sym = n.Linksym()
7634                 a.Offset += n.FrameOffset()
7635         default:
7636                 v.Fatalf("aux in %s not implemented %#v", v, v.Aux)
7637         }
7638 }
7639
7640 // extendIndex extends v to a full int width.
7641 // panic with the given kind if v does not fit in an int (only on 32-bit archs).
7642 func (s *state) extendIndex(idx, len *ssa.Value, kind ssa.BoundsKind, bounded bool) *ssa.Value {
7643         size := idx.Type.Size()
7644         if size == s.config.PtrSize {
7645                 return idx
7646         }
7647         if size > s.config.PtrSize {
7648                 // truncate 64-bit indexes on 32-bit pointer archs. Test the
7649                 // high word and branch to out-of-bounds failure if it is not 0.
7650                 var lo *ssa.Value
7651                 if idx.Type.IsSigned() {
7652                         lo = s.newValue1(ssa.OpInt64Lo, types.Types[types.TINT], idx)
7653                 } else {
7654                         lo = s.newValue1(ssa.OpInt64Lo, types.Types[types.TUINT], idx)
7655                 }
7656                 if bounded || base.Flag.B != 0 {
7657                         return lo
7658                 }
7659                 bNext := s.f.NewBlock(ssa.BlockPlain)
7660                 bPanic := s.f.NewBlock(ssa.BlockExit)
7661                 hi := s.newValue1(ssa.OpInt64Hi, types.Types[types.TUINT32], idx)
7662                 cmp := s.newValue2(ssa.OpEq32, types.Types[types.TBOOL], hi, s.constInt32(types.Types[types.TUINT32], 0))
7663                 if !idx.Type.IsSigned() {
7664                         switch kind {
7665                         case ssa.BoundsIndex:
7666                                 kind = ssa.BoundsIndexU
7667                         case ssa.BoundsSliceAlen:
7668                                 kind = ssa.BoundsSliceAlenU
7669                         case ssa.BoundsSliceAcap:
7670                                 kind = ssa.BoundsSliceAcapU
7671                         case ssa.BoundsSliceB:
7672                                 kind = ssa.BoundsSliceBU
7673                         case ssa.BoundsSlice3Alen:
7674                                 kind = ssa.BoundsSlice3AlenU
7675                         case ssa.BoundsSlice3Acap:
7676                                 kind = ssa.BoundsSlice3AcapU
7677                         case ssa.BoundsSlice3B:
7678                                 kind = ssa.BoundsSlice3BU
7679                         case ssa.BoundsSlice3C:
7680                                 kind = ssa.BoundsSlice3CU
7681                         }
7682                 }
7683                 b := s.endBlock()
7684                 b.Kind = ssa.BlockIf
7685                 b.SetControl(cmp)
7686                 b.Likely = ssa.BranchLikely
7687                 b.AddEdgeTo(bNext)
7688                 b.AddEdgeTo(bPanic)
7689
7690                 s.startBlock(bPanic)
7691                 mem := s.newValue4I(ssa.OpPanicExtend, types.TypeMem, int64(kind), hi, lo, len, s.mem())
7692                 s.endBlock().SetControl(mem)
7693                 s.startBlock(bNext)
7694
7695                 return lo
7696         }
7697
7698         // Extend value to the required size
7699         var op ssa.Op
7700         if idx.Type.IsSigned() {
7701                 switch 10*size + s.config.PtrSize {
7702                 case 14:
7703                         op = ssa.OpSignExt8to32
7704                 case 18:
7705                         op = ssa.OpSignExt8to64
7706                 case 24:
7707                         op = ssa.OpSignExt16to32
7708                 case 28:
7709                         op = ssa.OpSignExt16to64
7710                 case 48:
7711                         op = ssa.OpSignExt32to64
7712                 default:
7713                         s.Fatalf("bad signed index extension %s", idx.Type)
7714                 }
7715         } else {
7716                 switch 10*size + s.config.PtrSize {
7717                 case 14:
7718                         op = ssa.OpZeroExt8to32
7719                 case 18:
7720                         op = ssa.OpZeroExt8to64
7721                 case 24:
7722                         op = ssa.OpZeroExt16to32
7723                 case 28:
7724                         op = ssa.OpZeroExt16to64
7725                 case 48:
7726                         op = ssa.OpZeroExt32to64
7727                 default:
7728                         s.Fatalf("bad unsigned index extension %s", idx.Type)
7729                 }
7730         }
7731         return s.newValue1(op, types.Types[types.TINT], idx)
7732 }
7733
7734 // CheckLoweredPhi checks that regalloc and stackalloc correctly handled phi values.
7735 // Called during ssaGenValue.
7736 func CheckLoweredPhi(v *ssa.Value) {
7737         if v.Op != ssa.OpPhi {
7738                 v.Fatalf("CheckLoweredPhi called with non-phi value: %v", v.LongString())
7739         }
7740         if v.Type.IsMemory() {
7741                 return
7742         }
7743         f := v.Block.Func
7744         loc := f.RegAlloc[v.ID]
7745         for _, a := range v.Args {
7746                 if aloc := f.RegAlloc[a.ID]; aloc != loc { // TODO: .Equal() instead?
7747                         v.Fatalf("phi arg at different location than phi: %v @ %s, but arg %v @ %s\n%s\n", v, loc, a, aloc, v.Block.Func)
7748                 }
7749         }
7750 }
7751
7752 // CheckLoweredGetClosurePtr checks that v is the first instruction in the function's entry block,
7753 // except for incoming in-register arguments.
7754 // The output of LoweredGetClosurePtr is generally hardwired to the correct register.
7755 // That register contains the closure pointer on closure entry.
7756 func CheckLoweredGetClosurePtr(v *ssa.Value) {
7757         entry := v.Block.Func.Entry
7758         if entry != v.Block {
7759                 base.Fatalf("in %s, badly placed LoweredGetClosurePtr: %v %v", v.Block.Func.Name, v.Block, v)
7760         }
7761         for _, w := range entry.Values {
7762                 if w == v {
7763                         break
7764                 }
7765                 switch w.Op {
7766                 case ssa.OpArgIntReg, ssa.OpArgFloatReg:
7767                         // okay
7768                 default:
7769                         base.Fatalf("in %s, badly placed LoweredGetClosurePtr: %v %v", v.Block.Func.Name, v.Block, v)
7770                 }
7771         }
7772 }
7773
7774 // CheckArgReg ensures that v is in the function's entry block.
7775 func CheckArgReg(v *ssa.Value) {
7776         entry := v.Block.Func.Entry
7777         if entry != v.Block {
7778                 base.Fatalf("in %s, badly placed ArgIReg or ArgFReg: %v %v", v.Block.Func.Name, v.Block, v)
7779         }
7780 }
7781
7782 func AddrAuto(a *obj.Addr, v *ssa.Value) {
7783         n, off := ssa.AutoVar(v)
7784         a.Type = obj.TYPE_MEM
7785         a.Sym = n.Linksym()
7786         a.Reg = int16(Arch.REGSP)
7787         a.Offset = n.FrameOffset() + off
7788         if n.Class == ir.PPARAM || (n.Class == ir.PPARAMOUT && !n.IsOutputParamInRegisters()) {
7789                 a.Name = obj.NAME_PARAM
7790         } else {
7791                 a.Name = obj.NAME_AUTO
7792         }
7793 }
7794
7795 // Call returns a new CALL instruction for the SSA value v.
7796 // It uses PrepareCall to prepare the call.
7797 func (s *State) Call(v *ssa.Value) *obj.Prog {
7798         pPosIsStmt := s.pp.Pos.IsStmt() // The statement-ness fo the call comes from ssaGenState
7799         s.PrepareCall(v)
7800
7801         p := s.Prog(obj.ACALL)
7802         if pPosIsStmt == src.PosIsStmt {
7803                 p.Pos = v.Pos.WithIsStmt()
7804         } else {
7805                 p.Pos = v.Pos.WithNotStmt()
7806         }
7807         if sym, ok := v.Aux.(*ssa.AuxCall); ok && sym.Fn != nil {
7808                 p.To.Type = obj.TYPE_MEM
7809                 p.To.Name = obj.NAME_EXTERN
7810                 p.To.Sym = sym.Fn
7811         } else {
7812                 // TODO(mdempsky): Can these differences be eliminated?
7813                 switch Arch.LinkArch.Family {
7814                 case sys.AMD64, sys.I386, sys.PPC64, sys.RISCV64, sys.S390X, sys.Wasm:
7815                         p.To.Type = obj.TYPE_REG
7816                 case sys.ARM, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64:
7817                         p.To.Type = obj.TYPE_MEM
7818                 default:
7819                         base.Fatalf("unknown indirect call family")
7820                 }
7821                 p.To.Reg = v.Args[0].Reg()
7822         }
7823         return p
7824 }
7825
7826 // TailCall returns a new tail call instruction for the SSA value v.
7827 // It is like Call, but for a tail call.
7828 func (s *State) TailCall(v *ssa.Value) *obj.Prog {
7829         p := s.Call(v)
7830         p.As = obj.ARET
7831         return p
7832 }
7833
7834 // PrepareCall prepares to emit a CALL instruction for v and does call-related bookkeeping.
7835 // It must be called immediately before emitting the actual CALL instruction,
7836 // since it emits PCDATA for the stack map at the call (calls are safe points).
7837 func (s *State) PrepareCall(v *ssa.Value) {
7838         idx := s.livenessMap.Get(v)
7839         if !idx.StackMapValid() {
7840                 // See Liveness.hasStackMap.
7841                 if sym, ok := v.Aux.(*ssa.AuxCall); !ok || !(sym.Fn == ir.Syms.WBZero || sym.Fn == ir.Syms.WBMove) {
7842                         base.Fatalf("missing stack map index for %v", v.LongString())
7843                 }
7844         }
7845
7846         call, ok := v.Aux.(*ssa.AuxCall)
7847
7848         if ok {
7849                 // Record call graph information for nowritebarrierrec
7850                 // analysis.
7851                 if nowritebarrierrecCheck != nil {
7852                         nowritebarrierrecCheck.recordCall(s.pp.CurFunc, call.Fn, v.Pos)
7853                 }
7854         }
7855
7856         if s.maxarg < v.AuxInt {
7857                 s.maxarg = v.AuxInt
7858         }
7859 }
7860
7861 // UseArgs records the fact that an instruction needs a certain amount of
7862 // callee args space for its use.
7863 func (s *State) UseArgs(n int64) {
7864         if s.maxarg < n {
7865                 s.maxarg = n
7866         }
7867 }
7868
7869 // fieldIdx finds the index of the field referred to by the ODOT node n.
7870 func fieldIdx(n *ir.SelectorExpr) int {
7871         t := n.X.Type()
7872         if !t.IsStruct() {
7873                 panic("ODOT's LHS is not a struct")
7874         }
7875
7876         for i, f := range t.Fields() {
7877                 if f.Sym == n.Sel {
7878                         if f.Offset != n.Offset() {
7879                                 panic("field offset doesn't match")
7880                         }
7881                         return i
7882                 }
7883         }
7884         panic(fmt.Sprintf("can't find field in expr %v\n", n))
7885
7886         // TODO: keep the result of this function somewhere in the ODOT Node
7887         // so we don't have to recompute it each time we need it.
7888 }
7889
7890 // ssafn holds frontend information about a function that the backend is processing.
7891 // It also exports a bunch of compiler services for the ssa backend.
7892 type ssafn struct {
7893         curfn      *ir.Func
7894         strings    map[string]*obj.LSym // map from constant string to data symbols
7895         stksize    int64                // stack size for current frame
7896         stkptrsize int64                // prefix of stack containing pointers
7897
7898         // alignment for current frame.
7899         // NOTE: when stkalign > PtrSize, currently this only ensures the offsets of
7900         // objects in the stack frame are aligned. The stack pointer is still aligned
7901         // only PtrSize.
7902         stkalign int64
7903
7904         log bool // print ssa debug to the stdout
7905 }
7906
7907 // StringData returns a symbol which
7908 // is the data component of a global string constant containing s.
7909 func (e *ssafn) StringData(s string) *obj.LSym {
7910         if aux, ok := e.strings[s]; ok {
7911                 return aux
7912         }
7913         if e.strings == nil {
7914                 e.strings = make(map[string]*obj.LSym)
7915         }
7916         data := staticdata.StringSym(e.curfn.Pos(), s)
7917         e.strings[s] = data
7918         return data
7919 }
7920
7921 // SplitSlot returns a slot representing the data of parent starting at offset.
7922 func (e *ssafn) SplitSlot(parent *ssa.LocalSlot, suffix string, offset int64, t *types.Type) ssa.LocalSlot {
7923         node := parent.N
7924
7925         if node.Class != ir.PAUTO || node.Addrtaken() {
7926                 // addressed things and non-autos retain their parents (i.e., cannot truly be split)
7927                 return ssa.LocalSlot{N: node, Type: t, Off: parent.Off + offset}
7928         }
7929
7930         sym := &types.Sym{Name: node.Sym().Name + suffix, Pkg: types.LocalPkg}
7931         n := e.curfn.NewLocal(parent.N.Pos(), sym, t)
7932         n.SetUsed(true)
7933         n.SetEsc(ir.EscNever)
7934         types.CalcSize(t)
7935         return ssa.LocalSlot{N: n, Type: t, Off: 0, SplitOf: parent, SplitOffset: offset}
7936 }
7937
7938 // Logf logs a message from the compiler.
7939 func (e *ssafn) Logf(msg string, args ...interface{}) {
7940         if e.log {
7941                 fmt.Printf(msg, args...)
7942         }
7943 }
7944
7945 func (e *ssafn) Log() bool {
7946         return e.log
7947 }
7948
7949 // Fatalf reports a compiler error and exits.
7950 func (e *ssafn) Fatalf(pos src.XPos, msg string, args ...interface{}) {
7951         base.Pos = pos
7952         nargs := append([]interface{}{ir.FuncName(e.curfn)}, args...)
7953         base.Fatalf("'%s': "+msg, nargs...)
7954 }
7955
7956 // Warnl reports a "warning", which is usually flag-triggered
7957 // logging output for the benefit of tests.
7958 func (e *ssafn) Warnl(pos src.XPos, fmt_ string, args ...interface{}) {
7959         base.WarnfAt(pos, fmt_, args...)
7960 }
7961
7962 func (e *ssafn) Debug_checknil() bool {
7963         return base.Debug.Nil != 0
7964 }
7965
7966 func (e *ssafn) UseWriteBarrier() bool {
7967         return base.Flag.WB
7968 }
7969
7970 func (e *ssafn) Syslook(name string) *obj.LSym {
7971         switch name {
7972         case "goschedguarded":
7973                 return ir.Syms.Goschedguarded
7974         case "writeBarrier":
7975                 return ir.Syms.WriteBarrier
7976         case "wbZero":
7977                 return ir.Syms.WBZero
7978         case "wbMove":
7979                 return ir.Syms.WBMove
7980         case "cgoCheckMemmove":
7981                 return ir.Syms.CgoCheckMemmove
7982         case "cgoCheckPtrWrite":
7983                 return ir.Syms.CgoCheckPtrWrite
7984         }
7985         e.Fatalf(src.NoXPos, "unknown Syslook func %v", name)
7986         return nil
7987 }
7988
7989 func (e *ssafn) Func() *ir.Func {
7990         return e.curfn
7991 }
7992
7993 func clobberBase(n ir.Node) ir.Node {
7994         if n.Op() == ir.ODOT {
7995                 n := n.(*ir.SelectorExpr)
7996                 if n.X.Type().NumFields() == 1 {
7997                         return clobberBase(n.X)
7998                 }
7999         }
8000         if n.Op() == ir.OINDEX {
8001                 n := n.(*ir.IndexExpr)
8002                 if n.X.Type().IsArray() && n.X.Type().NumElem() == 1 {
8003                         return clobberBase(n.X)
8004                 }
8005         }
8006         return n
8007 }
8008
8009 // callTargetLSym returns the correct LSym to call 'callee' using its ABI.
8010 func callTargetLSym(callee *ir.Name) *obj.LSym {
8011         if callee.Func == nil {
8012                 // TODO(austin): This happens in case of interface method I.M from imported package.
8013                 // It's ABIInternal, and would be better if callee.Func was never nil and we didn't
8014                 // need this case.
8015                 return callee.Linksym()
8016         }
8017
8018         return callee.LinksymABI(callee.Func.ABI)
8019 }
8020
8021 func min8(a, b int8) int8 {
8022         if a < b {
8023                 return a
8024         }
8025         return b
8026 }
8027
8028 func max8(a, b int8) int8 {
8029         if a > b {
8030                 return a
8031         }
8032         return b
8033 }
8034
8035 // deferStructFnField is the field index of _defer.fn.
8036 const deferStructFnField = 4
8037
8038 var deferType *types.Type
8039
8040 // deferstruct returns a type interchangeable with runtime._defer.
8041 // Make sure this stays in sync with runtime/runtime2.go:_defer.
8042 func deferstruct() *types.Type {
8043         if deferType != nil {
8044                 return deferType
8045         }
8046
8047         makefield := func(name string, t *types.Type) *types.Field {
8048                 sym := (*types.Pkg)(nil).Lookup(name)
8049                 return types.NewField(src.NoXPos, sym, t)
8050         }
8051
8052         fields := []*types.Field{
8053                 makefield("heap", types.Types[types.TBOOL]),
8054                 makefield("rangefunc", types.Types[types.TBOOL]),
8055                 makefield("sp", types.Types[types.TUINTPTR]),
8056                 makefield("pc", types.Types[types.TUINTPTR]),
8057                 // Note: the types here don't really matter. Defer structures
8058                 // are always scanned explicitly during stack copying and GC,
8059                 // so we make them uintptr type even though they are real pointers.
8060                 makefield("fn", types.Types[types.TUINTPTR]),
8061                 makefield("link", types.Types[types.TUINTPTR]),
8062                 makefield("head", types.Types[types.TUINTPTR]),
8063         }
8064         if name := fields[deferStructFnField].Sym.Name; name != "fn" {
8065                 base.Fatalf("deferStructFnField is %q, not fn", name)
8066         }
8067
8068         n := ir.NewDeclNameAt(src.NoXPos, ir.OTYPE, ir.Pkgs.Runtime.Lookup("_defer"))
8069         typ := types.NewNamed(n)
8070         n.SetType(typ)
8071         n.SetTypecheck(1)
8072
8073         // build struct holding the above fields
8074         typ.SetUnderlying(types.NewStruct(fields))
8075         types.CalcStructSize(typ)
8076
8077         deferType = typ
8078         return typ
8079 }
8080
8081 // SpillSlotAddr uses LocalSlot information to initialize an obj.Addr
8082 // The resulting addr is used in a non-standard context -- in the prologue
8083 // of a function, before the frame has been constructed, so the standard
8084 // addressing for the parameters will be wrong.
8085 func SpillSlotAddr(spill ssa.Spill, baseReg int16, extraOffset int64) obj.Addr {
8086         return obj.Addr{
8087                 Name:   obj.NAME_NONE,
8088                 Type:   obj.TYPE_MEM,
8089                 Reg:    baseReg,
8090                 Offset: spill.Offset + extraOffset,
8091         }
8092 }
8093
8094 var (
8095         BoundsCheckFunc [ssa.BoundsKindCount]*obj.LSym
8096         ExtendCheckFunc [ssa.BoundsKindCount]*obj.LSym
8097 )