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