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