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.
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"
37 var ssaConfig *ssa.Config
38 var ssaCaches []ssa.Cache
40 var ssaDump string // early copy of $GOSSAFUNC; the func name to dump output for
41 var ssaDir string // optional destination for ssa dump file
42 var ssaDumpStdout bool // whether to dump to stdout
43 var ssaDumpCFG string // generate CFGs for these phases
44 const ssaDumpFile = "ssa.html"
46 // ssaDumpInlined holds all inlined functions when ssaDump contains a function name.
47 var ssaDumpInlined []*ir.Func
49 func DumpInline(fn *ir.Func) {
50 if ssaDump != "" && ssaDump == ir.FuncName(fn) {
51 ssaDumpInlined = append(ssaDumpInlined, fn)
56 ssaDump = os.Getenv("GOSSAFUNC")
57 ssaDir = os.Getenv("GOSSADIR")
59 if strings.HasSuffix(ssaDump, "+") {
60 ssaDump = ssaDump[:len(ssaDump)-1]
63 spl := strings.Split(ssaDump, ":")
72 types_ := ssa.NewTypes()
78 // Generate a few pointer types that are uncommon in the frontend but common in the backend.
79 // Caching is disabled in the backend, so generating these here avoids allocations.
80 _ = types.NewPtr(types.Types[types.TINTER]) // *interface{}
81 _ = types.NewPtr(types.NewPtr(types.Types[types.TSTRING])) // **string
82 _ = types.NewPtr(types.NewSlice(types.Types[types.TINTER])) // *[]interface{}
83 _ = types.NewPtr(types.NewPtr(types.ByteType)) // **byte
84 _ = types.NewPtr(types.NewSlice(types.ByteType)) // *[]byte
85 _ = types.NewPtr(types.NewSlice(types.Types[types.TSTRING])) // *[]string
86 _ = types.NewPtr(types.NewPtr(types.NewPtr(types.Types[types.TUINT8]))) // ***uint8
87 _ = types.NewPtr(types.Types[types.TINT16]) // *int16
88 _ = types.NewPtr(types.Types[types.TINT64]) // *int64
89 _ = types.NewPtr(types.ErrorType) // *error
90 _ = types.NewPtr(reflectdata.MapType()) // *runtime.hmap
91 _ = types.NewPtr(deferstruct()) // *runtime._defer
92 types.NewPtrCacheEnabled = false
93 ssaConfig = ssa.NewConfig(base.Ctxt.Arch.Name, *types_, base.Ctxt, base.Flag.N == 0, Arch.SoftFloat)
94 ssaConfig.Race = base.Flag.Race
95 ssaCaches = make([]ssa.Cache, base.Flag.LowerC)
97 // Set up some runtime functions we'll need to call.
98 ir.Syms.AssertE2I = typecheck.LookupRuntimeFunc("assertE2I")
99 ir.Syms.AssertE2I2 = typecheck.LookupRuntimeFunc("assertE2I2")
100 ir.Syms.AssertI2I = typecheck.LookupRuntimeFunc("assertI2I")
101 ir.Syms.AssertI2I2 = typecheck.LookupRuntimeFunc("assertI2I2")
102 ir.Syms.CgoCheckMemmove = typecheck.LookupRuntimeFunc("cgoCheckMemmove")
103 ir.Syms.CgoCheckPtrWrite = typecheck.LookupRuntimeFunc("cgoCheckPtrWrite")
104 ir.Syms.CheckPtrAlignment = typecheck.LookupRuntimeFunc("checkptrAlignment")
105 ir.Syms.Deferproc = typecheck.LookupRuntimeFunc("deferproc")
106 ir.Syms.Deferprocat = typecheck.LookupRuntimeFunc("deferprocat")
107 ir.Syms.DeferprocStack = typecheck.LookupRuntimeFunc("deferprocStack")
108 ir.Syms.Deferreturn = typecheck.LookupRuntimeFunc("deferreturn")
109 ir.Syms.Duffcopy = typecheck.LookupRuntimeFunc("duffcopy")
110 ir.Syms.Duffzero = typecheck.LookupRuntimeFunc("duffzero")
111 ir.Syms.GCWriteBarrier[0] = typecheck.LookupRuntimeFunc("gcWriteBarrier1")
112 ir.Syms.GCWriteBarrier[1] = typecheck.LookupRuntimeFunc("gcWriteBarrier2")
113 ir.Syms.GCWriteBarrier[2] = typecheck.LookupRuntimeFunc("gcWriteBarrier3")
114 ir.Syms.GCWriteBarrier[3] = typecheck.LookupRuntimeFunc("gcWriteBarrier4")
115 ir.Syms.GCWriteBarrier[4] = typecheck.LookupRuntimeFunc("gcWriteBarrier5")
116 ir.Syms.GCWriteBarrier[5] = typecheck.LookupRuntimeFunc("gcWriteBarrier6")
117 ir.Syms.GCWriteBarrier[6] = typecheck.LookupRuntimeFunc("gcWriteBarrier7")
118 ir.Syms.GCWriteBarrier[7] = typecheck.LookupRuntimeFunc("gcWriteBarrier8")
119 ir.Syms.Goschedguarded = typecheck.LookupRuntimeFunc("goschedguarded")
120 ir.Syms.Growslice = typecheck.LookupRuntimeFunc("growslice")
121 ir.Syms.InterfaceSwitch = typecheck.LookupRuntimeFunc("interfaceSwitch")
122 ir.Syms.Memmove = typecheck.LookupRuntimeFunc("memmove")
123 ir.Syms.Msanread = typecheck.LookupRuntimeFunc("msanread")
124 ir.Syms.Msanwrite = typecheck.LookupRuntimeFunc("msanwrite")
125 ir.Syms.Msanmove = typecheck.LookupRuntimeFunc("msanmove")
126 ir.Syms.Asanread = typecheck.LookupRuntimeFunc("asanread")
127 ir.Syms.Asanwrite = typecheck.LookupRuntimeFunc("asanwrite")
128 ir.Syms.Newobject = typecheck.LookupRuntimeFunc("newobject")
129 ir.Syms.Newproc = typecheck.LookupRuntimeFunc("newproc")
130 ir.Syms.Panicdivide = typecheck.LookupRuntimeFunc("panicdivide")
131 ir.Syms.PanicdottypeE = typecheck.LookupRuntimeFunc("panicdottypeE")
132 ir.Syms.PanicdottypeI = typecheck.LookupRuntimeFunc("panicdottypeI")
133 ir.Syms.Panicnildottype = typecheck.LookupRuntimeFunc("panicnildottype")
134 ir.Syms.Panicoverflow = typecheck.LookupRuntimeFunc("panicoverflow")
135 ir.Syms.Panicshift = typecheck.LookupRuntimeFunc("panicshift")
136 ir.Syms.Racefuncenter = typecheck.LookupRuntimeFunc("racefuncenter")
137 ir.Syms.Racefuncexit = typecheck.LookupRuntimeFunc("racefuncexit")
138 ir.Syms.Raceread = typecheck.LookupRuntimeFunc("raceread")
139 ir.Syms.Racereadrange = typecheck.LookupRuntimeFunc("racereadrange")
140 ir.Syms.Racewrite = typecheck.LookupRuntimeFunc("racewrite")
141 ir.Syms.Racewriterange = typecheck.LookupRuntimeFunc("racewriterange")
142 ir.Syms.WBZero = typecheck.LookupRuntimeFunc("wbZero")
143 ir.Syms.WBMove = typecheck.LookupRuntimeFunc("wbMove")
144 ir.Syms.X86HasPOPCNT = typecheck.LookupRuntimeVar("x86HasPOPCNT") // bool
145 ir.Syms.X86HasSSE41 = typecheck.LookupRuntimeVar("x86HasSSE41") // bool
146 ir.Syms.X86HasFMA = typecheck.LookupRuntimeVar("x86HasFMA") // bool
147 ir.Syms.ARMHasVFPv4 = typecheck.LookupRuntimeVar("armHasVFPv4") // bool
148 ir.Syms.ARM64HasATOMICS = typecheck.LookupRuntimeVar("arm64HasATOMICS") // bool
149 ir.Syms.Staticuint64s = typecheck.LookupRuntimeVar("staticuint64s")
150 ir.Syms.Typedmemmove = typecheck.LookupRuntimeFunc("typedmemmove")
151 ir.Syms.Udiv = typecheck.LookupRuntimeVar("udiv") // asm func with special ABI
152 ir.Syms.WriteBarrier = typecheck.LookupRuntimeVar("writeBarrier") // struct { bool; ... }
153 ir.Syms.Zerobase = typecheck.LookupRuntimeVar("zerobase")
155 if Arch.LinkArch.Family == sys.Wasm {
156 BoundsCheckFunc[ssa.BoundsIndex] = typecheck.LookupRuntimeFunc("goPanicIndex")
157 BoundsCheckFunc[ssa.BoundsIndexU] = typecheck.LookupRuntimeFunc("goPanicIndexU")
158 BoundsCheckFunc[ssa.BoundsSliceAlen] = typecheck.LookupRuntimeFunc("goPanicSliceAlen")
159 BoundsCheckFunc[ssa.BoundsSliceAlenU] = typecheck.LookupRuntimeFunc("goPanicSliceAlenU")
160 BoundsCheckFunc[ssa.BoundsSliceAcap] = typecheck.LookupRuntimeFunc("goPanicSliceAcap")
161 BoundsCheckFunc[ssa.BoundsSliceAcapU] = typecheck.LookupRuntimeFunc("goPanicSliceAcapU")
162 BoundsCheckFunc[ssa.BoundsSliceB] = typecheck.LookupRuntimeFunc("goPanicSliceB")
163 BoundsCheckFunc[ssa.BoundsSliceBU] = typecheck.LookupRuntimeFunc("goPanicSliceBU")
164 BoundsCheckFunc[ssa.BoundsSlice3Alen] = typecheck.LookupRuntimeFunc("goPanicSlice3Alen")
165 BoundsCheckFunc[ssa.BoundsSlice3AlenU] = typecheck.LookupRuntimeFunc("goPanicSlice3AlenU")
166 BoundsCheckFunc[ssa.BoundsSlice3Acap] = typecheck.LookupRuntimeFunc("goPanicSlice3Acap")
167 BoundsCheckFunc[ssa.BoundsSlice3AcapU] = typecheck.LookupRuntimeFunc("goPanicSlice3AcapU")
168 BoundsCheckFunc[ssa.BoundsSlice3B] = typecheck.LookupRuntimeFunc("goPanicSlice3B")
169 BoundsCheckFunc[ssa.BoundsSlice3BU] = typecheck.LookupRuntimeFunc("goPanicSlice3BU")
170 BoundsCheckFunc[ssa.BoundsSlice3C] = typecheck.LookupRuntimeFunc("goPanicSlice3C")
171 BoundsCheckFunc[ssa.BoundsSlice3CU] = typecheck.LookupRuntimeFunc("goPanicSlice3CU")
172 BoundsCheckFunc[ssa.BoundsConvert] = typecheck.LookupRuntimeFunc("goPanicSliceConvert")
174 BoundsCheckFunc[ssa.BoundsIndex] = typecheck.LookupRuntimeFunc("panicIndex")
175 BoundsCheckFunc[ssa.BoundsIndexU] = typecheck.LookupRuntimeFunc("panicIndexU")
176 BoundsCheckFunc[ssa.BoundsSliceAlen] = typecheck.LookupRuntimeFunc("panicSliceAlen")
177 BoundsCheckFunc[ssa.BoundsSliceAlenU] = typecheck.LookupRuntimeFunc("panicSliceAlenU")
178 BoundsCheckFunc[ssa.BoundsSliceAcap] = typecheck.LookupRuntimeFunc("panicSliceAcap")
179 BoundsCheckFunc[ssa.BoundsSliceAcapU] = typecheck.LookupRuntimeFunc("panicSliceAcapU")
180 BoundsCheckFunc[ssa.BoundsSliceB] = typecheck.LookupRuntimeFunc("panicSliceB")
181 BoundsCheckFunc[ssa.BoundsSliceBU] = typecheck.LookupRuntimeFunc("panicSliceBU")
182 BoundsCheckFunc[ssa.BoundsSlice3Alen] = typecheck.LookupRuntimeFunc("panicSlice3Alen")
183 BoundsCheckFunc[ssa.BoundsSlice3AlenU] = typecheck.LookupRuntimeFunc("panicSlice3AlenU")
184 BoundsCheckFunc[ssa.BoundsSlice3Acap] = typecheck.LookupRuntimeFunc("panicSlice3Acap")
185 BoundsCheckFunc[ssa.BoundsSlice3AcapU] = typecheck.LookupRuntimeFunc("panicSlice3AcapU")
186 BoundsCheckFunc[ssa.BoundsSlice3B] = typecheck.LookupRuntimeFunc("panicSlice3B")
187 BoundsCheckFunc[ssa.BoundsSlice3BU] = typecheck.LookupRuntimeFunc("panicSlice3BU")
188 BoundsCheckFunc[ssa.BoundsSlice3C] = typecheck.LookupRuntimeFunc("panicSlice3C")
189 BoundsCheckFunc[ssa.BoundsSlice3CU] = typecheck.LookupRuntimeFunc("panicSlice3CU")
190 BoundsCheckFunc[ssa.BoundsConvert] = typecheck.LookupRuntimeFunc("panicSliceConvert")
192 if Arch.LinkArch.PtrSize == 4 {
193 ExtendCheckFunc[ssa.BoundsIndex] = typecheck.LookupRuntimeVar("panicExtendIndex")
194 ExtendCheckFunc[ssa.BoundsIndexU] = typecheck.LookupRuntimeVar("panicExtendIndexU")
195 ExtendCheckFunc[ssa.BoundsSliceAlen] = typecheck.LookupRuntimeVar("panicExtendSliceAlen")
196 ExtendCheckFunc[ssa.BoundsSliceAlenU] = typecheck.LookupRuntimeVar("panicExtendSliceAlenU")
197 ExtendCheckFunc[ssa.BoundsSliceAcap] = typecheck.LookupRuntimeVar("panicExtendSliceAcap")
198 ExtendCheckFunc[ssa.BoundsSliceAcapU] = typecheck.LookupRuntimeVar("panicExtendSliceAcapU")
199 ExtendCheckFunc[ssa.BoundsSliceB] = typecheck.LookupRuntimeVar("panicExtendSliceB")
200 ExtendCheckFunc[ssa.BoundsSliceBU] = typecheck.LookupRuntimeVar("panicExtendSliceBU")
201 ExtendCheckFunc[ssa.BoundsSlice3Alen] = typecheck.LookupRuntimeVar("panicExtendSlice3Alen")
202 ExtendCheckFunc[ssa.BoundsSlice3AlenU] = typecheck.LookupRuntimeVar("panicExtendSlice3AlenU")
203 ExtendCheckFunc[ssa.BoundsSlice3Acap] = typecheck.LookupRuntimeVar("panicExtendSlice3Acap")
204 ExtendCheckFunc[ssa.BoundsSlice3AcapU] = typecheck.LookupRuntimeVar("panicExtendSlice3AcapU")
205 ExtendCheckFunc[ssa.BoundsSlice3B] = typecheck.LookupRuntimeVar("panicExtendSlice3B")
206 ExtendCheckFunc[ssa.BoundsSlice3BU] = typecheck.LookupRuntimeVar("panicExtendSlice3BU")
207 ExtendCheckFunc[ssa.BoundsSlice3C] = typecheck.LookupRuntimeVar("panicExtendSlice3C")
208 ExtendCheckFunc[ssa.BoundsSlice3CU] = typecheck.LookupRuntimeVar("panicExtendSlice3CU")
211 // Wasm (all asm funcs with special ABIs)
212 ir.Syms.WasmDiv = typecheck.LookupRuntimeVar("wasmDiv")
213 ir.Syms.WasmTruncS = typecheck.LookupRuntimeVar("wasmTruncS")
214 ir.Syms.WasmTruncU = typecheck.LookupRuntimeVar("wasmTruncU")
215 ir.Syms.SigPanic = typecheck.LookupRuntimeFunc("sigpanic")
218 // AbiForBodylessFuncStackMap returns the ABI for a bodyless function's stack map.
219 // This is not necessarily the ABI used to call it.
220 // Currently (1.17 dev) such a stack map is always ABI0;
221 // any ABI wrapper that is present is nosplit, hence a precise
222 // stack map is not needed there (the parameters survive only long
223 // enough to call the wrapped assembly function).
224 // This always returns a freshly copied ABI.
225 func AbiForBodylessFuncStackMap(fn *ir.Func) *abi.ABIConfig {
226 return ssaConfig.ABI0.Copy() // No idea what races will result, be safe
229 // abiForFunc implements ABI policy for a function, but does not return a copy of the ABI.
230 // Passing a nil function returns the default ABI based on experiment configuration.
231 func abiForFunc(fn *ir.Func, abi0, abi1 *abi.ABIConfig) *abi.ABIConfig {
232 if buildcfg.Experiment.RegabiArgs {
233 // Select the ABI based on the function's defining ABI.
240 case obj.ABIInternal:
241 // TODO(austin): Clean up the nomenclature here.
242 // It's not clear that "abi1" is ABIInternal.
245 base.Fatalf("function %v has unknown ABI %v", fn, fn.ABI)
246 panic("not reachable")
251 if fn.Pragma&ir.RegisterParams != 0 { // TODO(register args) remove after register abi is working
258 // dvarint writes a varint v to the funcdata in symbol x and returns the new offset.
259 func dvarint(x *obj.LSym, off int, v int64) int {
260 if v < 0 || v > 1e9 {
261 panic(fmt.Sprintf("dvarint: bad offset for funcdata - %v", v))
264 return objw.Uint8(x, off, uint8(v))
266 off = objw.Uint8(x, off, uint8((v&127)|128))
268 return objw.Uint8(x, off, uint8(v>>7))
270 off = objw.Uint8(x, off, uint8(((v>>7)&127)|128))
272 return objw.Uint8(x, off, uint8(v>>14))
274 off = objw.Uint8(x, off, uint8(((v>>14)&127)|128))
276 return objw.Uint8(x, off, uint8(v>>21))
278 off = objw.Uint8(x, off, uint8(((v>>21)&127)|128))
279 return objw.Uint8(x, off, uint8(v>>28))
282 // emitOpenDeferInfo emits FUNCDATA information about the defers in a function
283 // that is using open-coded defers. This funcdata is used to determine the active
284 // defers in a function and execute those defers during panic processing.
286 // The funcdata is all encoded in varints (since values will almost always be less than
287 // 128, but stack offsets could potentially be up to 2Gbyte). All "locations" (offsets)
288 // for stack variables are specified as the number of bytes below varp (pointer to the
289 // top of the local variables) for their starting address. The format is:
291 // - Offset of the deferBits variable
292 // - Offset of the first closure slot (the rest are laid out consecutively).
293 func (s *state) emitOpenDeferInfo() {
294 firstOffset := s.openDefers[0].closureNode.FrameOffset()
296 // Verify that cmpstackvarlt laid out the slots in order.
297 for i, r := range s.openDefers {
298 have := r.closureNode.FrameOffset()
299 want := firstOffset + int64(i)*int64(types.PtrSize)
301 base.FatalfAt(s.curfn.Pos(), "unexpected frame offset for open-coded defer slot #%v: have %v, want %v", i, have, want)
305 x := base.Ctxt.Lookup(s.curfn.LSym.Name + ".opendefer")
306 x.Set(obj.AttrContentAddressable, true)
307 s.curfn.LSym.Func().OpenCodedDeferInfo = x
310 off = dvarint(x, off, -s.deferBitsTemp.FrameOffset())
311 off = dvarint(x, off, -firstOffset)
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)
319 abiSelf := abiForFunc(fn, ssaConfig.ABI0, ssaConfig.ABI1)
322 // match either a simple name e.g. "(*Reader).Reset", package.name e.g. "compress/gzip.(*Reader).Reset", or subpackage name "gzip.(*Reader).Reset"
323 // optionally allows an ABI suffix specification in the GOSSAHASH, e.g. "(*Reader).Reset<0>" etc
324 if strings.Contains(ssaDump, name) { // in all the cases the function name is entirely contained within the GOSSAFUNC string.
326 if strings.Contains(ssaDump, ",") { // ABI specification
327 nameOptABI = ssa.FuncNameABI(name, abiSelf.Which())
328 } else if strings.HasSuffix(ssaDump, ">") { // if they use the linker syntax instead....
330 if l >= 3 && ssaDump[l-3] == '<' {
331 nameOptABI = ssa.FuncNameABI(name, abiSelf.Which())
332 ssaDump = ssaDump[:l-3] + "," + ssaDump[l-2:l-1]
335 pkgDotName := base.Ctxt.Pkgpath + "." + nameOptABI
336 printssa = nameOptABI == ssaDump || // "(*Reader).Reset"
337 pkgDotName == ssaDump || // "compress/gzip.(*Reader).Reset"
338 strings.HasSuffix(pkgDotName, ssaDump) && strings.HasSuffix(pkgDotName, "/"+ssaDump) // "gzip.(*Reader).Reset"
341 var astBuf *bytes.Buffer
343 astBuf = &bytes.Buffer{}
344 ir.FDumpList(astBuf, "buildssa-body", fn.Body)
346 fmt.Println("generating SSA for", name)
347 fmt.Print(astBuf.String())
355 s.hasdefer = fn.HasDefer()
356 if fn.Pragma&ir.CgoUnsafeArgs != 0 {
357 s.cgoUnsafeArgs = true
359 s.checkPtrEnabled = ir.ShouldCheckPtr(fn, 1)
361 if base.Flag.Cfg.Instrumenting && fn.Pragma&ir.Norace == 0 && !fn.Linksym().ABIWrapper() {
362 if !base.Flag.Race || !objabi.LookupPkgSpecial(fn.Sym().Pkg.Path).NoRaceFunc {
363 s.instrumentMemory = true
366 s.instrumentEnterExit = true
372 log: printssa && ssaDumpStdout,
376 cache := &ssaCaches[worker]
379 s.f = ssaConfig.NewFunc(&fe, cache)
383 s.f.PrintOrHtmlSSA = printssa
384 if fn.Pragma&ir.Nosplit != 0 {
387 s.f.ABI0 = ssaConfig.ABI0
388 s.f.ABI1 = ssaConfig.ABI1
389 s.f.ABIDefault = abiForFunc(nil, ssaConfig.ABI0, ssaConfig.ABI1)
390 s.f.ABISelf = abiSelf
392 s.panics = map[funcLine]*ssa.Block{}
393 s.softFloat = s.config.SoftFloat
395 // Allocate starting block
396 s.f.Entry = s.f.NewBlock(ssa.BlockPlain)
397 s.f.Entry.Pos = fn.Pos()
402 ssaDF = filepath.Join(ssaDir, base.Ctxt.Pkgpath+"."+s.f.NameABI()+".html")
403 ssaD := filepath.Dir(ssaDF)
404 os.MkdirAll(ssaD, 0755)
406 s.f.HTMLWriter = ssa.NewHTMLWriter(ssaDF, s.f, ssaDumpCFG)
407 // TODO: generate and print a mapping from nodes to values and blocks
408 dumpSourcesColumn(s.f.HTMLWriter, fn)
409 s.f.HTMLWriter.WriteAST("AST", astBuf)
412 // Allocate starting values
413 s.labels = map[string]*ssaLabel{}
414 s.fwdVars = map[ir.Node]*ssa.Value{}
415 s.startmem = s.entryNewValue0(ssa.OpInitMem, types.TypeMem)
417 s.hasOpenDefers = base.Flag.N == 0 && s.hasdefer && !s.curfn.OpenCodedDeferDisallowed()
419 case base.Debug.NoOpenDefer != 0:
420 s.hasOpenDefers = false
421 case s.hasOpenDefers && (base.Ctxt.Flag_shared || base.Ctxt.Flag_dynlink) && base.Ctxt.Arch.Name == "386":
422 // Don't support open-coded defers for 386 ONLY when using shared
423 // libraries, because there is extra code (added by rewriteToUseGot())
424 // preceding the deferreturn/ret code that we don't track correctly.
425 s.hasOpenDefers = false
427 if s.hasOpenDefers && s.instrumentEnterExit {
428 // Skip doing open defers if we need to instrument function
429 // returns for the race detector, since we will not generate that
430 // code in the case of the extra deferreturn/ret segment.
431 s.hasOpenDefers = false
434 // Similarly, skip if there are any heap-allocated result
435 // parameters that need to be copied back to their stack slots.
436 for _, f := range s.curfn.Type().Results() {
437 if !f.Nname.(*ir.Name).OnStack() {
438 s.hasOpenDefers = false
443 if s.hasOpenDefers &&
444 s.curfn.NumReturns*s.curfn.NumDefers > 15 {
445 // Since we are generating defer calls at every exit for
446 // open-coded defers, skip doing open-coded defers if there are
447 // too many returns (especially if there are multiple defers).
448 // Open-coded defers are most important for improving performance
449 // for smaller functions (which don't have many returns).
450 s.hasOpenDefers = false
453 s.sp = s.entryNewValue0(ssa.OpSP, types.Types[types.TUINTPTR]) // TODO: use generic pointer type (unsafe.Pointer?) instead
454 s.sb = s.entryNewValue0(ssa.OpSB, types.Types[types.TUINTPTR])
456 s.startBlock(s.f.Entry)
457 s.vars[memVar] = s.startmem
459 // Create the deferBits variable and stack slot. deferBits is a
460 // bitmask showing which of the open-coded defers in this function
461 // have been activated.
462 deferBitsTemp := typecheck.TempAt(src.NoXPos, s.curfn, types.Types[types.TUINT8])
463 deferBitsTemp.SetAddrtaken(true)
464 s.deferBitsTemp = deferBitsTemp
465 // For this value, AuxInt is initialized to zero by default
466 startDeferBits := s.entryNewValue0(ssa.OpConst8, types.Types[types.TUINT8])
467 s.vars[deferBitsVar] = startDeferBits
468 s.deferBitsAddr = s.addr(deferBitsTemp)
469 s.store(types.Types[types.TUINT8], s.deferBitsAddr, startDeferBits)
470 // Make sure that the deferBits stack slot is kept alive (for use
471 // by panics) and stores to deferBits are not eliminated, even if
472 // all checking code on deferBits in the function exit can be
473 // eliminated, because the defer statements were all
475 s.vars[memVar] = s.newValue1Apos(ssa.OpVarLive, types.TypeMem, deferBitsTemp, s.mem(), false)
478 var params *abi.ABIParamResultInfo
479 params = s.f.ABISelf.ABIAnalyze(fn.Type(), true)
481 // The backend's stackframe pass prunes away entries from the fn's
482 // Dcl list, including PARAMOUT nodes that correspond to output
483 // params passed in registers. Walk the Dcl list and capture these
484 // nodes to a side list, so that we'll have them available during
485 // DWARF-gen later on. See issue 48573 for more details.
486 var debugInfo ssa.FuncDebug
487 for _, n := range fn.Dcl {
488 if n.Class == ir.PPARAMOUT && n.IsOutputParamInRegisters() {
489 debugInfo.RegOutputParams = append(debugInfo.RegOutputParams, n)
492 fn.DebugInfo = &debugInfo
494 // Generate addresses of local declarations
495 s.decladdrs = map[*ir.Name]*ssa.Value{}
496 for _, n := range fn.Dcl {
499 // Be aware that blank and unnamed input parameters will not appear here, but do appear in the type
500 s.decladdrs[n] = s.entryNewValue2A(ssa.OpLocalAddr, types.NewPtr(n.Type()), n, s.sp, s.startmem)
502 s.decladdrs[n] = s.entryNewValue2A(ssa.OpLocalAddr, types.NewPtr(n.Type()), n, s.sp, s.startmem)
504 // processed at each use, to prevent Addr coming
507 s.Fatalf("local variable with class %v unimplemented", n.Class)
511 s.f.OwnAux = ssa.OwnAuxCall(fn.LSym, params)
513 // Populate SSAable arguments.
514 for _, n := range fn.Dcl {
515 if n.Class == ir.PPARAM {
517 v := s.newValue0A(ssa.OpArg, n.Type(), n)
519 s.addNamedValue(n, v) // This helps with debugging information, not needed for compilation itself.
520 } else { // address was taken AND/OR too large for SSA
521 paramAssignment := ssa.ParamAssignmentForArgName(s.f, n)
522 if len(paramAssignment.Registers) > 0 {
523 if ssa.CanSSA(n.Type()) { // SSA-able type, so address was taken -- receive value in OpArg, DO NOT bind to var, store immediately to memory.
524 v := s.newValue0A(ssa.OpArg, n.Type(), n)
525 s.store(n.Type(), s.decladdrs[n], v)
526 } else { // Too big for SSA.
527 // Brute force, and early, do a bunch of stores from registers
528 // TODO fix the nasty storeArgOrLoad recursion in ssa/expand_calls.go so this Just Works with store of a big Arg.
529 s.storeParameterRegsToStack(s.f.ABISelf, paramAssignment, n, s.decladdrs[n], false)
536 // Populate closure variables.
538 clo := s.entryNewValue0(ssa.OpGetClosurePtr, s.f.Config.Types.BytePtr)
539 offset := int64(types.PtrSize) // PtrSize to skip past function entry PC field
540 for _, n := range fn.ClosureVars {
543 typ = types.NewPtr(typ)
546 offset = types.RoundUp(offset, typ.Alignment())
547 ptr := s.newValue1I(ssa.OpOffPtr, types.NewPtr(typ), offset, clo)
550 // If n is a small variable captured by value, promote
551 // it to PAUTO so it can be converted to SSA.
553 // Note: While we never capture a variable by value if
554 // the user took its address, we may have generated
555 // runtime calls that did (#43701). Since we don't
556 // convert Addrtaken variables to SSA anyway, no point
557 // in promoting them either.
558 if n.Byval() && !n.Addrtaken() && ssa.CanSSA(n.Type()) {
560 fn.Dcl = append(fn.Dcl, n)
561 s.assign(n, s.load(n.Type(), ptr), false, 0)
566 ptr = s.load(typ, ptr)
568 s.setHeapaddr(fn.Pos(), n, ptr)
572 // Convert the AST-based IR to the SSA-based IR
573 if s.instrumentEnterExit {
574 s.rtcall(ir.Syms.Racefuncenter, true, nil, s.newValue0(ssa.OpGetCallerPC, types.Types[types.TUINTPTR]))
580 // fallthrough to exit
581 if s.curBlock != nil {
582 s.pushLine(fn.Endlineno)
587 for _, b := range s.f.Blocks {
588 if b.Pos != src.NoXPos {
589 s.updateUnsetPredPos(b)
593 s.f.HTMLWriter.WritePhase("before insert phis", "before insert phis")
597 // Main call to ssa package to compile function
602 if len(s.openDefers) != 0 {
603 s.emitOpenDeferInfo()
606 // Record incoming parameter spill information for morestack calls emitted in the assembler.
607 // This is done here, using all the parameters (used, partially used, and unused) because
608 // it mimics the behavior of the former ABI (everything stored) and because it's not 100%
609 // clear if naming conventions are respected in autogenerated code.
610 // TODO figure out exactly what's unused, don't spill it. Make liveness fine-grained, also.
611 for _, p := range params.InParams() {
612 typs, offs := p.RegisterTypesAndOffsets()
613 for i, t := range typs {
614 o := offs[i] // offset within parameter
615 fo := p.FrameOffset(params) // offset of parameter in frame
616 reg := ssa.ObjRegForAbiReg(p.Registers[i], s.f.Config)
617 s.f.RegArgs = append(s.f.RegArgs, ssa.Spill{Reg: reg, Offset: fo + o, Type: t})
624 func (s *state) storeParameterRegsToStack(abi *abi.ABIConfig, paramAssignment *abi.ABIParamAssignment, n *ir.Name, addr *ssa.Value, pointersOnly bool) {
625 typs, offs := paramAssignment.RegisterTypesAndOffsets()
626 for i, t := range typs {
627 if pointersOnly && !t.IsPtrShaped() {
630 r := paramAssignment.Registers[i]
632 op, reg := ssa.ArgOpAndRegisterFor(r, abi)
633 aux := &ssa.AuxNameOffset{Name: n, Offset: o}
634 v := s.newValue0I(op, t, reg)
636 p := s.newValue1I(ssa.OpOffPtr, types.NewPtr(t), o, addr)
641 // zeroResults zeros the return values at the start of the function.
642 // We need to do this very early in the function. Defer might stop a
643 // panic and show the return values as they exist at the time of
644 // panic. For precise stacks, the garbage collector assumes results
645 // are always live, so we need to zero them before any allocations,
646 // even allocations to move params/results to the heap.
647 func (s *state) zeroResults() {
648 for _, f := range s.curfn.Type().Results() {
649 n := f.Nname.(*ir.Name)
651 // The local which points to the return value is the
652 // thing that needs zeroing. This is already handled
653 // by a Needzero annotation in plive.go:(*liveness).epilogue.
656 // Zero the stack location containing f.
657 if typ := n.Type(); ssa.CanSSA(typ) {
658 s.assign(n, s.zeroVal(typ), false, 0)
660 if typ.HasPointers() {
661 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, n, s.mem())
663 s.zero(n.Type(), s.decladdrs[n])
668 // paramsToHeap produces code to allocate memory for heap-escaped parameters
669 // and to copy non-result parameters' values from the stack.
670 func (s *state) paramsToHeap() {
671 do := func(params []*types.Field) {
672 for _, f := range params {
674 continue // anonymous or blank parameter
676 n := f.Nname.(*ir.Name)
677 if ir.IsBlank(n) || n.OnStack() {
681 if n.Class == ir.PPARAM {
682 s.move(n.Type(), s.expr(n.Heapaddr), s.decladdrs[n])
687 typ := s.curfn.Type()
693 // newHeapaddr allocates heap memory for n and sets its heap address.
694 func (s *state) newHeapaddr(n *ir.Name) {
695 s.setHeapaddr(n.Pos(), n, s.newObject(n.Type(), nil))
698 // setHeapaddr allocates a new PAUTO variable to store ptr (which must be non-nil)
699 // and then sets it as n's heap address.
700 func (s *state) setHeapaddr(pos src.XPos, n *ir.Name, ptr *ssa.Value) {
701 if !ptr.Type.IsPtr() || !types.Identical(n.Type(), ptr.Type.Elem()) {
702 base.FatalfAt(n.Pos(), "setHeapaddr %L with type %v", n, ptr.Type)
705 // Declare variable to hold address.
706 sym := &types.Sym{Name: "&" + n.Sym().Name, Pkg: types.LocalPkg}
707 addr := s.curfn.NewLocal(pos, sym, types.NewPtr(n.Type()))
709 types.CalcSize(addr.Type())
711 if n.Class == ir.PPARAMOUT {
712 addr.SetIsOutputParamHeapAddr(true)
716 s.assign(addr, ptr, false, 0)
719 // newObject returns an SSA value denoting new(typ).
720 func (s *state) newObject(typ *types.Type, rtype *ssa.Value) *ssa.Value {
722 return s.newValue1A(ssa.OpAddr, types.NewPtr(typ), ir.Syms.Zerobase, s.sb)
725 rtype = s.reflectType(typ)
727 return s.rtcall(ir.Syms.Newobject, true, []*types.Type{types.NewPtr(typ)}, rtype)[0]
730 func (s *state) checkPtrAlignment(n *ir.ConvExpr, v *ssa.Value, count *ssa.Value) {
731 if !n.Type().IsPtr() {
732 s.Fatalf("expected pointer type: %v", n.Type())
734 elem, rtypeExpr := n.Type().Elem(), n.ElemRType
737 s.Fatalf("expected array type: %v", elem)
739 elem, rtypeExpr = elem.Elem(), n.ElemElemRType
742 // Casting from larger type to smaller one is ok, so for smallest type, do nothing.
743 if elem.Alignment() == 1 && (size == 0 || size == 1 || count == nil) {
747 count = s.constInt(types.Types[types.TUINTPTR], 1)
749 if count.Type.Size() != s.config.PtrSize {
750 s.Fatalf("expected count fit to a uintptr size, have: %d, want: %d", count.Type.Size(), s.config.PtrSize)
753 if rtypeExpr != nil {
754 rtype = s.expr(rtypeExpr)
756 rtype = s.reflectType(elem)
758 s.rtcall(ir.Syms.CheckPtrAlignment, true, nil, v, rtype, count)
761 // reflectType returns an SSA value representing a pointer to typ's
762 // reflection type descriptor.
763 func (s *state) reflectType(typ *types.Type) *ssa.Value {
764 // TODO(mdempsky): Make this Fatalf under Unified IR; frontend needs
765 // to supply RType expressions.
766 lsym := reflectdata.TypeLinksym(typ)
767 return s.entryNewValue1A(ssa.OpAddr, types.NewPtr(types.Types[types.TUINT8]), lsym, s.sb)
770 func dumpSourcesColumn(writer *ssa.HTMLWriter, fn *ir.Func) {
771 // Read sources of target function fn.
772 fname := base.Ctxt.PosTable.Pos(fn.Pos()).Filename()
773 targetFn, err := readFuncLines(fname, fn.Pos().Line(), fn.Endlineno.Line())
775 writer.Logf("cannot read sources for function %v: %v", fn, err)
778 // Read sources of inlined functions.
779 var inlFns []*ssa.FuncLines
780 for _, fi := range ssaDumpInlined {
782 fname := base.Ctxt.PosTable.Pos(fi.Pos()).Filename()
783 fnLines, err := readFuncLines(fname, fi.Pos().Line(), elno.Line())
785 writer.Logf("cannot read sources for inlined function %v: %v", fi, err)
788 inlFns = append(inlFns, fnLines)
791 sort.Sort(ssa.ByTopo(inlFns))
793 inlFns = append([]*ssa.FuncLines{targetFn}, inlFns...)
796 writer.WriteSources("sources", inlFns)
799 func readFuncLines(file string, start, end uint) (*ssa.FuncLines, error) {
800 f, err := os.Open(os.ExpandEnv(file))
807 scanner := bufio.NewScanner(f)
808 for scanner.Scan() && ln <= end {
810 lines = append(lines, scanner.Text())
814 return &ssa.FuncLines{Filename: file, StartLineno: start, Lines: lines}, nil
817 // updateUnsetPredPos propagates the earliest-value position information for b
818 // towards all of b's predecessors that need a position, and recurs on that
819 // predecessor if its position is updated. B should have a non-empty position.
820 func (s *state) updateUnsetPredPos(b *ssa.Block) {
821 if b.Pos == src.NoXPos {
822 s.Fatalf("Block %s should have a position", b)
824 bestPos := src.NoXPos
825 for _, e := range b.Preds {
830 if bestPos == src.NoXPos {
832 for _, v := range b.Values {
836 if v.Pos != src.NoXPos {
837 // Assume values are still in roughly textual order;
838 // TODO: could also seek minimum position?
845 s.updateUnsetPredPos(p) // We do not expect long chains of these, thus recursion is okay.
849 // Information about each open-coded defer.
850 type openDeferInfo struct {
851 // The node representing the call of the defer
853 // If defer call is closure call, the address of the argtmp where the
854 // closure is stored.
856 // The node representing the argtmp where the closure is stored - used for
857 // function, method, or interface call, to store a closure that panic
858 // processing can use for this defer.
863 // configuration (arch) information
866 // function we're building
873 labels map[string]*ssaLabel
875 // unlabeled break and continue statement tracking
876 breakTo *ssa.Block // current target for plain break statement
877 continueTo *ssa.Block // current target for plain continue statement
879 // current location where we're interpreting the AST
882 // variable assignments in the current block (map from variable symbol to ssa value)
883 // *Node is the unique identifier (an ONAME Node) for the variable.
884 // TODO: keep a single varnum map, then make all of these maps slices instead?
885 vars map[ir.Node]*ssa.Value
887 // fwdVars are variables that are used before they are defined in the current block.
888 // This map exists just to coalesce multiple references into a single FwdRef op.
889 // *Node is the unique identifier (an ONAME Node) for the variable.
890 fwdVars map[ir.Node]*ssa.Value
892 // all defined variables at the end of each block. Indexed by block ID.
893 defvars []map[ir.Node]*ssa.Value
895 // addresses of PPARAM and PPARAMOUT variables on the stack.
896 decladdrs map[*ir.Name]*ssa.Value
898 // starting values. Memory, stack pointer, and globals pointer
902 // value representing address of where deferBits autotmp is stored
903 deferBitsAddr *ssa.Value
904 deferBitsTemp *ir.Name
906 // line number stack. The current line number is top of stack
908 // the last line number processed; it may have been popped
911 // list of panic calls by function name and line number.
912 // Used to deduplicate panic calls.
913 panics map[funcLine]*ssa.Block
916 hasdefer bool // whether the function contains a defer statement
918 hasOpenDefers bool // whether we are doing open-coded defers
919 checkPtrEnabled bool // whether to insert checkptr instrumentation
920 instrumentEnterExit bool // whether to instrument function enter/exit
921 instrumentMemory bool // whether to instrument memory operations
923 // If doing open-coded defers, list of info about the defer calls in
924 // scanning order. Hence, at exit we should run these defers in reverse
925 // order of this list
926 openDefers []*openDeferInfo
927 // For open-coded defers, this is the beginning and end blocks of the last
928 // defer exit code that we have generated so far. We use these to share
929 // code between exits if the shareDeferExits option (disabled by default)
931 lastDeferExit *ssa.Block // Entry block of last defer exit code we generated
932 lastDeferFinalBlock *ssa.Block // Final block of last defer exit code we generated
933 lastDeferCount int // Number of defers encountered at that point
935 prevCall *ssa.Value // the previous call; use this to tie results to the call op.
938 type funcLine struct {
944 type ssaLabel struct {
945 target *ssa.Block // block identified by this label
946 breakTarget *ssa.Block // block to break to in control flow node identified by this label
947 continueTarget *ssa.Block // block to continue to in control flow node identified by this label
950 // label returns the label associated with sym, creating it if necessary.
951 func (s *state) label(sym *types.Sym) *ssaLabel {
952 lab := s.labels[sym.Name]
955 s.labels[sym.Name] = lab
960 func (s *state) Logf(msg string, args ...interface{}) { s.f.Logf(msg, args...) }
961 func (s *state) Log() bool { return s.f.Log() }
962 func (s *state) Fatalf(msg string, args ...interface{}) {
963 s.f.Frontend().Fatalf(s.peekPos(), msg, args...)
965 func (s *state) Warnl(pos src.XPos, msg string, args ...interface{}) { s.f.Warnl(pos, msg, args...) }
966 func (s *state) Debug_checknil() bool { return s.f.Frontend().Debug_checknil() }
968 func ssaMarker(name string) *ir.Name {
969 return ir.NewNameAt(base.Pos, &types.Sym{Name: name}, nil)
973 // marker node for the memory variable
974 memVar = ssaMarker("mem")
976 // marker nodes for temporary variables
977 ptrVar = ssaMarker("ptr")
978 lenVar = ssaMarker("len")
979 capVar = ssaMarker("cap")
980 typVar = ssaMarker("typ")
981 okVar = ssaMarker("ok")
982 deferBitsVar = ssaMarker("deferBits")
983 hashVar = ssaMarker("hash")
986 // startBlock sets the current block we're generating code in to b.
987 func (s *state) startBlock(b *ssa.Block) {
988 if s.curBlock != nil {
989 s.Fatalf("starting block %v when block %v has not ended", b, s.curBlock)
992 s.vars = map[ir.Node]*ssa.Value{}
993 for n := range s.fwdVars {
998 // endBlock marks the end of generating code for the current block.
999 // Returns the (former) current block. Returns nil if there is no current
1000 // block, i.e. if no code flows to the current execution point.
1001 func (s *state) endBlock() *ssa.Block {
1006 for len(s.defvars) <= int(b.ID) {
1007 s.defvars = append(s.defvars, nil)
1009 s.defvars[b.ID] = s.vars
1013 // Empty plain blocks get the line of their successor (handled after all blocks created),
1014 // except for increment blocks in For statements (handled in ssa conversion of OFOR),
1015 // and for blocks ending in GOTO/BREAK/CONTINUE.
1023 // pushLine pushes a line number on the line number stack.
1024 func (s *state) pushLine(line src.XPos) {
1025 if !line.IsKnown() {
1026 // the frontend may emit node with line number missing,
1027 // use the parent line number in this case.
1029 if base.Flag.K != 0 {
1030 base.Warn("buildssa: unknown position (line 0)")
1036 s.line = append(s.line, line)
1039 // popLine pops the top of the line number stack.
1040 func (s *state) popLine() {
1041 s.line = s.line[:len(s.line)-1]
1044 // peekPos peeks the top of the line number stack.
1045 func (s *state) peekPos() src.XPos {
1046 return s.line[len(s.line)-1]
1049 // newValue0 adds a new value with no arguments to the current block.
1050 func (s *state) newValue0(op ssa.Op, t *types.Type) *ssa.Value {
1051 return s.curBlock.NewValue0(s.peekPos(), op, t)
1054 // newValue0A adds a new value with no arguments and an aux value to the current block.
1055 func (s *state) newValue0A(op ssa.Op, t *types.Type, aux ssa.Aux) *ssa.Value {
1056 return s.curBlock.NewValue0A(s.peekPos(), op, t, aux)
1059 // newValue0I adds a new value with no arguments and an auxint value to the current block.
1060 func (s *state) newValue0I(op ssa.Op, t *types.Type, auxint int64) *ssa.Value {
1061 return s.curBlock.NewValue0I(s.peekPos(), op, t, auxint)
1064 // newValue1 adds a new value with one argument to the current block.
1065 func (s *state) newValue1(op ssa.Op, t *types.Type, arg *ssa.Value) *ssa.Value {
1066 return s.curBlock.NewValue1(s.peekPos(), op, t, arg)
1069 // newValue1A adds a new value with one argument and an aux value to the current block.
1070 func (s *state) newValue1A(op ssa.Op, t *types.Type, aux ssa.Aux, arg *ssa.Value) *ssa.Value {
1071 return s.curBlock.NewValue1A(s.peekPos(), op, t, aux, arg)
1074 // newValue1Apos adds a new value with one argument and an aux value to the current block.
1075 // isStmt determines whether the created values may be a statement or not
1076 // (i.e., false means never, yes means maybe).
1077 func (s *state) newValue1Apos(op ssa.Op, t *types.Type, aux ssa.Aux, arg *ssa.Value, isStmt bool) *ssa.Value {
1079 return s.curBlock.NewValue1A(s.peekPos(), op, t, aux, arg)
1081 return s.curBlock.NewValue1A(s.peekPos().WithNotStmt(), op, t, aux, arg)
1084 // newValue1I adds a new value with one argument and an auxint value to the current block.
1085 func (s *state) newValue1I(op ssa.Op, t *types.Type, aux int64, arg *ssa.Value) *ssa.Value {
1086 return s.curBlock.NewValue1I(s.peekPos(), op, t, aux, arg)
1089 // newValue2 adds a new value with two arguments to the current block.
1090 func (s *state) newValue2(op ssa.Op, t *types.Type, arg0, arg1 *ssa.Value) *ssa.Value {
1091 return s.curBlock.NewValue2(s.peekPos(), op, t, arg0, arg1)
1094 // newValue2A adds a new value with two arguments and an aux value to the current block.
1095 func (s *state) newValue2A(op ssa.Op, t *types.Type, aux ssa.Aux, arg0, arg1 *ssa.Value) *ssa.Value {
1096 return s.curBlock.NewValue2A(s.peekPos(), op, t, aux, arg0, arg1)
1099 // newValue2Apos adds a new value with two arguments and an aux value to the current block.
1100 // isStmt determines whether the created values may be a statement or not
1101 // (i.e., false means never, yes means maybe).
1102 func (s *state) newValue2Apos(op ssa.Op, t *types.Type, aux ssa.Aux, arg0, arg1 *ssa.Value, isStmt bool) *ssa.Value {
1104 return s.curBlock.NewValue2A(s.peekPos(), op, t, aux, arg0, arg1)
1106 return s.curBlock.NewValue2A(s.peekPos().WithNotStmt(), op, t, aux, arg0, arg1)
1109 // newValue2I adds a new value with two arguments and an auxint value to the current block.
1110 func (s *state) newValue2I(op ssa.Op, t *types.Type, aux int64, arg0, arg1 *ssa.Value) *ssa.Value {
1111 return s.curBlock.NewValue2I(s.peekPos(), op, t, aux, arg0, arg1)
1114 // newValue3 adds a new value with three arguments to the current block.
1115 func (s *state) newValue3(op ssa.Op, t *types.Type, arg0, arg1, arg2 *ssa.Value) *ssa.Value {
1116 return s.curBlock.NewValue3(s.peekPos(), op, t, arg0, arg1, arg2)
1119 // newValue3I adds a new value with three arguments and an auxint value to the current block.
1120 func (s *state) newValue3I(op ssa.Op, t *types.Type, aux int64, arg0, arg1, arg2 *ssa.Value) *ssa.Value {
1121 return s.curBlock.NewValue3I(s.peekPos(), op, t, aux, arg0, arg1, arg2)
1124 // newValue3A adds a new value with three arguments and an aux value to the current block.
1125 func (s *state) newValue3A(op ssa.Op, t *types.Type, aux ssa.Aux, arg0, arg1, arg2 *ssa.Value) *ssa.Value {
1126 return s.curBlock.NewValue3A(s.peekPos(), op, t, aux, arg0, arg1, arg2)
1129 // newValue3Apos adds a new value with three arguments and an aux value to the current block.
1130 // isStmt determines whether the created values may be a statement or not
1131 // (i.e., false means never, yes means maybe).
1132 func (s *state) newValue3Apos(op ssa.Op, t *types.Type, aux ssa.Aux, arg0, arg1, arg2 *ssa.Value, isStmt bool) *ssa.Value {
1134 return s.curBlock.NewValue3A(s.peekPos(), op, t, aux, arg0, arg1, arg2)
1136 return s.curBlock.NewValue3A(s.peekPos().WithNotStmt(), op, t, aux, arg0, arg1, arg2)
1139 // newValue4 adds a new value with four arguments to the current block.
1140 func (s *state) newValue4(op ssa.Op, t *types.Type, arg0, arg1, arg2, arg3 *ssa.Value) *ssa.Value {
1141 return s.curBlock.NewValue4(s.peekPos(), op, t, arg0, arg1, arg2, arg3)
1144 // newValue4I adds a new value with four arguments and an auxint value to the current block.
1145 func (s *state) newValue4I(op ssa.Op, t *types.Type, aux int64, arg0, arg1, arg2, arg3 *ssa.Value) *ssa.Value {
1146 return s.curBlock.NewValue4I(s.peekPos(), op, t, aux, arg0, arg1, arg2, arg3)
1149 func (s *state) entryBlock() *ssa.Block {
1151 if base.Flag.N > 0 && s.curBlock != nil {
1152 // If optimizations are off, allocate in current block instead. Since with -N
1153 // we're not doing the CSE or tighten passes, putting lots of stuff in the
1154 // entry block leads to O(n^2) entries in the live value map during regalloc.
1161 // entryNewValue0 adds a new value with no arguments to the entry block.
1162 func (s *state) entryNewValue0(op ssa.Op, t *types.Type) *ssa.Value {
1163 return s.entryBlock().NewValue0(src.NoXPos, op, t)
1166 // entryNewValue0A adds a new value with no arguments and an aux value to the entry block.
1167 func (s *state) entryNewValue0A(op ssa.Op, t *types.Type, aux ssa.Aux) *ssa.Value {
1168 return s.entryBlock().NewValue0A(src.NoXPos, op, t, aux)
1171 // entryNewValue1 adds a new value with one argument to the entry block.
1172 func (s *state) entryNewValue1(op ssa.Op, t *types.Type, arg *ssa.Value) *ssa.Value {
1173 return s.entryBlock().NewValue1(src.NoXPos, op, t, arg)
1176 // entryNewValue1I adds a new value with one argument and an auxint value to the entry block.
1177 func (s *state) entryNewValue1I(op ssa.Op, t *types.Type, auxint int64, arg *ssa.Value) *ssa.Value {
1178 return s.entryBlock().NewValue1I(src.NoXPos, op, t, auxint, arg)
1181 // entryNewValue1A adds a new value with one argument and an aux value to the entry block.
1182 func (s *state) entryNewValue1A(op ssa.Op, t *types.Type, aux ssa.Aux, arg *ssa.Value) *ssa.Value {
1183 return s.entryBlock().NewValue1A(src.NoXPos, op, t, aux, arg)
1186 // entryNewValue2 adds a new value with two arguments to the entry block.
1187 func (s *state) entryNewValue2(op ssa.Op, t *types.Type, arg0, arg1 *ssa.Value) *ssa.Value {
1188 return s.entryBlock().NewValue2(src.NoXPos, op, t, arg0, arg1)
1191 // entryNewValue2A adds a new value with two arguments and an aux value to the entry block.
1192 func (s *state) entryNewValue2A(op ssa.Op, t *types.Type, aux ssa.Aux, arg0, arg1 *ssa.Value) *ssa.Value {
1193 return s.entryBlock().NewValue2A(src.NoXPos, op, t, aux, arg0, arg1)
1196 // const* routines add a new const value to the entry block.
1197 func (s *state) constSlice(t *types.Type) *ssa.Value {
1198 return s.f.ConstSlice(t)
1200 func (s *state) constInterface(t *types.Type) *ssa.Value {
1201 return s.f.ConstInterface(t)
1203 func (s *state) constNil(t *types.Type) *ssa.Value { return s.f.ConstNil(t) }
1204 func (s *state) constEmptyString(t *types.Type) *ssa.Value {
1205 return s.f.ConstEmptyString(t)
1207 func (s *state) constBool(c bool) *ssa.Value {
1208 return s.f.ConstBool(types.Types[types.TBOOL], c)
1210 func (s *state) constInt8(t *types.Type, c int8) *ssa.Value {
1211 return s.f.ConstInt8(t, c)
1213 func (s *state) constInt16(t *types.Type, c int16) *ssa.Value {
1214 return s.f.ConstInt16(t, c)
1216 func (s *state) constInt32(t *types.Type, c int32) *ssa.Value {
1217 return s.f.ConstInt32(t, c)
1219 func (s *state) constInt64(t *types.Type, c int64) *ssa.Value {
1220 return s.f.ConstInt64(t, c)
1222 func (s *state) constFloat32(t *types.Type, c float64) *ssa.Value {
1223 return s.f.ConstFloat32(t, c)
1225 func (s *state) constFloat64(t *types.Type, c float64) *ssa.Value {
1226 return s.f.ConstFloat64(t, c)
1228 func (s *state) constInt(t *types.Type, c int64) *ssa.Value {
1229 if s.config.PtrSize == 8 {
1230 return s.constInt64(t, c)
1232 if int64(int32(c)) != c {
1233 s.Fatalf("integer constant too big %d", c)
1235 return s.constInt32(t, int32(c))
1237 func (s *state) constOffPtrSP(t *types.Type, c int64) *ssa.Value {
1238 return s.f.ConstOffPtrSP(t, c, s.sp)
1241 // newValueOrSfCall* are wrappers around newValue*, which may create a call to a
1242 // soft-float runtime function instead (when emitting soft-float code).
1243 func (s *state) newValueOrSfCall1(op ssa.Op, t *types.Type, arg *ssa.Value) *ssa.Value {
1245 if c, ok := s.sfcall(op, arg); ok {
1249 return s.newValue1(op, t, arg)
1251 func (s *state) newValueOrSfCall2(op ssa.Op, t *types.Type, arg0, arg1 *ssa.Value) *ssa.Value {
1253 if c, ok := s.sfcall(op, arg0, arg1); ok {
1257 return s.newValue2(op, t, arg0, arg1)
1260 type instrumentKind uint8
1263 instrumentRead = iota
1268 func (s *state) instrument(t *types.Type, addr *ssa.Value, kind instrumentKind) {
1269 s.instrument2(t, addr, nil, kind)
1272 // instrumentFields instruments a read/write operation on addr.
1273 // If it is instrumenting for MSAN or ASAN and t is a struct type, it instruments
1274 // operation for each field, instead of for the whole struct.
1275 func (s *state) instrumentFields(t *types.Type, addr *ssa.Value, kind instrumentKind) {
1276 if !(base.Flag.MSan || base.Flag.ASan) || !t.IsStruct() {
1277 s.instrument(t, addr, kind)
1280 for _, f := range t.Fields() {
1281 if f.Sym.IsBlank() {
1284 offptr := s.newValue1I(ssa.OpOffPtr, types.NewPtr(f.Type), f.Offset, addr)
1285 s.instrumentFields(f.Type, offptr, kind)
1289 func (s *state) instrumentMove(t *types.Type, dst, src *ssa.Value) {
1291 s.instrument2(t, dst, src, instrumentMove)
1293 s.instrument(t, src, instrumentRead)
1294 s.instrument(t, dst, instrumentWrite)
1298 func (s *state) instrument2(t *types.Type, addr, addr2 *ssa.Value, kind instrumentKind) {
1299 if !s.instrumentMemory {
1305 return // can't race on zero-sized things
1308 if ssa.IsSanitizerSafeAddr(addr) {
1315 if addr2 != nil && kind != instrumentMove {
1316 panic("instrument2: non-nil addr2 for non-move instrumentation")
1321 case instrumentRead:
1322 fn = ir.Syms.Msanread
1323 case instrumentWrite:
1324 fn = ir.Syms.Msanwrite
1325 case instrumentMove:
1326 fn = ir.Syms.Msanmove
1328 panic("unreachable")
1331 } else if base.Flag.Race && t.NumComponents(types.CountBlankFields) > 1 {
1332 // for composite objects we have to write every address
1333 // because a write might happen to any subobject.
1334 // composites with only one element don't have subobjects, though.
1336 case instrumentRead:
1337 fn = ir.Syms.Racereadrange
1338 case instrumentWrite:
1339 fn = ir.Syms.Racewriterange
1341 panic("unreachable")
1344 } else if base.Flag.Race {
1345 // for non-composite objects we can write just the start
1346 // address, as any write must write the first byte.
1348 case instrumentRead:
1349 fn = ir.Syms.Raceread
1350 case instrumentWrite:
1351 fn = ir.Syms.Racewrite
1353 panic("unreachable")
1355 } else if base.Flag.ASan {
1357 case instrumentRead:
1358 fn = ir.Syms.Asanread
1359 case instrumentWrite:
1360 fn = ir.Syms.Asanwrite
1362 panic("unreachable")
1366 panic("unreachable")
1369 args := []*ssa.Value{addr}
1371 args = append(args, addr2)
1374 args = append(args, s.constInt(types.Types[types.TUINTPTR], w))
1376 s.rtcall(fn, true, nil, args...)
1379 func (s *state) load(t *types.Type, src *ssa.Value) *ssa.Value {
1380 s.instrumentFields(t, src, instrumentRead)
1381 return s.rawLoad(t, src)
1384 func (s *state) rawLoad(t *types.Type, src *ssa.Value) *ssa.Value {
1385 return s.newValue2(ssa.OpLoad, t, src, s.mem())
1388 func (s *state) store(t *types.Type, dst, val *ssa.Value) {
1389 s.vars[memVar] = s.newValue3A(ssa.OpStore, types.TypeMem, t, dst, val, s.mem())
1392 func (s *state) zero(t *types.Type, dst *ssa.Value) {
1393 s.instrument(t, dst, instrumentWrite)
1394 store := s.newValue2I(ssa.OpZero, types.TypeMem, t.Size(), dst, s.mem())
1396 s.vars[memVar] = store
1399 func (s *state) move(t *types.Type, dst, src *ssa.Value) {
1400 s.moveWhichMayOverlap(t, dst, src, false)
1402 func (s *state) moveWhichMayOverlap(t *types.Type, dst, src *ssa.Value, mayOverlap bool) {
1403 s.instrumentMove(t, dst, src)
1404 if mayOverlap && t.IsArray() && t.NumElem() > 1 && !ssa.IsInlinableMemmove(dst, src, t.Size(), s.f.Config) {
1405 // Normally, when moving Go values of type T from one location to another,
1406 // we don't need to worry about partial overlaps. The two Ts must either be
1407 // in disjoint (nonoverlapping) memory or in exactly the same location.
1408 // There are 2 cases where this isn't true:
1409 // 1) Using unsafe you can arrange partial overlaps.
1410 // 2) Since Go 1.17, you can use a cast from a slice to a ptr-to-array.
1411 // https://go.dev/ref/spec#Conversions_from_slice_to_array_pointer
1412 // This feature can be used to construct partial overlaps of array types.
1414 // p := (*[2]int)(a[:])
1415 // q := (*[2]int)(a[1:])
1417 // We don't care about solving 1. Or at least, we haven't historically
1418 // and no one has complained.
1419 // For 2, we need to ensure that if there might be partial overlap,
1420 // then we can't use OpMove; we must use memmove instead.
1421 // (memmove handles partial overlap by copying in the correct
1422 // direction. OpMove does not.)
1424 // Note that we have to be careful here not to introduce a call when
1425 // we're marshaling arguments to a call or unmarshaling results from a call.
1426 // Cases where this is happening must pass mayOverlap to false.
1427 // (Currently this only happens when unmarshaling results of a call.)
1428 if t.HasPointers() {
1429 s.rtcall(ir.Syms.Typedmemmove, true, nil, s.reflectType(t), dst, src)
1430 // We would have otherwise implemented this move with straightline code,
1431 // including a write barrier. Pretend we issue a write barrier here,
1432 // so that the write barrier tests work. (Otherwise they'd need to know
1433 // the details of IsInlineableMemmove.)
1434 s.curfn.SetWBPos(s.peekPos())
1436 s.rtcall(ir.Syms.Memmove, true, nil, dst, src, s.constInt(types.Types[types.TUINTPTR], t.Size()))
1438 ssa.LogLargeCopy(s.f.Name, s.peekPos(), t.Size())
1441 store := s.newValue3I(ssa.OpMove, types.TypeMem, t.Size(), dst, src, s.mem())
1443 s.vars[memVar] = store
1446 // stmtList converts the statement list n to SSA and adds it to s.
1447 func (s *state) stmtList(l ir.Nodes) {
1448 for _, n := range l {
1453 // stmt converts the statement n to SSA and adds it to s.
1454 func (s *state) stmt(n ir.Node) {
1458 // If s.curBlock is nil, and n isn't a label (which might have an associated goto somewhere),
1459 // then this code is dead. Stop here.
1460 if s.curBlock == nil && n.Op() != ir.OLABEL {
1464 s.stmtList(n.Init())
1468 n := n.(*ir.BlockStmt)
1471 case ir.OFALL: // no-op
1473 // Expression statements
1475 n := n.(*ir.CallExpr)
1476 if ir.IsIntrinsicCall(n) {
1483 n := n.(*ir.CallExpr)
1484 s.callResult(n, callNormal)
1485 if n.Op() == ir.OCALLFUNC && n.Fun.Op() == ir.ONAME && n.Fun.(*ir.Name).Class == ir.PFUNC {
1486 if fn := n.Fun.Sym().Name; base.Flag.CompilingRuntime && fn == "throw" ||
1487 n.Fun.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") {
1490 b.Kind = ssa.BlockExit
1492 // TODO: never rewrite OPANIC to OCALLFUNC in the
1493 // first place. Need to wait until all backends
1498 n := n.(*ir.GoDeferStmt)
1499 if base.Debug.Defer > 0 {
1500 var defertype string
1501 if s.hasOpenDefers {
1502 defertype = "open-coded"
1503 } else if n.Esc() == ir.EscNever {
1504 defertype = "stack-allocated"
1506 defertype = "heap-allocated"
1508 base.WarnfAt(n.Pos(), "%s defer", defertype)
1510 if s.hasOpenDefers {
1511 s.openDeferRecord(n.Call.(*ir.CallExpr))
1514 if n.Esc() == ir.EscNever && n.DeferAt == nil {
1517 s.call(n.Call.(*ir.CallExpr), d, false, n.DeferAt)
1520 n := n.(*ir.GoDeferStmt)
1521 s.callResult(n.Call.(*ir.CallExpr), callGo)
1523 case ir.OAS2DOTTYPE:
1524 n := n.(*ir.AssignListStmt)
1525 var res, resok *ssa.Value
1526 if n.Rhs[0].Op() == ir.ODOTTYPE2 {
1527 res, resok = s.dottype(n.Rhs[0].(*ir.TypeAssertExpr), true)
1529 res, resok = s.dynamicDottype(n.Rhs[0].(*ir.DynamicTypeAssertExpr), true)
1532 if !ssa.CanSSA(n.Rhs[0].Type()) {
1533 if res.Op != ssa.OpLoad {
1534 s.Fatalf("dottype of non-load")
1537 if res.Args[1] != mem {
1538 s.Fatalf("memory no longer live from 2-result dottype load")
1543 s.assign(n.Lhs[0], res, deref, 0)
1544 s.assign(n.Lhs[1], resok, false, 0)
1548 // We come here only when it is an intrinsic call returning two values.
1549 n := n.(*ir.AssignListStmt)
1550 call := n.Rhs[0].(*ir.CallExpr)
1551 if !ir.IsIntrinsicCall(call) {
1552 s.Fatalf("non-intrinsic AS2FUNC not expanded %v", call)
1554 v := s.intrinsicCall(call)
1555 v1 := s.newValue1(ssa.OpSelect0, n.Lhs[0].Type(), v)
1556 v2 := s.newValue1(ssa.OpSelect1, n.Lhs[1].Type(), v)
1557 s.assign(n.Lhs[0], v1, false, 0)
1558 s.assign(n.Lhs[1], v2, false, 0)
1563 if v := n.X; v.Esc() == ir.EscHeap {
1568 n := n.(*ir.LabelStmt)
1571 // Nothing to do because the label isn't targetable. See issue 52278.
1576 // The label might already have a target block via a goto.
1577 if lab.target == nil {
1578 lab.target = s.f.NewBlock(ssa.BlockPlain)
1581 // Go to that label.
1582 // (We pretend "label:" is preceded by "goto label", unless the predecessor is unreachable.)
1583 if s.curBlock != nil {
1585 b.AddEdgeTo(lab.target)
1587 s.startBlock(lab.target)
1590 n := n.(*ir.BranchStmt)
1594 if lab.target == nil {
1595 lab.target = s.f.NewBlock(ssa.BlockPlain)
1599 b.Pos = s.lastPos.WithIsStmt() // Do this even if b is an empty block.
1600 b.AddEdgeTo(lab.target)
1603 n := n.(*ir.AssignStmt)
1604 if n.X == n.Y && n.X.Op() == ir.ONAME {
1605 // An x=x assignment. No point in doing anything
1606 // here. In addition, skipping this assignment
1607 // prevents generating:
1610 // which is bad because x is incorrectly considered
1611 // dead before the vardef. See issue #14904.
1615 // mayOverlap keeps track of whether the LHS and RHS might
1616 // refer to partially overlapping memory. Partial overlapping can
1617 // only happen for arrays, see the comment in moveWhichMayOverlap.
1619 // If both sides of the assignment are not dereferences, then partial
1620 // overlap can't happen. Partial overlap can only occur only when the
1621 // arrays referenced are strictly smaller parts of the same base array.
1622 // If one side of the assignment is a full array, then partial overlap
1623 // can't happen. (The arrays are either disjoint or identical.)
1624 mayOverlap := n.X.Op() == ir.ODEREF && (n.Y != nil && n.Y.Op() == ir.ODEREF)
1625 if n.Y != nil && n.Y.Op() == ir.ODEREF {
1626 p := n.Y.(*ir.StarExpr).X
1627 for p.Op() == ir.OCONVNOP {
1628 p = p.(*ir.ConvExpr).X
1630 if p.Op() == ir.OSPTR && p.(*ir.UnaryExpr).X.Type().IsString() {
1631 // Pointer fields of strings point to unmodifiable memory.
1632 // That memory can't overlap with the memory being written.
1641 case ir.OSTRUCTLIT, ir.OARRAYLIT, ir.OSLICELIT:
1642 // All literals with nonzero fields have already been
1643 // rewritten during walk. Any that remain are just T{}
1644 // or equivalents. Use the zero value.
1645 if !ir.IsZero(rhs) {
1646 s.Fatalf("literal with nonzero value in SSA: %v", rhs)
1650 rhs := rhs.(*ir.CallExpr)
1651 // Check whether we're writing the result of an append back to the same slice.
1652 // If so, we handle it specially to avoid write barriers on the fast
1653 // (non-growth) path.
1654 if !ir.SameSafeExpr(n.X, rhs.Args[0]) || base.Flag.N != 0 {
1657 // If the slice can be SSA'd, it'll be on the stack,
1658 // so there will be no write barriers,
1659 // so there's no need to attempt to prevent them.
1661 if base.Debug.Append > 0 { // replicating old diagnostic message
1662 base.WarnfAt(n.Pos(), "append: len-only update (in local slice)")
1666 if base.Debug.Append > 0 {
1667 base.WarnfAt(n.Pos(), "append: len-only update")
1674 if ir.IsBlank(n.X) {
1676 // Just evaluate rhs for side-effects.
1691 deref := !ssa.CanSSA(t)
1694 r = nil // Signal assign to use OpZero.
1707 if rhs != nil && (rhs.Op() == ir.OSLICE || rhs.Op() == ir.OSLICE3 || rhs.Op() == ir.OSLICESTR) && ir.SameSafeExpr(rhs.(*ir.SliceExpr).X, n.X) {
1708 // We're assigning a slicing operation back to its source.
1709 // Don't write back fields we aren't changing. See issue #14855.
1710 rhs := rhs.(*ir.SliceExpr)
1711 i, j, k := rhs.Low, rhs.High, rhs.Max
1712 if i != nil && (i.Op() == ir.OLITERAL && i.Val().Kind() == constant.Int && ir.Int64Val(i) == 0) {
1713 // [0:...] is the same as [:...]
1716 // TODO: detect defaults for len/cap also.
1717 // Currently doesn't really work because (*p)[:len(*p)] appears here as:
1720 // if j != nil && (j.Op == OLEN && SameSafeExpr(j.Left, n.Left)) {
1723 // if k != nil && (k.Op == OCAP && SameSafeExpr(k.Left, n.Left)) {
1737 s.assignWhichMayOverlap(n.X, r, deref, skip, mayOverlap)
1741 if ir.IsConst(n.Cond, constant.Bool) {
1742 s.stmtList(n.Cond.Init())
1743 if ir.BoolVal(n.Cond) {
1751 bEnd := s.f.NewBlock(ssa.BlockPlain)
1756 var bThen *ssa.Block
1757 if len(n.Body) != 0 {
1758 bThen = s.f.NewBlock(ssa.BlockPlain)
1762 var bElse *ssa.Block
1763 if len(n.Else) != 0 {
1764 bElse = s.f.NewBlock(ssa.BlockPlain)
1768 s.condBranch(n.Cond, bThen, bElse, likely)
1770 if len(n.Body) != 0 {
1773 if b := s.endBlock(); b != nil {
1777 if len(n.Else) != 0 {
1780 if b := s.endBlock(); b != nil {
1787 n := n.(*ir.ReturnStmt)
1788 s.stmtList(n.Results)
1790 b.Pos = s.lastPos.WithIsStmt()
1793 n := n.(*ir.TailCallStmt)
1794 s.callResult(n.Call, callTail)
1797 b.Kind = ssa.BlockRetJmp // could use BlockExit. BlockRetJmp is mostly for clarity.
1800 case ir.OCONTINUE, ir.OBREAK:
1801 n := n.(*ir.BranchStmt)
1804 // plain break/continue
1812 // labeled break/continue; look up the target
1817 to = lab.continueTarget
1819 to = lab.breakTarget
1824 b.Pos = s.lastPos.WithIsStmt() // Do this even if b is an empty block.
1828 // OFOR: for Ninit; Left; Right { Nbody }
1829 // cond (Left); body (Nbody); incr (Right)
1830 n := n.(*ir.ForStmt)
1831 base.Assert(!n.DistinctVars) // Should all be rewritten before escape analysis
1832 bCond := s.f.NewBlock(ssa.BlockPlain)
1833 bBody := s.f.NewBlock(ssa.BlockPlain)
1834 bIncr := s.f.NewBlock(ssa.BlockPlain)
1835 bEnd := s.f.NewBlock(ssa.BlockPlain)
1837 // ensure empty for loops have correct position; issue #30167
1840 // first, jump to condition test
1844 // generate code to test condition
1847 s.condBranch(n.Cond, bBody, bEnd, 1)
1850 b.Kind = ssa.BlockPlain
1854 // set up for continue/break in body
1855 prevContinue := s.continueTo
1856 prevBreak := s.breakTo
1857 s.continueTo = bIncr
1860 if sym := n.Label; sym != nil {
1863 lab.continueTarget = bIncr
1864 lab.breakTarget = bEnd
1871 // tear down continue/break
1872 s.continueTo = prevContinue
1873 s.breakTo = prevBreak
1875 lab.continueTarget = nil
1876 lab.breakTarget = nil
1879 // done with body, goto incr
1880 if b := s.endBlock(); b != nil {
1889 if b := s.endBlock(); b != nil {
1891 // It can happen that bIncr ends in a block containing only VARKILL,
1892 // and that muddles the debugging experience.
1893 if b.Pos == src.NoXPos {
1900 case ir.OSWITCH, ir.OSELECT:
1901 // These have been mostly rewritten by the front end into their Nbody fields.
1902 // Our main task is to correctly hook up any break statements.
1903 bEnd := s.f.NewBlock(ssa.BlockPlain)
1905 prevBreak := s.breakTo
1909 if n.Op() == ir.OSWITCH {
1910 n := n.(*ir.SwitchStmt)
1914 n := n.(*ir.SelectStmt)
1923 lab.breakTarget = bEnd
1926 // generate body code
1929 s.breakTo = prevBreak
1931 lab.breakTarget = nil
1934 // walk adds explicit OBREAK nodes to the end of all reachable code paths.
1935 // If we still have a current block here, then mark it unreachable.
1936 if s.curBlock != nil {
1939 b.Kind = ssa.BlockExit
1945 n := n.(*ir.JumpTableStmt)
1947 // Make blocks we'll need.
1948 jt := s.f.NewBlock(ssa.BlockJumpTable)
1949 bEnd := s.f.NewBlock(ssa.BlockPlain)
1951 // The only thing that needs evaluating is the index we're looking up.
1952 idx := s.expr(n.Idx)
1953 unsigned := idx.Type.IsUnsigned()
1955 // Extend so we can do everything in uintptr arithmetic.
1956 t := types.Types[types.TUINTPTR]
1957 idx = s.conv(nil, idx, idx.Type, t)
1959 // The ending condition for the current block decides whether we'll use
1960 // the jump table at all.
1961 // We check that min <= idx <= max and jump around the jump table
1962 // if that test fails.
1963 // We implement min <= idx <= max with 0 <= idx-min <= max-min, because
1964 // we'll need idx-min anyway as the control value for the jump table.
1967 min, _ = constant.Uint64Val(n.Cases[0])
1968 max, _ = constant.Uint64Val(n.Cases[len(n.Cases)-1])
1970 mn, _ := constant.Int64Val(n.Cases[0])
1971 mx, _ := constant.Int64Val(n.Cases[len(n.Cases)-1])
1975 // Compare idx-min with max-min, to see if we can use the jump table.
1976 idx = s.newValue2(s.ssaOp(ir.OSUB, t), t, idx, s.uintptrConstant(min))
1977 width := s.uintptrConstant(max - min)
1978 cmp := s.newValue2(s.ssaOp(ir.OLE, t), types.Types[types.TBOOL], idx, width)
1980 b.Kind = ssa.BlockIf
1982 b.AddEdgeTo(jt) // in range - use jump table
1983 b.AddEdgeTo(bEnd) // out of range - no case in the jump table will trigger
1984 b.Likely = ssa.BranchLikely // TODO: assumes missing the table entirely is unlikely. True?
1986 // Build jump table block.
1989 if base.Flag.Cfg.SpectreIndex {
1990 idx = s.newValue2(ssa.OpSpectreSliceIndex, t, idx, width)
1994 // Figure out where we should go for each index in the table.
1995 table := make([]*ssa.Block, max-min+1)
1996 for i := range table {
1997 table[i] = bEnd // default target
1999 for i := range n.Targets {
2001 lab := s.label(n.Targets[i])
2002 if lab.target == nil {
2003 lab.target = s.f.NewBlock(ssa.BlockPlain)
2007 val, _ = constant.Uint64Val(c)
2009 vl, _ := constant.Int64Val(c)
2012 // Overwrite the default target.
2013 table[val-min] = lab.target
2015 for _, t := range table {
2022 case ir.OINTERFACESWITCH:
2023 n := n.(*ir.InterfaceSwitchStmt)
2024 typs := s.f.Config.Types
2026 t := s.expr(n.RuntimeType)
2027 d := s.newValue1A(ssa.OpAddr, typs.BytePtr, n.Descriptor, s.sb)
2029 // Check the cache first.
2030 var merge *ssa.Block
2031 if base.Flag.N == 0 && rtabi.UseInterfaceSwitchCache(Arch.LinkArch.Name) {
2032 // Note: we can only use the cache if we have the right atomic load instruction.
2033 // Double-check that here.
2034 if _, ok := intrinsics[intrinsicKey{Arch.LinkArch.Arch, "runtime/internal/atomic", "Loadp"}]; !ok {
2035 s.Fatalf("atomic load not available")
2037 merge = s.f.NewBlock(ssa.BlockPlain)
2038 cacheHit := s.f.NewBlock(ssa.BlockPlain)
2039 cacheMiss := s.f.NewBlock(ssa.BlockPlain)
2040 loopHead := s.f.NewBlock(ssa.BlockPlain)
2041 loopBody := s.f.NewBlock(ssa.BlockPlain)
2043 // Pick right size ops.
2044 var mul, and, add, zext ssa.Op
2045 if s.config.PtrSize == 4 {
2054 zext = ssa.OpZeroExt32to64
2057 // Load cache pointer out of descriptor, with an atomic load so
2058 // we ensure that we see a fully written cache.
2059 atomicLoad := s.newValue2(ssa.OpAtomicLoadPtr, types.NewTuple(typs.BytePtr, types.TypeMem), d, s.mem())
2060 cache := s.newValue1(ssa.OpSelect0, typs.BytePtr, atomicLoad)
2061 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, atomicLoad)
2063 // Load hash from type.
2064 hash := s.newValue2(ssa.OpLoad, typs.UInt32, s.newValue1I(ssa.OpOffPtr, typs.UInt32Ptr, 2*s.config.PtrSize, t), s.mem())
2065 hash = s.newValue1(zext, typs.Uintptr, hash)
2066 s.vars[hashVar] = hash
2067 // Load mask from cache.
2068 mask := s.newValue2(ssa.OpLoad, typs.Uintptr, cache, s.mem())
2069 // Jump to loop head.
2071 b.AddEdgeTo(loopHead)
2073 // At loop head, get pointer to the cache entry.
2074 // e := &cache.Entries[hash&mask]
2075 s.startBlock(loopHead)
2076 entries := s.newValue2(ssa.OpAddPtr, typs.UintptrPtr, cache, s.uintptrConstant(uint64(s.config.PtrSize)))
2077 idx := s.newValue2(and, typs.Uintptr, s.variable(hashVar, typs.Uintptr), mask)
2078 idx = s.newValue2(mul, typs.Uintptr, idx, s.uintptrConstant(uint64(3*s.config.PtrSize)))
2079 e := s.newValue2(ssa.OpAddPtr, typs.UintptrPtr, entries, idx)
2081 s.vars[hashVar] = s.newValue2(add, typs.Uintptr, s.variable(hashVar, typs.Uintptr), s.uintptrConstant(1))
2083 // Look for a cache hit.
2084 // if e.Typ == t { goto hit }
2085 eTyp := s.newValue2(ssa.OpLoad, typs.Uintptr, e, s.mem())
2086 cmp1 := s.newValue2(ssa.OpEqPtr, typs.Bool, t, eTyp)
2088 b.Kind = ssa.BlockIf
2090 b.AddEdgeTo(cacheHit)
2091 b.AddEdgeTo(loopBody)
2093 // Look for an empty entry, the tombstone for this hash table.
2094 // if e.Typ == nil { goto miss }
2095 s.startBlock(loopBody)
2096 cmp2 := s.newValue2(ssa.OpEqPtr, typs.Bool, eTyp, s.constNil(typs.BytePtr))
2098 b.Kind = ssa.BlockIf
2100 b.AddEdgeTo(cacheMiss)
2101 b.AddEdgeTo(loopHead)
2103 // On a hit, load the data fields of the cache entry.
2106 s.startBlock(cacheHit)
2107 eCase := s.newValue2(ssa.OpLoad, typs.Int, s.newValue1I(ssa.OpOffPtr, typs.IntPtr, s.config.PtrSize, e), s.mem())
2108 eItab := s.newValue2(ssa.OpLoad, typs.BytePtr, s.newValue1I(ssa.OpOffPtr, typs.BytePtrPtr, 2*s.config.PtrSize, e), s.mem())
2109 s.assign(n.Case, eCase, false, 0)
2110 s.assign(n.Itab, eItab, false, 0)
2114 // On a miss, call into the runtime to get the answer.
2115 s.startBlock(cacheMiss)
2118 r := s.rtcall(ir.Syms.InterfaceSwitch, true, []*types.Type{typs.Int, typs.BytePtr}, d, t)
2119 s.assign(n.Case, r[0], false, 0)
2120 s.assign(n.Itab, r[1], false, 0)
2123 // Cache hits merge in here.
2125 b.Kind = ssa.BlockPlain
2131 n := n.(*ir.UnaryExpr)
2136 n := n.(*ir.InlineMarkStmt)
2137 s.newValue1I(ssa.OpInlMark, types.TypeVoid, n.Index, s.mem())
2140 s.Fatalf("unhandled stmt %v", n.Op())
2144 // If true, share as many open-coded defer exits as possible (with the downside of
2145 // worse line-number information)
2146 const shareDeferExits = false
2148 // exit processes any code that needs to be generated just before returning.
2149 // It returns a BlockRet block that ends the control flow. Its control value
2150 // will be set to the final memory state.
2151 func (s *state) exit() *ssa.Block {
2153 if s.hasOpenDefers {
2154 if shareDeferExits && s.lastDeferExit != nil && len(s.openDefers) == s.lastDeferCount {
2155 if s.curBlock.Kind != ssa.BlockPlain {
2156 panic("Block for an exit should be BlockPlain")
2158 s.curBlock.AddEdgeTo(s.lastDeferExit)
2160 return s.lastDeferFinalBlock
2164 s.rtcall(ir.Syms.Deferreturn, true, nil)
2168 // Do actual return.
2169 // These currently turn into self-copies (in many cases).
2170 resultFields := s.curfn.Type().Results()
2171 results := make([]*ssa.Value, len(resultFields)+1, len(resultFields)+1)
2172 // Store SSAable and heap-escaped PPARAMOUT variables back to stack locations.
2173 for i, f := range resultFields {
2174 n := f.Nname.(*ir.Name)
2175 if s.canSSA(n) { // result is in some SSA variable
2176 if !n.IsOutputParamInRegisters() && n.Type().HasPointers() {
2177 // We are about to store to the result slot.
2178 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, n, s.mem())
2180 results[i] = s.variable(n, n.Type())
2181 } else if !n.OnStack() { // result is actually heap allocated
2182 // We are about to copy the in-heap result to the result slot.
2183 if n.Type().HasPointers() {
2184 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, n, s.mem())
2186 ha := s.expr(n.Heapaddr)
2187 s.instrumentFields(n.Type(), ha, instrumentRead)
2188 results[i] = s.newValue2(ssa.OpDereference, n.Type(), ha, s.mem())
2189 } else { // result is not SSA-able; not escaped, so not on heap, but too large for SSA.
2190 // Before register ABI this ought to be a self-move, home=dest,
2191 // With register ABI, it's still a self-move if parameter is on stack (i.e., too big or overflowed)
2192 // No VarDef, as the result slot is already holding live value.
2193 results[i] = s.newValue2(ssa.OpDereference, n.Type(), s.addr(n), s.mem())
2197 // In -race mode, we need to call racefuncexit.
2198 // Note: This has to happen after we load any heap-allocated results,
2199 // otherwise races will be attributed to the caller instead.
2200 if s.instrumentEnterExit {
2201 s.rtcall(ir.Syms.Racefuncexit, true, nil)
2204 results[len(results)-1] = s.mem()
2205 m := s.newValue0(ssa.OpMakeResult, s.f.OwnAux.LateExpansionResultType())
2206 m.AddArgs(results...)
2209 b.Kind = ssa.BlockRet
2211 if s.hasdefer && s.hasOpenDefers {
2212 s.lastDeferFinalBlock = b
2217 type opAndType struct {
2222 var opToSSA = map[opAndType]ssa.Op{
2223 {ir.OADD, types.TINT8}: ssa.OpAdd8,
2224 {ir.OADD, types.TUINT8}: ssa.OpAdd8,
2225 {ir.OADD, types.TINT16}: ssa.OpAdd16,
2226 {ir.OADD, types.TUINT16}: ssa.OpAdd16,
2227 {ir.OADD, types.TINT32}: ssa.OpAdd32,
2228 {ir.OADD, types.TUINT32}: ssa.OpAdd32,
2229 {ir.OADD, types.TINT64}: ssa.OpAdd64,
2230 {ir.OADD, types.TUINT64}: ssa.OpAdd64,
2231 {ir.OADD, types.TFLOAT32}: ssa.OpAdd32F,
2232 {ir.OADD, types.TFLOAT64}: ssa.OpAdd64F,
2234 {ir.OSUB, types.TINT8}: ssa.OpSub8,
2235 {ir.OSUB, types.TUINT8}: ssa.OpSub8,
2236 {ir.OSUB, types.TINT16}: ssa.OpSub16,
2237 {ir.OSUB, types.TUINT16}: ssa.OpSub16,
2238 {ir.OSUB, types.TINT32}: ssa.OpSub32,
2239 {ir.OSUB, types.TUINT32}: ssa.OpSub32,
2240 {ir.OSUB, types.TINT64}: ssa.OpSub64,
2241 {ir.OSUB, types.TUINT64}: ssa.OpSub64,
2242 {ir.OSUB, types.TFLOAT32}: ssa.OpSub32F,
2243 {ir.OSUB, types.TFLOAT64}: ssa.OpSub64F,
2245 {ir.ONOT, types.TBOOL}: ssa.OpNot,
2247 {ir.ONEG, types.TINT8}: ssa.OpNeg8,
2248 {ir.ONEG, types.TUINT8}: ssa.OpNeg8,
2249 {ir.ONEG, types.TINT16}: ssa.OpNeg16,
2250 {ir.ONEG, types.TUINT16}: ssa.OpNeg16,
2251 {ir.ONEG, types.TINT32}: ssa.OpNeg32,
2252 {ir.ONEG, types.TUINT32}: ssa.OpNeg32,
2253 {ir.ONEG, types.TINT64}: ssa.OpNeg64,
2254 {ir.ONEG, types.TUINT64}: ssa.OpNeg64,
2255 {ir.ONEG, types.TFLOAT32}: ssa.OpNeg32F,
2256 {ir.ONEG, types.TFLOAT64}: ssa.OpNeg64F,
2258 {ir.OBITNOT, types.TINT8}: ssa.OpCom8,
2259 {ir.OBITNOT, types.TUINT8}: ssa.OpCom8,
2260 {ir.OBITNOT, types.TINT16}: ssa.OpCom16,
2261 {ir.OBITNOT, types.TUINT16}: ssa.OpCom16,
2262 {ir.OBITNOT, types.TINT32}: ssa.OpCom32,
2263 {ir.OBITNOT, types.TUINT32}: ssa.OpCom32,
2264 {ir.OBITNOT, types.TINT64}: ssa.OpCom64,
2265 {ir.OBITNOT, types.TUINT64}: ssa.OpCom64,
2267 {ir.OIMAG, types.TCOMPLEX64}: ssa.OpComplexImag,
2268 {ir.OIMAG, types.TCOMPLEX128}: ssa.OpComplexImag,
2269 {ir.OREAL, types.TCOMPLEX64}: ssa.OpComplexReal,
2270 {ir.OREAL, types.TCOMPLEX128}: ssa.OpComplexReal,
2272 {ir.OMUL, types.TINT8}: ssa.OpMul8,
2273 {ir.OMUL, types.TUINT8}: ssa.OpMul8,
2274 {ir.OMUL, types.TINT16}: ssa.OpMul16,
2275 {ir.OMUL, types.TUINT16}: ssa.OpMul16,
2276 {ir.OMUL, types.TINT32}: ssa.OpMul32,
2277 {ir.OMUL, types.TUINT32}: ssa.OpMul32,
2278 {ir.OMUL, types.TINT64}: ssa.OpMul64,
2279 {ir.OMUL, types.TUINT64}: ssa.OpMul64,
2280 {ir.OMUL, types.TFLOAT32}: ssa.OpMul32F,
2281 {ir.OMUL, types.TFLOAT64}: ssa.OpMul64F,
2283 {ir.ODIV, types.TFLOAT32}: ssa.OpDiv32F,
2284 {ir.ODIV, types.TFLOAT64}: ssa.OpDiv64F,
2286 {ir.ODIV, types.TINT8}: ssa.OpDiv8,
2287 {ir.ODIV, types.TUINT8}: ssa.OpDiv8u,
2288 {ir.ODIV, types.TINT16}: ssa.OpDiv16,
2289 {ir.ODIV, types.TUINT16}: ssa.OpDiv16u,
2290 {ir.ODIV, types.TINT32}: ssa.OpDiv32,
2291 {ir.ODIV, types.TUINT32}: ssa.OpDiv32u,
2292 {ir.ODIV, types.TINT64}: ssa.OpDiv64,
2293 {ir.ODIV, types.TUINT64}: ssa.OpDiv64u,
2295 {ir.OMOD, types.TINT8}: ssa.OpMod8,
2296 {ir.OMOD, types.TUINT8}: ssa.OpMod8u,
2297 {ir.OMOD, types.TINT16}: ssa.OpMod16,
2298 {ir.OMOD, types.TUINT16}: ssa.OpMod16u,
2299 {ir.OMOD, types.TINT32}: ssa.OpMod32,
2300 {ir.OMOD, types.TUINT32}: ssa.OpMod32u,
2301 {ir.OMOD, types.TINT64}: ssa.OpMod64,
2302 {ir.OMOD, types.TUINT64}: ssa.OpMod64u,
2304 {ir.OAND, types.TINT8}: ssa.OpAnd8,
2305 {ir.OAND, types.TUINT8}: ssa.OpAnd8,
2306 {ir.OAND, types.TINT16}: ssa.OpAnd16,
2307 {ir.OAND, types.TUINT16}: ssa.OpAnd16,
2308 {ir.OAND, types.TINT32}: ssa.OpAnd32,
2309 {ir.OAND, types.TUINT32}: ssa.OpAnd32,
2310 {ir.OAND, types.TINT64}: ssa.OpAnd64,
2311 {ir.OAND, types.TUINT64}: ssa.OpAnd64,
2313 {ir.OOR, types.TINT8}: ssa.OpOr8,
2314 {ir.OOR, types.TUINT8}: ssa.OpOr8,
2315 {ir.OOR, types.TINT16}: ssa.OpOr16,
2316 {ir.OOR, types.TUINT16}: ssa.OpOr16,
2317 {ir.OOR, types.TINT32}: ssa.OpOr32,
2318 {ir.OOR, types.TUINT32}: ssa.OpOr32,
2319 {ir.OOR, types.TINT64}: ssa.OpOr64,
2320 {ir.OOR, types.TUINT64}: ssa.OpOr64,
2322 {ir.OXOR, types.TINT8}: ssa.OpXor8,
2323 {ir.OXOR, types.TUINT8}: ssa.OpXor8,
2324 {ir.OXOR, types.TINT16}: ssa.OpXor16,
2325 {ir.OXOR, types.TUINT16}: ssa.OpXor16,
2326 {ir.OXOR, types.TINT32}: ssa.OpXor32,
2327 {ir.OXOR, types.TUINT32}: ssa.OpXor32,
2328 {ir.OXOR, types.TINT64}: ssa.OpXor64,
2329 {ir.OXOR, types.TUINT64}: ssa.OpXor64,
2331 {ir.OEQ, types.TBOOL}: ssa.OpEqB,
2332 {ir.OEQ, types.TINT8}: ssa.OpEq8,
2333 {ir.OEQ, types.TUINT8}: ssa.OpEq8,
2334 {ir.OEQ, types.TINT16}: ssa.OpEq16,
2335 {ir.OEQ, types.TUINT16}: ssa.OpEq16,
2336 {ir.OEQ, types.TINT32}: ssa.OpEq32,
2337 {ir.OEQ, types.TUINT32}: ssa.OpEq32,
2338 {ir.OEQ, types.TINT64}: ssa.OpEq64,
2339 {ir.OEQ, types.TUINT64}: ssa.OpEq64,
2340 {ir.OEQ, types.TINTER}: ssa.OpEqInter,
2341 {ir.OEQ, types.TSLICE}: ssa.OpEqSlice,
2342 {ir.OEQ, types.TFUNC}: ssa.OpEqPtr,
2343 {ir.OEQ, types.TMAP}: ssa.OpEqPtr,
2344 {ir.OEQ, types.TCHAN}: ssa.OpEqPtr,
2345 {ir.OEQ, types.TPTR}: ssa.OpEqPtr,
2346 {ir.OEQ, types.TUINTPTR}: ssa.OpEqPtr,
2347 {ir.OEQ, types.TUNSAFEPTR}: ssa.OpEqPtr,
2348 {ir.OEQ, types.TFLOAT64}: ssa.OpEq64F,
2349 {ir.OEQ, types.TFLOAT32}: ssa.OpEq32F,
2351 {ir.ONE, types.TBOOL}: ssa.OpNeqB,
2352 {ir.ONE, types.TINT8}: ssa.OpNeq8,
2353 {ir.ONE, types.TUINT8}: ssa.OpNeq8,
2354 {ir.ONE, types.TINT16}: ssa.OpNeq16,
2355 {ir.ONE, types.TUINT16}: ssa.OpNeq16,
2356 {ir.ONE, types.TINT32}: ssa.OpNeq32,
2357 {ir.ONE, types.TUINT32}: ssa.OpNeq32,
2358 {ir.ONE, types.TINT64}: ssa.OpNeq64,
2359 {ir.ONE, types.TUINT64}: ssa.OpNeq64,
2360 {ir.ONE, types.TINTER}: ssa.OpNeqInter,
2361 {ir.ONE, types.TSLICE}: ssa.OpNeqSlice,
2362 {ir.ONE, types.TFUNC}: ssa.OpNeqPtr,
2363 {ir.ONE, types.TMAP}: ssa.OpNeqPtr,
2364 {ir.ONE, types.TCHAN}: ssa.OpNeqPtr,
2365 {ir.ONE, types.TPTR}: ssa.OpNeqPtr,
2366 {ir.ONE, types.TUINTPTR}: ssa.OpNeqPtr,
2367 {ir.ONE, types.TUNSAFEPTR}: ssa.OpNeqPtr,
2368 {ir.ONE, types.TFLOAT64}: ssa.OpNeq64F,
2369 {ir.ONE, types.TFLOAT32}: ssa.OpNeq32F,
2371 {ir.OLT, types.TINT8}: ssa.OpLess8,
2372 {ir.OLT, types.TUINT8}: ssa.OpLess8U,
2373 {ir.OLT, types.TINT16}: ssa.OpLess16,
2374 {ir.OLT, types.TUINT16}: ssa.OpLess16U,
2375 {ir.OLT, types.TINT32}: ssa.OpLess32,
2376 {ir.OLT, types.TUINT32}: ssa.OpLess32U,
2377 {ir.OLT, types.TINT64}: ssa.OpLess64,
2378 {ir.OLT, types.TUINT64}: ssa.OpLess64U,
2379 {ir.OLT, types.TFLOAT64}: ssa.OpLess64F,
2380 {ir.OLT, types.TFLOAT32}: ssa.OpLess32F,
2382 {ir.OLE, types.TINT8}: ssa.OpLeq8,
2383 {ir.OLE, types.TUINT8}: ssa.OpLeq8U,
2384 {ir.OLE, types.TINT16}: ssa.OpLeq16,
2385 {ir.OLE, types.TUINT16}: ssa.OpLeq16U,
2386 {ir.OLE, types.TINT32}: ssa.OpLeq32,
2387 {ir.OLE, types.TUINT32}: ssa.OpLeq32U,
2388 {ir.OLE, types.TINT64}: ssa.OpLeq64,
2389 {ir.OLE, types.TUINT64}: ssa.OpLeq64U,
2390 {ir.OLE, types.TFLOAT64}: ssa.OpLeq64F,
2391 {ir.OLE, types.TFLOAT32}: ssa.OpLeq32F,
2394 func (s *state) concreteEtype(t *types.Type) types.Kind {
2400 if s.config.PtrSize == 8 {
2405 if s.config.PtrSize == 8 {
2406 return types.TUINT64
2408 return types.TUINT32
2409 case types.TUINTPTR:
2410 if s.config.PtrSize == 8 {
2411 return types.TUINT64
2413 return types.TUINT32
2417 func (s *state) ssaOp(op ir.Op, t *types.Type) ssa.Op {
2418 etype := s.concreteEtype(t)
2419 x, ok := opToSSA[opAndType{op, etype}]
2421 s.Fatalf("unhandled binary op %v %s", op, etype)
2426 type opAndTwoTypes struct {
2432 type twoTypes struct {
2437 type twoOpsAndType struct {
2440 intermediateType types.Kind
2443 var fpConvOpToSSA = map[twoTypes]twoOpsAndType{
2445 {types.TINT8, types.TFLOAT32}: {ssa.OpSignExt8to32, ssa.OpCvt32to32F, types.TINT32},
2446 {types.TINT16, types.TFLOAT32}: {ssa.OpSignExt16to32, ssa.OpCvt32to32F, types.TINT32},
2447 {types.TINT32, types.TFLOAT32}: {ssa.OpCopy, ssa.OpCvt32to32F, types.TINT32},
2448 {types.TINT64, types.TFLOAT32}: {ssa.OpCopy, ssa.OpCvt64to32F, types.TINT64},
2450 {types.TINT8, types.TFLOAT64}: {ssa.OpSignExt8to32, ssa.OpCvt32to64F, types.TINT32},
2451 {types.TINT16, types.TFLOAT64}: {ssa.OpSignExt16to32, ssa.OpCvt32to64F, types.TINT32},
2452 {types.TINT32, types.TFLOAT64}: {ssa.OpCopy, ssa.OpCvt32to64F, types.TINT32},
2453 {types.TINT64, types.TFLOAT64}: {ssa.OpCopy, ssa.OpCvt64to64F, types.TINT64},
2455 {types.TFLOAT32, types.TINT8}: {ssa.OpCvt32Fto32, ssa.OpTrunc32to8, types.TINT32},
2456 {types.TFLOAT32, types.TINT16}: {ssa.OpCvt32Fto32, ssa.OpTrunc32to16, types.TINT32},
2457 {types.TFLOAT32, types.TINT32}: {ssa.OpCvt32Fto32, ssa.OpCopy, types.TINT32},
2458 {types.TFLOAT32, types.TINT64}: {ssa.OpCvt32Fto64, ssa.OpCopy, types.TINT64},
2460 {types.TFLOAT64, types.TINT8}: {ssa.OpCvt64Fto32, ssa.OpTrunc32to8, types.TINT32},
2461 {types.TFLOAT64, types.TINT16}: {ssa.OpCvt64Fto32, ssa.OpTrunc32to16, types.TINT32},
2462 {types.TFLOAT64, types.TINT32}: {ssa.OpCvt64Fto32, ssa.OpCopy, types.TINT32},
2463 {types.TFLOAT64, types.TINT64}: {ssa.OpCvt64Fto64, ssa.OpCopy, types.TINT64},
2465 {types.TUINT8, types.TFLOAT32}: {ssa.OpZeroExt8to32, ssa.OpCvt32to32F, types.TINT32},
2466 {types.TUINT16, types.TFLOAT32}: {ssa.OpZeroExt16to32, ssa.OpCvt32to32F, types.TINT32},
2467 {types.TUINT32, types.TFLOAT32}: {ssa.OpZeroExt32to64, ssa.OpCvt64to32F, types.TINT64}, // go wide to dodge unsigned
2468 {types.TUINT64, types.TFLOAT32}: {ssa.OpCopy, ssa.OpInvalid, types.TUINT64}, // Cvt64Uto32F, branchy code expansion instead
2470 {types.TUINT8, types.TFLOAT64}: {ssa.OpZeroExt8to32, ssa.OpCvt32to64F, types.TINT32},
2471 {types.TUINT16, types.TFLOAT64}: {ssa.OpZeroExt16to32, ssa.OpCvt32to64F, types.TINT32},
2472 {types.TUINT32, types.TFLOAT64}: {ssa.OpZeroExt32to64, ssa.OpCvt64to64F, types.TINT64}, // go wide to dodge unsigned
2473 {types.TUINT64, types.TFLOAT64}: {ssa.OpCopy, ssa.OpInvalid, types.TUINT64}, // Cvt64Uto64F, branchy code expansion instead
2475 {types.TFLOAT32, types.TUINT8}: {ssa.OpCvt32Fto32, ssa.OpTrunc32to8, types.TINT32},
2476 {types.TFLOAT32, types.TUINT16}: {ssa.OpCvt32Fto32, ssa.OpTrunc32to16, types.TINT32},
2477 {types.TFLOAT32, types.TUINT32}: {ssa.OpCvt32Fto64, ssa.OpTrunc64to32, types.TINT64}, // go wide to dodge unsigned
2478 {types.TFLOAT32, types.TUINT64}: {ssa.OpInvalid, ssa.OpCopy, types.TUINT64}, // Cvt32Fto64U, branchy code expansion instead
2480 {types.TFLOAT64, types.TUINT8}: {ssa.OpCvt64Fto32, ssa.OpTrunc32to8, types.TINT32},
2481 {types.TFLOAT64, types.TUINT16}: {ssa.OpCvt64Fto32, ssa.OpTrunc32to16, types.TINT32},
2482 {types.TFLOAT64, types.TUINT32}: {ssa.OpCvt64Fto64, ssa.OpTrunc64to32, types.TINT64}, // go wide to dodge unsigned
2483 {types.TFLOAT64, types.TUINT64}: {ssa.OpInvalid, ssa.OpCopy, types.TUINT64}, // Cvt64Fto64U, branchy code expansion instead
2486 {types.TFLOAT64, types.TFLOAT32}: {ssa.OpCvt64Fto32F, ssa.OpCopy, types.TFLOAT32},
2487 {types.TFLOAT64, types.TFLOAT64}: {ssa.OpRound64F, ssa.OpCopy, types.TFLOAT64},
2488 {types.TFLOAT32, types.TFLOAT32}: {ssa.OpRound32F, ssa.OpCopy, types.TFLOAT32},
2489 {types.TFLOAT32, types.TFLOAT64}: {ssa.OpCvt32Fto64F, ssa.OpCopy, types.TFLOAT64},
2492 // this map is used only for 32-bit arch, and only includes the difference
2493 // on 32-bit arch, don't use int64<->float conversion for uint32
2494 var fpConvOpToSSA32 = map[twoTypes]twoOpsAndType{
2495 {types.TUINT32, types.TFLOAT32}: {ssa.OpCopy, ssa.OpCvt32Uto32F, types.TUINT32},
2496 {types.TUINT32, types.TFLOAT64}: {ssa.OpCopy, ssa.OpCvt32Uto64F, types.TUINT32},
2497 {types.TFLOAT32, types.TUINT32}: {ssa.OpCvt32Fto32U, ssa.OpCopy, types.TUINT32},
2498 {types.TFLOAT64, types.TUINT32}: {ssa.OpCvt64Fto32U, ssa.OpCopy, types.TUINT32},
2501 // uint64<->float conversions, only on machines that have instructions for that
2502 var uint64fpConvOpToSSA = map[twoTypes]twoOpsAndType{
2503 {types.TUINT64, types.TFLOAT32}: {ssa.OpCopy, ssa.OpCvt64Uto32F, types.TUINT64},
2504 {types.TUINT64, types.TFLOAT64}: {ssa.OpCopy, ssa.OpCvt64Uto64F, types.TUINT64},
2505 {types.TFLOAT32, types.TUINT64}: {ssa.OpCvt32Fto64U, ssa.OpCopy, types.TUINT64},
2506 {types.TFLOAT64, types.TUINT64}: {ssa.OpCvt64Fto64U, ssa.OpCopy, types.TUINT64},
2509 var shiftOpToSSA = map[opAndTwoTypes]ssa.Op{
2510 {ir.OLSH, types.TINT8, types.TUINT8}: ssa.OpLsh8x8,
2511 {ir.OLSH, types.TUINT8, types.TUINT8}: ssa.OpLsh8x8,
2512 {ir.OLSH, types.TINT8, types.TUINT16}: ssa.OpLsh8x16,
2513 {ir.OLSH, types.TUINT8, types.TUINT16}: ssa.OpLsh8x16,
2514 {ir.OLSH, types.TINT8, types.TUINT32}: ssa.OpLsh8x32,
2515 {ir.OLSH, types.TUINT8, types.TUINT32}: ssa.OpLsh8x32,
2516 {ir.OLSH, types.TINT8, types.TUINT64}: ssa.OpLsh8x64,
2517 {ir.OLSH, types.TUINT8, types.TUINT64}: ssa.OpLsh8x64,
2519 {ir.OLSH, types.TINT16, types.TUINT8}: ssa.OpLsh16x8,
2520 {ir.OLSH, types.TUINT16, types.TUINT8}: ssa.OpLsh16x8,
2521 {ir.OLSH, types.TINT16, types.TUINT16}: ssa.OpLsh16x16,
2522 {ir.OLSH, types.TUINT16, types.TUINT16}: ssa.OpLsh16x16,
2523 {ir.OLSH, types.TINT16, types.TUINT32}: ssa.OpLsh16x32,
2524 {ir.OLSH, types.TUINT16, types.TUINT32}: ssa.OpLsh16x32,
2525 {ir.OLSH, types.TINT16, types.TUINT64}: ssa.OpLsh16x64,
2526 {ir.OLSH, types.TUINT16, types.TUINT64}: ssa.OpLsh16x64,
2528 {ir.OLSH, types.TINT32, types.TUINT8}: ssa.OpLsh32x8,
2529 {ir.OLSH, types.TUINT32, types.TUINT8}: ssa.OpLsh32x8,
2530 {ir.OLSH, types.TINT32, types.TUINT16}: ssa.OpLsh32x16,
2531 {ir.OLSH, types.TUINT32, types.TUINT16}: ssa.OpLsh32x16,
2532 {ir.OLSH, types.TINT32, types.TUINT32}: ssa.OpLsh32x32,
2533 {ir.OLSH, types.TUINT32, types.TUINT32}: ssa.OpLsh32x32,
2534 {ir.OLSH, types.TINT32, types.TUINT64}: ssa.OpLsh32x64,
2535 {ir.OLSH, types.TUINT32, types.TUINT64}: ssa.OpLsh32x64,
2537 {ir.OLSH, types.TINT64, types.TUINT8}: ssa.OpLsh64x8,
2538 {ir.OLSH, types.TUINT64, types.TUINT8}: ssa.OpLsh64x8,
2539 {ir.OLSH, types.TINT64, types.TUINT16}: ssa.OpLsh64x16,
2540 {ir.OLSH, types.TUINT64, types.TUINT16}: ssa.OpLsh64x16,
2541 {ir.OLSH, types.TINT64, types.TUINT32}: ssa.OpLsh64x32,
2542 {ir.OLSH, types.TUINT64, types.TUINT32}: ssa.OpLsh64x32,
2543 {ir.OLSH, types.TINT64, types.TUINT64}: ssa.OpLsh64x64,
2544 {ir.OLSH, types.TUINT64, types.TUINT64}: ssa.OpLsh64x64,
2546 {ir.ORSH, types.TINT8, types.TUINT8}: ssa.OpRsh8x8,
2547 {ir.ORSH, types.TUINT8, types.TUINT8}: ssa.OpRsh8Ux8,
2548 {ir.ORSH, types.TINT8, types.TUINT16}: ssa.OpRsh8x16,
2549 {ir.ORSH, types.TUINT8, types.TUINT16}: ssa.OpRsh8Ux16,
2550 {ir.ORSH, types.TINT8, types.TUINT32}: ssa.OpRsh8x32,
2551 {ir.ORSH, types.TUINT8, types.TUINT32}: ssa.OpRsh8Ux32,
2552 {ir.ORSH, types.TINT8, types.TUINT64}: ssa.OpRsh8x64,
2553 {ir.ORSH, types.TUINT8, types.TUINT64}: ssa.OpRsh8Ux64,
2555 {ir.ORSH, types.TINT16, types.TUINT8}: ssa.OpRsh16x8,
2556 {ir.ORSH, types.TUINT16, types.TUINT8}: ssa.OpRsh16Ux8,
2557 {ir.ORSH, types.TINT16, types.TUINT16}: ssa.OpRsh16x16,
2558 {ir.ORSH, types.TUINT16, types.TUINT16}: ssa.OpRsh16Ux16,
2559 {ir.ORSH, types.TINT16, types.TUINT32}: ssa.OpRsh16x32,
2560 {ir.ORSH, types.TUINT16, types.TUINT32}: ssa.OpRsh16Ux32,
2561 {ir.ORSH, types.TINT16, types.TUINT64}: ssa.OpRsh16x64,
2562 {ir.ORSH, types.TUINT16, types.TUINT64}: ssa.OpRsh16Ux64,
2564 {ir.ORSH, types.TINT32, types.TUINT8}: ssa.OpRsh32x8,
2565 {ir.ORSH, types.TUINT32, types.TUINT8}: ssa.OpRsh32Ux8,
2566 {ir.ORSH, types.TINT32, types.TUINT16}: ssa.OpRsh32x16,
2567 {ir.ORSH, types.TUINT32, types.TUINT16}: ssa.OpRsh32Ux16,
2568 {ir.ORSH, types.TINT32, types.TUINT32}: ssa.OpRsh32x32,
2569 {ir.ORSH, types.TUINT32, types.TUINT32}: ssa.OpRsh32Ux32,
2570 {ir.ORSH, types.TINT32, types.TUINT64}: ssa.OpRsh32x64,
2571 {ir.ORSH, types.TUINT32, types.TUINT64}: ssa.OpRsh32Ux64,
2573 {ir.ORSH, types.TINT64, types.TUINT8}: ssa.OpRsh64x8,
2574 {ir.ORSH, types.TUINT64, types.TUINT8}: ssa.OpRsh64Ux8,
2575 {ir.ORSH, types.TINT64, types.TUINT16}: ssa.OpRsh64x16,
2576 {ir.ORSH, types.TUINT64, types.TUINT16}: ssa.OpRsh64Ux16,
2577 {ir.ORSH, types.TINT64, types.TUINT32}: ssa.OpRsh64x32,
2578 {ir.ORSH, types.TUINT64, types.TUINT32}: ssa.OpRsh64Ux32,
2579 {ir.ORSH, types.TINT64, types.TUINT64}: ssa.OpRsh64x64,
2580 {ir.ORSH, types.TUINT64, types.TUINT64}: ssa.OpRsh64Ux64,
2583 func (s *state) ssaShiftOp(op ir.Op, t *types.Type, u *types.Type) ssa.Op {
2584 etype1 := s.concreteEtype(t)
2585 etype2 := s.concreteEtype(u)
2586 x, ok := shiftOpToSSA[opAndTwoTypes{op, etype1, etype2}]
2588 s.Fatalf("unhandled shift op %v etype=%s/%s", op, etype1, etype2)
2593 func (s *state) uintptrConstant(v uint64) *ssa.Value {
2594 if s.config.PtrSize == 4 {
2595 return s.newValue0I(ssa.OpConst32, types.Types[types.TUINTPTR], int64(v))
2597 return s.newValue0I(ssa.OpConst64, types.Types[types.TUINTPTR], int64(v))
2600 func (s *state) conv(n ir.Node, v *ssa.Value, ft, tt *types.Type) *ssa.Value {
2601 if ft.IsBoolean() && tt.IsKind(types.TUINT8) {
2602 // Bool -> uint8 is generated internally when indexing into runtime.staticbyte.
2603 return s.newValue1(ssa.OpCvtBoolToUint8, tt, v)
2605 if ft.IsInteger() && tt.IsInteger() {
2607 if tt.Size() == ft.Size() {
2609 } else if tt.Size() < ft.Size() {
2611 switch 10*ft.Size() + tt.Size() {
2613 op = ssa.OpTrunc16to8
2615 op = ssa.OpTrunc32to8
2617 op = ssa.OpTrunc32to16
2619 op = ssa.OpTrunc64to8
2621 op = ssa.OpTrunc64to16
2623 op = ssa.OpTrunc64to32
2625 s.Fatalf("weird integer truncation %v -> %v", ft, tt)
2627 } else if ft.IsSigned() {
2629 switch 10*ft.Size() + tt.Size() {
2631 op = ssa.OpSignExt8to16
2633 op = ssa.OpSignExt8to32
2635 op = ssa.OpSignExt8to64
2637 op = ssa.OpSignExt16to32
2639 op = ssa.OpSignExt16to64
2641 op = ssa.OpSignExt32to64
2643 s.Fatalf("bad integer sign extension %v -> %v", ft, tt)
2647 switch 10*ft.Size() + tt.Size() {
2649 op = ssa.OpZeroExt8to16
2651 op = ssa.OpZeroExt8to32
2653 op = ssa.OpZeroExt8to64
2655 op = ssa.OpZeroExt16to32
2657 op = ssa.OpZeroExt16to64
2659 op = ssa.OpZeroExt32to64
2661 s.Fatalf("weird integer sign extension %v -> %v", ft, tt)
2664 return s.newValue1(op, tt, v)
2667 if ft.IsComplex() && tt.IsComplex() {
2669 if ft.Size() == tt.Size() {
2676 s.Fatalf("weird complex conversion %v -> %v", ft, tt)
2678 } else if ft.Size() == 8 && tt.Size() == 16 {
2679 op = ssa.OpCvt32Fto64F
2680 } else if ft.Size() == 16 && tt.Size() == 8 {
2681 op = ssa.OpCvt64Fto32F
2683 s.Fatalf("weird complex conversion %v -> %v", ft, tt)
2685 ftp := types.FloatForComplex(ft)
2686 ttp := types.FloatForComplex(tt)
2687 return s.newValue2(ssa.OpComplexMake, tt,
2688 s.newValueOrSfCall1(op, ttp, s.newValue1(ssa.OpComplexReal, ftp, v)),
2689 s.newValueOrSfCall1(op, ttp, s.newValue1(ssa.OpComplexImag, ftp, v)))
2692 if tt.IsComplex() { // and ft is not complex
2693 // Needed for generics support - can't happen in normal Go code.
2694 et := types.FloatForComplex(tt)
2695 v = s.conv(n, v, ft, et)
2696 return s.newValue2(ssa.OpComplexMake, tt, v, s.zeroVal(et))
2699 if ft.IsFloat() || tt.IsFloat() {
2700 conv, ok := fpConvOpToSSA[twoTypes{s.concreteEtype(ft), s.concreteEtype(tt)}]
2701 if s.config.RegSize == 4 && Arch.LinkArch.Family != sys.MIPS && !s.softFloat {
2702 if conv1, ok1 := fpConvOpToSSA32[twoTypes{s.concreteEtype(ft), s.concreteEtype(tt)}]; ok1 {
2706 if Arch.LinkArch.Family == sys.ARM64 || Arch.LinkArch.Family == sys.Wasm || Arch.LinkArch.Family == sys.S390X || s.softFloat {
2707 if conv1, ok1 := uint64fpConvOpToSSA[twoTypes{s.concreteEtype(ft), s.concreteEtype(tt)}]; ok1 {
2712 if Arch.LinkArch.Family == sys.MIPS && !s.softFloat {
2713 if ft.Size() == 4 && ft.IsInteger() && !ft.IsSigned() {
2714 // tt is float32 or float64, and ft is also unsigned
2716 return s.uint32Tofloat32(n, v, ft, tt)
2719 return s.uint32Tofloat64(n, v, ft, tt)
2721 } else if tt.Size() == 4 && tt.IsInteger() && !tt.IsSigned() {
2722 // ft is float32 or float64, and tt is unsigned integer
2724 return s.float32ToUint32(n, v, ft, tt)
2727 return s.float64ToUint32(n, v, ft, tt)
2733 s.Fatalf("weird float conversion %v -> %v", ft, tt)
2735 op1, op2, it := conv.op1, conv.op2, conv.intermediateType
2737 if op1 != ssa.OpInvalid && op2 != ssa.OpInvalid {
2738 // normal case, not tripping over unsigned 64
2739 if op1 == ssa.OpCopy {
2740 if op2 == ssa.OpCopy {
2743 return s.newValueOrSfCall1(op2, tt, v)
2745 if op2 == ssa.OpCopy {
2746 return s.newValueOrSfCall1(op1, tt, v)
2748 return s.newValueOrSfCall1(op2, tt, s.newValueOrSfCall1(op1, types.Types[it], v))
2750 // Tricky 64-bit unsigned cases.
2752 // tt is float32 or float64, and ft is also unsigned
2754 return s.uint64Tofloat32(n, v, ft, tt)
2757 return s.uint64Tofloat64(n, v, ft, tt)
2759 s.Fatalf("weird unsigned integer to float conversion %v -> %v", ft, tt)
2761 // ft is float32 or float64, and tt is unsigned integer
2763 return s.float32ToUint64(n, v, ft, tt)
2766 return s.float64ToUint64(n, v, ft, tt)
2768 s.Fatalf("weird float to unsigned integer conversion %v -> %v", ft, tt)
2772 s.Fatalf("unhandled OCONV %s -> %s", ft.Kind(), tt.Kind())
2776 // expr converts the expression n to ssa, adds it to s and returns the ssa result.
2777 func (s *state) expr(n ir.Node) *ssa.Value {
2778 return s.exprCheckPtr(n, true)
2781 func (s *state) exprCheckPtr(n ir.Node, checkPtrOK bool) *ssa.Value {
2782 if ir.HasUniquePos(n) {
2783 // ONAMEs and named OLITERALs have the line number
2784 // of the decl, not the use. See issue 14742.
2789 s.stmtList(n.Init())
2791 case ir.OBYTES2STRTMP:
2792 n := n.(*ir.ConvExpr)
2793 slice := s.expr(n.X)
2794 ptr := s.newValue1(ssa.OpSlicePtr, s.f.Config.Types.BytePtr, slice)
2795 len := s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], slice)
2796 return s.newValue2(ssa.OpStringMake, n.Type(), ptr, len)
2797 case ir.OSTR2BYTESTMP:
2798 n := n.(*ir.ConvExpr)
2800 ptr := s.newValue1(ssa.OpStringPtr, s.f.Config.Types.BytePtr, str)
2802 // We need to ensure []byte("") evaluates to []byte{}, and not []byte(nil).
2804 // TODO(mdempsky): Investigate using "len != 0" instead of "ptr != nil".
2805 cond := s.newValue2(ssa.OpNeqPtr, types.Types[types.TBOOL], ptr, s.constNil(ptr.Type))
2806 zerobase := s.newValue1A(ssa.OpAddr, ptr.Type, ir.Syms.Zerobase, s.sb)
2807 ptr = s.ternary(cond, ptr, zerobase)
2809 len := s.newValue1(ssa.OpStringLen, types.Types[types.TINT], str)
2810 return s.newValue3(ssa.OpSliceMake, n.Type(), ptr, len, len)
2812 n := n.(*ir.UnaryExpr)
2813 aux := n.X.(*ir.Name).Linksym()
2814 // OCFUNC is used to build function values, which must
2815 // always reference ABIInternal entry points.
2816 if aux.ABI() != obj.ABIInternal {
2817 s.Fatalf("expected ABIInternal: %v", aux.ABI())
2819 return s.entryNewValue1A(ssa.OpAddr, n.Type(), aux, s.sb)
2822 if n.Class == ir.PFUNC {
2823 // "value" of a function is the address of the function's closure
2824 sym := staticdata.FuncLinksym(n)
2825 return s.entryNewValue1A(ssa.OpAddr, types.NewPtr(n.Type()), sym, s.sb)
2828 return s.variable(n, n.Type())
2830 return s.load(n.Type(), s.addr(n))
2831 case ir.OLINKSYMOFFSET:
2832 n := n.(*ir.LinksymOffsetExpr)
2833 return s.load(n.Type(), s.addr(n))
2835 n := n.(*ir.NilExpr)
2839 return s.constSlice(t)
2840 case t.IsInterface():
2841 return s.constInterface(t)
2843 return s.constNil(t)
2846 switch u := n.Val(); u.Kind() {
2848 i := ir.IntVal(n.Type(), u)
2849 switch n.Type().Size() {
2851 return s.constInt8(n.Type(), int8(i))
2853 return s.constInt16(n.Type(), int16(i))
2855 return s.constInt32(n.Type(), int32(i))
2857 return s.constInt64(n.Type(), i)
2859 s.Fatalf("bad integer size %d", n.Type().Size())
2862 case constant.String:
2863 i := constant.StringVal(u)
2865 return s.constEmptyString(n.Type())
2867 return s.entryNewValue0A(ssa.OpConstString, n.Type(), ssa.StringToAux(i))
2869 return s.constBool(constant.BoolVal(u))
2870 case constant.Float:
2871 f, _ := constant.Float64Val(u)
2872 switch n.Type().Size() {
2874 return s.constFloat32(n.Type(), f)
2876 return s.constFloat64(n.Type(), f)
2878 s.Fatalf("bad float size %d", n.Type().Size())
2881 case constant.Complex:
2882 re, _ := constant.Float64Val(constant.Real(u))
2883 im, _ := constant.Float64Val(constant.Imag(u))
2884 switch n.Type().Size() {
2886 pt := types.Types[types.TFLOAT32]
2887 return s.newValue2(ssa.OpComplexMake, n.Type(),
2888 s.constFloat32(pt, re),
2889 s.constFloat32(pt, im))
2891 pt := types.Types[types.TFLOAT64]
2892 return s.newValue2(ssa.OpComplexMake, n.Type(),
2893 s.constFloat64(pt, re),
2894 s.constFloat64(pt, im))
2896 s.Fatalf("bad complex size %d", n.Type().Size())
2900 s.Fatalf("unhandled OLITERAL %v", u.Kind())
2904 n := n.(*ir.ConvExpr)
2908 // Assume everything will work out, so set up our return value.
2909 // Anything interesting that happens from here is a fatal.
2915 // Special case for not confusing GC and liveness.
2916 // We don't want pointers accidentally classified
2917 // as not-pointers or vice-versa because of copy
2919 if to.IsPtrShaped() != from.IsPtrShaped() {
2920 return s.newValue2(ssa.OpConvert, to, x, s.mem())
2923 v := s.newValue1(ssa.OpCopy, to, x) // ensure that v has the right type
2926 if to.Kind() == types.TFUNC && from.IsPtrShaped() {
2930 // named <--> unnamed type or typed <--> untyped const
2931 if from.Kind() == to.Kind() {
2935 // unsafe.Pointer <--> *T
2936 if to.IsUnsafePtr() && from.IsPtrShaped() || from.IsUnsafePtr() && to.IsPtrShaped() {
2937 if s.checkPtrEnabled && checkPtrOK && to.IsPtr() && from.IsUnsafePtr() {
2938 s.checkPtrAlignment(n, v, nil)
2944 if to.Kind() == types.TMAP && from == types.NewPtr(reflectdata.MapType()) {
2948 types.CalcSize(from)
2950 if from.Size() != to.Size() {
2951 s.Fatalf("CONVNOP width mismatch %v (%d) -> %v (%d)\n", from, from.Size(), to, to.Size())
2954 if etypesign(from.Kind()) != etypesign(to.Kind()) {
2955 s.Fatalf("CONVNOP sign mismatch %v (%s) -> %v (%s)\n", from, from.Kind(), to, to.Kind())
2959 if base.Flag.Cfg.Instrumenting {
2960 // These appear to be fine, but they fail the
2961 // integer constraint below, so okay them here.
2962 // Sample non-integer conversion: map[string]string -> *uint8
2966 if etypesign(from.Kind()) == 0 {
2967 s.Fatalf("CONVNOP unrecognized non-integer %v -> %v\n", from, to)
2971 // integer, same width, same sign
2975 n := n.(*ir.ConvExpr)
2977 return s.conv(n, x, n.X.Type(), n.Type())
2980 n := n.(*ir.TypeAssertExpr)
2981 res, _ := s.dottype(n, false)
2984 case ir.ODYNAMICDOTTYPE:
2985 n := n.(*ir.DynamicTypeAssertExpr)
2986 res, _ := s.dynamicDottype(n, false)
2990 case ir.OLT, ir.OEQ, ir.ONE, ir.OLE, ir.OGE, ir.OGT:
2991 n := n.(*ir.BinaryExpr)
2994 if n.X.Type().IsComplex() {
2995 pt := types.FloatForComplex(n.X.Type())
2996 op := s.ssaOp(ir.OEQ, pt)
2997 r := s.newValueOrSfCall2(op, types.Types[types.TBOOL], s.newValue1(ssa.OpComplexReal, pt, a), s.newValue1(ssa.OpComplexReal, pt, b))
2998 i := s.newValueOrSfCall2(op, types.Types[types.TBOOL], s.newValue1(ssa.OpComplexImag, pt, a), s.newValue1(ssa.OpComplexImag, pt, b))
2999 c := s.newValue2(ssa.OpAndB, types.Types[types.TBOOL], r, i)
3004 return s.newValue1(ssa.OpNot, types.Types[types.TBOOL], c)
3006 s.Fatalf("ordered complex compare %v", n.Op())
3010 // Convert OGE and OGT into OLE and OLT.
3014 op, a, b = ir.OLE, b, a
3016 op, a, b = ir.OLT, b, a
3018 if n.X.Type().IsFloat() {
3020 return s.newValueOrSfCall2(s.ssaOp(op, n.X.Type()), types.Types[types.TBOOL], a, b)
3022 // integer comparison
3023 return s.newValue2(s.ssaOp(op, n.X.Type()), types.Types[types.TBOOL], a, b)
3025 n := n.(*ir.BinaryExpr)
3028 if n.Type().IsComplex() {
3029 mulop := ssa.OpMul64F
3030 addop := ssa.OpAdd64F
3031 subop := ssa.OpSub64F
3032 pt := types.FloatForComplex(n.Type()) // Could be Float32 or Float64
3033 wt := types.Types[types.TFLOAT64] // Compute in Float64 to minimize cancellation error
3035 areal := s.newValue1(ssa.OpComplexReal, pt, a)
3036 breal := s.newValue1(ssa.OpComplexReal, pt, b)
3037 aimag := s.newValue1(ssa.OpComplexImag, pt, a)
3038 bimag := s.newValue1(ssa.OpComplexImag, pt, b)
3040 if pt != wt { // Widen for calculation
3041 areal = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, areal)
3042 breal = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, breal)
3043 aimag = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, aimag)
3044 bimag = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, bimag)
3047 xreal := s.newValueOrSfCall2(subop, wt, s.newValueOrSfCall2(mulop, wt, areal, breal), s.newValueOrSfCall2(mulop, wt, aimag, bimag))
3048 ximag := s.newValueOrSfCall2(addop, wt, s.newValueOrSfCall2(mulop, wt, areal, bimag), s.newValueOrSfCall2(mulop, wt, aimag, breal))
3050 if pt != wt { // Narrow to store back
3051 xreal = s.newValueOrSfCall1(ssa.OpCvt64Fto32F, pt, xreal)
3052 ximag = s.newValueOrSfCall1(ssa.OpCvt64Fto32F, pt, ximag)
3055 return s.newValue2(ssa.OpComplexMake, n.Type(), xreal, ximag)
3058 if n.Type().IsFloat() {
3059 return s.newValueOrSfCall2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
3062 return s.newValue2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
3065 n := n.(*ir.BinaryExpr)
3068 if n.Type().IsComplex() {
3069 // TODO this is not executed because the front-end substitutes a runtime call.
3070 // That probably ought to change; with modest optimization the widen/narrow
3071 // conversions could all be elided in larger expression trees.
3072 mulop := ssa.OpMul64F
3073 addop := ssa.OpAdd64F
3074 subop := ssa.OpSub64F
3075 divop := ssa.OpDiv64F
3076 pt := types.FloatForComplex(n.Type()) // Could be Float32 or Float64
3077 wt := types.Types[types.TFLOAT64] // Compute in Float64 to minimize cancellation error
3079 areal := s.newValue1(ssa.OpComplexReal, pt, a)
3080 breal := s.newValue1(ssa.OpComplexReal, pt, b)
3081 aimag := s.newValue1(ssa.OpComplexImag, pt, a)
3082 bimag := s.newValue1(ssa.OpComplexImag, pt, b)
3084 if pt != wt { // Widen for calculation
3085 areal = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, areal)
3086 breal = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, breal)
3087 aimag = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, aimag)
3088 bimag = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, bimag)
3091 denom := s.newValueOrSfCall2(addop, wt, s.newValueOrSfCall2(mulop, wt, breal, breal), s.newValueOrSfCall2(mulop, wt, bimag, bimag))
3092 xreal := s.newValueOrSfCall2(addop, wt, s.newValueOrSfCall2(mulop, wt, areal, breal), s.newValueOrSfCall2(mulop, wt, aimag, bimag))
3093 ximag := s.newValueOrSfCall2(subop, wt, s.newValueOrSfCall2(mulop, wt, aimag, breal), s.newValueOrSfCall2(mulop, wt, areal, bimag))
3095 // TODO not sure if this is best done in wide precision or narrow
3096 // Double-rounding might be an issue.
3097 // Note that the pre-SSA implementation does the entire calculation
3098 // in wide format, so wide is compatible.
3099 xreal = s.newValueOrSfCall2(divop, wt, xreal, denom)
3100 ximag = s.newValueOrSfCall2(divop, wt, ximag, denom)
3102 if pt != wt { // Narrow to store back
3103 xreal = s.newValueOrSfCall1(ssa.OpCvt64Fto32F, pt, xreal)
3104 ximag = s.newValueOrSfCall1(ssa.OpCvt64Fto32F, pt, ximag)
3106 return s.newValue2(ssa.OpComplexMake, n.Type(), xreal, ximag)
3108 if n.Type().IsFloat() {
3109 return s.newValueOrSfCall2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
3111 return s.intDivide(n, a, b)
3113 n := n.(*ir.BinaryExpr)
3116 return s.intDivide(n, a, b)
3117 case ir.OADD, ir.OSUB:
3118 n := n.(*ir.BinaryExpr)
3121 if n.Type().IsComplex() {
3122 pt := types.FloatForComplex(n.Type())
3123 op := s.ssaOp(n.Op(), pt)
3124 return s.newValue2(ssa.OpComplexMake, n.Type(),
3125 s.newValueOrSfCall2(op, pt, s.newValue1(ssa.OpComplexReal, pt, a), s.newValue1(ssa.OpComplexReal, pt, b)),
3126 s.newValueOrSfCall2(op, pt, s.newValue1(ssa.OpComplexImag, pt, a), s.newValue1(ssa.OpComplexImag, pt, b)))
3128 if n.Type().IsFloat() {
3129 return s.newValueOrSfCall2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
3131 return s.newValue2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
3132 case ir.OAND, ir.OOR, ir.OXOR:
3133 n := n.(*ir.BinaryExpr)
3136 return s.newValue2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
3138 n := n.(*ir.BinaryExpr)
3141 b = s.newValue1(s.ssaOp(ir.OBITNOT, b.Type), b.Type, b)
3142 return s.newValue2(s.ssaOp(ir.OAND, n.Type()), a.Type, a, b)
3143 case ir.OLSH, ir.ORSH:
3144 n := n.(*ir.BinaryExpr)
3149 cmp := s.newValue2(s.ssaOp(ir.OLE, bt), types.Types[types.TBOOL], s.zeroVal(bt), b)
3150 s.check(cmp, ir.Syms.Panicshift)
3151 bt = bt.ToUnsigned()
3153 return s.newValue2(s.ssaShiftOp(n.Op(), n.Type(), bt), a.Type, a, b)
3154 case ir.OANDAND, ir.OOROR:
3155 // To implement OANDAND (and OOROR), we introduce a
3156 // new temporary variable to hold the result. The
3157 // variable is associated with the OANDAND node in the
3158 // s.vars table (normally variables are only
3159 // associated with ONAME nodes). We convert
3166 // Using var in the subsequent block introduces the
3167 // necessary phi variable.
3168 n := n.(*ir.LogicalExpr)
3173 b.Kind = ssa.BlockIf
3175 // In theory, we should set b.Likely here based on context.
3176 // However, gc only gives us likeliness hints
3177 // in a single place, for plain OIF statements,
3178 // and passing around context is finnicky, so don't bother for now.
3180 bRight := s.f.NewBlock(ssa.BlockPlain)
3181 bResult := s.f.NewBlock(ssa.BlockPlain)
3182 if n.Op() == ir.OANDAND {
3184 b.AddEdgeTo(bResult)
3185 } else if n.Op() == ir.OOROR {
3186 b.AddEdgeTo(bResult)
3190 s.startBlock(bRight)
3195 b.AddEdgeTo(bResult)
3197 s.startBlock(bResult)
3198 return s.variable(n, types.Types[types.TBOOL])
3200 n := n.(*ir.BinaryExpr)
3203 return s.newValue2(ssa.OpComplexMake, n.Type(), r, i)
3207 n := n.(*ir.UnaryExpr)
3209 if n.Type().IsComplex() {
3210 tp := types.FloatForComplex(n.Type())
3211 negop := s.ssaOp(n.Op(), tp)
3212 return s.newValue2(ssa.OpComplexMake, n.Type(),
3213 s.newValue1(negop, tp, s.newValue1(ssa.OpComplexReal, tp, a)),
3214 s.newValue1(negop, tp, s.newValue1(ssa.OpComplexImag, tp, a)))
3216 return s.newValue1(s.ssaOp(n.Op(), n.Type()), a.Type, a)
3217 case ir.ONOT, ir.OBITNOT:
3218 n := n.(*ir.UnaryExpr)
3220 return s.newValue1(s.ssaOp(n.Op(), n.Type()), a.Type, a)
3221 case ir.OIMAG, ir.OREAL:
3222 n := n.(*ir.UnaryExpr)
3224 return s.newValue1(s.ssaOp(n.Op(), n.X.Type()), n.Type(), a)
3226 n := n.(*ir.UnaryExpr)
3230 n := n.(*ir.AddrExpr)
3234 n := n.(*ir.ResultExpr)
3235 if s.prevCall == nil || s.prevCall.Op != ssa.OpStaticLECall && s.prevCall.Op != ssa.OpInterLECall && s.prevCall.Op != ssa.OpClosureLECall {
3236 panic("Expected to see a previous call")
3240 panic(fmt.Errorf("ORESULT %v does not match call %s", n, s.prevCall))
3242 return s.resultOfCall(s.prevCall, which, n.Type())
3245 n := n.(*ir.StarExpr)
3246 p := s.exprPtr(n.X, n.Bounded(), n.Pos())
3247 return s.load(n.Type(), p)
3250 n := n.(*ir.SelectorExpr)
3251 if n.X.Op() == ir.OSTRUCTLIT {
3252 // All literals with nonzero fields have already been
3253 // rewritten during walk. Any that remain are just T{}
3254 // or equivalents. Use the zero value.
3255 if !ir.IsZero(n.X) {
3256 s.Fatalf("literal with nonzero value in SSA: %v", n.X)
3258 return s.zeroVal(n.Type())
3260 // If n is addressable and can't be represented in
3261 // SSA, then load just the selected field. This
3262 // prevents false memory dependencies in race/msan/asan
3264 if ir.IsAddressable(n) && !s.canSSA(n) {
3266 return s.load(n.Type(), p)
3269 return s.newValue1I(ssa.OpStructSelect, n.Type(), int64(fieldIdx(n)), v)
3272 n := n.(*ir.SelectorExpr)
3273 p := s.exprPtr(n.X, n.Bounded(), n.Pos())
3274 p = s.newValue1I(ssa.OpOffPtr, types.NewPtr(n.Type()), n.Offset(), p)
3275 return s.load(n.Type(), p)
3278 n := n.(*ir.IndexExpr)
3280 case n.X.Type().IsString():
3281 if n.Bounded() && ir.IsConst(n.X, constant.String) && ir.IsConst(n.Index, constant.Int) {
3282 // Replace "abc"[1] with 'b'.
3283 // Delayed until now because "abc"[1] is not an ideal constant.
3284 // See test/fixedbugs/issue11370.go.
3285 return s.newValue0I(ssa.OpConst8, types.Types[types.TUINT8], int64(int8(ir.StringVal(n.X)[ir.Int64Val(n.Index)])))
3288 i := s.expr(n.Index)
3289 len := s.newValue1(ssa.OpStringLen, types.Types[types.TINT], a)
3290 i = s.boundsCheck(i, len, ssa.BoundsIndex, n.Bounded())
3291 ptrtyp := s.f.Config.Types.BytePtr
3292 ptr := s.newValue1(ssa.OpStringPtr, ptrtyp, a)
3293 if ir.IsConst(n.Index, constant.Int) {
3294 ptr = s.newValue1I(ssa.OpOffPtr, ptrtyp, ir.Int64Val(n.Index), ptr)
3296 ptr = s.newValue2(ssa.OpAddPtr, ptrtyp, ptr, i)
3298 return s.load(types.Types[types.TUINT8], ptr)
3299 case n.X.Type().IsSlice():
3301 return s.load(n.X.Type().Elem(), p)
3302 case n.X.Type().IsArray():
3303 if ssa.CanSSA(n.X.Type()) {
3304 // SSA can handle arrays of length at most 1.
3305 bound := n.X.Type().NumElem()
3307 i := s.expr(n.Index)
3309 // Bounds check will never succeed. Might as well
3310 // use constants for the bounds check.
3311 z := s.constInt(types.Types[types.TINT], 0)
3312 s.boundsCheck(z, z, ssa.BoundsIndex, false)
3313 // The return value won't be live, return junk.
3314 // But not quite junk, in case bounds checks are turned off. See issue 48092.
3315 return s.zeroVal(n.Type())
3317 len := s.constInt(types.Types[types.TINT], bound)
3318 s.boundsCheck(i, len, ssa.BoundsIndex, n.Bounded()) // checks i == 0
3319 return s.newValue1I(ssa.OpArraySelect, n.Type(), 0, a)
3322 return s.load(n.X.Type().Elem(), p)
3324 s.Fatalf("bad type for index %v", n.X.Type())
3328 case ir.OLEN, ir.OCAP:
3329 n := n.(*ir.UnaryExpr)
3331 case n.X.Type().IsSlice():
3332 op := ssa.OpSliceLen
3333 if n.Op() == ir.OCAP {
3336 return s.newValue1(op, types.Types[types.TINT], s.expr(n.X))
3337 case n.X.Type().IsString(): // string; not reachable for OCAP
3338 return s.newValue1(ssa.OpStringLen, types.Types[types.TINT], s.expr(n.X))
3339 case n.X.Type().IsMap(), n.X.Type().IsChan():
3340 return s.referenceTypeBuiltin(n, s.expr(n.X))
3342 return s.constInt(types.Types[types.TINT], n.X.Type().NumElem())
3346 n := n.(*ir.UnaryExpr)
3348 if n.X.Type().IsSlice() {
3350 return s.newValue1(ssa.OpSlicePtr, n.Type(), a)
3352 return s.newValue1(ssa.OpSlicePtrUnchecked, n.Type(), a)
3354 return s.newValue1(ssa.OpStringPtr, n.Type(), a)
3358 n := n.(*ir.UnaryExpr)
3360 return s.newValue1(ssa.OpITab, n.Type(), a)
3363 n := n.(*ir.UnaryExpr)
3365 return s.newValue1(ssa.OpIData, n.Type(), a)
3368 n := n.(*ir.BinaryExpr)
3371 return s.newValue2(ssa.OpIMake, n.Type(), tab, data)
3373 case ir.OSLICEHEADER:
3374 n := n.(*ir.SliceHeaderExpr)
3378 return s.newValue3(ssa.OpSliceMake, n.Type(), p, l, c)
3380 case ir.OSTRINGHEADER:
3381 n := n.(*ir.StringHeaderExpr)
3384 return s.newValue2(ssa.OpStringMake, n.Type(), p, l)
3386 case ir.OSLICE, ir.OSLICEARR, ir.OSLICE3, ir.OSLICE3ARR:
3387 n := n.(*ir.SliceExpr)
3388 check := s.checkPtrEnabled && n.Op() == ir.OSLICE3ARR && n.X.Op() == ir.OCONVNOP && n.X.(*ir.ConvExpr).X.Type().IsUnsafePtr()
3389 v := s.exprCheckPtr(n.X, !check)
3390 var i, j, k *ssa.Value
3400 p, l, c := s.slice(v, i, j, k, n.Bounded())
3402 // Emit checkptr instrumentation after bound check to prevent false positive, see #46938.
3403 s.checkPtrAlignment(n.X.(*ir.ConvExpr), v, s.conv(n.Max, k, k.Type, types.Types[types.TUINTPTR]))
3405 return s.newValue3(ssa.OpSliceMake, n.Type(), p, l, c)
3408 n := n.(*ir.SliceExpr)
3417 p, l, _ := s.slice(v, i, j, nil, n.Bounded())
3418 return s.newValue2(ssa.OpStringMake, n.Type(), p, l)
3420 case ir.OSLICE2ARRPTR:
3421 // if arrlen > slice.len {
3425 n := n.(*ir.ConvExpr)
3427 nelem := n.Type().Elem().NumElem()
3428 arrlen := s.constInt(types.Types[types.TINT], nelem)
3429 cap := s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], v)
3430 s.boundsCheck(arrlen, cap, ssa.BoundsConvert, false)
3431 op := ssa.OpSlicePtr
3433 op = ssa.OpSlicePtrUnchecked
3435 return s.newValue1(op, n.Type(), v)
3438 n := n.(*ir.CallExpr)
3439 if ir.IsIntrinsicCall(n) {
3440 return s.intrinsicCall(n)
3445 n := n.(*ir.CallExpr)
3446 return s.callResult(n, callNormal)
3449 n := n.(*ir.CallExpr)
3450 return s.newValue1(ssa.OpGetG, n.Type(), s.mem())
3452 case ir.OGETCALLERPC:
3453 n := n.(*ir.CallExpr)
3454 return s.newValue0(ssa.OpGetCallerPC, n.Type())
3456 case ir.OGETCALLERSP:
3457 n := n.(*ir.CallExpr)
3458 return s.newValue1(ssa.OpGetCallerSP, n.Type(), s.mem())
3461 return s.append(n.(*ir.CallExpr), false)
3463 case ir.OMIN, ir.OMAX:
3464 return s.minMax(n.(*ir.CallExpr))
3466 case ir.OSTRUCTLIT, ir.OARRAYLIT:
3467 // All literals with nonzero fields have already been
3468 // rewritten during walk. Any that remain are just T{}
3469 // or equivalents. Use the zero value.
3470 n := n.(*ir.CompLitExpr)
3472 s.Fatalf("literal with nonzero value in SSA: %v", n)
3474 return s.zeroVal(n.Type())
3477 n := n.(*ir.UnaryExpr)
3478 var rtype *ssa.Value
3479 if x, ok := n.X.(*ir.DynamicType); ok && x.Op() == ir.ODYNAMICTYPE {
3480 rtype = s.expr(x.RType)
3482 return s.newObject(n.Type().Elem(), rtype)
3485 n := n.(*ir.BinaryExpr)
3489 // Force len to uintptr to prevent misuse of garbage bits in the
3490 // upper part of the register (#48536).
3491 len = s.conv(n, len, len.Type, types.Types[types.TUINTPTR])
3493 return s.newValue2(ssa.OpAddPtr, n.Type(), ptr, len)
3496 s.Fatalf("unhandled expr %v", n.Op())
3501 func (s *state) resultOfCall(c *ssa.Value, which int64, t *types.Type) *ssa.Value {
3502 aux := c.Aux.(*ssa.AuxCall)
3503 pa := aux.ParamAssignmentForResult(which)
3504 // TODO(register args) determine if in-memory TypeOK is better loaded early from SelectNAddr or later when SelectN is expanded.
3505 // SelectN is better for pattern-matching and possible call-aware analysis we might want to do in the future.
3506 if len(pa.Registers) == 0 && !ssa.CanSSA(t) {
3507 addr := s.newValue1I(ssa.OpSelectNAddr, types.NewPtr(t), which, c)
3508 return s.rawLoad(t, addr)
3510 return s.newValue1I(ssa.OpSelectN, t, which, c)
3513 func (s *state) resultAddrOfCall(c *ssa.Value, which int64, t *types.Type) *ssa.Value {
3514 aux := c.Aux.(*ssa.AuxCall)
3515 pa := aux.ParamAssignmentForResult(which)
3516 if len(pa.Registers) == 0 {
3517 return s.newValue1I(ssa.OpSelectNAddr, types.NewPtr(t), which, c)
3519 _, addr := s.temp(c.Pos, t)
3520 rval := s.newValue1I(ssa.OpSelectN, t, which, c)
3521 s.vars[memVar] = s.newValue3Apos(ssa.OpStore, types.TypeMem, t, addr, rval, s.mem(), false)
3525 // append converts an OAPPEND node to SSA.
3526 // If inplace is false, it converts the OAPPEND expression n to an ssa.Value,
3527 // adds it to s, and returns the Value.
3528 // If inplace is true, it writes the result of the OAPPEND expression n
3529 // back to the slice being appended to, and returns nil.
3530 // inplace MUST be set to false if the slice can be SSA'd.
3531 // Note: this code only handles fixed-count appends. Dotdotdot appends
3532 // have already been rewritten at this point (by walk).
3533 func (s *state) append(n *ir.CallExpr, inplace bool) *ssa.Value {
3534 // If inplace is false, process as expression "append(s, e1, e2, e3)":
3536 // ptr, len, cap := s
3538 // if uint(len) > uint(cap) {
3539 // ptr, len, cap = growslice(ptr, len, cap, 3, typ)
3540 // Note that len is unmodified by growslice.
3542 // // with write barriers, if needed:
3543 // *(ptr+(len-3)) = e1
3544 // *(ptr+(len-2)) = e2
3545 // *(ptr+(len-1)) = e3
3546 // return makeslice(ptr, len, cap)
3549 // If inplace is true, process as statement "s = append(s, e1, e2, e3)":
3552 // ptr, len, cap := s
3554 // if uint(len) > uint(cap) {
3555 // ptr, len, cap = growslice(ptr, len, cap, 3, typ)
3556 // vardef(a) // if necessary, advise liveness we are writing a new a
3557 // *a.cap = cap // write before ptr to avoid a spill
3558 // *a.ptr = ptr // with write barrier
3561 // // with write barriers, if needed:
3562 // *(ptr+(len-3)) = e1
3563 // *(ptr+(len-2)) = e2
3564 // *(ptr+(len-1)) = e3
3566 et := n.Type().Elem()
3567 pt := types.NewPtr(et)
3570 sn := n.Args[0] // the slice node is the first in the list
3571 var slice, addr *ssa.Value
3574 slice = s.load(n.Type(), addr)
3579 // Allocate new blocks
3580 grow := s.f.NewBlock(ssa.BlockPlain)
3581 assign := s.f.NewBlock(ssa.BlockPlain)
3583 // Decomposse input slice.
3584 p := s.newValue1(ssa.OpSlicePtr, pt, slice)
3585 l := s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], slice)
3586 c := s.newValue1(ssa.OpSliceCap, types.Types[types.TINT], slice)
3588 // Add number of new elements to length.
3589 nargs := s.constInt(types.Types[types.TINT], int64(len(n.Args)-1))
3590 l = s.newValue2(s.ssaOp(ir.OADD, types.Types[types.TINT]), types.Types[types.TINT], l, nargs)
3592 // Decide if we need to grow
3593 cmp := s.newValue2(s.ssaOp(ir.OLT, types.Types[types.TUINT]), types.Types[types.TBOOL], c, l)
3595 // Record values of ptr/len/cap before branch.
3603 b.Kind = ssa.BlockIf
3604 b.Likely = ssa.BranchUnlikely
3611 taddr := s.expr(n.Fun)
3612 r := s.rtcall(ir.Syms.Growslice, true, []*types.Type{n.Type()}, p, l, c, nargs, taddr)
3614 // Decompose output slice
3615 p = s.newValue1(ssa.OpSlicePtr, pt, r[0])
3616 l = s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], r[0])
3617 c = s.newValue1(ssa.OpSliceCap, types.Types[types.TINT], r[0])
3623 if sn.Op() == ir.ONAME {
3625 if sn.Class != ir.PEXTERN {
3626 // Tell liveness we're about to build a new slice
3627 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, sn, s.mem())
3630 capaddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, types.SliceCapOffset, addr)
3631 s.store(types.Types[types.TINT], capaddr, c)
3632 s.store(pt, addr, p)
3638 // assign new elements to slots
3639 s.startBlock(assign)
3640 p = s.variable(ptrVar, pt) // generates phi for ptr
3641 l = s.variable(lenVar, types.Types[types.TINT]) // generates phi for len
3643 c = s.variable(capVar, types.Types[types.TINT]) // generates phi for cap
3647 // Update length in place.
3648 // We have to wait until here to make sure growslice succeeded.
3649 lenaddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, types.SliceLenOffset, addr)
3650 s.store(types.Types[types.TINT], lenaddr, l)
3654 type argRec struct {
3655 // if store is true, we're appending the value v. If false, we're appending the
3660 args := make([]argRec, 0, len(n.Args[1:]))
3661 for _, n := range n.Args[1:] {
3662 if ssa.CanSSA(n.Type()) {
3663 args = append(args, argRec{v: s.expr(n), store: true})
3666 args = append(args, argRec{v: v})
3670 // Write args into slice.
3671 oldLen := s.newValue2(s.ssaOp(ir.OSUB, types.Types[types.TINT]), types.Types[types.TINT], l, nargs)
3672 p2 := s.newValue2(ssa.OpPtrIndex, pt, p, oldLen)
3673 for i, arg := range args {
3674 addr := s.newValue2(ssa.OpPtrIndex, pt, p2, s.constInt(types.Types[types.TINT], int64(i)))
3676 s.storeType(et, addr, arg.v, 0, true)
3678 s.move(et, addr, arg.v)
3682 // The following deletions have no practical effect at this time
3683 // because state.vars has been reset by the preceding state.startBlock.
3684 // They only enforce the fact that these variables are no longer need in
3685 // the current scope.
3686 delete(s.vars, ptrVar)
3687 delete(s.vars, lenVar)
3689 delete(s.vars, capVar)
3696 return s.newValue3(ssa.OpSliceMake, n.Type(), p, l, c)
3699 // minMax converts an OMIN/OMAX builtin call into SSA.
3700 func (s *state) minMax(n *ir.CallExpr) *ssa.Value {
3701 // The OMIN/OMAX builtin is variadic, but its semantics are
3702 // equivalent to left-folding a binary min/max operation across the
3704 fold := func(op func(x, a *ssa.Value) *ssa.Value) *ssa.Value {
3705 x := s.expr(n.Args[0])
3706 for _, arg := range n.Args[1:] {
3707 x = op(x, s.expr(arg))
3714 if typ.IsFloat() || typ.IsString() {
3715 // min/max semantics for floats are tricky because of NaNs and
3716 // negative zero. Some architectures have instructions which
3717 // we can use to generate the right result. For others we must
3718 // call into the runtime instead.
3720 // Strings are conceptually simpler, but we currently desugar
3721 // string comparisons during walk, not ssagen.
3724 switch Arch.LinkArch.Family {
3725 case sys.AMD64, sys.ARM64:
3728 case typ.Kind() == types.TFLOAT64 && n.Op() == ir.OMIN:
3730 case typ.Kind() == types.TFLOAT64 && n.Op() == ir.OMAX:
3732 case typ.Kind() == types.TFLOAT32 && n.Op() == ir.OMIN:
3734 case typ.Kind() == types.TFLOAT32 && n.Op() == ir.OMAX:
3737 return fold(func(x, a *ssa.Value) *ssa.Value {
3738 return s.newValue2(op, typ, x, a)
3744 case types.TFLOAT32:
3751 case types.TFLOAT64:
3766 fn := typecheck.LookupRuntimeFunc(name)
3768 return fold(func(x, a *ssa.Value) *ssa.Value {
3769 return s.rtcall(fn, true, []*types.Type{typ}, x, a)[0]
3773 lt := s.ssaOp(ir.OLT, typ)
3775 return fold(func(x, a *ssa.Value) *ssa.Value {
3779 return s.ternary(s.newValue2(lt, types.Types[types.TBOOL], a, x), a, x)
3782 return s.ternary(s.newValue2(lt, types.Types[types.TBOOL], x, a), a, x)
3784 panic("unreachable")
3788 // ternary emits code to evaluate cond ? x : y.
3789 func (s *state) ternary(cond, x, y *ssa.Value) *ssa.Value {
3790 // Note that we need a new ternaryVar each time (unlike okVar where we can
3791 // reuse the variable) because it might have a different type every time.
3792 ternaryVar := ssaMarker("ternary")
3794 bThen := s.f.NewBlock(ssa.BlockPlain)
3795 bElse := s.f.NewBlock(ssa.BlockPlain)
3796 bEnd := s.f.NewBlock(ssa.BlockPlain)
3799 b.Kind = ssa.BlockIf
3805 s.vars[ternaryVar] = x
3806 s.endBlock().AddEdgeTo(bEnd)
3809 s.vars[ternaryVar] = y
3810 s.endBlock().AddEdgeTo(bEnd)
3813 r := s.variable(ternaryVar, x.Type)
3814 delete(s.vars, ternaryVar)
3818 // condBranch evaluates the boolean expression cond and branches to yes
3819 // if cond is true and no if cond is false.
3820 // This function is intended to handle && and || better than just calling
3821 // s.expr(cond) and branching on the result.
3822 func (s *state) condBranch(cond ir.Node, yes, no *ssa.Block, likely int8) {
3825 cond := cond.(*ir.LogicalExpr)
3826 mid := s.f.NewBlock(ssa.BlockPlain)
3827 s.stmtList(cond.Init())
3828 s.condBranch(cond.X, mid, no, max8(likely, 0))
3830 s.condBranch(cond.Y, yes, no, likely)
3832 // Note: if likely==1, then both recursive calls pass 1.
3833 // If likely==-1, then we don't have enough information to decide
3834 // whether the first branch is likely or not. So we pass 0 for
3835 // the likeliness of the first branch.
3836 // TODO: have the frontend give us branch prediction hints for
3837 // OANDAND and OOROR nodes (if it ever has such info).
3839 cond := cond.(*ir.LogicalExpr)
3840 mid := s.f.NewBlock(ssa.BlockPlain)
3841 s.stmtList(cond.Init())
3842 s.condBranch(cond.X, yes, mid, min8(likely, 0))
3844 s.condBranch(cond.Y, yes, no, likely)
3846 // Note: if likely==-1, then both recursive calls pass -1.
3847 // If likely==1, then we don't have enough info to decide
3848 // the likelihood of the first branch.
3850 cond := cond.(*ir.UnaryExpr)
3851 s.stmtList(cond.Init())
3852 s.condBranch(cond.X, no, yes, -likely)
3855 cond := cond.(*ir.ConvExpr)
3856 s.stmtList(cond.Init())
3857 s.condBranch(cond.X, yes, no, likely)
3862 b.Kind = ssa.BlockIf
3864 b.Likely = ssa.BranchPrediction(likely) // gc and ssa both use -1/0/+1 for likeliness
3872 skipPtr skipMask = 1 << iota
3877 // assign does left = right.
3878 // Right has already been evaluated to ssa, left has not.
3879 // If deref is true, then we do left = *right instead (and right has already been nil-checked).
3880 // If deref is true and right == nil, just do left = 0.
3881 // skip indicates assignments (at the top level) that can be avoided.
3882 // mayOverlap indicates whether left&right might partially overlap in memory. Default is false.
3883 func (s *state) assign(left ir.Node, right *ssa.Value, deref bool, skip skipMask) {
3884 s.assignWhichMayOverlap(left, right, deref, skip, false)
3886 func (s *state) assignWhichMayOverlap(left ir.Node, right *ssa.Value, deref bool, skip skipMask, mayOverlap bool) {
3887 if left.Op() == ir.ONAME && ir.IsBlank(left) {
3894 s.Fatalf("can SSA LHS %v but not RHS %s", left, right)
3896 if left.Op() == ir.ODOT {
3897 // We're assigning to a field of an ssa-able value.
3898 // We need to build a new structure with the new value for the
3899 // field we're assigning and the old values for the other fields.
3901 // type T struct {a, b, c int}
3904 // For the x.b = 5 assignment we want to generate x = T{x.a, 5, x.c}
3906 // Grab information about the structure type.
3907 left := left.(*ir.SelectorExpr)
3910 idx := fieldIdx(left)
3912 // Grab old value of structure.
3913 old := s.expr(left.X)
3915 // Make new structure.
3916 new := s.newValue0(ssa.StructMakeOp(t.NumFields()), t)
3918 // Add fields as args.
3919 for i := 0; i < nf; i++ {
3923 new.AddArg(s.newValue1I(ssa.OpStructSelect, t.FieldType(i), int64(i), old))
3927 // Recursively assign the new value we've made to the base of the dot op.
3928 s.assign(left.X, new, false, 0)
3929 // TODO: do we need to update named values here?
3932 if left.Op() == ir.OINDEX && left.(*ir.IndexExpr).X.Type().IsArray() {
3933 left := left.(*ir.IndexExpr)
3934 s.pushLine(left.Pos())
3936 // We're assigning to an element of an ssa-able array.
3941 i := s.expr(left.Index) // index
3943 // The bounds check must fail. Might as well
3944 // ignore the actual index and just use zeros.
3945 z := s.constInt(types.Types[types.TINT], 0)
3946 s.boundsCheck(z, z, ssa.BoundsIndex, false)
3950 s.Fatalf("assigning to non-1-length array")
3952 // Rewrite to a = [1]{v}
3953 len := s.constInt(types.Types[types.TINT], 1)
3954 s.boundsCheck(i, len, ssa.BoundsIndex, false) // checks i == 0
3955 v := s.newValue1(ssa.OpArrayMake1, t, right)
3956 s.assign(left.X, v, false, 0)
3959 left := left.(*ir.Name)
3960 // Update variable assignment.
3961 s.vars[left] = right
3962 s.addNamedValue(left, right)
3966 // If this assignment clobbers an entire local variable, then emit
3967 // OpVarDef so liveness analysis knows the variable is redefined.
3968 if base, ok := clobberBase(left).(*ir.Name); ok && base.OnStack() && skip == 0 && t.HasPointers() {
3969 s.vars[memVar] = s.newValue1Apos(ssa.OpVarDef, types.TypeMem, base, s.mem(), !ir.IsAutoTmp(base))
3972 // Left is not ssa-able. Compute its address.
3973 addr := s.addr(left)
3974 if ir.IsReflectHeaderDataField(left) {
3975 // Package unsafe's documentation says storing pointers into
3976 // reflect.SliceHeader and reflect.StringHeader's Data fields
3977 // is valid, even though they have type uintptr (#19168).
3978 // Mark it pointer type to signal the writebarrier pass to
3979 // insert a write barrier.
3980 t = types.Types[types.TUNSAFEPTR]
3983 // Treat as a mem->mem move.
3987 s.moveWhichMayOverlap(t, addr, right, mayOverlap)
3991 // Treat as a store.
3992 s.storeType(t, addr, right, skip, !ir.IsAutoTmp(left))
3995 // zeroVal returns the zero value for type t.
3996 func (s *state) zeroVal(t *types.Type) *ssa.Value {
4001 return s.constInt8(t, 0)
4003 return s.constInt16(t, 0)
4005 return s.constInt32(t, 0)
4007 return s.constInt64(t, 0)
4009 s.Fatalf("bad sized integer type %v", t)
4014 return s.constFloat32(t, 0)
4016 return s.constFloat64(t, 0)
4018 s.Fatalf("bad sized float type %v", t)
4023 z := s.constFloat32(types.Types[types.TFLOAT32], 0)
4024 return s.entryNewValue2(ssa.OpComplexMake, t, z, z)
4026 z := s.constFloat64(types.Types[types.TFLOAT64], 0)
4027 return s.entryNewValue2(ssa.OpComplexMake, t, z, z)
4029 s.Fatalf("bad sized complex type %v", t)
4033 return s.constEmptyString(t)
4034 case t.IsPtrShaped():
4035 return s.constNil(t)
4037 return s.constBool(false)
4038 case t.IsInterface():
4039 return s.constInterface(t)
4041 return s.constSlice(t)
4044 v := s.entryNewValue0(ssa.StructMakeOp(t.NumFields()), t)
4045 for i := 0; i < n; i++ {
4046 v.AddArg(s.zeroVal(t.FieldType(i)))
4050 switch t.NumElem() {
4052 return s.entryNewValue0(ssa.OpArrayMake0, t)
4054 return s.entryNewValue1(ssa.OpArrayMake1, t, s.zeroVal(t.Elem()))
4057 s.Fatalf("zero for type %v not implemented", t)
4064 callNormal callKind = iota
4071 type sfRtCallDef struct {
4076 var softFloatOps map[ssa.Op]sfRtCallDef
4078 func softfloatInit() {
4079 // Some of these operations get transformed by sfcall.
4080 softFloatOps = map[ssa.Op]sfRtCallDef{
4081 ssa.OpAdd32F: {typecheck.LookupRuntimeFunc("fadd32"), types.TFLOAT32},
4082 ssa.OpAdd64F: {typecheck.LookupRuntimeFunc("fadd64"), types.TFLOAT64},
4083 ssa.OpSub32F: {typecheck.LookupRuntimeFunc("fadd32"), types.TFLOAT32},
4084 ssa.OpSub64F: {typecheck.LookupRuntimeFunc("fadd64"), types.TFLOAT64},
4085 ssa.OpMul32F: {typecheck.LookupRuntimeFunc("fmul32"), types.TFLOAT32},
4086 ssa.OpMul64F: {typecheck.LookupRuntimeFunc("fmul64"), types.TFLOAT64},
4087 ssa.OpDiv32F: {typecheck.LookupRuntimeFunc("fdiv32"), types.TFLOAT32},
4088 ssa.OpDiv64F: {typecheck.LookupRuntimeFunc("fdiv64"), types.TFLOAT64},
4090 ssa.OpEq64F: {typecheck.LookupRuntimeFunc("feq64"), types.TBOOL},
4091 ssa.OpEq32F: {typecheck.LookupRuntimeFunc("feq32"), types.TBOOL},
4092 ssa.OpNeq64F: {typecheck.LookupRuntimeFunc("feq64"), types.TBOOL},
4093 ssa.OpNeq32F: {typecheck.LookupRuntimeFunc("feq32"), types.TBOOL},
4094 ssa.OpLess64F: {typecheck.LookupRuntimeFunc("fgt64"), types.TBOOL},
4095 ssa.OpLess32F: {typecheck.LookupRuntimeFunc("fgt32"), types.TBOOL},
4096 ssa.OpLeq64F: {typecheck.LookupRuntimeFunc("fge64"), types.TBOOL},
4097 ssa.OpLeq32F: {typecheck.LookupRuntimeFunc("fge32"), types.TBOOL},
4099 ssa.OpCvt32to32F: {typecheck.LookupRuntimeFunc("fint32to32"), types.TFLOAT32},
4100 ssa.OpCvt32Fto32: {typecheck.LookupRuntimeFunc("f32toint32"), types.TINT32},
4101 ssa.OpCvt64to32F: {typecheck.LookupRuntimeFunc("fint64to32"), types.TFLOAT32},
4102 ssa.OpCvt32Fto64: {typecheck.LookupRuntimeFunc("f32toint64"), types.TINT64},
4103 ssa.OpCvt64Uto32F: {typecheck.LookupRuntimeFunc("fuint64to32"), types.TFLOAT32},
4104 ssa.OpCvt32Fto64U: {typecheck.LookupRuntimeFunc("f32touint64"), types.TUINT64},
4105 ssa.OpCvt32to64F: {typecheck.LookupRuntimeFunc("fint32to64"), types.TFLOAT64},
4106 ssa.OpCvt64Fto32: {typecheck.LookupRuntimeFunc("f64toint32"), types.TINT32},
4107 ssa.OpCvt64to64F: {typecheck.LookupRuntimeFunc("fint64to64"), types.TFLOAT64},
4108 ssa.OpCvt64Fto64: {typecheck.LookupRuntimeFunc("f64toint64"), types.TINT64},
4109 ssa.OpCvt64Uto64F: {typecheck.LookupRuntimeFunc("fuint64to64"), types.TFLOAT64},
4110 ssa.OpCvt64Fto64U: {typecheck.LookupRuntimeFunc("f64touint64"), types.TUINT64},
4111 ssa.OpCvt32Fto64F: {typecheck.LookupRuntimeFunc("f32to64"), types.TFLOAT64},
4112 ssa.OpCvt64Fto32F: {typecheck.LookupRuntimeFunc("f64to32"), types.TFLOAT32},
4116 // TODO: do not emit sfcall if operation can be optimized to constant in later
4118 func (s *state) sfcall(op ssa.Op, args ...*ssa.Value) (*ssa.Value, bool) {
4119 f2i := func(t *types.Type) *types.Type {
4121 case types.TFLOAT32:
4122 return types.Types[types.TUINT32]
4123 case types.TFLOAT64:
4124 return types.Types[types.TUINT64]
4129 if callDef, ok := softFloatOps[op]; ok {
4135 args[0], args[1] = args[1], args[0]
4138 args[1] = s.newValue1(s.ssaOp(ir.ONEG, types.Types[callDef.rtype]), args[1].Type, args[1])
4141 // runtime functions take uints for floats and returns uints.
4142 // Convert to uints so we use the right calling convention.
4143 for i, a := range args {
4144 if a.Type.IsFloat() {
4145 args[i] = s.newValue1(ssa.OpCopy, f2i(a.Type), a)
4149 rt := types.Types[callDef.rtype]
4150 result := s.rtcall(callDef.rtfn, true, []*types.Type{f2i(rt)}, args...)[0]
4152 result = s.newValue1(ssa.OpCopy, rt, result)
4154 if op == ssa.OpNeq32F || op == ssa.OpNeq64F {
4155 result = s.newValue1(ssa.OpNot, result.Type, result)
4162 var intrinsics map[intrinsicKey]intrinsicBuilder
4164 // An intrinsicBuilder converts a call node n into an ssa value that
4165 // implements that call as an intrinsic. args is a list of arguments to the func.
4166 type intrinsicBuilder func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value
4168 type intrinsicKey struct {
4175 intrinsics = map[intrinsicKey]intrinsicBuilder{}
4180 var lwatomics []*sys.Arch
4181 for _, a := range &sys.Archs {
4182 all = append(all, a)
4188 if a.Family != sys.PPC64 {
4189 lwatomics = append(lwatomics, a)
4193 // add adds the intrinsic b for pkg.fn for the given list of architectures.
4194 add := func(pkg, fn string, b intrinsicBuilder, archs ...*sys.Arch) {
4195 for _, a := range archs {
4196 intrinsics[intrinsicKey{a, pkg, fn}] = b
4199 // addF does the same as add but operates on architecture families.
4200 addF := func(pkg, fn string, b intrinsicBuilder, archFamilies ...sys.ArchFamily) {
4202 for _, f := range archFamilies {
4204 panic("too many architecture families")
4208 for _, a := range all {
4209 if m>>uint(a.Family)&1 != 0 {
4210 intrinsics[intrinsicKey{a, pkg, fn}] = b
4214 // alias defines pkg.fn = pkg2.fn2 for all architectures in archs for which pkg2.fn2 exists.
4215 alias := func(pkg, fn, pkg2, fn2 string, archs ...*sys.Arch) {
4217 for _, a := range archs {
4218 if b, ok := intrinsics[intrinsicKey{a, pkg2, fn2}]; ok {
4219 intrinsics[intrinsicKey{a, pkg, fn}] = b
4224 panic(fmt.Sprintf("attempted to alias undefined intrinsic: %s.%s", pkg, fn))
4228 /******** runtime ********/
4229 if !base.Flag.Cfg.Instrumenting {
4230 add("runtime", "slicebytetostringtmp",
4231 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4232 // Compiler frontend optimizations emit OBYTES2STRTMP nodes
4233 // for the backend instead of slicebytetostringtmp calls
4234 // when not instrumenting.
4235 return s.newValue2(ssa.OpStringMake, n.Type(), args[0], args[1])
4239 addF("runtime/internal/math", "MulUintptr",
4240 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4241 if s.config.PtrSize == 4 {
4242 return s.newValue2(ssa.OpMul32uover, types.NewTuple(types.Types[types.TUINT], types.Types[types.TUINT]), args[0], args[1])
4244 return s.newValue2(ssa.OpMul64uover, types.NewTuple(types.Types[types.TUINT], types.Types[types.TUINT]), args[0], args[1])
4246 sys.AMD64, sys.I386, sys.Loong64, sys.MIPS64, sys.RISCV64, sys.ARM64)
4247 add("runtime", "KeepAlive",
4248 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4249 data := s.newValue1(ssa.OpIData, s.f.Config.Types.BytePtr, args[0])
4250 s.vars[memVar] = s.newValue2(ssa.OpKeepAlive, types.TypeMem, data, s.mem())
4254 add("runtime", "getclosureptr",
4255 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4256 return s.newValue0(ssa.OpGetClosurePtr, s.f.Config.Types.Uintptr)
4260 add("runtime", "getcallerpc",
4261 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4262 return s.newValue0(ssa.OpGetCallerPC, s.f.Config.Types.Uintptr)
4266 add("runtime", "getcallersp",
4267 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4268 return s.newValue1(ssa.OpGetCallerSP, s.f.Config.Types.Uintptr, s.mem())
4272 addF("runtime", "publicationBarrier",
4273 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4274 s.vars[memVar] = s.newValue1(ssa.OpPubBarrier, types.TypeMem, s.mem())
4277 sys.ARM64, sys.PPC64, sys.RISCV64)
4279 brev_arch := []sys.ArchFamily{sys.AMD64, sys.I386, sys.ARM64, sys.ARM, sys.S390X}
4280 if buildcfg.GOPPC64 >= 10 {
4281 // Use only on Power10 as the new byte reverse instructions that Power10 provide
4282 // make it worthwhile as an intrinsic
4283 brev_arch = append(brev_arch, sys.PPC64)
4285 /******** runtime/internal/sys ********/
4286 addF("runtime/internal/sys", "Bswap32",
4287 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4288 return s.newValue1(ssa.OpBswap32, types.Types[types.TUINT32], args[0])
4291 addF("runtime/internal/sys", "Bswap64",
4292 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4293 return s.newValue1(ssa.OpBswap64, types.Types[types.TUINT64], args[0])
4297 /****** Prefetch ******/
4298 makePrefetchFunc := func(op ssa.Op) func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4299 return func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4300 s.vars[memVar] = s.newValue2(op, types.TypeMem, args[0], s.mem())
4305 // Make Prefetch intrinsics for supported platforms
4306 // On the unsupported platforms stub function will be eliminated
4307 addF("runtime/internal/sys", "Prefetch", makePrefetchFunc(ssa.OpPrefetchCache),
4308 sys.AMD64, sys.ARM64, sys.PPC64)
4309 addF("runtime/internal/sys", "PrefetchStreamed", makePrefetchFunc(ssa.OpPrefetchCacheStreamed),
4310 sys.AMD64, sys.ARM64, sys.PPC64)
4312 /******** runtime/internal/atomic ********/
4313 addF("runtime/internal/atomic", "Load",
4314 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4315 v := s.newValue2(ssa.OpAtomicLoad32, types.NewTuple(types.Types[types.TUINT32], types.TypeMem), args[0], s.mem())
4316 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4317 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT32], v)
4319 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4320 addF("runtime/internal/atomic", "Load8",
4321 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4322 v := s.newValue2(ssa.OpAtomicLoad8, types.NewTuple(types.Types[types.TUINT8], types.TypeMem), args[0], s.mem())
4323 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4324 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT8], v)
4326 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4327 addF("runtime/internal/atomic", "Load64",
4328 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4329 v := s.newValue2(ssa.OpAtomicLoad64, types.NewTuple(types.Types[types.TUINT64], types.TypeMem), args[0], s.mem())
4330 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4331 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT64], v)
4333 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4334 addF("runtime/internal/atomic", "LoadAcq",
4335 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4336 v := s.newValue2(ssa.OpAtomicLoadAcq32, types.NewTuple(types.Types[types.TUINT32], types.TypeMem), args[0], s.mem())
4337 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4338 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT32], v)
4340 sys.PPC64, sys.S390X)
4341 addF("runtime/internal/atomic", "LoadAcq64",
4342 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4343 v := s.newValue2(ssa.OpAtomicLoadAcq64, types.NewTuple(types.Types[types.TUINT64], types.TypeMem), args[0], s.mem())
4344 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4345 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT64], v)
4348 addF("runtime/internal/atomic", "Loadp",
4349 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4350 v := s.newValue2(ssa.OpAtomicLoadPtr, types.NewTuple(s.f.Config.Types.BytePtr, types.TypeMem), args[0], s.mem())
4351 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4352 return s.newValue1(ssa.OpSelect0, s.f.Config.Types.BytePtr, v)
4354 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4356 addF("runtime/internal/atomic", "Store",
4357 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4358 s.vars[memVar] = s.newValue3(ssa.OpAtomicStore32, types.TypeMem, args[0], args[1], s.mem())
4361 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4362 addF("runtime/internal/atomic", "Store8",
4363 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4364 s.vars[memVar] = s.newValue3(ssa.OpAtomicStore8, types.TypeMem, args[0], args[1], s.mem())
4367 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4368 addF("runtime/internal/atomic", "Store64",
4369 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4370 s.vars[memVar] = s.newValue3(ssa.OpAtomicStore64, types.TypeMem, args[0], args[1], s.mem())
4373 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4374 addF("runtime/internal/atomic", "StorepNoWB",
4375 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4376 s.vars[memVar] = s.newValue3(ssa.OpAtomicStorePtrNoWB, types.TypeMem, args[0], args[1], s.mem())
4379 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.RISCV64, sys.S390X)
4380 addF("runtime/internal/atomic", "StoreRel",
4381 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4382 s.vars[memVar] = s.newValue3(ssa.OpAtomicStoreRel32, types.TypeMem, args[0], args[1], s.mem())
4385 sys.PPC64, sys.S390X)
4386 addF("runtime/internal/atomic", "StoreRel64",
4387 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4388 s.vars[memVar] = s.newValue3(ssa.OpAtomicStoreRel64, types.TypeMem, args[0], args[1], s.mem())
4393 addF("runtime/internal/atomic", "Xchg",
4394 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4395 v := s.newValue3(ssa.OpAtomicExchange32, types.NewTuple(types.Types[types.TUINT32], types.TypeMem), args[0], args[1], s.mem())
4396 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4397 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT32], v)
4399 sys.AMD64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4400 addF("runtime/internal/atomic", "Xchg64",
4401 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4402 v := s.newValue3(ssa.OpAtomicExchange64, types.NewTuple(types.Types[types.TUINT64], types.TypeMem), args[0], args[1], s.mem())
4403 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4404 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT64], v)
4406 sys.AMD64, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4408 type atomicOpEmitter func(s *state, n *ir.CallExpr, args []*ssa.Value, op ssa.Op, typ types.Kind)
4410 makeAtomicGuardedIntrinsicARM64 := func(op0, op1 ssa.Op, typ, rtyp types.Kind, emit atomicOpEmitter) intrinsicBuilder {
4412 return func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4413 // Target Atomic feature is identified by dynamic detection
4414 addr := s.entryNewValue1A(ssa.OpAddr, types.Types[types.TBOOL].PtrTo(), ir.Syms.ARM64HasATOMICS, s.sb)
4415 v := s.load(types.Types[types.TBOOL], addr)
4417 b.Kind = ssa.BlockIf
4419 bTrue := s.f.NewBlock(ssa.BlockPlain)
4420 bFalse := s.f.NewBlock(ssa.BlockPlain)
4421 bEnd := s.f.NewBlock(ssa.BlockPlain)
4424 b.Likely = ssa.BranchLikely
4426 // We have atomic instructions - use it directly.
4428 emit(s, n, args, op1, typ)
4429 s.endBlock().AddEdgeTo(bEnd)
4431 // Use original instruction sequence.
4432 s.startBlock(bFalse)
4433 emit(s, n, args, op0, typ)
4434 s.endBlock().AddEdgeTo(bEnd)
4438 if rtyp == types.TNIL {
4441 return s.variable(n, types.Types[rtyp])
4446 atomicXchgXaddEmitterARM64 := func(s *state, n *ir.CallExpr, args []*ssa.Value, op ssa.Op, typ types.Kind) {
4447 v := s.newValue3(op, types.NewTuple(types.Types[typ], types.TypeMem), args[0], args[1], s.mem())
4448 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4449 s.vars[n] = s.newValue1(ssa.OpSelect0, types.Types[typ], v)
4451 addF("runtime/internal/atomic", "Xchg",
4452 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicExchange32, ssa.OpAtomicExchange32Variant, types.TUINT32, types.TUINT32, atomicXchgXaddEmitterARM64),
4454 addF("runtime/internal/atomic", "Xchg64",
4455 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicExchange64, ssa.OpAtomicExchange64Variant, types.TUINT64, types.TUINT64, atomicXchgXaddEmitterARM64),
4458 addF("runtime/internal/atomic", "Xadd",
4459 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4460 v := s.newValue3(ssa.OpAtomicAdd32, types.NewTuple(types.Types[types.TUINT32], types.TypeMem), args[0], args[1], s.mem())
4461 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4462 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT32], v)
4464 sys.AMD64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4465 addF("runtime/internal/atomic", "Xadd64",
4466 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4467 v := s.newValue3(ssa.OpAtomicAdd64, types.NewTuple(types.Types[types.TUINT64], types.TypeMem), args[0], args[1], s.mem())
4468 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4469 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT64], v)
4471 sys.AMD64, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4473 addF("runtime/internal/atomic", "Xadd",
4474 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicAdd32, ssa.OpAtomicAdd32Variant, types.TUINT32, types.TUINT32, atomicXchgXaddEmitterARM64),
4476 addF("runtime/internal/atomic", "Xadd64",
4477 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicAdd64, ssa.OpAtomicAdd64Variant, types.TUINT64, types.TUINT64, atomicXchgXaddEmitterARM64),
4480 addF("runtime/internal/atomic", "Cas",
4481 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4482 v := s.newValue4(ssa.OpAtomicCompareAndSwap32, types.NewTuple(types.Types[types.TBOOL], types.TypeMem), args[0], args[1], args[2], s.mem())
4483 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4484 return s.newValue1(ssa.OpSelect0, types.Types[types.TBOOL], v)
4486 sys.AMD64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4487 addF("runtime/internal/atomic", "Cas64",
4488 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4489 v := s.newValue4(ssa.OpAtomicCompareAndSwap64, types.NewTuple(types.Types[types.TBOOL], types.TypeMem), args[0], args[1], args[2], s.mem())
4490 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4491 return s.newValue1(ssa.OpSelect0, types.Types[types.TBOOL], v)
4493 sys.AMD64, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4494 addF("runtime/internal/atomic", "CasRel",
4495 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4496 v := s.newValue4(ssa.OpAtomicCompareAndSwap32, types.NewTuple(types.Types[types.TBOOL], types.TypeMem), args[0], args[1], args[2], s.mem())
4497 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4498 return s.newValue1(ssa.OpSelect0, types.Types[types.TBOOL], v)
4502 atomicCasEmitterARM64 := func(s *state, n *ir.CallExpr, args []*ssa.Value, op ssa.Op, typ types.Kind) {
4503 v := s.newValue4(op, types.NewTuple(types.Types[types.TBOOL], types.TypeMem), args[0], args[1], args[2], s.mem())
4504 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4505 s.vars[n] = s.newValue1(ssa.OpSelect0, types.Types[typ], v)
4508 addF("runtime/internal/atomic", "Cas",
4509 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicCompareAndSwap32, ssa.OpAtomicCompareAndSwap32Variant, types.TUINT32, types.TBOOL, atomicCasEmitterARM64),
4511 addF("runtime/internal/atomic", "Cas64",
4512 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicCompareAndSwap64, ssa.OpAtomicCompareAndSwap64Variant, types.TUINT64, types.TBOOL, atomicCasEmitterARM64),
4515 addF("runtime/internal/atomic", "And8",
4516 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4517 s.vars[memVar] = s.newValue3(ssa.OpAtomicAnd8, types.TypeMem, args[0], args[1], s.mem())
4520 sys.AMD64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4521 addF("runtime/internal/atomic", "And",
4522 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4523 s.vars[memVar] = s.newValue3(ssa.OpAtomicAnd32, types.TypeMem, args[0], args[1], s.mem())
4526 sys.AMD64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4527 addF("runtime/internal/atomic", "Or8",
4528 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4529 s.vars[memVar] = s.newValue3(ssa.OpAtomicOr8, types.TypeMem, args[0], args[1], s.mem())
4532 sys.AMD64, sys.ARM64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4533 addF("runtime/internal/atomic", "Or",
4534 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4535 s.vars[memVar] = s.newValue3(ssa.OpAtomicOr32, types.TypeMem, args[0], args[1], s.mem())
4538 sys.AMD64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4540 atomicAndOrEmitterARM64 := func(s *state, n *ir.CallExpr, args []*ssa.Value, op ssa.Op, typ types.Kind) {
4541 s.vars[memVar] = s.newValue3(op, types.TypeMem, args[0], args[1], s.mem())
4544 addF("runtime/internal/atomic", "And8",
4545 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicAnd8, ssa.OpAtomicAnd8Variant, types.TNIL, types.TNIL, atomicAndOrEmitterARM64),
4547 addF("runtime/internal/atomic", "And",
4548 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicAnd32, ssa.OpAtomicAnd32Variant, types.TNIL, types.TNIL, atomicAndOrEmitterARM64),
4550 addF("runtime/internal/atomic", "Or8",
4551 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicOr8, ssa.OpAtomicOr8Variant, types.TNIL, types.TNIL, atomicAndOrEmitterARM64),
4553 addF("runtime/internal/atomic", "Or",
4554 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicOr32, ssa.OpAtomicOr32Variant, types.TNIL, types.TNIL, atomicAndOrEmitterARM64),
4557 // Aliases for atomic load operations
4558 alias("runtime/internal/atomic", "Loadint32", "runtime/internal/atomic", "Load", all...)
4559 alias("runtime/internal/atomic", "Loadint64", "runtime/internal/atomic", "Load64", all...)
4560 alias("runtime/internal/atomic", "Loaduintptr", "runtime/internal/atomic", "Load", p4...)
4561 alias("runtime/internal/atomic", "Loaduintptr", "runtime/internal/atomic", "Load64", p8...)
4562 alias("runtime/internal/atomic", "Loaduint", "runtime/internal/atomic", "Load", p4...)
4563 alias("runtime/internal/atomic", "Loaduint", "runtime/internal/atomic", "Load64", p8...)
4564 alias("runtime/internal/atomic", "LoadAcq", "runtime/internal/atomic", "Load", lwatomics...)
4565 alias("runtime/internal/atomic", "LoadAcq64", "runtime/internal/atomic", "Load64", lwatomics...)
4566 alias("runtime/internal/atomic", "LoadAcquintptr", "runtime/internal/atomic", "LoadAcq", p4...)
4567 alias("sync", "runtime_LoadAcquintptr", "runtime/internal/atomic", "LoadAcq", p4...) // linknamed
4568 alias("runtime/internal/atomic", "LoadAcquintptr", "runtime/internal/atomic", "LoadAcq64", p8...)
4569 alias("sync", "runtime_LoadAcquintptr", "runtime/internal/atomic", "LoadAcq64", p8...) // linknamed
4571 // Aliases for atomic store operations
4572 alias("runtime/internal/atomic", "Storeint32", "runtime/internal/atomic", "Store", all...)
4573 alias("runtime/internal/atomic", "Storeint64", "runtime/internal/atomic", "Store64", all...)
4574 alias("runtime/internal/atomic", "Storeuintptr", "runtime/internal/atomic", "Store", p4...)
4575 alias("runtime/internal/atomic", "Storeuintptr", "runtime/internal/atomic", "Store64", p8...)
4576 alias("runtime/internal/atomic", "StoreRel", "runtime/internal/atomic", "Store", lwatomics...)
4577 alias("runtime/internal/atomic", "StoreRel64", "runtime/internal/atomic", "Store64", lwatomics...)
4578 alias("runtime/internal/atomic", "StoreReluintptr", "runtime/internal/atomic", "StoreRel", p4...)
4579 alias("sync", "runtime_StoreReluintptr", "runtime/internal/atomic", "StoreRel", p4...) // linknamed
4580 alias("runtime/internal/atomic", "StoreReluintptr", "runtime/internal/atomic", "StoreRel64", p8...)
4581 alias("sync", "runtime_StoreReluintptr", "runtime/internal/atomic", "StoreRel64", p8...) // linknamed
4583 // Aliases for atomic swap operations
4584 alias("runtime/internal/atomic", "Xchgint32", "runtime/internal/atomic", "Xchg", all...)
4585 alias("runtime/internal/atomic", "Xchgint64", "runtime/internal/atomic", "Xchg64", all...)
4586 alias("runtime/internal/atomic", "Xchguintptr", "runtime/internal/atomic", "Xchg", p4...)
4587 alias("runtime/internal/atomic", "Xchguintptr", "runtime/internal/atomic", "Xchg64", p8...)
4589 // Aliases for atomic add operations
4590 alias("runtime/internal/atomic", "Xaddint32", "runtime/internal/atomic", "Xadd", all...)
4591 alias("runtime/internal/atomic", "Xaddint64", "runtime/internal/atomic", "Xadd64", all...)
4592 alias("runtime/internal/atomic", "Xadduintptr", "runtime/internal/atomic", "Xadd", p4...)
4593 alias("runtime/internal/atomic", "Xadduintptr", "runtime/internal/atomic", "Xadd64", p8...)
4595 // Aliases for atomic CAS operations
4596 alias("runtime/internal/atomic", "Casint32", "runtime/internal/atomic", "Cas", all...)
4597 alias("runtime/internal/atomic", "Casint64", "runtime/internal/atomic", "Cas64", all...)
4598 alias("runtime/internal/atomic", "Casuintptr", "runtime/internal/atomic", "Cas", p4...)
4599 alias("runtime/internal/atomic", "Casuintptr", "runtime/internal/atomic", "Cas64", p8...)
4600 alias("runtime/internal/atomic", "Casp1", "runtime/internal/atomic", "Cas", p4...)
4601 alias("runtime/internal/atomic", "Casp1", "runtime/internal/atomic", "Cas64", p8...)
4602 alias("runtime/internal/atomic", "CasRel", "runtime/internal/atomic", "Cas", lwatomics...)
4604 /******** math ********/
4605 addF("math", "sqrt",
4606 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4607 return s.newValue1(ssa.OpSqrt, types.Types[types.TFLOAT64], args[0])
4609 sys.I386, sys.AMD64, sys.ARM, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X, sys.Wasm)
4610 addF("math", "Trunc",
4611 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4612 return s.newValue1(ssa.OpTrunc, types.Types[types.TFLOAT64], args[0])
4614 sys.ARM64, sys.PPC64, sys.S390X, sys.Wasm)
4615 addF("math", "Ceil",
4616 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4617 return s.newValue1(ssa.OpCeil, types.Types[types.TFLOAT64], args[0])
4619 sys.ARM64, sys.PPC64, sys.S390X, sys.Wasm)
4620 addF("math", "Floor",
4621 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4622 return s.newValue1(ssa.OpFloor, types.Types[types.TFLOAT64], args[0])
4624 sys.ARM64, sys.PPC64, sys.S390X, sys.Wasm)
4625 addF("math", "Round",
4626 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4627 return s.newValue1(ssa.OpRound, types.Types[types.TFLOAT64], args[0])
4629 sys.ARM64, sys.PPC64, sys.S390X)
4630 addF("math", "RoundToEven",
4631 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4632 return s.newValue1(ssa.OpRoundToEven, types.Types[types.TFLOAT64], args[0])
4634 sys.ARM64, sys.S390X, sys.Wasm)
4636 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4637 return s.newValue1(ssa.OpAbs, types.Types[types.TFLOAT64], args[0])
4639 sys.ARM64, sys.ARM, sys.PPC64, sys.RISCV64, sys.Wasm, sys.MIPS, sys.MIPS64)
4640 addF("math", "Copysign",
4641 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4642 return s.newValue2(ssa.OpCopysign, types.Types[types.TFLOAT64], args[0], args[1])
4644 sys.PPC64, sys.RISCV64, sys.Wasm)
4646 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4647 return s.newValue3(ssa.OpFMA, types.Types[types.TFLOAT64], args[0], args[1], args[2])
4649 sys.ARM64, sys.PPC64, sys.RISCV64, sys.S390X)
4651 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4652 if !s.config.UseFMA {
4653 s.vars[n] = s.callResult(n, callNormal) // types.Types[TFLOAT64]
4654 return s.variable(n, types.Types[types.TFLOAT64])
4657 if buildcfg.GOAMD64 >= 3 {
4658 return s.newValue3(ssa.OpFMA, types.Types[types.TFLOAT64], args[0], args[1], args[2])
4661 v := s.entryNewValue0A(ssa.OpHasCPUFeature, types.Types[types.TBOOL], ir.Syms.X86HasFMA)
4663 b.Kind = ssa.BlockIf
4665 bTrue := s.f.NewBlock(ssa.BlockPlain)
4666 bFalse := s.f.NewBlock(ssa.BlockPlain)
4667 bEnd := s.f.NewBlock(ssa.BlockPlain)
4670 b.Likely = ssa.BranchLikely // >= haswell cpus are common
4672 // We have the intrinsic - use it directly.
4674 s.vars[n] = s.newValue3(ssa.OpFMA, types.Types[types.TFLOAT64], args[0], args[1], args[2])
4675 s.endBlock().AddEdgeTo(bEnd)
4677 // Call the pure Go version.
4678 s.startBlock(bFalse)
4679 s.vars[n] = s.callResult(n, callNormal) // types.Types[TFLOAT64]
4680 s.endBlock().AddEdgeTo(bEnd)
4684 return s.variable(n, types.Types[types.TFLOAT64])
4688 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4689 if !s.config.UseFMA {
4690 s.vars[n] = s.callResult(n, callNormal) // types.Types[TFLOAT64]
4691 return s.variable(n, types.Types[types.TFLOAT64])
4693 addr := s.entryNewValue1A(ssa.OpAddr, types.Types[types.TBOOL].PtrTo(), ir.Syms.ARMHasVFPv4, s.sb)
4694 v := s.load(types.Types[types.TBOOL], addr)
4696 b.Kind = ssa.BlockIf
4698 bTrue := s.f.NewBlock(ssa.BlockPlain)
4699 bFalse := s.f.NewBlock(ssa.BlockPlain)
4700 bEnd := s.f.NewBlock(ssa.BlockPlain)
4703 b.Likely = ssa.BranchLikely
4705 // We have the intrinsic - use it directly.
4707 s.vars[n] = s.newValue3(ssa.OpFMA, types.Types[types.TFLOAT64], args[0], args[1], args[2])
4708 s.endBlock().AddEdgeTo(bEnd)
4710 // Call the pure Go version.
4711 s.startBlock(bFalse)
4712 s.vars[n] = s.callResult(n, callNormal) // types.Types[TFLOAT64]
4713 s.endBlock().AddEdgeTo(bEnd)
4717 return s.variable(n, types.Types[types.TFLOAT64])
4721 makeRoundAMD64 := func(op ssa.Op) func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4722 return func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4723 if buildcfg.GOAMD64 >= 2 {
4724 return s.newValue1(op, types.Types[types.TFLOAT64], args[0])
4727 v := s.entryNewValue0A(ssa.OpHasCPUFeature, types.Types[types.TBOOL], ir.Syms.X86HasSSE41)
4729 b.Kind = ssa.BlockIf
4731 bTrue := s.f.NewBlock(ssa.BlockPlain)
4732 bFalse := s.f.NewBlock(ssa.BlockPlain)
4733 bEnd := s.f.NewBlock(ssa.BlockPlain)
4736 b.Likely = ssa.BranchLikely // most machines have sse4.1 nowadays
4738 // We have the intrinsic - use it directly.
4740 s.vars[n] = s.newValue1(op, types.Types[types.TFLOAT64], args[0])
4741 s.endBlock().AddEdgeTo(bEnd)
4743 // Call the pure Go version.
4744 s.startBlock(bFalse)
4745 s.vars[n] = s.callResult(n, callNormal) // types.Types[TFLOAT64]
4746 s.endBlock().AddEdgeTo(bEnd)
4750 return s.variable(n, types.Types[types.TFLOAT64])
4753 addF("math", "RoundToEven",
4754 makeRoundAMD64(ssa.OpRoundToEven),
4756 addF("math", "Floor",
4757 makeRoundAMD64(ssa.OpFloor),
4759 addF("math", "Ceil",
4760 makeRoundAMD64(ssa.OpCeil),
4762 addF("math", "Trunc",
4763 makeRoundAMD64(ssa.OpTrunc),
4766 /******** math/bits ********/
4767 addF("math/bits", "TrailingZeros64",
4768 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4769 return s.newValue1(ssa.OpCtz64, types.Types[types.TINT], args[0])
4771 sys.AMD64, sys.I386, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4772 addF("math/bits", "TrailingZeros32",
4773 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4774 return s.newValue1(ssa.OpCtz32, types.Types[types.TINT], args[0])
4776 sys.AMD64, sys.I386, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4777 addF("math/bits", "TrailingZeros16",
4778 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4779 x := s.newValue1(ssa.OpZeroExt16to32, types.Types[types.TUINT32], args[0])
4780 c := s.constInt32(types.Types[types.TUINT32], 1<<16)
4781 y := s.newValue2(ssa.OpOr32, types.Types[types.TUINT32], x, c)
4782 return s.newValue1(ssa.OpCtz32, types.Types[types.TINT], y)
4785 addF("math/bits", "TrailingZeros16",
4786 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4787 return s.newValue1(ssa.OpCtz16, types.Types[types.TINT], args[0])
4789 sys.AMD64, sys.I386, sys.ARM, sys.ARM64, sys.Wasm)
4790 addF("math/bits", "TrailingZeros16",
4791 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4792 x := s.newValue1(ssa.OpZeroExt16to64, types.Types[types.TUINT64], args[0])
4793 c := s.constInt64(types.Types[types.TUINT64], 1<<16)
4794 y := s.newValue2(ssa.OpOr64, types.Types[types.TUINT64], x, c)
4795 return s.newValue1(ssa.OpCtz64, types.Types[types.TINT], y)
4797 sys.S390X, sys.PPC64)
4798 addF("math/bits", "TrailingZeros8",
4799 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4800 x := s.newValue1(ssa.OpZeroExt8to32, types.Types[types.TUINT32], args[0])
4801 c := s.constInt32(types.Types[types.TUINT32], 1<<8)
4802 y := s.newValue2(ssa.OpOr32, types.Types[types.TUINT32], x, c)
4803 return s.newValue1(ssa.OpCtz32, types.Types[types.TINT], y)
4806 addF("math/bits", "TrailingZeros8",
4807 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4808 return s.newValue1(ssa.OpCtz8, types.Types[types.TINT], args[0])
4810 sys.AMD64, sys.I386, sys.ARM, sys.ARM64, sys.Wasm)
4811 addF("math/bits", "TrailingZeros8",
4812 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4813 x := s.newValue1(ssa.OpZeroExt8to64, types.Types[types.TUINT64], args[0])
4814 c := s.constInt64(types.Types[types.TUINT64], 1<<8)
4815 y := s.newValue2(ssa.OpOr64, types.Types[types.TUINT64], x, c)
4816 return s.newValue1(ssa.OpCtz64, types.Types[types.TINT], y)
4819 alias("math/bits", "ReverseBytes64", "runtime/internal/sys", "Bswap64", all...)
4820 alias("math/bits", "ReverseBytes32", "runtime/internal/sys", "Bswap32", all...)
4821 // ReverseBytes inlines correctly, no need to intrinsify it.
4822 // Nothing special is needed for targets where ReverseBytes16 lowers to a rotate
4823 // On Power10, 16-bit rotate is not available so use BRH instruction
4824 if buildcfg.GOPPC64 >= 10 {
4825 addF("math/bits", "ReverseBytes16",
4826 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4827 return s.newValue1(ssa.OpBswap16, types.Types[types.TUINT], args[0])
4832 addF("math/bits", "Len64",
4833 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4834 return s.newValue1(ssa.OpBitLen64, types.Types[types.TINT], args[0])
4836 sys.AMD64, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4837 addF("math/bits", "Len32",
4838 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4839 return s.newValue1(ssa.OpBitLen32, types.Types[types.TINT], args[0])
4841 sys.AMD64, sys.ARM64, sys.PPC64)
4842 addF("math/bits", "Len32",
4843 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4844 if s.config.PtrSize == 4 {
4845 return s.newValue1(ssa.OpBitLen32, types.Types[types.TINT], args[0])
4847 x := s.newValue1(ssa.OpZeroExt32to64, types.Types[types.TUINT64], args[0])
4848 return s.newValue1(ssa.OpBitLen64, types.Types[types.TINT], x)
4850 sys.ARM, sys.S390X, sys.MIPS, sys.Wasm)
4851 addF("math/bits", "Len16",
4852 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4853 if s.config.PtrSize == 4 {
4854 x := s.newValue1(ssa.OpZeroExt16to32, types.Types[types.TUINT32], args[0])
4855 return s.newValue1(ssa.OpBitLen32, types.Types[types.TINT], x)
4857 x := s.newValue1(ssa.OpZeroExt16to64, types.Types[types.TUINT64], args[0])
4858 return s.newValue1(ssa.OpBitLen64, types.Types[types.TINT], x)
4860 sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4861 addF("math/bits", "Len16",
4862 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4863 return s.newValue1(ssa.OpBitLen16, types.Types[types.TINT], args[0])
4866 addF("math/bits", "Len8",
4867 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4868 if s.config.PtrSize == 4 {
4869 x := s.newValue1(ssa.OpZeroExt8to32, types.Types[types.TUINT32], args[0])
4870 return s.newValue1(ssa.OpBitLen32, types.Types[types.TINT], x)
4872 x := s.newValue1(ssa.OpZeroExt8to64, types.Types[types.TUINT64], args[0])
4873 return s.newValue1(ssa.OpBitLen64, types.Types[types.TINT], x)
4875 sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4876 addF("math/bits", "Len8",
4877 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4878 return s.newValue1(ssa.OpBitLen8, types.Types[types.TINT], args[0])
4881 addF("math/bits", "Len",
4882 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4883 if s.config.PtrSize == 4 {
4884 return s.newValue1(ssa.OpBitLen32, types.Types[types.TINT], args[0])
4886 return s.newValue1(ssa.OpBitLen64, types.Types[types.TINT], args[0])
4888 sys.AMD64, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4889 // LeadingZeros is handled because it trivially calls Len.
4890 addF("math/bits", "Reverse64",
4891 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4892 return s.newValue1(ssa.OpBitRev64, types.Types[types.TINT], args[0])
4895 addF("math/bits", "Reverse32",
4896 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4897 return s.newValue1(ssa.OpBitRev32, types.Types[types.TINT], args[0])
4900 addF("math/bits", "Reverse16",
4901 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4902 return s.newValue1(ssa.OpBitRev16, types.Types[types.TINT], args[0])
4905 addF("math/bits", "Reverse8",
4906 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4907 return s.newValue1(ssa.OpBitRev8, types.Types[types.TINT], args[0])
4910 addF("math/bits", "Reverse",
4911 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4912 return s.newValue1(ssa.OpBitRev64, types.Types[types.TINT], args[0])
4915 addF("math/bits", "RotateLeft8",
4916 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4917 return s.newValue2(ssa.OpRotateLeft8, types.Types[types.TUINT8], args[0], args[1])
4920 addF("math/bits", "RotateLeft16",
4921 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4922 return s.newValue2(ssa.OpRotateLeft16, types.Types[types.TUINT16], args[0], args[1])
4925 addF("math/bits", "RotateLeft32",
4926 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4927 return s.newValue2(ssa.OpRotateLeft32, types.Types[types.TUINT32], args[0], args[1])
4929 sys.AMD64, sys.ARM, sys.ARM64, sys.S390X, sys.PPC64, sys.Wasm, sys.Loong64)
4930 addF("math/bits", "RotateLeft64",
4931 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4932 return s.newValue2(ssa.OpRotateLeft64, types.Types[types.TUINT64], args[0], args[1])
4934 sys.AMD64, sys.ARM64, sys.S390X, sys.PPC64, sys.Wasm, sys.Loong64)
4935 alias("math/bits", "RotateLeft", "math/bits", "RotateLeft64", p8...)
4937 makeOnesCountAMD64 := func(op ssa.Op) func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4938 return func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4939 if buildcfg.GOAMD64 >= 2 {
4940 return s.newValue1(op, types.Types[types.TINT], args[0])
4943 v := s.entryNewValue0A(ssa.OpHasCPUFeature, types.Types[types.TBOOL], ir.Syms.X86HasPOPCNT)
4945 b.Kind = ssa.BlockIf
4947 bTrue := s.f.NewBlock(ssa.BlockPlain)
4948 bFalse := s.f.NewBlock(ssa.BlockPlain)
4949 bEnd := s.f.NewBlock(ssa.BlockPlain)
4952 b.Likely = ssa.BranchLikely // most machines have popcnt nowadays
4954 // We have the intrinsic - use it directly.
4956 s.vars[n] = s.newValue1(op, types.Types[types.TINT], args[0])
4957 s.endBlock().AddEdgeTo(bEnd)
4959 // Call the pure Go version.
4960 s.startBlock(bFalse)
4961 s.vars[n] = s.callResult(n, callNormal) // types.Types[TINT]
4962 s.endBlock().AddEdgeTo(bEnd)
4966 return s.variable(n, types.Types[types.TINT])
4969 addF("math/bits", "OnesCount64",
4970 makeOnesCountAMD64(ssa.OpPopCount64),
4972 addF("math/bits", "OnesCount64",
4973 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4974 return s.newValue1(ssa.OpPopCount64, types.Types[types.TINT], args[0])
4976 sys.PPC64, sys.ARM64, sys.S390X, sys.Wasm)
4977 addF("math/bits", "OnesCount32",
4978 makeOnesCountAMD64(ssa.OpPopCount32),
4980 addF("math/bits", "OnesCount32",
4981 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4982 return s.newValue1(ssa.OpPopCount32, types.Types[types.TINT], args[0])
4984 sys.PPC64, sys.ARM64, sys.S390X, sys.Wasm)
4985 addF("math/bits", "OnesCount16",
4986 makeOnesCountAMD64(ssa.OpPopCount16),
4988 addF("math/bits", "OnesCount16",
4989 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4990 return s.newValue1(ssa.OpPopCount16, types.Types[types.TINT], args[0])
4992 sys.ARM64, sys.S390X, sys.PPC64, sys.Wasm)
4993 addF("math/bits", "OnesCount8",
4994 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4995 return s.newValue1(ssa.OpPopCount8, types.Types[types.TINT], args[0])
4997 sys.S390X, sys.PPC64, sys.Wasm)
4998 addF("math/bits", "OnesCount",
4999 makeOnesCountAMD64(ssa.OpPopCount64),
5001 addF("math/bits", "Mul64",
5002 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
5003 return s.newValue2(ssa.OpMul64uhilo, types.NewTuple(types.Types[types.TUINT64], types.Types[types.TUINT64]), args[0], args[1])
5005 sys.AMD64, sys.ARM64, sys.PPC64, sys.S390X, sys.MIPS64, sys.RISCV64, sys.Loong64)
5006 alias("math/bits", "Mul", "math/bits", "Mul64", p8...)
5007 alias("runtime/internal/math", "Mul64", "math/bits", "Mul64", p8...)
5008 addF("math/bits", "Add64",
5009 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
5010 return s.newValue3(ssa.OpAdd64carry, types.NewTuple(types.Types[types.TUINT64], types.Types[types.TUINT64]), args[0], args[1], args[2])
5012 sys.AMD64, sys.ARM64, sys.PPC64, sys.S390X, sys.RISCV64, sys.Loong64, sys.MIPS64)
5013 alias("math/bits", "Add", "math/bits", "Add64", p8...)
5014 alias("runtime/internal/math", "Add64", "math/bits", "Add64", all...)
5015 addF("math/bits", "Sub64",
5016 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
5017 return s.newValue3(ssa.OpSub64borrow, types.NewTuple(types.Types[types.TUINT64], types.Types[types.TUINT64]), args[0], args[1], args[2])
5019 sys.AMD64, sys.ARM64, sys.PPC64, sys.S390X, sys.RISCV64, sys.Loong64, sys.MIPS64)
5020 alias("math/bits", "Sub", "math/bits", "Sub64", p8...)
5021 addF("math/bits", "Div64",
5022 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
5023 // check for divide-by-zero/overflow and panic with appropriate message
5024 cmpZero := s.newValue2(s.ssaOp(ir.ONE, types.Types[types.TUINT64]), types.Types[types.TBOOL], args[2], s.zeroVal(types.Types[types.TUINT64]))
5025 s.check(cmpZero, ir.Syms.Panicdivide)
5026 cmpOverflow := s.newValue2(s.ssaOp(ir.OLT, types.Types[types.TUINT64]), types.Types[types.TBOOL], args[0], args[2])
5027 s.check(cmpOverflow, ir.Syms.Panicoverflow)
5028 return s.newValue3(ssa.OpDiv128u, types.NewTuple(types.Types[types.TUINT64], types.Types[types.TUINT64]), args[0], args[1], args[2])
5031 alias("math/bits", "Div", "math/bits", "Div64", sys.ArchAMD64)
5033 alias("runtime/internal/sys", "TrailingZeros8", "math/bits", "TrailingZeros8", all...)
5034 alias("runtime/internal/sys", "TrailingZeros32", "math/bits", "TrailingZeros32", all...)
5035 alias("runtime/internal/sys", "TrailingZeros64", "math/bits", "TrailingZeros64", all...)
5036 alias("runtime/internal/sys", "Len8", "math/bits", "Len8", all...)
5037 alias("runtime/internal/sys", "Len64", "math/bits", "Len64", all...)
5038 alias("runtime/internal/sys", "OnesCount64", "math/bits", "OnesCount64", all...)
5040 /******** sync/atomic ********/
5042 // Note: these are disabled by flag_race in findIntrinsic below.
5043 alias("sync/atomic", "LoadInt32", "runtime/internal/atomic", "Load", all...)
5044 alias("sync/atomic", "LoadInt64", "runtime/internal/atomic", "Load64", all...)
5045 alias("sync/atomic", "LoadPointer", "runtime/internal/atomic", "Loadp", all...)
5046 alias("sync/atomic", "LoadUint32", "runtime/internal/atomic", "Load", all...)
5047 alias("sync/atomic", "LoadUint64", "runtime/internal/atomic", "Load64", all...)
5048 alias("sync/atomic", "LoadUintptr", "runtime/internal/atomic", "Load", p4...)
5049 alias("sync/atomic", "LoadUintptr", "runtime/internal/atomic", "Load64", p8...)
5051 alias("sync/atomic", "StoreInt32", "runtime/internal/atomic", "Store", all...)
5052 alias("sync/atomic", "StoreInt64", "runtime/internal/atomic", "Store64", all...)
5053 // Note: not StorePointer, that needs a write barrier. Same below for {CompareAnd}Swap.
5054 alias("sync/atomic", "StoreUint32", "runtime/internal/atomic", "Store", all...)
5055 alias("sync/atomic", "StoreUint64", "runtime/internal/atomic", "Store64", all...)
5056 alias("sync/atomic", "StoreUintptr", "runtime/internal/atomic", "Store", p4...)
5057 alias("sync/atomic", "StoreUintptr", "runtime/internal/atomic", "Store64", p8...)
5059 alias("sync/atomic", "SwapInt32", "runtime/internal/atomic", "Xchg", all...)
5060 alias("sync/atomic", "SwapInt64", "runtime/internal/atomic", "Xchg64", all...)
5061 alias("sync/atomic", "SwapUint32", "runtime/internal/atomic", "Xchg", all...)
5062 alias("sync/atomic", "SwapUint64", "runtime/internal/atomic", "Xchg64", all...)
5063 alias("sync/atomic", "SwapUintptr", "runtime/internal/atomic", "Xchg", p4...)
5064 alias("sync/atomic", "SwapUintptr", "runtime/internal/atomic", "Xchg64", p8...)
5066 alias("sync/atomic", "CompareAndSwapInt32", "runtime/internal/atomic", "Cas", all...)
5067 alias("sync/atomic", "CompareAndSwapInt64", "runtime/internal/atomic", "Cas64", all...)
5068 alias("sync/atomic", "CompareAndSwapUint32", "runtime/internal/atomic", "Cas", all...)
5069 alias("sync/atomic", "CompareAndSwapUint64", "runtime/internal/atomic", "Cas64", all...)
5070 alias("sync/atomic", "CompareAndSwapUintptr", "runtime/internal/atomic", "Cas", p4...)
5071 alias("sync/atomic", "CompareAndSwapUintptr", "runtime/internal/atomic", "Cas64", p8...)
5073 alias("sync/atomic", "AddInt32", "runtime/internal/atomic", "Xadd", all...)
5074 alias("sync/atomic", "AddInt64", "runtime/internal/atomic", "Xadd64", all...)
5075 alias("sync/atomic", "AddUint32", "runtime/internal/atomic", "Xadd", all...)
5076 alias("sync/atomic", "AddUint64", "runtime/internal/atomic", "Xadd64", all...)
5077 alias("sync/atomic", "AddUintptr", "runtime/internal/atomic", "Xadd", p4...)
5078 alias("sync/atomic", "AddUintptr", "runtime/internal/atomic", "Xadd64", p8...)
5080 /******** math/big ********/
5081 alias("math/big", "mulWW", "math/bits", "Mul64", p8...)
5084 // findIntrinsic returns a function which builds the SSA equivalent of the
5085 // function identified by the symbol sym. If sym is not an intrinsic call, returns nil.
5086 func findIntrinsic(sym *types.Sym) intrinsicBuilder {
5087 if sym == nil || sym.Pkg == nil {
5091 if sym.Pkg == ir.Pkgs.Runtime {
5094 if base.Flag.Race && pkg == "sync/atomic" {
5095 // The race detector needs to be able to intercept these calls.
5096 // We can't intrinsify them.
5099 // Skip intrinsifying math functions (which may contain hard-float
5100 // instructions) when soft-float
5101 if Arch.SoftFloat && pkg == "math" {
5106 if ssa.IntrinsicsDisable {
5107 if pkg == "runtime" && (fn == "getcallerpc" || fn == "getcallersp" || fn == "getclosureptr") {
5108 // These runtime functions don't have definitions, must be intrinsics.
5113 return intrinsics[intrinsicKey{Arch.LinkArch.Arch, pkg, fn}]
5116 func IsIntrinsicCall(n *ir.CallExpr) bool {
5120 name, ok := n.Fun.(*ir.Name)
5124 return findIntrinsic(name.Sym()) != nil
5127 // intrinsicCall converts a call to a recognized intrinsic function into the intrinsic SSA operation.
5128 func (s *state) intrinsicCall(n *ir.CallExpr) *ssa.Value {
5129 v := findIntrinsic(n.Fun.Sym())(s, n, s.intrinsicArgs(n))
5130 if ssa.IntrinsicsDebug > 0 {
5135 if x.Op == ssa.OpSelect0 || x.Op == ssa.OpSelect1 {
5138 base.WarnfAt(n.Pos(), "intrinsic substitution for %v with %s", n.Fun.Sym().Name, x.LongString())
5143 // intrinsicArgs extracts args from n, evaluates them to SSA values, and returns them.
5144 func (s *state) intrinsicArgs(n *ir.CallExpr) []*ssa.Value {
5145 args := make([]*ssa.Value, len(n.Args))
5146 for i, n := range n.Args {
5152 // openDeferRecord adds code to evaluate and store the function for an open-code defer
5153 // call, and records info about the defer, so we can generate proper code on the
5154 // exit paths. n is the sub-node of the defer node that is the actual function
5155 // call. We will also record funcdata information on where the function is stored
5156 // (as well as the deferBits variable), and this will enable us to run the proper
5157 // defer calls during panics.
5158 func (s *state) openDeferRecord(n *ir.CallExpr) {
5159 if len(n.Args) != 0 || n.Op() != ir.OCALLFUNC || n.Fun.Type().NumResults() != 0 {
5160 s.Fatalf("defer call with arguments or results: %v", n)
5163 opendefer := &openDeferInfo{
5167 // We must always store the function value in a stack slot for the
5168 // runtime panic code to use. But in the defer exit code, we will
5169 // call the function directly if it is a static function.
5170 closureVal := s.expr(fn)
5171 closure := s.openDeferSave(fn.Type(), closureVal)
5172 opendefer.closureNode = closure.Aux.(*ir.Name)
5173 if !(fn.Op() == ir.ONAME && fn.(*ir.Name).Class == ir.PFUNC) {
5174 opendefer.closure = closure
5176 index := len(s.openDefers)
5177 s.openDefers = append(s.openDefers, opendefer)
5179 // Update deferBits only after evaluation and storage to stack of
5180 // the function is successful.
5181 bitvalue := s.constInt8(types.Types[types.TUINT8], 1<<uint(index))
5182 newDeferBits := s.newValue2(ssa.OpOr8, types.Types[types.TUINT8], s.variable(deferBitsVar, types.Types[types.TUINT8]), bitvalue)
5183 s.vars[deferBitsVar] = newDeferBits
5184 s.store(types.Types[types.TUINT8], s.deferBitsAddr, newDeferBits)
5187 // openDeferSave generates SSA nodes to store a value (with type t) for an
5188 // open-coded defer at an explicit autotmp location on the stack, so it can be
5189 // reloaded and used for the appropriate call on exit. Type t must be a function type
5190 // (therefore SSAable). val is the value to be stored. The function returns an SSA
5191 // value representing a pointer to the autotmp location.
5192 func (s *state) openDeferSave(t *types.Type, val *ssa.Value) *ssa.Value {
5194 s.Fatalf("openDeferSave of non-SSA-able type %v val=%v", t, val)
5196 if !t.HasPointers() {
5197 s.Fatalf("openDeferSave of pointerless type %v val=%v", t, val)
5200 temp := typecheck.TempAt(pos.WithNotStmt(), s.curfn, t)
5201 temp.SetOpenDeferSlot(true)
5202 temp.SetFrameOffset(int64(len(s.openDefers))) // so cmpstackvarlt can order them
5203 var addrTemp *ssa.Value
5204 // Use OpVarLive to make sure stack slot for the closure is not removed by
5205 // dead-store elimination
5206 if s.curBlock.ID != s.f.Entry.ID {
5207 // Force the tmp storing this defer function to be declared in the entry
5208 // block, so that it will be live for the defer exit code (which will
5209 // actually access it only if the associated defer call has been activated).
5210 if t.HasPointers() {
5211 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])
5213 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])
5214 addrTemp = s.f.Entry.NewValue2A(src.NoXPos, ssa.OpLocalAddr, types.NewPtr(temp.Type()), temp, s.sp, s.defvars[s.f.Entry.ID][memVar])
5216 // Special case if we're still in the entry block. We can't use
5217 // the above code, since s.defvars[s.f.Entry.ID] isn't defined
5218 // until we end the entry block with s.endBlock().
5219 if t.HasPointers() {
5220 s.vars[memVar] = s.newValue1Apos(ssa.OpVarDef, types.TypeMem, temp, s.mem(), false)
5222 s.vars[memVar] = s.newValue1Apos(ssa.OpVarLive, types.TypeMem, temp, s.mem(), false)
5223 addrTemp = s.newValue2Apos(ssa.OpLocalAddr, types.NewPtr(temp.Type()), temp, s.sp, s.mem(), false)
5225 // Since we may use this temp during exit depending on the
5226 // deferBits, we must define it unconditionally on entry.
5227 // Therefore, we must make sure it is zeroed out in the entry
5228 // block if it contains pointers, else GC may wrongly follow an
5229 // uninitialized pointer value.
5230 temp.SetNeedzero(true)
5231 // We are storing to the stack, hence we can avoid the full checks in
5232 // storeType() (no write barrier) and do a simple store().
5233 s.store(t, addrTemp, val)
5237 // openDeferExit generates SSA for processing all the open coded defers at exit.
5238 // The code involves loading deferBits, and checking each of the bits to see if
5239 // the corresponding defer statement was executed. For each bit that is turned
5240 // on, the associated defer call is made.
5241 func (s *state) openDeferExit() {
5242 deferExit := s.f.NewBlock(ssa.BlockPlain)
5243 s.endBlock().AddEdgeTo(deferExit)
5244 s.startBlock(deferExit)
5245 s.lastDeferExit = deferExit
5246 s.lastDeferCount = len(s.openDefers)
5247 zeroval := s.constInt8(types.Types[types.TUINT8], 0)
5248 // Test for and run defers in reverse order
5249 for i := len(s.openDefers) - 1; i >= 0; i-- {
5250 r := s.openDefers[i]
5251 bCond := s.f.NewBlock(ssa.BlockPlain)
5252 bEnd := s.f.NewBlock(ssa.BlockPlain)
5254 deferBits := s.variable(deferBitsVar, types.Types[types.TUINT8])
5255 // Generate code to check if the bit associated with the current
5257 bitval := s.constInt8(types.Types[types.TUINT8], 1<<uint(i))
5258 andval := s.newValue2(ssa.OpAnd8, types.Types[types.TUINT8], deferBits, bitval)
5259 eqVal := s.newValue2(ssa.OpEq8, types.Types[types.TBOOL], andval, zeroval)
5261 b.Kind = ssa.BlockIf
5265 bCond.AddEdgeTo(bEnd)
5268 // Clear this bit in deferBits and force store back to stack, so
5269 // we will not try to re-run this defer call if this defer call panics.
5270 nbitval := s.newValue1(ssa.OpCom8, types.Types[types.TUINT8], bitval)
5271 maskedval := s.newValue2(ssa.OpAnd8, types.Types[types.TUINT8], deferBits, nbitval)
5272 s.store(types.Types[types.TUINT8], s.deferBitsAddr, maskedval)
5273 // Use this value for following tests, so we keep previous
5275 s.vars[deferBitsVar] = maskedval
5277 // Generate code to call the function call of the defer, using the
5278 // closure that were stored in argtmps at the point of the defer
5281 stksize := fn.Type().ArgWidth()
5282 var callArgs []*ssa.Value
5284 if r.closure != nil {
5285 v := s.load(r.closure.Type.Elem(), r.closure)
5286 s.maybeNilCheckClosure(v, callDefer)
5287 codeptr := s.rawLoad(types.Types[types.TUINTPTR], v)
5288 aux := ssa.ClosureAuxCall(s.f.ABIDefault.ABIAnalyzeTypes(nil, nil))
5289 call = s.newValue2A(ssa.OpClosureLECall, aux.LateExpansionResultType(), aux, codeptr, v)
5291 aux := ssa.StaticAuxCall(fn.(*ir.Name).Linksym(), s.f.ABIDefault.ABIAnalyzeTypes(nil, nil))
5292 call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux)
5294 callArgs = append(callArgs, s.mem())
5295 call.AddArgs(callArgs...)
5296 call.AuxInt = stksize
5297 s.vars[memVar] = s.newValue1I(ssa.OpSelectN, types.TypeMem, 0, call)
5298 // Make sure that the stack slots with pointers are kept live
5299 // through the call (which is a pre-emption point). Also, we will
5300 // use the first call of the last defer exit to compute liveness
5301 // for the deferreturn, so we want all stack slots to be live.
5302 if r.closureNode != nil {
5303 s.vars[memVar] = s.newValue1Apos(ssa.OpVarLive, types.TypeMem, r.closureNode, s.mem(), false)
5311 func (s *state) callResult(n *ir.CallExpr, k callKind) *ssa.Value {
5312 return s.call(n, k, false, nil)
5315 func (s *state) callAddr(n *ir.CallExpr, k callKind) *ssa.Value {
5316 return s.call(n, k, true, nil)
5319 // Calls the function n using the specified call type.
5320 // Returns the address of the return value (or nil if none).
5321 func (s *state) call(n *ir.CallExpr, k callKind, returnResultAddr bool, deferExtra ir.Expr) *ssa.Value {
5323 var callee *ir.Name // target function (if static)
5324 var closure *ssa.Value // ptr to closure to run (if dynamic)
5325 var codeptr *ssa.Value // ptr to target code (if dynamic)
5326 var dextra *ssa.Value // defer extra arg
5327 var rcvr *ssa.Value // receiver to set
5329 var ACArgs []*types.Type // AuxCall args
5330 var ACResults []*types.Type // AuxCall results
5331 var callArgs []*ssa.Value // For late-expansion, the args themselves (not stored, args to the call instead).
5333 callABI := s.f.ABIDefault
5335 if k != callNormal && k != callTail && (len(n.Args) != 0 || n.Op() == ir.OCALLINTER || n.Fun.Type().NumResults() != 0) {
5336 s.Fatalf("go/defer call with arguments: %v", n)
5341 if (k == callNormal || k == callTail) && fn.Op() == ir.ONAME && fn.(*ir.Name).Class == ir.PFUNC {
5344 if buildcfg.Experiment.RegabiArgs {
5345 // This is a static call, so it may be
5346 // a direct call to a non-ABIInternal
5347 // function. fn.Func may be nil for
5348 // some compiler-generated functions,
5349 // but those are all ABIInternal.
5351 callABI = abiForFunc(fn.Func, s.f.ABI0, s.f.ABI1)
5354 // TODO(register args) remove after register abi is working
5355 inRegistersImported := fn.Pragma()&ir.RegisterParams != 0
5356 inRegistersSamePackage := fn.Func != nil && fn.Func.Pragma&ir.RegisterParams != 0
5357 if inRegistersImported || inRegistersSamePackage {
5363 closure = s.expr(fn)
5364 if k != callDefer && k != callDeferStack {
5365 // Deferred nil function needs to panic when the function is invoked,
5366 // not the point of defer statement.
5367 s.maybeNilCheckClosure(closure, k)
5370 if fn.Op() != ir.ODOTINTER {
5371 s.Fatalf("OCALLINTER: n.Left not an ODOTINTER: %v", fn.Op())
5373 fn := fn.(*ir.SelectorExpr)
5374 var iclosure *ssa.Value
5375 iclosure, rcvr = s.getClosureAndRcvr(fn)
5376 if k == callNormal {
5377 codeptr = s.load(types.Types[types.TUINTPTR], iclosure)
5382 if deferExtra != nil {
5383 dextra = s.expr(deferExtra)
5386 params := callABI.ABIAnalyze(n.Fun.Type(), false /* Do not set (register) nNames from caller side -- can cause races. */)
5387 types.CalcSize(fn.Type())
5388 stksize := params.ArgWidth() // includes receiver, args, and results
5390 res := n.Fun.Type().Results()
5391 if k == callNormal || k == callTail {
5392 for _, p := range params.OutParams() {
5393 ACResults = append(ACResults, p.Type)
5398 if k == callDeferStack {
5400 s.Fatalf("deferprocStack with non-zero stack size %d: %v", stksize, n)
5402 // Make a defer struct on the stack.
5404 _, addr := s.temp(n.Pos(), t)
5405 s.store(closure.Type,
5406 s.newValue1I(ssa.OpOffPtr, closure.Type.PtrTo(), t.FieldOff(deferStructFnField), addr),
5409 // Call runtime.deferprocStack with pointer to _defer record.
5410 ACArgs = append(ACArgs, types.Types[types.TUINTPTR])
5411 aux := ssa.StaticAuxCall(ir.Syms.DeferprocStack, s.f.ABIDefault.ABIAnalyzeTypes(ACArgs, ACResults))
5412 callArgs = append(callArgs, addr, s.mem())
5413 call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux)
5414 call.AddArgs(callArgs...)
5415 call.AuxInt = int64(types.PtrSize) // deferprocStack takes a *_defer arg
5417 // Store arguments to stack, including defer/go arguments and receiver for method calls.
5418 // These are written in SP-offset order.
5419 argStart := base.Ctxt.Arch.FixedFrameSize
5421 if k != callNormal && k != callTail {
5422 // Write closure (arg to newproc/deferproc).
5423 ACArgs = append(ACArgs, types.Types[types.TUINTPTR]) // not argExtra
5424 callArgs = append(callArgs, closure)
5425 stksize += int64(types.PtrSize)
5426 argStart += int64(types.PtrSize)
5428 // Extra token of type any for deferproc
5429 ACArgs = append(ACArgs, types.Types[types.TINTER])
5430 callArgs = append(callArgs, dextra)
5431 stksize += 2 * int64(types.PtrSize)
5432 argStart += 2 * int64(types.PtrSize)
5436 // Set receiver (for interface calls).
5438 callArgs = append(callArgs, rcvr)
5445 for _, p := range params.InParams() { // includes receiver for interface calls
5446 ACArgs = append(ACArgs, p.Type)
5449 // Split the entry block if there are open defers, because later calls to
5450 // openDeferSave may cause a mismatch between the mem for an OpDereference
5451 // and the call site which uses it. See #49282.
5452 if s.curBlock.ID == s.f.Entry.ID && s.hasOpenDefers {
5454 b.Kind = ssa.BlockPlain
5455 curb := s.f.NewBlock(ssa.BlockPlain)
5460 for i, n := range args {
5461 callArgs = append(callArgs, s.putArg(n, t.Param(i).Type))
5464 callArgs = append(callArgs, s.mem())
5468 case k == callDefer:
5469 sym := ir.Syms.Deferproc
5471 sym = ir.Syms.Deferprocat
5473 aux := ssa.StaticAuxCall(sym, s.f.ABIDefault.ABIAnalyzeTypes(ACArgs, ACResults)) // TODO paramResultInfo for Deferproc(at)
5474 call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux)
5476 aux := ssa.StaticAuxCall(ir.Syms.Newproc, s.f.ABIDefault.ABIAnalyzeTypes(ACArgs, ACResults))
5477 call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux) // TODO paramResultInfo for Newproc
5478 case closure != nil:
5479 // rawLoad because loading the code pointer from a
5480 // closure is always safe, but IsSanitizerSafeAddr
5481 // can't always figure that out currently, and it's
5482 // critical that we not clobber any arguments already
5483 // stored onto the stack.
5484 codeptr = s.rawLoad(types.Types[types.TUINTPTR], closure)
5485 aux := ssa.ClosureAuxCall(callABI.ABIAnalyzeTypes(ACArgs, ACResults))
5486 call = s.newValue2A(ssa.OpClosureLECall, aux.LateExpansionResultType(), aux, codeptr, closure)
5487 case codeptr != nil:
5488 // Note that the "receiver" parameter is nil because the actual receiver is the first input parameter.
5489 aux := ssa.InterfaceAuxCall(params)
5490 call = s.newValue1A(ssa.OpInterLECall, aux.LateExpansionResultType(), aux, codeptr)
5492 aux := ssa.StaticAuxCall(callTargetLSym(callee), params)
5493 call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux)
5495 call.Op = ssa.OpTailLECall
5496 stksize = 0 // Tail call does not use stack. We reuse caller's frame.
5499 s.Fatalf("bad call type %v %v", n.Op(), n)
5501 call.AddArgs(callArgs...)
5502 call.AuxInt = stksize // Call operations carry the argsize of the callee along with them
5505 s.vars[memVar] = s.newValue1I(ssa.OpSelectN, types.TypeMem, int64(len(ACResults)), call)
5506 // Insert VarLive opcodes.
5507 for _, v := range n.KeepAlive {
5509 s.Fatalf("KeepAlive variable %v must have Addrtaken set", v)
5512 case ir.PAUTO, ir.PPARAM, ir.PPARAMOUT:
5514 s.Fatalf("KeepAlive variable %v must be Auto or Arg", v)
5516 s.vars[memVar] = s.newValue1A(ssa.OpVarLive, types.TypeMem, v, s.mem())
5519 // Finish block for defers
5520 if k == callDefer || k == callDeferStack {
5522 b.Kind = ssa.BlockDefer
5524 bNext := s.f.NewBlock(ssa.BlockPlain)
5526 // Add recover edge to exit code.
5527 r := s.f.NewBlock(ssa.BlockPlain)
5531 b.Likely = ssa.BranchLikely
5535 if len(res) == 0 || k != callNormal {
5536 // call has no return value. Continue with the next statement.
5540 if returnResultAddr {
5541 return s.resultAddrOfCall(call, 0, fp.Type)
5543 return s.newValue1I(ssa.OpSelectN, fp.Type, 0, call)
5546 // maybeNilCheckClosure checks if a nil check of a closure is needed in some
5547 // architecture-dependent situations and, if so, emits the nil check.
5548 func (s *state) maybeNilCheckClosure(closure *ssa.Value, k callKind) {
5549 if Arch.LinkArch.Family == sys.Wasm || buildcfg.GOOS == "aix" && k != callGo {
5550 // 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.
5551 // TODO(neelance): On other architectures this should be eliminated by the optimization steps
5556 // getClosureAndRcvr returns values for the appropriate closure and receiver of an
5558 func (s *state) getClosureAndRcvr(fn *ir.SelectorExpr) (*ssa.Value, *ssa.Value) {
5560 itab := s.newValue1(ssa.OpITab, types.Types[types.TUINTPTR], i)
5562 itabidx := fn.Offset() + 2*int64(types.PtrSize) + 8 // offset of fun field in runtime.itab
5563 closure := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.UintptrPtr, itabidx, itab)
5564 rcvr := s.newValue1(ssa.OpIData, s.f.Config.Types.BytePtr, i)
5565 return closure, rcvr
5568 // etypesign returns the signed-ness of e, for integer/pointer etypes.
5569 // -1 means signed, +1 means unsigned, 0 means non-integer/non-pointer.
5570 func etypesign(e types.Kind) int8 {
5572 case types.TINT8, types.TINT16, types.TINT32, types.TINT64, types.TINT:
5574 case types.TUINT8, types.TUINT16, types.TUINT32, types.TUINT64, types.TUINT, types.TUINTPTR, types.TUNSAFEPTR:
5580 // addr converts the address of the expression n to SSA, adds it to s and returns the SSA result.
5581 // The value that the returned Value represents is guaranteed to be non-nil.
5582 func (s *state) addr(n ir.Node) *ssa.Value {
5583 if n.Op() != ir.ONAME {
5589 s.Fatalf("addr of canSSA expression: %+v", n)
5592 t := types.NewPtr(n.Type())
5593 linksymOffset := func(lsym *obj.LSym, offset int64) *ssa.Value {
5594 v := s.entryNewValue1A(ssa.OpAddr, t, lsym, s.sb)
5595 // TODO: Make OpAddr use AuxInt as well as Aux.
5597 v = s.entryNewValue1I(ssa.OpOffPtr, v.Type, offset, v)
5602 case ir.OLINKSYMOFFSET:
5603 no := n.(*ir.LinksymOffsetExpr)
5604 return linksymOffset(no.Linksym, no.Offset_)
5607 if n.Heapaddr != nil {
5608 return s.expr(n.Heapaddr)
5613 return linksymOffset(n.Linksym(), 0)
5620 s.Fatalf("addr of undeclared ONAME %v. declared: %v", n, s.decladdrs)
5623 return s.newValue2Apos(ssa.OpLocalAddr, t, n, s.sp, s.mem(), !ir.IsAutoTmp(n))
5625 case ir.PPARAMOUT: // Same as PAUTO -- cannot generate LEA early.
5626 // ensure that we reuse symbols for out parameters so
5627 // that cse works on their addresses
5628 return s.newValue2Apos(ssa.OpLocalAddr, t, n, s.sp, s.mem(), true)
5630 s.Fatalf("variable address class %v not implemented", n.Class)
5634 // load return from callee
5635 n := n.(*ir.ResultExpr)
5636 return s.resultAddrOfCall(s.prevCall, n.Index, n.Type())
5638 n := n.(*ir.IndexExpr)
5639 if n.X.Type().IsSlice() {
5641 i := s.expr(n.Index)
5642 len := s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], a)
5643 i = s.boundsCheck(i, len, ssa.BoundsIndex, n.Bounded())
5644 p := s.newValue1(ssa.OpSlicePtr, t, a)
5645 return s.newValue2(ssa.OpPtrIndex, t, p, i)
5648 i := s.expr(n.Index)
5649 len := s.constInt(types.Types[types.TINT], n.X.Type().NumElem())
5650 i = s.boundsCheck(i, len, ssa.BoundsIndex, n.Bounded())
5651 return s.newValue2(ssa.OpPtrIndex, types.NewPtr(n.X.Type().Elem()), a, i)
5654 n := n.(*ir.StarExpr)
5655 return s.exprPtr(n.X, n.Bounded(), n.Pos())
5657 n := n.(*ir.SelectorExpr)
5659 return s.newValue1I(ssa.OpOffPtr, t, n.Offset(), p)
5661 n := n.(*ir.SelectorExpr)
5662 p := s.exprPtr(n.X, n.Bounded(), n.Pos())
5663 return s.newValue1I(ssa.OpOffPtr, t, n.Offset(), p)
5665 n := n.(*ir.ConvExpr)
5666 if n.Type() == n.X.Type() {
5670 return s.newValue1(ssa.OpCopy, t, addr) // ensure that addr has the right type
5671 case ir.OCALLFUNC, ir.OCALLINTER:
5672 n := n.(*ir.CallExpr)
5673 return s.callAddr(n, callNormal)
5674 case ir.ODOTTYPE, ir.ODYNAMICDOTTYPE:
5676 if n.Op() == ir.ODOTTYPE {
5677 v, _ = s.dottype(n.(*ir.TypeAssertExpr), false)
5679 v, _ = s.dynamicDottype(n.(*ir.DynamicTypeAssertExpr), false)
5681 if v.Op != ssa.OpLoad {
5682 s.Fatalf("dottype of non-load")
5684 if v.Args[1] != s.mem() {
5685 s.Fatalf("memory no longer live from dottype load")
5689 s.Fatalf("unhandled addr %v", n.Op())
5694 // canSSA reports whether n is SSA-able.
5695 // n must be an ONAME (or an ODOT sequence with an ONAME base).
5696 func (s *state) canSSA(n ir.Node) bool {
5697 if base.Flag.N != 0 {
5702 if nn.Op() == ir.ODOT {
5703 nn := nn.(*ir.SelectorExpr)
5707 if nn.Op() == ir.OINDEX {
5708 nn := nn.(*ir.IndexExpr)
5709 if nn.X.Type().IsArray() {
5716 if n.Op() != ir.ONAME {
5719 return s.canSSAName(n.(*ir.Name)) && ssa.CanSSA(n.Type())
5722 func (s *state) canSSAName(name *ir.Name) bool {
5723 if name.Addrtaken() || !name.OnStack() {
5729 // TODO: handle this case? Named return values must be
5730 // in memory so that the deferred function can see them.
5731 // Maybe do: if !strings.HasPrefix(n.String(), "~") { return false }
5732 // Or maybe not, see issue 18860. Even unnamed return values
5733 // must be written back so if a defer recovers, the caller can see them.
5736 if s.cgoUnsafeArgs {
5737 // Cgo effectively takes the address of all result args,
5738 // but the compiler can't see that.
5743 // TODO: try to make more variables SSAable?
5746 // exprPtr evaluates n to a pointer and nil-checks it.
5747 func (s *state) exprPtr(n ir.Node, bounded bool, lineno src.XPos) *ssa.Value {
5749 if bounded || n.NonNil() {
5750 if s.f.Frontend().Debug_checknil() && lineno.Line() > 1 {
5751 s.f.Warnl(lineno, "removed nil check")
5759 // nilCheck generates nil pointer checking code.
5760 // Used only for automatically inserted nil checks,
5761 // not for user code like 'x != nil'.
5762 func (s *state) nilCheck(ptr *ssa.Value) {
5763 if base.Debug.DisableNil != 0 || s.curfn.NilCheckDisabled() {
5766 s.newValue2(ssa.OpNilCheck, types.TypeVoid, ptr, s.mem())
5769 // boundsCheck generates bounds checking code. Checks if 0 <= idx <[=] len, branches to exit if not.
5770 // Starts a new block on return.
5771 // On input, len must be converted to full int width and be nonnegative.
5772 // Returns idx converted to full int width.
5773 // If bounded is true then caller guarantees the index is not out of bounds
5774 // (but boundsCheck will still extend the index to full int width).
5775 func (s *state) boundsCheck(idx, len *ssa.Value, kind ssa.BoundsKind, bounded bool) *ssa.Value {
5776 idx = s.extendIndex(idx, len, kind, bounded)
5778 if bounded || base.Flag.B != 0 {
5779 // If bounded or bounds checking is flag-disabled, then no check necessary,
5780 // just return the extended index.
5782 // Here, bounded == true if the compiler generated the index itself,
5783 // such as in the expansion of a slice initializer. These indexes are
5784 // compiler-generated, not Go program variables, so they cannot be
5785 // attacker-controlled, so we can omit Spectre masking as well.
5787 // Note that we do not want to omit Spectre masking in code like:
5789 // if 0 <= i && i < len(x) {
5793 // Lucky for us, bounded==false for that code.
5794 // In that case (handled below), we emit a bound check (and Spectre mask)
5795 // and then the prove pass will remove the bounds check.
5796 // In theory the prove pass could potentially remove certain
5797 // Spectre masks, but it's very delicate and probably better
5798 // to be conservative and leave them all in.
5802 bNext := s.f.NewBlock(ssa.BlockPlain)
5803 bPanic := s.f.NewBlock(ssa.BlockExit)
5805 if !idx.Type.IsSigned() {
5807 case ssa.BoundsIndex:
5808 kind = ssa.BoundsIndexU
5809 case ssa.BoundsSliceAlen:
5810 kind = ssa.BoundsSliceAlenU
5811 case ssa.BoundsSliceAcap:
5812 kind = ssa.BoundsSliceAcapU
5813 case ssa.BoundsSliceB:
5814 kind = ssa.BoundsSliceBU
5815 case ssa.BoundsSlice3Alen:
5816 kind = ssa.BoundsSlice3AlenU
5817 case ssa.BoundsSlice3Acap:
5818 kind = ssa.BoundsSlice3AcapU
5819 case ssa.BoundsSlice3B:
5820 kind = ssa.BoundsSlice3BU
5821 case ssa.BoundsSlice3C:
5822 kind = ssa.BoundsSlice3CU
5827 if kind == ssa.BoundsIndex || kind == ssa.BoundsIndexU {
5828 cmp = s.newValue2(ssa.OpIsInBounds, types.Types[types.TBOOL], idx, len)
5830 cmp = s.newValue2(ssa.OpIsSliceInBounds, types.Types[types.TBOOL], idx, len)
5833 b.Kind = ssa.BlockIf
5835 b.Likely = ssa.BranchLikely
5839 s.startBlock(bPanic)
5840 if Arch.LinkArch.Family == sys.Wasm {
5841 // TODO(khr): figure out how to do "register" based calling convention for bounds checks.
5842 // Should be similar to gcWriteBarrier, but I can't make it work.
5843 s.rtcall(BoundsCheckFunc[kind], false, nil, idx, len)
5845 mem := s.newValue3I(ssa.OpPanicBounds, types.TypeMem, int64(kind), idx, len, s.mem())
5846 s.endBlock().SetControl(mem)
5850 // In Spectre index mode, apply an appropriate mask to avoid speculative out-of-bounds accesses.
5851 if base.Flag.Cfg.SpectreIndex {
5852 op := ssa.OpSpectreIndex
5853 if kind != ssa.BoundsIndex && kind != ssa.BoundsIndexU {
5854 op = ssa.OpSpectreSliceIndex
5856 idx = s.newValue2(op, types.Types[types.TINT], idx, len)
5862 // If cmp (a bool) is false, panic using the given function.
5863 func (s *state) check(cmp *ssa.Value, fn *obj.LSym) {
5865 b.Kind = ssa.BlockIf
5867 b.Likely = ssa.BranchLikely
5868 bNext := s.f.NewBlock(ssa.BlockPlain)
5870 pos := base.Ctxt.PosTable.Pos(line)
5871 fl := funcLine{f: fn, base: pos.Base(), line: pos.Line()}
5872 bPanic := s.panics[fl]
5874 bPanic = s.f.NewBlock(ssa.BlockPlain)
5875 s.panics[fl] = bPanic
5876 s.startBlock(bPanic)
5877 // The panic call takes/returns memory to ensure that the right
5878 // memory state is observed if the panic happens.
5879 s.rtcall(fn, false, nil)
5886 func (s *state) intDivide(n ir.Node, a, b *ssa.Value) *ssa.Value {
5889 case ssa.OpConst8, ssa.OpConst16, ssa.OpConst32, ssa.OpConst64:
5895 // do a size-appropriate check for zero
5896 cmp := s.newValue2(s.ssaOp(ir.ONE, n.Type()), types.Types[types.TBOOL], b, s.zeroVal(n.Type()))
5897 s.check(cmp, ir.Syms.Panicdivide)
5899 return s.newValue2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
5902 // rtcall issues a call to the given runtime function fn with the listed args.
5903 // Returns a slice of results of the given result types.
5904 // The call is added to the end of the current block.
5905 // If returns is false, the block is marked as an exit block.
5906 func (s *state) rtcall(fn *obj.LSym, returns bool, results []*types.Type, args ...*ssa.Value) []*ssa.Value {
5908 // Write args to the stack
5909 off := base.Ctxt.Arch.FixedFrameSize
5910 var callArgs []*ssa.Value
5911 var callArgTypes []*types.Type
5913 for _, arg := range args {
5915 off = types.RoundUp(off, t.Alignment())
5917 callArgs = append(callArgs, arg)
5918 callArgTypes = append(callArgTypes, t)
5921 off = types.RoundUp(off, int64(types.RegSize))
5925 aux := ssa.StaticAuxCall(fn, s.f.ABIDefault.ABIAnalyzeTypes(callArgTypes, results))
5926 callArgs = append(callArgs, s.mem())
5927 call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux)
5928 call.AddArgs(callArgs...)
5929 s.vars[memVar] = s.newValue1I(ssa.OpSelectN, types.TypeMem, int64(len(results)), call)
5934 b.Kind = ssa.BlockExit
5936 call.AuxInt = off - base.Ctxt.Arch.FixedFrameSize
5937 if len(results) > 0 {
5938 s.Fatalf("panic call can't have results")
5944 res := make([]*ssa.Value, len(results))
5945 for i, t := range results {
5946 off = types.RoundUp(off, t.Alignment())
5947 res[i] = s.resultOfCall(call, int64(i), t)
5950 off = types.RoundUp(off, int64(types.PtrSize))
5952 // Remember how much callee stack space we needed.
5958 // do *left = right for type t.
5959 func (s *state) storeType(t *types.Type, left, right *ssa.Value, skip skipMask, leftIsStmt bool) {
5960 s.instrument(t, left, instrumentWrite)
5962 if skip == 0 && (!t.HasPointers() || ssa.IsStackAddr(left)) {
5963 // Known to not have write barrier. Store the whole type.
5964 s.vars[memVar] = s.newValue3Apos(ssa.OpStore, types.TypeMem, t, left, right, s.mem(), leftIsStmt)
5968 // store scalar fields first, so write barrier stores for
5969 // pointer fields can be grouped together, and scalar values
5970 // don't need to be live across the write barrier call.
5971 // TODO: if the writebarrier pass knows how to reorder stores,
5972 // we can do a single store here as long as skip==0.
5973 s.storeTypeScalars(t, left, right, skip)
5974 if skip&skipPtr == 0 && t.HasPointers() {
5975 s.storeTypePtrs(t, left, right)
5979 // do *left = right for all scalar (non-pointer) parts of t.
5980 func (s *state) storeTypeScalars(t *types.Type, left, right *ssa.Value, skip skipMask) {
5982 case t.IsBoolean() || t.IsInteger() || t.IsFloat() || t.IsComplex():
5983 s.store(t, left, right)
5984 case t.IsPtrShaped():
5985 if t.IsPtr() && t.Elem().NotInHeap() {
5986 s.store(t, left, right) // see issue 42032
5988 // otherwise, no scalar fields.
5990 if skip&skipLen != 0 {
5993 len := s.newValue1(ssa.OpStringLen, types.Types[types.TINT], right)
5994 lenAddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, s.config.PtrSize, left)
5995 s.store(types.Types[types.TINT], lenAddr, len)
5997 if skip&skipLen == 0 {
5998 len := s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], right)
5999 lenAddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, s.config.PtrSize, left)
6000 s.store(types.Types[types.TINT], lenAddr, len)
6002 if skip&skipCap == 0 {
6003 cap := s.newValue1(ssa.OpSliceCap, types.Types[types.TINT], right)
6004 capAddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, 2*s.config.PtrSize, left)
6005 s.store(types.Types[types.TINT], capAddr, cap)
6007 case t.IsInterface():
6008 // itab field doesn't need a write barrier (even though it is a pointer).
6009 itab := s.newValue1(ssa.OpITab, s.f.Config.Types.BytePtr, right)
6010 s.store(types.Types[types.TUINTPTR], left, itab)
6013 for i := 0; i < n; i++ {
6014 ft := t.FieldType(i)
6015 addr := s.newValue1I(ssa.OpOffPtr, ft.PtrTo(), t.FieldOff(i), left)
6016 val := s.newValue1I(ssa.OpStructSelect, ft, int64(i), right)
6017 s.storeTypeScalars(ft, addr, val, 0)
6019 case t.IsArray() && t.NumElem() == 0:
6021 case t.IsArray() && t.NumElem() == 1:
6022 s.storeTypeScalars(t.Elem(), left, s.newValue1I(ssa.OpArraySelect, t.Elem(), 0, right), 0)
6024 s.Fatalf("bad write barrier type %v", t)
6028 // do *left = right for all pointer parts of t.
6029 func (s *state) storeTypePtrs(t *types.Type, left, right *ssa.Value) {
6031 case t.IsPtrShaped():
6032 if t.IsPtr() && t.Elem().NotInHeap() {
6033 break // see issue 42032
6035 s.store(t, left, right)
6037 ptr := s.newValue1(ssa.OpStringPtr, s.f.Config.Types.BytePtr, right)
6038 s.store(s.f.Config.Types.BytePtr, left, ptr)
6040 elType := types.NewPtr(t.Elem())
6041 ptr := s.newValue1(ssa.OpSlicePtr, elType, right)
6042 s.store(elType, left, ptr)
6043 case t.IsInterface():
6044 // itab field is treated as a scalar.
6045 idata := s.newValue1(ssa.OpIData, s.f.Config.Types.BytePtr, right)
6046 idataAddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.BytePtrPtr, s.config.PtrSize, left)
6047 s.store(s.f.Config.Types.BytePtr, idataAddr, idata)
6050 for i := 0; i < n; i++ {
6051 ft := t.FieldType(i)
6052 if !ft.HasPointers() {
6055 addr := s.newValue1I(ssa.OpOffPtr, ft.PtrTo(), t.FieldOff(i), left)
6056 val := s.newValue1I(ssa.OpStructSelect, ft, int64(i), right)
6057 s.storeTypePtrs(ft, addr, val)
6059 case t.IsArray() && t.NumElem() == 0:
6061 case t.IsArray() && t.NumElem() == 1:
6062 s.storeTypePtrs(t.Elem(), left, s.newValue1I(ssa.OpArraySelect, t.Elem(), 0, right))
6064 s.Fatalf("bad write barrier type %v", t)
6068 // putArg evaluates n for the purpose of passing it as an argument to a function and returns the value for the call.
6069 func (s *state) putArg(n ir.Node, t *types.Type) *ssa.Value {
6072 a = s.newValue2(ssa.OpDereference, t, s.addr(n), s.mem())
6079 func (s *state) storeArgWithBase(n ir.Node, t *types.Type, base *ssa.Value, off int64) {
6080 pt := types.NewPtr(t)
6083 // Use special routine that avoids allocation on duplicate offsets.
6084 addr = s.constOffPtrSP(pt, off)
6086 addr = s.newValue1I(ssa.OpOffPtr, pt, off, base)
6096 s.storeType(t, addr, a, 0, false)
6099 // slice computes the slice v[i:j:k] and returns ptr, len, and cap of result.
6100 // i,j,k may be nil, in which case they are set to their default value.
6101 // v may be a slice, string or pointer to an array.
6102 func (s *state) slice(v, i, j, k *ssa.Value, bounded bool) (p, l, c *ssa.Value) {
6104 var ptr, len, cap *ssa.Value
6107 ptr = s.newValue1(ssa.OpSlicePtr, types.NewPtr(t.Elem()), v)
6108 len = s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], v)
6109 cap = s.newValue1(ssa.OpSliceCap, types.Types[types.TINT], v)
6111 ptr = s.newValue1(ssa.OpStringPtr, types.NewPtr(types.Types[types.TUINT8]), v)
6112 len = s.newValue1(ssa.OpStringLen, types.Types[types.TINT], v)
6115 if !t.Elem().IsArray() {
6116 s.Fatalf("bad ptr to array in slice %v\n", t)
6119 ptr = s.newValue1(ssa.OpCopy, types.NewPtr(t.Elem().Elem()), v)
6120 len = s.constInt(types.Types[types.TINT], t.Elem().NumElem())
6123 s.Fatalf("bad type in slice %v\n", t)
6126 // Set default values
6128 i = s.constInt(types.Types[types.TINT], 0)
6139 // Panic if slice indices are not in bounds.
6140 // Make sure we check these in reverse order so that we're always
6141 // comparing against a value known to be nonnegative. See issue 28797.
6144 kind := ssa.BoundsSlice3Alen
6146 kind = ssa.BoundsSlice3Acap
6148 k = s.boundsCheck(k, cap, kind, bounded)
6151 j = s.boundsCheck(j, k, ssa.BoundsSlice3B, bounded)
6153 i = s.boundsCheck(i, j, ssa.BoundsSlice3C, bounded)
6156 kind := ssa.BoundsSliceAlen
6158 kind = ssa.BoundsSliceAcap
6160 j = s.boundsCheck(j, k, kind, bounded)
6162 i = s.boundsCheck(i, j, ssa.BoundsSliceB, bounded)
6165 // Word-sized integer operations.
6166 subOp := s.ssaOp(ir.OSUB, types.Types[types.TINT])
6167 mulOp := s.ssaOp(ir.OMUL, types.Types[types.TINT])
6168 andOp := s.ssaOp(ir.OAND, types.Types[types.TINT])
6170 // Calculate the length (rlen) and capacity (rcap) of the new slice.
6171 // For strings the capacity of the result is unimportant. However,
6172 // we use rcap to test if we've generated a zero-length slice.
6173 // Use length of strings for that.
6174 rlen := s.newValue2(subOp, types.Types[types.TINT], j, i)
6176 if j != k && !t.IsString() {
6177 rcap = s.newValue2(subOp, types.Types[types.TINT], k, i)
6180 if (i.Op == ssa.OpConst64 || i.Op == ssa.OpConst32) && i.AuxInt == 0 {
6181 // No pointer arithmetic necessary.
6182 return ptr, rlen, rcap
6185 // Calculate the base pointer (rptr) for the new slice.
6187 // Generate the following code assuming that indexes are in bounds.
6188 // The masking is to make sure that we don't generate a slice
6189 // that points to the next object in memory. We cannot just set
6190 // the pointer to nil because then we would create a nil slice or
6195 // rptr = ptr + (mask(rcap) & (i * stride))
6197 // Where mask(x) is 0 if x==0 and -1 if x>0 and stride is the width
6198 // of the element type.
6199 stride := s.constInt(types.Types[types.TINT], ptr.Type.Elem().Size())
6201 // The delta is the number of bytes to offset ptr by.
6202 delta := s.newValue2(mulOp, types.Types[types.TINT], i, stride)
6204 // If we're slicing to the point where the capacity is zero,
6205 // zero out the delta.
6206 mask := s.newValue1(ssa.OpSlicemask, types.Types[types.TINT], rcap)
6207 delta = s.newValue2(andOp, types.Types[types.TINT], delta, mask)
6209 // Compute rptr = ptr + delta.
6210 rptr := s.newValue2(ssa.OpAddPtr, ptr.Type, ptr, delta)
6212 return rptr, rlen, rcap
6215 type u642fcvtTab struct {
6216 leq, cvt2F, and, rsh, or, add ssa.Op
6217 one func(*state, *types.Type, int64) *ssa.Value
6220 var u64_f64 = u642fcvtTab{
6222 cvt2F: ssa.OpCvt64to64F,
6224 rsh: ssa.OpRsh64Ux64,
6227 one: (*state).constInt64,
6230 var u64_f32 = u642fcvtTab{
6232 cvt2F: ssa.OpCvt64to32F,
6234 rsh: ssa.OpRsh64Ux64,
6237 one: (*state).constInt64,
6240 func (s *state) uint64Tofloat64(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6241 return s.uint64Tofloat(&u64_f64, n, x, ft, tt)
6244 func (s *state) uint64Tofloat32(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6245 return s.uint64Tofloat(&u64_f32, n, x, ft, tt)
6248 func (s *state) uint64Tofloat(cvttab *u642fcvtTab, n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6250 // result = (floatY) x
6252 // y = uintX(x) ; y = x & 1
6253 // z = uintX(x) ; z = z >> 1
6255 // result = floatY(z)
6256 // result = result + result
6259 // Code borrowed from old code generator.
6260 // What's going on: large 64-bit "unsigned" looks like
6261 // negative number to hardware's integer-to-float
6262 // conversion. However, because the mantissa is only
6263 // 63 bits, we don't need the LSB, so instead we do an
6264 // unsigned right shift (divide by two), convert, and
6265 // double. However, before we do that, we need to be
6266 // sure that we do not lose a "1" if that made the
6267 // difference in the resulting rounding. Therefore, we
6268 // preserve it, and OR (not ADD) it back in. The case
6269 // that matters is when the eleven discarded bits are
6270 // equal to 10000000001; that rounds up, and the 1 cannot
6271 // be lost else it would round down if the LSB of the
6272 // candidate mantissa is 0.
6273 cmp := s.newValue2(cvttab.leq, types.Types[types.TBOOL], s.zeroVal(ft), x)
6275 b.Kind = ssa.BlockIf
6277 b.Likely = ssa.BranchLikely
6279 bThen := s.f.NewBlock(ssa.BlockPlain)
6280 bElse := s.f.NewBlock(ssa.BlockPlain)
6281 bAfter := s.f.NewBlock(ssa.BlockPlain)
6285 a0 := s.newValue1(cvttab.cvt2F, tt, x)
6288 bThen.AddEdgeTo(bAfter)
6292 one := cvttab.one(s, ft, 1)
6293 y := s.newValue2(cvttab.and, ft, x, one)
6294 z := s.newValue2(cvttab.rsh, ft, x, one)
6295 z = s.newValue2(cvttab.or, ft, z, y)
6296 a := s.newValue1(cvttab.cvt2F, tt, z)
6297 a1 := s.newValue2(cvttab.add, tt, a, a)
6300 bElse.AddEdgeTo(bAfter)
6302 s.startBlock(bAfter)
6303 return s.variable(n, n.Type())
6306 type u322fcvtTab struct {
6307 cvtI2F, cvtF2F ssa.Op
6310 var u32_f64 = u322fcvtTab{
6311 cvtI2F: ssa.OpCvt32to64F,
6315 var u32_f32 = u322fcvtTab{
6316 cvtI2F: ssa.OpCvt32to32F,
6317 cvtF2F: ssa.OpCvt64Fto32F,
6320 func (s *state) uint32Tofloat64(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6321 return s.uint32Tofloat(&u32_f64, n, x, ft, tt)
6324 func (s *state) uint32Tofloat32(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6325 return s.uint32Tofloat(&u32_f32, n, x, ft, tt)
6328 func (s *state) uint32Tofloat(cvttab *u322fcvtTab, n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6330 // result = floatY(x)
6332 // result = floatY(float64(x) + (1<<32))
6334 cmp := s.newValue2(ssa.OpLeq32, types.Types[types.TBOOL], s.zeroVal(ft), x)
6336 b.Kind = ssa.BlockIf
6338 b.Likely = ssa.BranchLikely
6340 bThen := s.f.NewBlock(ssa.BlockPlain)
6341 bElse := s.f.NewBlock(ssa.BlockPlain)
6342 bAfter := s.f.NewBlock(ssa.BlockPlain)
6346 a0 := s.newValue1(cvttab.cvtI2F, tt, x)
6349 bThen.AddEdgeTo(bAfter)
6353 a1 := s.newValue1(ssa.OpCvt32to64F, types.Types[types.TFLOAT64], x)
6354 twoToThe32 := s.constFloat64(types.Types[types.TFLOAT64], float64(1<<32))
6355 a2 := s.newValue2(ssa.OpAdd64F, types.Types[types.TFLOAT64], a1, twoToThe32)
6356 a3 := s.newValue1(cvttab.cvtF2F, tt, a2)
6360 bElse.AddEdgeTo(bAfter)
6362 s.startBlock(bAfter)
6363 return s.variable(n, n.Type())
6366 // referenceTypeBuiltin generates code for the len/cap builtins for maps and channels.
6367 func (s *state) referenceTypeBuiltin(n *ir.UnaryExpr, x *ssa.Value) *ssa.Value {
6368 if !n.X.Type().IsMap() && !n.X.Type().IsChan() {
6369 s.Fatalf("node must be a map or a channel")
6375 // return *((*int)n)
6377 // return *(((*int)n)+1)
6380 nilValue := s.constNil(types.Types[types.TUINTPTR])
6381 cmp := s.newValue2(ssa.OpEqPtr, types.Types[types.TBOOL], x, nilValue)
6383 b.Kind = ssa.BlockIf
6385 b.Likely = ssa.BranchUnlikely
6387 bThen := s.f.NewBlock(ssa.BlockPlain)
6388 bElse := s.f.NewBlock(ssa.BlockPlain)
6389 bAfter := s.f.NewBlock(ssa.BlockPlain)
6391 // length/capacity of a nil map/chan is zero
6394 s.vars[n] = s.zeroVal(lenType)
6396 bThen.AddEdgeTo(bAfter)
6402 // length is stored in the first word for map/chan
6403 s.vars[n] = s.load(lenType, x)
6405 // capacity is stored in the second word for chan
6406 sw := s.newValue1I(ssa.OpOffPtr, lenType.PtrTo(), lenType.Size(), x)
6407 s.vars[n] = s.load(lenType, sw)
6409 s.Fatalf("op must be OLEN or OCAP")
6412 bElse.AddEdgeTo(bAfter)
6414 s.startBlock(bAfter)
6415 return s.variable(n, lenType)
6418 type f2uCvtTab struct {
6419 ltf, cvt2U, subf, or ssa.Op
6420 floatValue func(*state, *types.Type, float64) *ssa.Value
6421 intValue func(*state, *types.Type, int64) *ssa.Value
6425 var f32_u64 = f2uCvtTab{
6427 cvt2U: ssa.OpCvt32Fto64,
6430 floatValue: (*state).constFloat32,
6431 intValue: (*state).constInt64,
6435 var f64_u64 = f2uCvtTab{
6437 cvt2U: ssa.OpCvt64Fto64,
6440 floatValue: (*state).constFloat64,
6441 intValue: (*state).constInt64,
6445 var f32_u32 = f2uCvtTab{
6447 cvt2U: ssa.OpCvt32Fto32,
6450 floatValue: (*state).constFloat32,
6451 intValue: func(s *state, t *types.Type, v int64) *ssa.Value { return s.constInt32(t, int32(v)) },
6455 var f64_u32 = f2uCvtTab{
6457 cvt2U: ssa.OpCvt64Fto32,
6460 floatValue: (*state).constFloat64,
6461 intValue: func(s *state, t *types.Type, v int64) *ssa.Value { return s.constInt32(t, int32(v)) },
6465 func (s *state) float32ToUint64(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6466 return s.floatToUint(&f32_u64, n, x, ft, tt)
6468 func (s *state) float64ToUint64(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6469 return s.floatToUint(&f64_u64, n, x, ft, tt)
6472 func (s *state) float32ToUint32(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6473 return s.floatToUint(&f32_u32, n, x, ft, tt)
6476 func (s *state) float64ToUint32(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6477 return s.floatToUint(&f64_u32, n, x, ft, tt)
6480 func (s *state) floatToUint(cvttab *f2uCvtTab, n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6481 // cutoff:=1<<(intY_Size-1)
6482 // if x < floatX(cutoff) {
6483 // result = uintY(x)
6485 // y = x - floatX(cutoff)
6487 // result = z | -(cutoff)
6489 cutoff := cvttab.floatValue(s, ft, float64(cvttab.cutoff))
6490 cmp := s.newValue2(cvttab.ltf, types.Types[types.TBOOL], x, cutoff)
6492 b.Kind = ssa.BlockIf
6494 b.Likely = ssa.BranchLikely
6496 bThen := s.f.NewBlock(ssa.BlockPlain)
6497 bElse := s.f.NewBlock(ssa.BlockPlain)
6498 bAfter := s.f.NewBlock(ssa.BlockPlain)
6502 a0 := s.newValue1(cvttab.cvt2U, tt, x)
6505 bThen.AddEdgeTo(bAfter)
6509 y := s.newValue2(cvttab.subf, ft, x, cutoff)
6510 y = s.newValue1(cvttab.cvt2U, tt, y)
6511 z := cvttab.intValue(s, tt, int64(-cvttab.cutoff))
6512 a1 := s.newValue2(cvttab.or, tt, y, z)
6515 bElse.AddEdgeTo(bAfter)
6517 s.startBlock(bAfter)
6518 return s.variable(n, n.Type())
6521 // dottype generates SSA for a type assertion node.
6522 // commaok indicates whether to panic or return a bool.
6523 // If commaok is false, resok will be nil.
6524 func (s *state) dottype(n *ir.TypeAssertExpr, commaok bool) (res, resok *ssa.Value) {
6525 iface := s.expr(n.X) // input interface
6526 target := s.reflectType(n.Type()) // target type
6527 var targetItab *ssa.Value
6529 targetItab = s.expr(n.ITab)
6531 return s.dottype1(n.Pos(), n.X.Type(), n.Type(), iface, nil, target, targetItab, commaok)
6534 func (s *state) dynamicDottype(n *ir.DynamicTypeAssertExpr, commaok bool) (res, resok *ssa.Value) {
6535 iface := s.expr(n.X)
6536 var source, target, targetItab *ssa.Value
6537 if n.SrcRType != nil {
6538 source = s.expr(n.SrcRType)
6540 if !n.X.Type().IsEmptyInterface() && !n.Type().IsInterface() {
6541 byteptr := s.f.Config.Types.BytePtr
6542 targetItab = s.expr(n.ITab)
6543 // TODO(mdempsky): Investigate whether compiling n.RType could be
6544 // better than loading itab.typ.
6545 target = s.load(byteptr, s.newValue1I(ssa.OpOffPtr, byteptr, int64(types.PtrSize), targetItab)) // itab.typ
6547 target = s.expr(n.RType)
6549 return s.dottype1(n.Pos(), n.X.Type(), n.Type(), iface, source, target, targetItab, commaok)
6552 // dottype1 implements a x.(T) operation. iface is the argument (x), dst is the type we're asserting to (T)
6553 // and src is the type we're asserting from.
6554 // source is the *runtime._type of src
6555 // target is the *runtime._type of dst.
6556 // If src is a nonempty interface and dst is not an interface, targetItab is an itab representing (dst, src). Otherwise it is nil.
6557 // commaok is true if the caller wants a boolean success value. Otherwise, the generated code panics if the conversion fails.
6558 func (s *state) dottype1(pos src.XPos, src, dst *types.Type, iface, source, target, targetItab *ssa.Value, commaok bool) (res, resok *ssa.Value) {
6559 byteptr := s.f.Config.Types.BytePtr
6560 if dst.IsInterface() {
6561 if dst.IsEmptyInterface() {
6562 // Converting to an empty interface.
6563 // Input could be an empty or nonempty interface.
6564 if base.Debug.TypeAssert > 0 {
6565 base.WarnfAt(pos, "type assertion inlined")
6568 // Get itab/type field from input.
6569 itab := s.newValue1(ssa.OpITab, byteptr, iface)
6570 // Conversion succeeds iff that field is not nil.
6571 cond := s.newValue2(ssa.OpNeqPtr, types.Types[types.TBOOL], itab, s.constNil(byteptr))
6573 if src.IsEmptyInterface() && commaok {
6574 // Converting empty interface to empty interface with ,ok is just a nil check.
6578 // Branch on nilness.
6580 b.Kind = ssa.BlockIf
6582 b.Likely = ssa.BranchLikely
6583 bOk := s.f.NewBlock(ssa.BlockPlain)
6584 bFail := s.f.NewBlock(ssa.BlockPlain)
6589 // On failure, panic by calling panicnildottype.
6591 s.rtcall(ir.Syms.Panicnildottype, false, nil, target)
6593 // On success, return (perhaps modified) input interface.
6595 if src.IsEmptyInterface() {
6596 res = iface // Use input interface unchanged.
6599 // Load type out of itab, build interface with existing idata.
6600 off := s.newValue1I(ssa.OpOffPtr, byteptr, int64(types.PtrSize), itab)
6601 typ := s.load(byteptr, off)
6602 idata := s.newValue1(ssa.OpIData, byteptr, iface)
6603 res = s.newValue2(ssa.OpIMake, dst, typ, idata)
6608 // nonempty -> empty
6609 // Need to load type from itab
6610 off := s.newValue1I(ssa.OpOffPtr, byteptr, int64(types.PtrSize), itab)
6611 s.vars[typVar] = s.load(byteptr, off)
6614 // itab is nil, might as well use that as the nil result.
6616 s.vars[typVar] = itab
6620 bEnd := s.f.NewBlock(ssa.BlockPlain)
6622 bFail.AddEdgeTo(bEnd)
6624 idata := s.newValue1(ssa.OpIData, byteptr, iface)
6625 res = s.newValue2(ssa.OpIMake, dst, s.variable(typVar, byteptr), idata)
6627 delete(s.vars, typVar) // no practical effect, just to indicate typVar is no longer live.
6630 // converting to a nonempty interface needs a runtime call.
6631 if base.Debug.TypeAssert > 0 {
6632 base.WarnfAt(pos, "type assertion not inlined")
6635 fn := ir.Syms.AssertI2I
6636 if src.IsEmptyInterface() {
6637 fn = ir.Syms.AssertE2I
6639 data := s.newValue1(ssa.OpIData, types.Types[types.TUNSAFEPTR], iface)
6640 tab := s.newValue1(ssa.OpITab, byteptr, iface)
6641 tab = s.rtcall(fn, true, []*types.Type{byteptr}, target, tab)[0]
6642 return s.newValue2(ssa.OpIMake, dst, tab, data), nil
6644 fn := ir.Syms.AssertI2I2
6645 if src.IsEmptyInterface() {
6646 fn = ir.Syms.AssertE2I2
6648 res = s.rtcall(fn, true, []*types.Type{dst}, target, iface)[0]
6649 resok = s.newValue2(ssa.OpNeqInter, types.Types[types.TBOOL], res, s.constInterface(dst))
6653 if base.Debug.TypeAssert > 0 {
6654 base.WarnfAt(pos, "type assertion inlined")
6657 // Converting to a concrete type.
6658 direct := types.IsDirectIface(dst)
6659 itab := s.newValue1(ssa.OpITab, byteptr, iface) // type word of interface
6660 if base.Debug.TypeAssert > 0 {
6661 base.WarnfAt(pos, "type assertion inlined")
6663 var wantedFirstWord *ssa.Value
6664 if src.IsEmptyInterface() {
6665 // Looking for pointer to target type.
6666 wantedFirstWord = target
6668 // Looking for pointer to itab for target type and source interface.
6669 wantedFirstWord = targetItab
6672 var tmp ir.Node // temporary for use with large types
6673 var addr *ssa.Value // address of tmp
6674 if commaok && !ssa.CanSSA(dst) {
6675 // unSSAable type, use temporary.
6676 // TODO: get rid of some of these temporaries.
6677 tmp, addr = s.temp(pos, dst)
6680 cond := s.newValue2(ssa.OpEqPtr, types.Types[types.TBOOL], itab, wantedFirstWord)
6682 b.Kind = ssa.BlockIf
6684 b.Likely = ssa.BranchLikely
6686 bOk := s.f.NewBlock(ssa.BlockPlain)
6687 bFail := s.f.NewBlock(ssa.BlockPlain)
6692 // on failure, panic by calling panicdottype
6696 taddr = s.reflectType(src)
6698 if src.IsEmptyInterface() {
6699 s.rtcall(ir.Syms.PanicdottypeE, false, nil, itab, target, taddr)
6701 s.rtcall(ir.Syms.PanicdottypeI, false, nil, itab, target, taddr)
6704 // on success, return data from interface
6707 return s.newValue1(ssa.OpIData, dst, iface), nil
6709 p := s.newValue1(ssa.OpIData, types.NewPtr(dst), iface)
6710 return s.load(dst, p), nil
6713 // commaok is the more complicated case because we have
6714 // a control flow merge point.
6715 bEnd := s.f.NewBlock(ssa.BlockPlain)
6716 // Note that we need a new valVar each time (unlike okVar where we can
6717 // reuse the variable) because it might have a different type every time.
6718 valVar := ssaMarker("val")
6720 // type assertion succeeded
6724 s.vars[valVar] = s.newValue1(ssa.OpIData, dst, iface)
6726 p := s.newValue1(ssa.OpIData, types.NewPtr(dst), iface)
6727 s.vars[valVar] = s.load(dst, p)
6730 p := s.newValue1(ssa.OpIData, types.NewPtr(dst), iface)
6731 s.move(dst, addr, p)
6733 s.vars[okVar] = s.constBool(true)
6737 // type assertion failed
6740 s.vars[valVar] = s.zeroVal(dst)
6744 s.vars[okVar] = s.constBool(false)
6746 bFail.AddEdgeTo(bEnd)
6751 res = s.variable(valVar, dst)
6752 delete(s.vars, valVar) // no practical effect, just to indicate typVar is no longer live.
6754 res = s.load(dst, addr)
6756 resok = s.variable(okVar, types.Types[types.TBOOL])
6757 delete(s.vars, okVar) // ditto
6761 // temp allocates a temp of type t at position pos
6762 func (s *state) temp(pos src.XPos, t *types.Type) (*ir.Name, *ssa.Value) {
6763 tmp := typecheck.TempAt(pos, s.curfn, t)
6764 if t.HasPointers() {
6765 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, tmp, s.mem())
6771 // variable returns the value of a variable at the current location.
6772 func (s *state) variable(n ir.Node, t *types.Type) *ssa.Value {
6782 if s.curBlock == s.f.Entry {
6783 // No variable should be live at entry.
6784 s.f.Fatalf("value %v (%v) incorrectly live at entry", n, v)
6786 // Make a FwdRef, which records a value that's live on block input.
6787 // We'll find the matching definition as part of insertPhis.
6788 v = s.newValue0A(ssa.OpFwdRef, t, fwdRefAux{N: n})
6790 if n.Op() == ir.ONAME {
6791 s.addNamedValue(n.(*ir.Name), v)
6796 func (s *state) mem() *ssa.Value {
6797 return s.variable(memVar, types.TypeMem)
6800 func (s *state) addNamedValue(n *ir.Name, v *ssa.Value) {
6801 if n.Class == ir.Pxxx {
6802 // Don't track our marker nodes (memVar etc.).
6805 if ir.IsAutoTmp(n) {
6806 // Don't track temporary variables.
6809 if n.Class == ir.PPARAMOUT {
6810 // Don't track named output values. This prevents return values
6811 // from being assigned too early. See #14591 and #14762. TODO: allow this.
6814 loc := ssa.LocalSlot{N: n, Type: n.Type(), Off: 0}
6815 values, ok := s.f.NamedValues[loc]
6817 s.f.Names = append(s.f.Names, &loc)
6818 s.f.CanonicalLocalSlots[loc] = &loc
6820 s.f.NamedValues[loc] = append(values, v)
6823 // Branch is an unresolved branch.
6824 type Branch struct {
6825 P *obj.Prog // branch instruction
6826 B *ssa.Block // target
6829 // State contains state needed during Prog generation.
6835 // Branches remembers all the branch instructions we've seen
6836 // and where they would like to go.
6839 // JumpTables remembers all the jump tables we've seen.
6840 JumpTables []*ssa.Block
6842 // bstart remembers where each block starts (indexed by block ID)
6845 maxarg int64 // largest frame size for arguments to calls made by the function
6847 // Map from GC safe points to liveness index, generated by
6848 // liveness analysis.
6849 livenessMap liveness.Map
6851 // partLiveArgs includes arguments that may be partially live, for which we
6852 // need to generate instructions that spill the argument registers.
6853 partLiveArgs map[*ir.Name]bool
6855 // lineRunStart records the beginning of the current run of instructions
6856 // within a single block sharing the same line number
6857 // Used to move statement marks to the beginning of such runs.
6858 lineRunStart *obj.Prog
6860 // wasm: The number of values on the WebAssembly stack. This is only used as a safeguard.
6861 OnWasmStackSkipped int
6864 func (s *State) FuncInfo() *obj.FuncInfo {
6865 return s.pp.CurFunc.LSym.Func()
6868 // Prog appends a new Prog.
6869 func (s *State) Prog(as obj.As) *obj.Prog {
6871 if objw.LosesStmtMark(as) {
6874 // Float a statement start to the beginning of any same-line run.
6875 // lineRunStart is reset at block boundaries, which appears to work well.
6876 if s.lineRunStart == nil || s.lineRunStart.Pos.Line() != p.Pos.Line() {
6878 } else if p.Pos.IsStmt() == src.PosIsStmt {
6879 s.lineRunStart.Pos = s.lineRunStart.Pos.WithIsStmt()
6880 p.Pos = p.Pos.WithNotStmt()
6885 // Pc returns the current Prog.
6886 func (s *State) Pc() *obj.Prog {
6890 // SetPos sets the current source position.
6891 func (s *State) SetPos(pos src.XPos) {
6895 // Br emits a single branch instruction and returns the instruction.
6896 // Not all architectures need the returned instruction, but otherwise
6897 // the boilerplate is common to all.
6898 func (s *State) Br(op obj.As, target *ssa.Block) *obj.Prog {
6900 p.To.Type = obj.TYPE_BRANCH
6901 s.Branches = append(s.Branches, Branch{P: p, B: target})
6905 // DebugFriendlySetPosFrom adjusts Pos.IsStmt subject to heuristics
6906 // that reduce "jumpy" line number churn when debugging.
6907 // Spill/fill/copy instructions from the register allocator,
6908 // phi functions, and instructions with a no-pos position
6909 // are examples of instructions that can cause churn.
6910 func (s *State) DebugFriendlySetPosFrom(v *ssa.Value) {
6912 case ssa.OpPhi, ssa.OpCopy, ssa.OpLoadReg, ssa.OpStoreReg:
6913 // These are not statements
6914 s.SetPos(v.Pos.WithNotStmt())
6917 if p != src.NoXPos {
6918 // If the position is defined, update the position.
6919 // Also convert default IsStmt to NotStmt; only
6920 // explicit statement boundaries should appear
6921 // in the generated code.
6922 if p.IsStmt() != src.PosIsStmt {
6923 if s.pp.Pos.IsStmt() == src.PosIsStmt && s.pp.Pos.SameFileAndLine(p) {
6924 // If s.pp.Pos already has a statement mark, then it was set here (below) for
6925 // the previous value. If an actual instruction had been emitted for that
6926 // value, then the statement mark would have been reset. Since the statement
6927 // mark of s.pp.Pos was not reset, this position (file/line) still needs a
6928 // statement mark on an instruction. If file and line for this value are
6929 // the same as the previous value, then the first instruction for this
6930 // value will work to take the statement mark. Return early to avoid
6931 // resetting the statement mark.
6933 // The reset of s.pp.Pos occurs in (*Progs).Prog() -- if it emits
6934 // an instruction, and the instruction's statement mark was set,
6935 // and it is not one of the LosesStmtMark instructions,
6936 // then Prog() resets the statement mark on the (*Progs).Pos.
6940 // Calls use the pos attached to v, but copy the statement mark from State
6944 s.SetPos(s.pp.Pos.WithNotStmt())
6949 // emit argument info (locations on stack) for traceback.
6950 func emitArgInfo(e *ssafn, f *ssa.Func, pp *objw.Progs) {
6951 ft := e.curfn.Type()
6952 if ft.NumRecvs() == 0 && ft.NumParams() == 0 {
6956 x := EmitArgInfo(e.curfn, f.OwnAux.ABIInfo())
6957 x.Set(obj.AttrContentAddressable, true)
6958 e.curfn.LSym.Func().ArgInfo = x
6960 // Emit a funcdata pointing at the arg info data.
6961 p := pp.Prog(obj.AFUNCDATA)
6962 p.From.SetConst(rtabi.FUNCDATA_ArgInfo)
6963 p.To.Type = obj.TYPE_MEM
6964 p.To.Name = obj.NAME_EXTERN
6968 // emit argument info (locations on stack) of f for traceback.
6969 func EmitArgInfo(f *ir.Func, abiInfo *abi.ABIParamResultInfo) *obj.LSym {
6970 x := base.Ctxt.Lookup(fmt.Sprintf("%s.arginfo%d", f.LSym.Name, f.ABI))
6971 // NOTE: do not set ContentAddressable here. This may be referenced from
6972 // assembly code by name (in this case f is a declaration).
6973 // Instead, set it in emitArgInfo above.
6975 PtrSize := int64(types.PtrSize)
6976 uintptrTyp := types.Types[types.TUINTPTR]
6978 isAggregate := func(t *types.Type) bool {
6979 return t.IsStruct() || t.IsArray() || t.IsComplex() || t.IsInterface() || t.IsString() || t.IsSlice()
6982 // Populate the data.
6983 // The data is a stream of bytes, which contains the offsets and sizes of the
6984 // non-aggregate arguments or non-aggregate fields/elements of aggregate-typed
6985 // arguments, along with special "operators". Specifically,
6986 // - for each non-aggrgate arg/field/element, its offset from FP (1 byte) and
6988 // - special operators:
6989 // - 0xff - end of sequence
6990 // - 0xfe - print { (at the start of an aggregate-typed argument)
6991 // - 0xfd - print } (at the end of an aggregate-typed argument)
6992 // - 0xfc - print ... (more args/fields/elements)
6993 // - 0xfb - print _ (offset too large)
6994 // These constants need to be in sync with runtime.traceback.go:printArgs.
7000 _offsetTooLarge = 0xfb
7001 _special = 0xf0 // above this are operators, below this are ordinary offsets
7005 limit = 10 // print no more than 10 args/components
7006 maxDepth = 5 // no more than 5 layers of nesting
7008 // maxLen is a (conservative) upper bound of the byte stream length. For
7009 // each arg/component, it has no more than 2 bytes of data (size, offset),
7010 // and no more than one {, }, ... at each level (it cannot have both the
7011 // data and ... unless it is the last one, just be conservative). Plus 1
7013 maxLen = (maxDepth*3+2)*limit + 1
7018 writebyte := func(o uint8) { wOff = objw.Uint8(x, wOff, o) }
7020 // Write one non-aggrgate arg/field/element.
7021 write1 := func(sz, offset int64) {
7022 if offset >= _special {
7023 writebyte(_offsetTooLarge)
7025 writebyte(uint8(offset))
7026 writebyte(uint8(sz))
7031 // Visit t recursively and write it out.
7032 // Returns whether to continue visiting.
7033 var visitType func(baseOffset int64, t *types.Type, depth int) bool
7034 visitType = func(baseOffset int64, t *types.Type, depth int) bool {
7036 writebyte(_dotdotdot)
7039 if !isAggregate(t) {
7040 write1(t.Size(), baseOffset)
7043 writebyte(_startAgg)
7045 if depth >= maxDepth {
7046 writebyte(_dotdotdot)
7052 case t.IsInterface(), t.IsString():
7053 _ = visitType(baseOffset, uintptrTyp, depth) &&
7054 visitType(baseOffset+PtrSize, uintptrTyp, depth)
7056 _ = visitType(baseOffset, uintptrTyp, depth) &&
7057 visitType(baseOffset+PtrSize, uintptrTyp, depth) &&
7058 visitType(baseOffset+PtrSize*2, uintptrTyp, depth)
7060 _ = visitType(baseOffset, types.FloatForComplex(t), depth) &&
7061 visitType(baseOffset+t.Size()/2, types.FloatForComplex(t), depth)
7063 if t.NumElem() == 0 {
7064 n++ // {} counts as a component
7067 for i := int64(0); i < t.NumElem(); i++ {
7068 if !visitType(baseOffset, t.Elem(), depth) {
7071 baseOffset += t.Elem().Size()
7074 if t.NumFields() == 0 {
7075 n++ // {} counts as a component
7078 for _, field := range t.Fields() {
7079 if !visitType(baseOffset+field.Offset, field.Type, depth) {
7089 if strings.Contains(f.LSym.Name, "[") {
7090 // Skip the dictionary argument - it is implicit and the user doesn't need to see it.
7094 for _, a := range abiInfo.InParams()[start:] {
7095 if !visitType(a.FrameOffset(abiInfo), a.Type, 0) {
7101 base.Fatalf("ArgInfo too large")
7107 // for wrapper, emit info of wrapped function.
7108 func emitWrappedFuncInfo(e *ssafn, pp *objw.Progs) {
7109 if base.Ctxt.Flag_linkshared {
7110 // Relative reference (SymPtrOff) to another shared object doesn't work.
7115 wfn := e.curfn.WrappedFunc
7120 wsym := wfn.Linksym()
7121 x := base.Ctxt.LookupInit(fmt.Sprintf("%s.wrapinfo", wsym.Name), func(x *obj.LSym) {
7122 objw.SymPtrOff(x, 0, wsym)
7123 x.Set(obj.AttrContentAddressable, true)
7125 e.curfn.LSym.Func().WrapInfo = x
7127 // Emit a funcdata pointing at the wrap info data.
7128 p := pp.Prog(obj.AFUNCDATA)
7129 p.From.SetConst(rtabi.FUNCDATA_WrapInfo)
7130 p.To.Type = obj.TYPE_MEM
7131 p.To.Name = obj.NAME_EXTERN
7135 // genssa appends entries to pp for each instruction in f.
7136 func genssa(f *ssa.Func, pp *objw.Progs) {
7138 s.ABI = f.OwnAux.Fn.ABI()
7140 e := f.Frontend().(*ssafn)
7142 s.livenessMap, s.partLiveArgs = liveness.Compute(e.curfn, f, e.stkptrsize, pp)
7143 emitArgInfo(e, f, pp)
7144 argLiveBlockMap, argLiveValueMap := liveness.ArgLiveness(e.curfn, f, pp)
7146 openDeferInfo := e.curfn.LSym.Func().OpenCodedDeferInfo
7147 if openDeferInfo != nil {
7148 // This function uses open-coded defers -- write out the funcdata
7149 // info that we computed at the end of genssa.
7150 p := pp.Prog(obj.AFUNCDATA)
7151 p.From.SetConst(rtabi.FUNCDATA_OpenCodedDeferInfo)
7152 p.To.Type = obj.TYPE_MEM
7153 p.To.Name = obj.NAME_EXTERN
7154 p.To.Sym = openDeferInfo
7157 emitWrappedFuncInfo(e, pp)
7159 // Remember where each block starts.
7160 s.bstart = make([]*obj.Prog, f.NumBlocks())
7162 var progToValue map[*obj.Prog]*ssa.Value
7163 var progToBlock map[*obj.Prog]*ssa.Block
7164 var valueToProgAfter []*obj.Prog // The first Prog following computation of a value v; v is visible at this point.
7165 gatherPrintInfo := f.PrintOrHtmlSSA || ssa.GenssaDump[f.Name]
7166 if gatherPrintInfo {
7167 progToValue = make(map[*obj.Prog]*ssa.Value, f.NumValues())
7168 progToBlock = make(map[*obj.Prog]*ssa.Block, f.NumBlocks())
7169 f.Logf("genssa %s\n", f.Name)
7170 progToBlock[s.pp.Next] = f.Blocks[0]
7173 if base.Ctxt.Flag_locationlists {
7174 if cap(f.Cache.ValueToProgAfter) < f.NumValues() {
7175 f.Cache.ValueToProgAfter = make([]*obj.Prog, f.NumValues())
7177 valueToProgAfter = f.Cache.ValueToProgAfter[:f.NumValues()]
7178 for i := range valueToProgAfter {
7179 valueToProgAfter[i] = nil
7183 // If the very first instruction is not tagged as a statement,
7184 // debuggers may attribute it to previous function in program.
7185 firstPos := src.NoXPos
7186 for _, v := range f.Entry.Values {
7187 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 {
7189 v.Pos = firstPos.WithDefaultStmt()
7194 // inlMarks has an entry for each Prog that implements an inline mark.
7195 // It maps from that Prog to the global inlining id of the inlined body
7196 // which should unwind to this Prog's location.
7197 var inlMarks map[*obj.Prog]int32
7198 var inlMarkList []*obj.Prog
7200 // inlMarksByPos maps from a (column 1) source position to the set of
7201 // Progs that are in the set above and have that source position.
7202 var inlMarksByPos map[src.XPos][]*obj.Prog
7204 var argLiveIdx int = -1 // argument liveness info index
7206 // Emit basic blocks
7207 for i, b := range f.Blocks {
7208 s.bstart[b.ID] = s.pp.Next
7209 s.lineRunStart = nil
7210 s.SetPos(s.pp.Pos.WithNotStmt()) // It needs a non-empty Pos, but cannot be a statement boundary (yet).
7212 if idx, ok := argLiveBlockMap[b.ID]; ok && idx != argLiveIdx {
7214 p := s.pp.Prog(obj.APCDATA)
7215 p.From.SetConst(rtabi.PCDATA_ArgLiveIndex)
7216 p.To.SetConst(int64(idx))
7219 // Emit values in block
7220 Arch.SSAMarkMoves(&s, b)
7221 for _, v := range b.Values {
7223 s.DebugFriendlySetPosFrom(v)
7225 if v.Op.ResultInArg0() && v.ResultReg() != v.Args[0].Reg() {
7226 v.Fatalf("input[0] and output not in same register %s", v.LongString())
7231 // memory arg needs no code
7233 // input args need no code
7234 case ssa.OpSP, ssa.OpSB:
7236 case ssa.OpSelect0, ssa.OpSelect1, ssa.OpSelectN, ssa.OpMakeResult:
7239 // nothing to do when there's a g register,
7240 // and checkLower complains if there's not
7241 case ssa.OpVarDef, ssa.OpVarLive, ssa.OpKeepAlive, ssa.OpWBend:
7242 // nothing to do; already used by liveness
7246 // nothing to do; no-op conversion for liveness
7247 if v.Args[0].Reg() != v.Reg() {
7248 v.Fatalf("OpConvert should be a no-op: %s; %s", v.Args[0].LongString(), v.LongString())
7251 p := Arch.Ginsnop(s.pp)
7252 if inlMarks == nil {
7253 inlMarks = map[*obj.Prog]int32{}
7254 inlMarksByPos = map[src.XPos][]*obj.Prog{}
7256 inlMarks[p] = v.AuxInt32()
7257 inlMarkList = append(inlMarkList, p)
7258 pos := v.Pos.AtColumn1()
7259 inlMarksByPos[pos] = append(inlMarksByPos[pos], p)
7260 firstPos = src.NoXPos
7263 // Special case for first line in function; move it to the start (which cannot be a register-valued instruction)
7264 if firstPos != src.NoXPos && v.Op != ssa.OpArgIntReg && v.Op != ssa.OpArgFloatReg && v.Op != ssa.OpLoadReg && v.Op != ssa.OpStoreReg {
7266 firstPos = src.NoXPos
7268 // Attach this safe point to the next
7270 s.pp.NextLive = s.livenessMap.Get(v)
7271 s.pp.NextUnsafe = s.livenessMap.GetUnsafe(v)
7273 // let the backend handle it
7274 Arch.SSAGenValue(&s, v)
7277 if idx, ok := argLiveValueMap[v.ID]; ok && idx != argLiveIdx {
7279 p := s.pp.Prog(obj.APCDATA)
7280 p.From.SetConst(rtabi.PCDATA_ArgLiveIndex)
7281 p.To.SetConst(int64(idx))
7284 if base.Ctxt.Flag_locationlists {
7285 valueToProgAfter[v.ID] = s.pp.Next
7288 if gatherPrintInfo {
7289 for ; x != s.pp.Next; x = x.Link {
7294 // If this is an empty infinite loop, stick a hardware NOP in there so that debuggers are less confused.
7295 if s.bstart[b.ID] == s.pp.Next && len(b.Succs) == 1 && b.Succs[0].Block() == b {
7296 p := Arch.Ginsnop(s.pp)
7297 p.Pos = p.Pos.WithIsStmt()
7298 if b.Pos == src.NoXPos {
7299 b.Pos = p.Pos // It needs a file, otherwise a no-file non-zero line causes confusion. See #35652.
7300 if b.Pos == src.NoXPos {
7301 b.Pos = pp.Text.Pos // Sometimes p.Pos is empty. See #35695.
7304 b.Pos = b.Pos.WithBogusLine() // Debuggers are not good about infinite loops, force a change in line number
7307 // Set unsafe mark for any end-of-block generated instructions
7308 // (normally, conditional or unconditional branches).
7309 // This is particularly important for empty blocks, as there
7310 // are no values to inherit the unsafe mark from.
7311 s.pp.NextUnsafe = s.livenessMap.GetUnsafeBlock(b)
7313 // Emit control flow instructions for block
7315 if i < len(f.Blocks)-1 && base.Flag.N == 0 {
7316 // If -N, leave next==nil so every block with successors
7317 // ends in a JMP (except call blocks - plive doesn't like
7318 // select{send,recv} followed by a JMP call). Helps keep
7319 // line numbers for otherwise empty blocks.
7320 next = f.Blocks[i+1]
7324 Arch.SSAGenBlock(&s, b, next)
7325 if gatherPrintInfo {
7326 for ; x != s.pp.Next; x = x.Link {
7331 if f.Blocks[len(f.Blocks)-1].Kind == ssa.BlockExit {
7332 // We need the return address of a panic call to
7333 // still be inside the function in question. So if
7334 // it ends in a call which doesn't return, add a
7335 // nop (which will never execute) after the call.
7338 if openDeferInfo != nil {
7339 // When doing open-coded defers, generate a disconnected call to
7340 // deferreturn and a return. This will be used to during panic
7341 // recovery to unwind the stack and return back to the runtime.
7342 s.pp.NextLive = s.livenessMap.DeferReturn
7343 p := pp.Prog(obj.ACALL)
7344 p.To.Type = obj.TYPE_MEM
7345 p.To.Name = obj.NAME_EXTERN
7346 p.To.Sym = ir.Syms.Deferreturn
7348 // Load results into registers. So when a deferred function
7349 // recovers a panic, it will return to caller with right results.
7350 // The results are already in memory, because they are not SSA'd
7351 // when the function has defers (see canSSAName).
7352 for _, o := range f.OwnAux.ABIInfo().OutParams() {
7354 rts, offs := o.RegisterTypesAndOffsets()
7355 for i := range o.Registers {
7356 Arch.LoadRegResult(&s, f, rts[i], ssa.ObjRegForAbiReg(o.Registers[i], f.Config), n, offs[i])
7363 if inlMarks != nil {
7366 // We have some inline marks. Try to find other instructions we're
7367 // going to emit anyway, and use those instructions instead of the
7369 for p := pp.Text; p != nil; p = p.Link {
7370 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 {
7371 // Don't use 0-sized instructions as inline marks, because we need
7372 // to identify inline mark instructions by pc offset.
7373 // (Some of these instructions are sometimes zero-sized, sometimes not.
7374 // We must not use anything that even might be zero-sized.)
7375 // TODO: are there others?
7378 if _, ok := inlMarks[p]; ok {
7379 // Don't use inline marks themselves. We don't know
7380 // whether they will be zero-sized or not yet.
7383 if p.As == obj.ACALL || p.As == obj.ADUFFCOPY || p.As == obj.ADUFFZERO {
7386 pos := p.Pos.AtColumn1()
7387 s := inlMarksByPos[pos]
7391 for _, m := range s {
7392 // We found an instruction with the same source position as
7393 // some of the inline marks.
7394 // Use this instruction instead.
7395 p.Pos = p.Pos.WithIsStmt() // promote position to a statement
7396 pp.CurFunc.LSym.Func().AddInlMark(p, inlMarks[m])
7397 // Make the inline mark a real nop, so it doesn't generate any code.
7403 delete(inlMarksByPos, pos)
7405 // Any unmatched inline marks now need to be added to the inlining tree (and will generate a nop instruction).
7406 for _, p := range inlMarkList {
7407 if p.As != obj.ANOP {
7408 pp.CurFunc.LSym.Func().AddInlMark(p, inlMarks[p])
7412 if e.stksize == 0 && !hasCall {
7413 // Frameless leaf function. It doesn't need any preamble,
7414 // so make sure its first instruction isn't from an inlined callee.
7415 // If it is, add a nop at the start of the function with a position
7416 // equal to the start of the function.
7417 // This ensures that runtime.FuncForPC(uintptr(reflect.ValueOf(fn).Pointer())).Name()
7418 // returns the right answer. See issue 58300.
7419 for p := pp.Text; p != nil; p = p.Link {
7420 if p.As == obj.AFUNCDATA || p.As == obj.APCDATA || p.As == obj.ATEXT || p.As == obj.ANOP {
7423 if base.Ctxt.PosTable.Pos(p.Pos).Base().InliningIndex() >= 0 {
7424 // Make a real (not 0-sized) nop.
7425 nop := Arch.Ginsnop(pp)
7426 nop.Pos = e.curfn.Pos().WithIsStmt()
7428 // Unfortunately, Ginsnop puts the instruction at the
7429 // end of the list. Move it up to just before p.
7431 // Unlink from the current list.
7432 for x := pp.Text; x != nil; x = x.Link {
7438 // Splice in right before p.
7439 for x := pp.Text; x != nil; x = x.Link {
7452 if base.Ctxt.Flag_locationlists {
7453 var debugInfo *ssa.FuncDebug
7454 debugInfo = e.curfn.DebugInfo.(*ssa.FuncDebug)
7455 if e.curfn.ABI == obj.ABIInternal && base.Flag.N != 0 {
7456 ssa.BuildFuncDebugNoOptimized(base.Ctxt, f, base.Debug.LocationLists > 1, StackOffset, debugInfo)
7458 ssa.BuildFuncDebug(base.Ctxt, f, base.Debug.LocationLists, StackOffset, debugInfo)
7461 idToIdx := make([]int, f.NumBlocks())
7462 for i, b := range f.Blocks {
7465 // Note that at this moment, Prog.Pc is a sequence number; it's
7466 // not a real PC until after assembly, so this mapping has to
7468 debugInfo.GetPC = func(b, v ssa.ID) int64 {
7470 case ssa.BlockStart.ID:
7471 if b == f.Entry.ID {
7472 return 0 // Start at the very beginning, at the assembler-generated prologue.
7473 // this should only happen for function args (ssa.OpArg)
7476 case ssa.BlockEnd.ID:
7477 blk := f.Blocks[idToIdx[b]]
7478 nv := len(blk.Values)
7479 return valueToProgAfter[blk.Values[nv-1].ID].Pc
7480 case ssa.FuncEnd.ID:
7481 return e.curfn.LSym.Size
7483 return valueToProgAfter[v].Pc
7488 // Resolve branches, and relax DefaultStmt into NotStmt
7489 for _, br := range s.Branches {
7490 br.P.To.SetTarget(s.bstart[br.B.ID])
7491 if br.P.Pos.IsStmt() != src.PosIsStmt {
7492 br.P.Pos = br.P.Pos.WithNotStmt()
7493 } else if v0 := br.B.FirstPossibleStmtValue(); v0 != nil && v0.Pos.Line() == br.P.Pos.Line() && v0.Pos.IsStmt() == src.PosIsStmt {
7494 br.P.Pos = br.P.Pos.WithNotStmt()
7499 // Resolve jump table destinations.
7500 for _, jt := range s.JumpTables {
7501 // Convert from *Block targets to *Prog targets.
7502 targets := make([]*obj.Prog, len(jt.Succs))
7503 for i, e := range jt.Succs {
7504 targets[i] = s.bstart[e.Block().ID]
7506 // Add to list of jump tables to be resolved at assembly time.
7507 // The assembler converts from *Prog entries to absolute addresses
7508 // once it knows instruction byte offsets.
7509 fi := pp.CurFunc.LSym.Func()
7510 fi.JumpTables = append(fi.JumpTables, obj.JumpTable{Sym: jt.Aux.(*obj.LSym), Targets: targets})
7513 if e.log { // spew to stdout
7515 for p := pp.Text; p != nil; p = p.Link {
7516 if p.Pos.IsKnown() && p.InnermostFilename() != filename {
7517 filename = p.InnermostFilename()
7518 f.Logf("# %s\n", filename)
7522 if v, ok := progToValue[p]; ok {
7524 } else if b, ok := progToBlock[p]; ok {
7527 s = " " // most value and branch strings are 2-3 characters long
7529 f.Logf(" %-6s\t%.5d (%s)\t%s\n", s, p.Pc, p.InnermostLineNumber(), p.InstructionString())
7532 if f.HTMLWriter != nil { // spew to ssa.html
7533 var buf strings.Builder
7534 buf.WriteString("<code>")
7535 buf.WriteString("<dl class=\"ssa-gen\">")
7537 for p := pp.Text; p != nil; p = p.Link {
7538 // Don't spam every line with the file name, which is often huge.
7539 // Only print changes, and "unknown" is not a change.
7540 if p.Pos.IsKnown() && p.InnermostFilename() != filename {
7541 filename = p.InnermostFilename()
7542 buf.WriteString("<dt class=\"ssa-prog-src\"></dt><dd class=\"ssa-prog\">")
7543 buf.WriteString(html.EscapeString("# " + filename))
7544 buf.WriteString("</dd>")
7547 buf.WriteString("<dt class=\"ssa-prog-src\">")
7548 if v, ok := progToValue[p]; ok {
7549 buf.WriteString(v.HTML())
7550 } else if b, ok := progToBlock[p]; ok {
7551 buf.WriteString("<b>" + b.HTML() + "</b>")
7553 buf.WriteString("</dt>")
7554 buf.WriteString("<dd class=\"ssa-prog\">")
7555 fmt.Fprintf(&buf, "%.5d <span class=\"l%v line-number\">(%s)</span> %s", p.Pc, p.InnermostLineNumber(), p.InnermostLineNumberHTML(), html.EscapeString(p.InstructionString()))
7556 buf.WriteString("</dd>")
7558 buf.WriteString("</dl>")
7559 buf.WriteString("</code>")
7560 f.HTMLWriter.WriteColumn("genssa", "genssa", "ssa-prog", buf.String())
7562 if ssa.GenssaDump[f.Name] {
7563 fi := f.DumpFileForPhase("genssa")
7566 // inliningDiffers if any filename changes or if any line number except the innermost (last index) changes.
7567 inliningDiffers := func(a, b []src.Pos) bool {
7568 if len(a) != len(b) {
7572 if a[i].Filename() != b[i].Filename() {
7575 if i != len(a)-1 && a[i].Line() != b[i].Line() {
7582 var allPosOld []src.Pos
7583 var allPos []src.Pos
7585 for p := pp.Text; p != nil; p = p.Link {
7586 if p.Pos.IsKnown() {
7588 p.Ctxt.AllPos(p.Pos, func(pos src.Pos) { allPos = append(allPos, pos) })
7589 if inliningDiffers(allPos, allPosOld) {
7590 for _, pos := range allPos {
7591 fmt.Fprintf(fi, "# %s:%d\n", pos.Filename(), pos.Line())
7593 allPos, allPosOld = allPosOld, allPos // swap, not copy, so that they do not share slice storage.
7598 if v, ok := progToValue[p]; ok {
7600 } else if b, ok := progToBlock[p]; ok {
7603 s = " " // most value and branch strings are 2-3 characters long
7605 fmt.Fprintf(fi, " %-6s\t%.5d %s\t%s\n", s, p.Pc, ssa.StmtString(p.Pos), p.InstructionString())
7613 f.HTMLWriter.Close()
7617 func defframe(s *State, e *ssafn, f *ssa.Func) {
7620 s.maxarg = types.RoundUp(s.maxarg, e.stkalign)
7621 frame := s.maxarg + e.stksize
7622 if Arch.PadFrame != nil {
7623 frame = Arch.PadFrame(frame)
7626 // Fill in argument and frame size.
7627 pp.Text.To.Type = obj.TYPE_TEXTSIZE
7628 pp.Text.To.Val = int32(types.RoundUp(f.OwnAux.ArgWidth(), int64(types.RegSize)))
7629 pp.Text.To.Offset = frame
7633 // Insert code to spill argument registers if the named slot may be partially
7634 // live. That is, the named slot is considered live by liveness analysis,
7635 // (because a part of it is live), but we may not spill all parts into the
7636 // slot. This can only happen with aggregate-typed arguments that are SSA-able
7637 // and not address-taken (for non-SSA-able or address-taken arguments we always
7639 // Note: spilling is unnecessary in the -N/no-optimize case, since all values
7640 // will be considered non-SSAable and spilled up front.
7641 // TODO(register args) Make liveness more fine-grained to that partial spilling is okay.
7642 if f.OwnAux.ABIInfo().InRegistersUsed() != 0 && base.Flag.N == 0 {
7643 // First, see if it is already spilled before it may be live. Look for a spill
7644 // in the entry block up to the first safepoint.
7645 type nameOff struct {
7649 partLiveArgsSpilled := make(map[nameOff]bool)
7650 for _, v := range f.Entry.Values {
7654 if v.Op != ssa.OpStoreReg || v.Args[0].Op != ssa.OpArgIntReg {
7657 n, off := ssa.AutoVar(v)
7658 if n.Class != ir.PPARAM || n.Addrtaken() || !ssa.CanSSA(n.Type()) || !s.partLiveArgs[n] {
7661 partLiveArgsSpilled[nameOff{n, off}] = true
7664 // Then, insert code to spill registers if not already.
7665 for _, a := range f.OwnAux.ABIInfo().InParams() {
7667 if n == nil || n.Addrtaken() || !ssa.CanSSA(n.Type()) || !s.partLiveArgs[n] || len(a.Registers) <= 1 {
7670 rts, offs := a.RegisterTypesAndOffsets()
7671 for i := range a.Registers {
7672 if !rts[i].HasPointers() {
7675 if partLiveArgsSpilled[nameOff{n, offs[i]}] {
7676 continue // already spilled
7678 reg := ssa.ObjRegForAbiReg(a.Registers[i], f.Config)
7679 p = Arch.SpillArgReg(pp, p, f, rts[i], reg, n, offs[i])
7684 // Insert code to zero ambiguously live variables so that the
7685 // garbage collector only sees initialized values when it
7686 // looks for pointers.
7689 // Opaque state for backend to use. Current backends use it to
7690 // keep track of which helper registers have been zeroed.
7693 // Iterate through declarations. Autos are sorted in decreasing
7694 // frame offset order.
7695 for _, n := range e.curfn.Dcl {
7699 if n.Class != ir.PAUTO {
7700 e.Fatalf(n.Pos(), "needzero class %d", n.Class)
7702 if n.Type().Size()%int64(types.PtrSize) != 0 || n.FrameOffset()%int64(types.PtrSize) != 0 || n.Type().Size() == 0 {
7703 e.Fatalf(n.Pos(), "var %L has size %d offset %d", n, n.Type().Size(), n.Offset_)
7706 if lo != hi && n.FrameOffset()+n.Type().Size() >= lo-int64(2*types.RegSize) {
7707 // Merge with range we already have.
7708 lo = n.FrameOffset()
7713 p = Arch.ZeroRange(pp, p, frame+lo, hi-lo, &state)
7716 lo = n.FrameOffset()
7717 hi = lo + n.Type().Size()
7720 // Zero final range.
7721 Arch.ZeroRange(pp, p, frame+lo, hi-lo, &state)
7724 // For generating consecutive jump instructions to model a specific branching
7725 type IndexJump struct {
7730 func (s *State) oneJump(b *ssa.Block, jump *IndexJump) {
7731 p := s.Br(jump.Jump, b.Succs[jump.Index].Block())
7735 // CombJump generates combinational instructions (2 at present) for a block jump,
7736 // thereby the behaviour of non-standard condition codes could be simulated
7737 func (s *State) CombJump(b, next *ssa.Block, jumps *[2][2]IndexJump) {
7739 case b.Succs[0].Block():
7740 s.oneJump(b, &jumps[0][0])
7741 s.oneJump(b, &jumps[0][1])
7742 case b.Succs[1].Block():
7743 s.oneJump(b, &jumps[1][0])
7744 s.oneJump(b, &jumps[1][1])
7747 if b.Likely != ssa.BranchUnlikely {
7748 s.oneJump(b, &jumps[1][0])
7749 s.oneJump(b, &jumps[1][1])
7750 q = s.Br(obj.AJMP, b.Succs[1].Block())
7752 s.oneJump(b, &jumps[0][0])
7753 s.oneJump(b, &jumps[0][1])
7754 q = s.Br(obj.AJMP, b.Succs[0].Block())
7760 // AddAux adds the offset in the aux fields (AuxInt and Aux) of v to a.
7761 func AddAux(a *obj.Addr, v *ssa.Value) {
7762 AddAux2(a, v, v.AuxInt)
7764 func AddAux2(a *obj.Addr, v *ssa.Value, offset int64) {
7765 if a.Type != obj.TYPE_MEM && a.Type != obj.TYPE_ADDR {
7766 v.Fatalf("bad AddAux addr %v", a)
7768 // add integer offset
7771 // If no additional symbol offset, we're done.
7775 // Add symbol's offset from its base register.
7776 switch n := v.Aux.(type) {
7778 a.Name = obj.NAME_EXTERN
7781 a.Name = obj.NAME_EXTERN
7784 if n.Class == ir.PPARAM || (n.Class == ir.PPARAMOUT && !n.IsOutputParamInRegisters()) {
7785 a.Name = obj.NAME_PARAM
7787 a.Name = obj.NAME_AUTO
7790 a.Offset += n.FrameOffset()
7792 v.Fatalf("aux in %s not implemented %#v", v, v.Aux)
7796 // extendIndex extends v to a full int width.
7797 // panic with the given kind if v does not fit in an int (only on 32-bit archs).
7798 func (s *state) extendIndex(idx, len *ssa.Value, kind ssa.BoundsKind, bounded bool) *ssa.Value {
7799 size := idx.Type.Size()
7800 if size == s.config.PtrSize {
7803 if size > s.config.PtrSize {
7804 // truncate 64-bit indexes on 32-bit pointer archs. Test the
7805 // high word and branch to out-of-bounds failure if it is not 0.
7807 if idx.Type.IsSigned() {
7808 lo = s.newValue1(ssa.OpInt64Lo, types.Types[types.TINT], idx)
7810 lo = s.newValue1(ssa.OpInt64Lo, types.Types[types.TUINT], idx)
7812 if bounded || base.Flag.B != 0 {
7815 bNext := s.f.NewBlock(ssa.BlockPlain)
7816 bPanic := s.f.NewBlock(ssa.BlockExit)
7817 hi := s.newValue1(ssa.OpInt64Hi, types.Types[types.TUINT32], idx)
7818 cmp := s.newValue2(ssa.OpEq32, types.Types[types.TBOOL], hi, s.constInt32(types.Types[types.TUINT32], 0))
7819 if !idx.Type.IsSigned() {
7821 case ssa.BoundsIndex:
7822 kind = ssa.BoundsIndexU
7823 case ssa.BoundsSliceAlen:
7824 kind = ssa.BoundsSliceAlenU
7825 case ssa.BoundsSliceAcap:
7826 kind = ssa.BoundsSliceAcapU
7827 case ssa.BoundsSliceB:
7828 kind = ssa.BoundsSliceBU
7829 case ssa.BoundsSlice3Alen:
7830 kind = ssa.BoundsSlice3AlenU
7831 case ssa.BoundsSlice3Acap:
7832 kind = ssa.BoundsSlice3AcapU
7833 case ssa.BoundsSlice3B:
7834 kind = ssa.BoundsSlice3BU
7835 case ssa.BoundsSlice3C:
7836 kind = ssa.BoundsSlice3CU
7840 b.Kind = ssa.BlockIf
7842 b.Likely = ssa.BranchLikely
7846 s.startBlock(bPanic)
7847 mem := s.newValue4I(ssa.OpPanicExtend, types.TypeMem, int64(kind), hi, lo, len, s.mem())
7848 s.endBlock().SetControl(mem)
7854 // Extend value to the required size
7856 if idx.Type.IsSigned() {
7857 switch 10*size + s.config.PtrSize {
7859 op = ssa.OpSignExt8to32
7861 op = ssa.OpSignExt8to64
7863 op = ssa.OpSignExt16to32
7865 op = ssa.OpSignExt16to64
7867 op = ssa.OpSignExt32to64
7869 s.Fatalf("bad signed index extension %s", idx.Type)
7872 switch 10*size + s.config.PtrSize {
7874 op = ssa.OpZeroExt8to32
7876 op = ssa.OpZeroExt8to64
7878 op = ssa.OpZeroExt16to32
7880 op = ssa.OpZeroExt16to64
7882 op = ssa.OpZeroExt32to64
7884 s.Fatalf("bad unsigned index extension %s", idx.Type)
7887 return s.newValue1(op, types.Types[types.TINT], idx)
7890 // CheckLoweredPhi checks that regalloc and stackalloc correctly handled phi values.
7891 // Called during ssaGenValue.
7892 func CheckLoweredPhi(v *ssa.Value) {
7893 if v.Op != ssa.OpPhi {
7894 v.Fatalf("CheckLoweredPhi called with non-phi value: %v", v.LongString())
7896 if v.Type.IsMemory() {
7900 loc := f.RegAlloc[v.ID]
7901 for _, a := range v.Args {
7902 if aloc := f.RegAlloc[a.ID]; aloc != loc { // TODO: .Equal() instead?
7903 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)
7908 // CheckLoweredGetClosurePtr checks that v is the first instruction in the function's entry block,
7909 // except for incoming in-register arguments.
7910 // The output of LoweredGetClosurePtr is generally hardwired to the correct register.
7911 // That register contains the closure pointer on closure entry.
7912 func CheckLoweredGetClosurePtr(v *ssa.Value) {
7913 entry := v.Block.Func.Entry
7914 if entry != v.Block {
7915 base.Fatalf("in %s, badly placed LoweredGetClosurePtr: %v %v", v.Block.Func.Name, v.Block, v)
7917 for _, w := range entry.Values {
7922 case ssa.OpArgIntReg, ssa.OpArgFloatReg:
7925 base.Fatalf("in %s, badly placed LoweredGetClosurePtr: %v %v", v.Block.Func.Name, v.Block, v)
7930 // CheckArgReg ensures that v is in the function's entry block.
7931 func CheckArgReg(v *ssa.Value) {
7932 entry := v.Block.Func.Entry
7933 if entry != v.Block {
7934 base.Fatalf("in %s, badly placed ArgIReg or ArgFReg: %v %v", v.Block.Func.Name, v.Block, v)
7938 func AddrAuto(a *obj.Addr, v *ssa.Value) {
7939 n, off := ssa.AutoVar(v)
7940 a.Type = obj.TYPE_MEM
7942 a.Reg = int16(Arch.REGSP)
7943 a.Offset = n.FrameOffset() + off
7944 if n.Class == ir.PPARAM || (n.Class == ir.PPARAMOUT && !n.IsOutputParamInRegisters()) {
7945 a.Name = obj.NAME_PARAM
7947 a.Name = obj.NAME_AUTO
7951 // Call returns a new CALL instruction for the SSA value v.
7952 // It uses PrepareCall to prepare the call.
7953 func (s *State) Call(v *ssa.Value) *obj.Prog {
7954 pPosIsStmt := s.pp.Pos.IsStmt() // The statement-ness fo the call comes from ssaGenState
7957 p := s.Prog(obj.ACALL)
7958 if pPosIsStmt == src.PosIsStmt {
7959 p.Pos = v.Pos.WithIsStmt()
7961 p.Pos = v.Pos.WithNotStmt()
7963 if sym, ok := v.Aux.(*ssa.AuxCall); ok && sym.Fn != nil {
7964 p.To.Type = obj.TYPE_MEM
7965 p.To.Name = obj.NAME_EXTERN
7968 // TODO(mdempsky): Can these differences be eliminated?
7969 switch Arch.LinkArch.Family {
7970 case sys.AMD64, sys.I386, sys.PPC64, sys.RISCV64, sys.S390X, sys.Wasm:
7971 p.To.Type = obj.TYPE_REG
7972 case sys.ARM, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64:
7973 p.To.Type = obj.TYPE_MEM
7975 base.Fatalf("unknown indirect call family")
7977 p.To.Reg = v.Args[0].Reg()
7982 // TailCall returns a new tail call instruction for the SSA value v.
7983 // It is like Call, but for a tail call.
7984 func (s *State) TailCall(v *ssa.Value) *obj.Prog {
7990 // PrepareCall prepares to emit a CALL instruction for v and does call-related bookkeeping.
7991 // It must be called immediately before emitting the actual CALL instruction,
7992 // since it emits PCDATA for the stack map at the call (calls are safe points).
7993 func (s *State) PrepareCall(v *ssa.Value) {
7994 idx := s.livenessMap.Get(v)
7995 if !idx.StackMapValid() {
7996 // See Liveness.hasStackMap.
7997 if sym, ok := v.Aux.(*ssa.AuxCall); !ok || !(sym.Fn == ir.Syms.WBZero || sym.Fn == ir.Syms.WBMove) {
7998 base.Fatalf("missing stack map index for %v", v.LongString())
8002 call, ok := v.Aux.(*ssa.AuxCall)
8005 // Record call graph information for nowritebarrierrec
8007 if nowritebarrierrecCheck != nil {
8008 nowritebarrierrecCheck.recordCall(s.pp.CurFunc, call.Fn, v.Pos)
8012 if s.maxarg < v.AuxInt {
8017 // UseArgs records the fact that an instruction needs a certain amount of
8018 // callee args space for its use.
8019 func (s *State) UseArgs(n int64) {
8025 // fieldIdx finds the index of the field referred to by the ODOT node n.
8026 func fieldIdx(n *ir.SelectorExpr) int {
8029 panic("ODOT's LHS is not a struct")
8032 for i, f := range t.Fields() {
8034 if f.Offset != n.Offset() {
8035 panic("field offset doesn't match")
8040 panic(fmt.Sprintf("can't find field in expr %v\n", n))
8042 // TODO: keep the result of this function somewhere in the ODOT Node
8043 // so we don't have to recompute it each time we need it.
8046 // ssafn holds frontend information about a function that the backend is processing.
8047 // It also exports a bunch of compiler services for the ssa backend.
8050 strings map[string]*obj.LSym // map from constant string to data symbols
8051 stksize int64 // stack size for current frame
8052 stkptrsize int64 // prefix of stack containing pointers
8054 // alignment for current frame.
8055 // NOTE: when stkalign > PtrSize, currently this only ensures the offsets of
8056 // objects in the stack frame are aligned. The stack pointer is still aligned
8060 log bool // print ssa debug to the stdout
8063 // StringData returns a symbol which
8064 // is the data component of a global string constant containing s.
8065 func (e *ssafn) StringData(s string) *obj.LSym {
8066 if aux, ok := e.strings[s]; ok {
8069 if e.strings == nil {
8070 e.strings = make(map[string]*obj.LSym)
8072 data := staticdata.StringSym(e.curfn.Pos(), s)
8077 // SplitSlot returns a slot representing the data of parent starting at offset.
8078 func (e *ssafn) SplitSlot(parent *ssa.LocalSlot, suffix string, offset int64, t *types.Type) ssa.LocalSlot {
8081 if node.Class != ir.PAUTO || node.Addrtaken() {
8082 // addressed things and non-autos retain their parents (i.e., cannot truly be split)
8083 return ssa.LocalSlot{N: node, Type: t, Off: parent.Off + offset}
8086 sym := &types.Sym{Name: node.Sym().Name + suffix, Pkg: types.LocalPkg}
8087 n := e.curfn.NewLocal(parent.N.Pos(), sym, t)
8089 n.SetEsc(ir.EscNever)
8091 return ssa.LocalSlot{N: n, Type: t, Off: 0, SplitOf: parent, SplitOffset: offset}
8094 // Logf logs a message from the compiler.
8095 func (e *ssafn) Logf(msg string, args ...interface{}) {
8097 fmt.Printf(msg, args...)
8101 func (e *ssafn) Log() bool {
8105 // Fatalf reports a compiler error and exits.
8106 func (e *ssafn) Fatalf(pos src.XPos, msg string, args ...interface{}) {
8108 nargs := append([]interface{}{ir.FuncName(e.curfn)}, args...)
8109 base.Fatalf("'%s': "+msg, nargs...)
8112 // Warnl reports a "warning", which is usually flag-triggered
8113 // logging output for the benefit of tests.
8114 func (e *ssafn) Warnl(pos src.XPos, fmt_ string, args ...interface{}) {
8115 base.WarnfAt(pos, fmt_, args...)
8118 func (e *ssafn) Debug_checknil() bool {
8119 return base.Debug.Nil != 0
8122 func (e *ssafn) UseWriteBarrier() bool {
8126 func (e *ssafn) Syslook(name string) *obj.LSym {
8128 case "goschedguarded":
8129 return ir.Syms.Goschedguarded
8130 case "writeBarrier":
8131 return ir.Syms.WriteBarrier
8133 return ir.Syms.WBZero
8135 return ir.Syms.WBMove
8136 case "cgoCheckMemmove":
8137 return ir.Syms.CgoCheckMemmove
8138 case "cgoCheckPtrWrite":
8139 return ir.Syms.CgoCheckPtrWrite
8141 e.Fatalf(src.NoXPos, "unknown Syslook func %v", name)
8145 func (e *ssafn) Func() *ir.Func {
8149 func clobberBase(n ir.Node) ir.Node {
8150 if n.Op() == ir.ODOT {
8151 n := n.(*ir.SelectorExpr)
8152 if n.X.Type().NumFields() == 1 {
8153 return clobberBase(n.X)
8156 if n.Op() == ir.OINDEX {
8157 n := n.(*ir.IndexExpr)
8158 if n.X.Type().IsArray() && n.X.Type().NumElem() == 1 {
8159 return clobberBase(n.X)
8165 // callTargetLSym returns the correct LSym to call 'callee' using its ABI.
8166 func callTargetLSym(callee *ir.Name) *obj.LSym {
8167 if callee.Func == nil {
8168 // TODO(austin): This happens in case of interface method I.M from imported package.
8169 // It's ABIInternal, and would be better if callee.Func was never nil and we didn't
8171 return callee.Linksym()
8174 return callee.LinksymABI(callee.Func.ABI)
8177 func min8(a, b int8) int8 {
8184 func max8(a, b int8) int8 {
8191 // deferStructFnField is the field index of _defer.fn.
8192 const deferStructFnField = 4
8194 var deferType *types.Type
8196 // deferstruct returns a type interchangeable with runtime._defer.
8197 // Make sure this stays in sync with runtime/runtime2.go:_defer.
8198 func deferstruct() *types.Type {
8199 if deferType != nil {
8203 makefield := func(name string, t *types.Type) *types.Field {
8204 sym := (*types.Pkg)(nil).Lookup(name)
8205 return types.NewField(src.NoXPos, sym, t)
8208 fields := []*types.Field{
8209 makefield("heap", types.Types[types.TBOOL]),
8210 makefield("rangefunc", types.Types[types.TBOOL]),
8211 makefield("sp", types.Types[types.TUINTPTR]),
8212 makefield("pc", types.Types[types.TUINTPTR]),
8213 // Note: the types here don't really matter. Defer structures
8214 // are always scanned explicitly during stack copying and GC,
8215 // so we make them uintptr type even though they are real pointers.
8216 makefield("fn", types.Types[types.TUINTPTR]),
8217 makefield("link", types.Types[types.TUINTPTR]),
8218 makefield("head", types.Types[types.TUINTPTR]),
8220 if name := fields[deferStructFnField].Sym.Name; name != "fn" {
8221 base.Fatalf("deferStructFnField is %q, not fn", name)
8224 n := ir.NewDeclNameAt(src.NoXPos, ir.OTYPE, ir.Pkgs.Runtime.Lookup("_defer"))
8225 typ := types.NewNamed(n)
8229 // build struct holding the above fields
8230 typ.SetUnderlying(types.NewStruct(fields))
8231 types.CalcStructSize(typ)
8237 // SpillSlotAddr uses LocalSlot information to initialize an obj.Addr
8238 // The resulting addr is used in a non-standard context -- in the prologue
8239 // of a function, before the frame has been constructed, so the standard
8240 // addressing for the parameters will be wrong.
8241 func SpillSlotAddr(spill ssa.Spill, baseReg int16, extraOffset int64) obj.Addr {
8243 Name: obj.NAME_NONE,
8246 Offset: spill.Offset + extraOffset,
8251 BoundsCheckFunc [ssa.BoundsKindCount]*obj.LSym
8252 ExtendCheckFunc [ssa.BoundsKindCount]*obj.LSym