Debian Codegraph @

go/ssa/builder.go

raw symbols SCIP
1 // Copyright 2013 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package ssa
6
7 // This file defines the builder, which builds SSA-form IR for function bodies.
8 //
9 // SSA construction has two phases, "create" and "build". First, one
10 // or more packages are created in any order by a sequence of calls to
11 // CreatePackage, either from syntax or from mere type information.
12 // Each created package has a complete set of Members (const, var,
13 // type, func) that can be accessed through methods like
14 // Program.FuncValue.
15 //
16 // It is not necessary to call CreatePackage for all dependencies of
17 // each syntax package, only for its direct imports. (In future
18 // perhaps even this restriction may be lifted.)
19 //
20 // Second, packages created from syntax are built, by one or more
21 // calls to Package.Build, which may be concurrent; or by a call to
22 // Program.Build, which builds all packages in parallel. Building
23 // traverses the type-annotated syntax tree of each function body and
24 // creates SSA-form IR, a control-flow graph of instructions,
25 // populating fields such as Function.Body, .Params, and others.
26 //
27 // Building may create additional methods, including:
28 // - wrapper methods (e.g. for embedding, or implicit &recv)
29 // - bound method closures (e.g. for use(recv.f))
30 // - thunks (e.g. for use(I.f) or use(T.f))
31 // - generic instances (e.g. to produce f[int] from f[any]).
32 // As these methods are created, they are added to the build queue,
33 // and then processed in turn, until a fixed point is reached,
34 // Since these methods might belong to packages that were not
35 // created (by a call to CreatePackage), their Pkg field is unset.
36 //
37 // Instances of generic functions may be either instantiated (f[int]
38 // is a copy of f[T] with substitutions) or wrapped (f[int] delegates
39 // to f[T]), depending on the availability of generic syntax and the
40 // InstantiateGenerics mode flag.
41 //
42 // Each package has an initializer function named "init" that calls
43 // the initializer functions of each direct import, computes and
44 // assigns the initial value of each global variable, and calls each
45 // source-level function named "init". (These generate SSA functions
46 // named "init#1", "init#2", etc.)
47 //
48 // Runtime types
49 //
50 // Each MakeInterface operation is a conversion from a non-interface
51 // type to an interface type. The semantics of this operation requires
52 // a runtime type descriptor, which is the type portion of an
53 // interface, and the value abstracted by reflect.Type.
54 //
55 // The program accumulates all non-parameterized types that are
56 // encountered as MakeInterface operands, along with all types that
57 // may be derived from them using reflection. This set is available as
58 // Program.RuntimeTypes, and the methods of these types may be
59 // reachable via interface calls or reflection even if they are never
60 // referenced from the SSA IR. (In practice, algorithms such as RTA
61 // that compute reachability from package main perform their own
62 // tracking of runtime types at a finer grain, so this feature is not
63 // very useful.)
64 //
65 // Function literals
66 //
67 // Anonymous functions must be built as soon as they are encountered,
68 // as it may affect locals of the enclosing function, but they are not
69 // marked 'built' until the end of the outermost enclosing function.
70 // (Among other things, this causes them to be logged in top-down order.)
71 //
72 // The Function.build fields determines the algorithm for building the
73 // function body. It is cleared to mark that building is complete.
74
75 import (
76 "fmt"
77 "go/ast"
78 "go/constant"
79 "go/token"
80 "go/types"
81 "os"
82 "runtime"
83 "sync"
84
85 "slices"
86
87 "golang.org/x/tools/internal/typeparams"
88 "golang.org/x/tools/internal/versions"
89 )
90
91 type opaqueType struct{ name string }
92
93 func (t *opaqueType) String() string { return t.name }
94 func (t *opaqueType) Underlying() types.Type { return t }
95
96 var (
97 varOk = newVar("ok", tBool)
98 varIndex = newVar("index", tInt)
99
100 // Type constants.
101 tBool = types.Typ[types.Bool]
102 tByte = types.Typ[types.Byte]
103 tRune = types.Universe.Lookup("rune").Type() // prints as "rune" (Typ[Rune] is same as Int32)
104 tInt = types.Typ[types.Int]
105 tInvalid = types.Typ[types.Invalid]
106 tString = types.Typ[types.String]
107 tUntypedNil = types.Typ[types.UntypedNil]
108
109 tRangeIter = &opaqueType{"iter"} // the type of all "range" iterators
110 tDeferStack = types.NewPointer(&opaqueType{"deferStack"}) // the type of a "deferStack" from ssa:deferstack()
111 tEface = types.NewInterfaceType(nil, nil).Complete()
112
113 // SSA Value constants.
114 vZero = intConst(0)
115 vOne = intConst(1)
116 vTrue = NewConst(constant.MakeBool(true), tBool)
117 vFalse = NewConst(constant.MakeBool(false), tBool)
118 vNoReturn = NewConst(constant.MakeString("noreturn"), tString)
119
120 jReady = intConst(0) // range-over-func jump is READY
121 jBusy = intConst(-1) // range-over-func jump is BUSY
122 jDone = intConst(-2) // range-over-func jump is DONE
123
124 // The ssa:deferstack intrinsic returns the current function's defer stack.
125 vDeferStack = &Builtin{
126 name: "ssa:deferstack",
127 sig: types.NewSignatureType(nil, nil, nil, nil, types.NewTuple(anonVar(tDeferStack)), false),
128 }
129 )
130
131 // builder holds state associated with the package currently being built.
132 // Its methods contain all the logic for AST-to-SSA conversion.
133 //
134 // All Functions belong to the same Program.
135 //
136 // builders are not thread-safe.
137 type builder struct {
138 fns []*Function // Functions that have finished their CREATE phases.
139
140 finished int // finished is the length of the prefix of fns containing built functions.
141
142 // The task of building shared functions within the builder.
143 // Shared functions are ones the builder may either create or lookup.
144 // These may be built by other builders in parallel.
145 // The task is done when the builder has finished iterating, and it
146 // waits for all shared functions to finish building.
147 // nil implies there are no hared functions to wait on.
148 buildshared *task
149 }
150
151 // shared is done when the builder has built all of the
152 // enqueued functions to a fixed-point.
153 func (b *builder) shared() *task {
154 if b.buildshared == nil { // lazily-initialize
155 b.buildshared = &task{done: make(chan unit)}
156 }
157 return b.buildshared
158 }
159
160 // enqueue fn to be built by the builder.
161 func (b *builder) enqueue(fn *Function) {
162 b.fns = append(b.fns, fn)
163 }
164
165 // waitForSharedFunction indicates that the builder should wait until
166 // the potentially shared function fn has finished building.
167 //
168 // This should include any functions that may be built by other
169 // builders.
170 func (b *builder) waitForSharedFunction(fn *Function) {
171 if fn.buildshared != nil { // maybe need to wait?
172 s := b.shared()
173 s.addEdge(fn.buildshared)
174 }
175 }
176
177 // cond emits to fn code to evaluate boolean condition e and jump
178 // to t or f depending on its value, performing various simplifications.
179 //
180 // Postcondition: fn.currentBlock is nil.
181 func (b *builder) cond(fn *Function, e ast.Expr, t, f *BasicBlock) {
182 switch e := e.(type) {
183 case *ast.ParenExpr:
184 b.cond(fn, e.X, t, f)
185 return
186
187 case *ast.BinaryExpr:
188 switch e.Op {
189 case token.LAND:
190 ltrue := fn.newBasicBlock("cond.true")
191 b.cond(fn, e.X, ltrue, f)
192 fn.currentBlock = ltrue
193 b.cond(fn, e.Y, t, f)
194 return
195
196 case token.LOR:
197 lfalse := fn.newBasicBlock("cond.false")
198 b.cond(fn, e.X, t, lfalse)
199 fn.currentBlock = lfalse
200 b.cond(fn, e.Y, t, f)
201 return
202 }
203
204 case *ast.UnaryExpr:
205 if e.Op == token.NOT {
206 b.cond(fn, e.X, f, t)
207 return
208 }
209 }
210
211 // A traditional compiler would simplify "if false" (etc) here
212 // but we do not, for better fidelity to the source code.
213 //
214 // The value of a constant condition may be platform-specific,
215 // and may cause blocks that are reachable in some configuration
216 // to be hidden from subsequent analyses such as bug-finding tools.
217 emitIf(fn, b.expr(fn, e), t, f)
218 }
219
220 // logicalBinop emits code to fn to evaluate e, a &&- or
221 // ||-expression whose reified boolean value is wanted.
222 // The value is returned.
223 func (b *builder) logicalBinop(fn *Function, e *ast.BinaryExpr) Value {
224 rhs := fn.newBasicBlock("binop.rhs")
225 done := fn.newBasicBlock("binop.done")
226
227 // T(e) = T(e.X) = T(e.Y) after untyped constants have been
228 // eliminated.
229 // TODO(adonovan): not true; MyBool==MyBool yields UntypedBool.
230 t := fn.typeOf(e)
231
232 var short Value // value of the short-circuit path
233 switch e.Op {
234 case token.LAND:
235 b.cond(fn, e.X, rhs, done)
236 short = NewConst(constant.MakeBool(false), t)
237
238 case token.LOR:
239 b.cond(fn, e.X, done, rhs)
240 short = NewConst(constant.MakeBool(true), t)
241 }
242
243 // Is rhs unreachable?
244 if rhs.Preds == nil {
245 // Simplify false&&y to false, true||y to true.
246 fn.currentBlock = done
247 return short
248 }
249
250 // Is done unreachable?
251 if done.Preds == nil {
252 // Simplify true&&y (or false||y) to y.
253 fn.currentBlock = rhs
254 return b.expr(fn, e.Y)
255 }
256
257 // All edges from e.X to done carry the short-circuit value.
258 var edges []Value
259 for range done.Preds {
260 edges = append(edges, short)
261 }
262
263 // The edge from e.Y to done carries the value of e.Y.
264 fn.currentBlock = rhs
265 edges = append(edges, b.expr(fn, e.Y))
266 emitJump(fn, done)
267 fn.currentBlock = done
268
269 phi := &Phi{Edges: edges, Comment: e.Op.String()}
270 phi.pos = e.OpPos
271 phi.typ = t
272 return done.emit(phi)
273 }
274
275 // exprN lowers a multi-result expression e to SSA form, emitting code
276 // to fn and returning a single Value whose type is a *types.Tuple.
277 // The caller must access the components via Extract.
278 //
279 // Multi-result expressions include CallExprs in a multi-value
280 // assignment or return statement, and "value,ok" uses of
281 // TypeAssertExpr, IndexExpr (when X is a map), and UnaryExpr (when Op
282 // is token.ARROW).
283 func (b *builder) exprN(fn *Function, e ast.Expr) Value {
284 typ := fn.typeOf(e).(*types.Tuple)
285 switch e := e.(type) {
286 case *ast.ParenExpr:
287 return b.exprN(fn, e.X)
288
289 case *ast.CallExpr:
290 // Currently, no built-in function nor type conversion
291 // has multiple results, so we can avoid some of the
292 // cases for single-valued CallExpr.
293 var c Call
294 b.setCall(fn, e, &c.Call)
295 c.typ = typ
296 return emitCall(fn, &c)
297
298 case *ast.IndexExpr:
299 mapt := typeparams.CoreType(fn.typeOf(e.X)).(*types.Map) // ,ok must be a map.
300 lookup := &Lookup{
301 X: b.expr(fn, e.X),
302 Index: emitConv(fn, b.expr(fn, e.Index), mapt.Key()),
303 CommaOk: true,
304 }
305 lookup.setType(typ)
306 lookup.setPos(e.Lbrack)
307 return fn.emit(lookup)
308
309 case *ast.TypeAssertExpr:
310 return emitTypeTest(fn, b.expr(fn, e.X), typ.At(0).Type(), e.Lparen)
311
312 case *ast.UnaryExpr: // must be receive <-
313 unop := &UnOp{
314 Op: token.ARROW,
315 X: b.expr(fn, e.X),
316 CommaOk: true,
317 }
318 unop.setType(typ)
319 unop.setPos(e.OpPos)
320 return fn.emit(unop)
321 }
322 panic(fmt.Sprintf("exprN(%T) in %s", e, fn))
323 }
324
325 // builtin emits to fn SSA instructions to implement a call to the
326 // built-in function obj with the specified arguments
327 // and return type. It returns the value defined by the result.
328 //
329 // The result is nil if no special handling was required; in this case
330 // the caller should treat this like an ordinary library function
331 // call.
332 func (b *builder) builtin(fn *Function, obj *types.Builtin, args []ast.Expr, typ types.Type, pos token.Pos) Value {
333 typ = fn.typ(typ)
334 switch obj.Name() {
335 case "make":
336 switch ct := typeparams.CoreType(typ).(type) {
337 case *types.Slice:
338 n := b.expr(fn, args[1])
339 m := n
340 if len(args) == 3 {
341 m = b.expr(fn, args[2])
342 }
343 if m, ok := m.(*Const); ok {
344 // treat make([]T, n, m) as new([m]T)[:n]
345 cap := m.Int64()
346 at := types.NewArray(ct.Elem(), cap)
347 v := &Slice{
348 X: emitNew(fn, at, pos, "makeslice"),
349 High: n,
350 }
351 v.setPos(pos)
352 v.setType(typ)
353 return fn.emit(v)
354 }
355 v := &MakeSlice{
356 Len: n,
357 Cap: m,
358 }
359 v.setPos(pos)
360 v.setType(typ)
361 return fn.emit(v)
362
363 case *types.Map:
364 var res Value
365 if len(args) == 2 {
366 res = b.expr(fn, args[1])
367 }
368 v := &MakeMap{Reserve: res}
369 v.setPos(pos)
370 v.setType(typ)
371 return fn.emit(v)
372
373 case *types.Chan:
374 var sz Value = vZero
375 if len(args) == 2 {
376 sz = b.expr(fn, args[1])
377 }
378 v := &MakeChan{Size: sz}
379 v.setPos(pos)
380 v.setType(typ)
381 return fn.emit(v)
382 }
383
384 case "new":
385 alloc := emitNew(fn, typeparams.MustDeref(typ), pos, "new")
386 if !fn.info.Types[args[0]].IsType() {
387 // new(expr), requires go1.26
388 v := b.expr(fn, args[0])
389 emitStore(fn, alloc, v, pos)
390 }
391 return alloc
392
393 case "len", "cap":
394 // Special case: len or cap of an array or *array is
395 // based on the type, not the value which may be nil.
396 // We must still evaluate the value, though. (If it
397 // was side-effect free, the whole call would have
398 // been constant-folded.)
399 t := typeparams.Deref(fn.typeOf(args[0]))
400 if at, ok := typeparams.CoreType(t).(*types.Array); ok {
401 b.expr(fn, args[0]) // for effects only
402 return intConst(at.Len())
403 }
404 // Otherwise treat as normal.
405
406 case "panic":
407 fn.emit(&Panic{
408 X: emitConv(fn, b.expr(fn, args[0]), tEface),
409 pos: pos,
410 })
411 fn.currentBlock = fn.newBasicBlock("unreachable")
412 return vTrue // any non-nil Value will do
413 }
414 return nil // treat all others as a regular function call
415 }
416
417 // addr lowers a single-result addressable expression e to SSA form,
418 // emitting code to fn and returning the location (an lvalue) defined
419 // by the expression.
420 //
421 // If escaping is true, addr marks the base variable of the
422 // addressable expression e as being a potentially escaping pointer
423 // value. For example, in this code:
424 //
425 // a := A{
426 // b: [1]B{B{c: 1}}
427 // }
428 // return &a.b[0].c
429 //
430 // the application of & causes a.b[0].c to have its address taken,
431 // which means that ultimately the local variable a must be
432 // heap-allocated. This is a simple but very conservative escape
433 // analysis.
434 //
435 // Operations forming potentially escaping pointers include:
436 // - &x, including when implicit in method call or composite literals.
437 // - a[:] iff a is an array (not *array)
438 // - references to variables in lexically enclosing functions.
439 func (b *builder) addr(fn *Function, e ast.Expr, escaping bool) lvalue {
440 switch e := e.(type) {
441 case *ast.Ident:
442 if isBlankIdent(e) {
443 return blank{}
444 }
445 obj := fn.objectOf(e).(*types.Var)
446 var v Value
447 if g := fn.Prog.packageLevelMember(obj); g != nil {
448 v = g.(*Global) // var (address)
449 } else {
450 v = fn.lookup(obj, escaping)
451 }
452 return &address{addr: v, pos: e.Pos(), expr: e}
453
454 case *ast.CompositeLit:
455 typ := typeparams.Deref(fn.typeOf(e))
456 var v *Alloc
457 if escaping {
458 v = emitNew(fn, typ, e.Lbrace, "complit")
459 } else {
460 v = emitLocal(fn, typ, e.Lbrace, "complit")
461 }
462 var sb storebuf
463 b.compLit(fn, v, e, true, &sb)
464 sb.emit(fn)
465 return &address{addr: v, pos: e.Lbrace, expr: e}
466
467 case *ast.ParenExpr:
468 return b.addr(fn, e.X, escaping)
469
470 case *ast.SelectorExpr:
471 sel := fn.selection(e)
472 if sel == nil {
473 // qualified identifier
474 return b.addr(fn, e.Sel, escaping)
475 }
476 if sel.kind != types.FieldVal {
477 panic(sel)
478 }
479 wantAddr := true
480 v := b.receiver(fn, e.X, wantAddr, escaping, sel)
481 index := sel.index[len(sel.index)-1]
482 fld := fieldOf(typeparams.MustDeref(v.Type()), index) // v is an addr.
483
484 // Due to the two phases of resolving AssignStmt, a panic from x.f = p()
485 // when x is nil is required to come after the side-effects of
486 // evaluating x and p().
487 emit := func(fn *Function) Value {
488 return emitFieldSelection(fn, v, index, true, e.Sel)
489 }
490 return &lazyAddress{addr: emit, t: fld.Type(), pos: e.Sel.Pos(), expr: e.Sel}
491
492 case *ast.IndexExpr:
493 xt := fn.typeOf(e.X)
494 elem, mode := indexType(xt)
495 var x Value
496 var et types.Type
497 switch mode {
498 case ixArrVar: // array, array|slice, array|*array, or array|*array|slice.
499 x = b.addr(fn, e.X, escaping).address(fn)
500 et = types.NewPointer(elem)
501 case ixVar: // *array, slice, *array|slice
502 x = b.expr(fn, e.X)
503 et = types.NewPointer(elem)
504 case ixMap:
505 mt := typeparams.CoreType(xt).(*types.Map)
506 return &element{
507 m: b.expr(fn, e.X),
508 k: emitConv(fn, b.expr(fn, e.Index), mt.Key()),
509 t: mt.Elem(),
510 pos: e.Lbrack,
511 }
512 default:
513 panic("unexpected container type in IndexExpr: " + xt.String())
514 }
515 index := b.expr(fn, e.Index)
516 if isUntyped(index.Type()) {
517 index = emitConv(fn, index, tInt)
518 }
519 // Due to the two phases of resolving AssignStmt, a panic from x[i] = p()
520 // when x is nil or i is out-of-bounds is required to come after the
521 // side-effects of evaluating x, i and p().
522 emit := func(fn *Function) Value {
523 v := &IndexAddr{
524 X: x,
525 Index: index,
526 }
527 v.setPos(e.Lbrack)
528 v.setType(et)
529 return fn.emit(v)
530 }
531 return &lazyAddress{addr: emit, t: typeparams.MustDeref(et), pos: e.Lbrack, expr: e}
532
533 case *ast.StarExpr:
534 return &address{addr: b.expr(fn, e.X), pos: e.Star, expr: e}
535 }
536
537 panic(fmt.Sprintf("unexpected address expression: %T", e))
538 }
539
540 type store struct {
541 lhs lvalue
542 rhs Value
543 }
544
545 type storebuf struct{ stores []store }
546
547 func (sb *storebuf) store(lhs lvalue, rhs Value) {
548 sb.stores = append(sb.stores, store{lhs, rhs})
549 }
550
551 func (sb *storebuf) emit(fn *Function) {
552 for _, s := range sb.stores {
553 s.lhs.store(fn, s.rhs)
554 }
555 }
556
557 // assign emits to fn code to initialize the lvalue loc with the value
558 // of expression e. If isZero is true, assign assumes that loc holds
559 // the zero value for its type.
560 //
561 // This is equivalent to loc.store(fn, b.expr(fn, e)), but may generate
562 // better code in some cases, e.g., for composite literals in an
563 // addressable location.
564 //
565 // If sb is not nil, assign generates code to evaluate expression e, but
566 // not to update loc. Instead, the necessary stores are appended to the
567 // storebuf sb so that they can be executed later. This allows correct
568 // in-place update of existing variables when the RHS is a composite
569 // literal that may reference parts of the LHS.
570 func (b *builder) assign(fn *Function, loc lvalue, e ast.Expr, isZero bool, sb *storebuf) {
571 // Can we initialize it in place?
572 if e, ok := ast.Unparen(e).(*ast.CompositeLit); ok {
573 // A CompositeLit never evaluates to a pointer,
574 // so if the type of the location is a pointer,
575 // an &-operation is implied.
576 if !is[blank](loc) && isPointerCore(loc.typ()) { // avoid calling blank.typ()
577 ptr := b.addr(fn, e, true).address(fn)
578 // copy address
579 if sb != nil {
580 sb.store(loc, ptr)
581 } else {
582 loc.store(fn, ptr)
583 }
584 return
585 }
586
587 if _, ok := loc.(*address); ok {
588 if isNonTypeParamInterface(loc.typ()) {
589 // e.g. var x interface{} = T{...}
590 // Can't in-place initialize an interface value.
591 // Fall back to copying.
592 } else {
593 // x = T{...} or x := T{...}
594 addr := loc.address(fn)
595 if sb != nil {
596 b.compLit(fn, addr, e, isZero, sb)
597 } else {
598 var sb storebuf
599 b.compLit(fn, addr, e, isZero, &sb)
600 sb.emit(fn)
601 }
602
603 // Subtle: emit debug ref for aggregate types only;
604 // slice and map are handled by store ops in compLit.
605 switch typeparams.CoreType(loc.typ()).(type) {
606 case *types.Struct, *types.Array:
607 emitDebugRef(fn, e, addr, true)
608 }
609
610 return
611 }
612 }
613 }
614
615 // simple case: just copy
616 rhs := b.expr(fn, e)
617 if sb != nil {
618 sb.store(loc, rhs)
619 } else {
620 loc.store(fn, rhs)
621 }
622 }
623
624 // expr lowers a single-result expression e to SSA form, emitting code
625 // to fn and returning the Value defined by the expression.
626 func (b *builder) expr(fn *Function, e ast.Expr) Value {
627 e = ast.Unparen(e)
628
629 tv := fn.info.Types[e]
630
631 // Is expression a constant?
632 if tv.Value != nil {
633 return NewConst(tv.Value, fn.typ(tv.Type))
634 }
635
636 var v Value
637 if tv.Addressable() {
638 // Prefer pointer arithmetic ({Index,Field}Addr) followed
639 // by Load over subelement extraction (e.g. Index, Field),
640 // to avoid large copies.
641 v = b.addr(fn, e, false).load(fn)
642 } else {
643 v = b.expr0(fn, e, tv)
644 }
645 if fn.debugInfo() {
646 emitDebugRef(fn, e, v, false)
647 }
648 return v
649 }
650
651 func (b *builder) expr0(fn *Function, e ast.Expr, tv types.TypeAndValue) Value {
652 switch e := e.(type) {
653 case *ast.BasicLit:
654 panic("non-constant BasicLit") // unreachable
655
656 case *ast.FuncLit:
657 /* function literal */
658 anon := &Function{
659 name: fmt.Sprintf("%s$%d", fn.Name(), 1+len(fn.AnonFuncs)),
660 Signature: fn.typeOf(e.Type).(*types.Signature),
661 pos: e.Type.Func,
662 parent: fn,
663 anonIdx: int32(len(fn.AnonFuncs)),
664 Pkg: fn.Pkg,
665 Prog: fn.Prog,
666 syntax: e,
667 info: fn.info,
668 goversion: fn.goversion,
669 build: (*builder).buildFromSyntax,
670 topLevelOrigin: nil, // use anonIdx to lookup an anon instance's origin.
671 typeparams: fn.typeparams, // share the parent's type parameters.
672 typeargs: fn.typeargs, // share the parent's type arguments.
673 subst: fn.subst, // share the parent's type substitutions.
674 uniq: fn.uniq, // start from parent's unique values
675 }
676 fn.AnonFuncs = append(fn.AnonFuncs, anon)
677 // Build anon immediately, as it may cause fn's locals to escape.
678 // (It is not marked 'built' until the end of the enclosing FuncDecl.)
679 anon.build(b, anon)
680 fn.uniq = anon.uniq // resume after anon's unique values
681 if anon.FreeVars == nil {
682 return anon
683 }
684 v := &MakeClosure{Fn: anon}
685 v.setType(fn.typ(tv.Type))
686 for _, fv := range anon.FreeVars {
687 v.Bindings = append(v.Bindings, fv.outer)
688 fv.outer = nil
689 }
690 return fn.emit(v)
691
692 case *ast.TypeAssertExpr: // single-result form only
693 return emitTypeAssert(fn, b.expr(fn, e.X), fn.typ(tv.Type), e.Lparen)
694
695 case *ast.CallExpr:
696 if fn.info.Types[e.Fun].IsType() {
697 // Explicit type conversion, e.g. string(x) or big.Int(x)
698 x := b.expr(fn, e.Args[0])
699 y := emitConv(fn, x, fn.typ(tv.Type))
700 if y != x {
701 switch y := y.(type) {
702 case *Convert:
703 y.pos = e.Lparen
704 case *ChangeType:
705 y.pos = e.Lparen
706 case *MakeInterface:
707 y.pos = e.Lparen
708 case *SliceToArrayPointer:
709 y.pos = e.Lparen
710 case *UnOp: // conversion from slice to array.
711 y.pos = e.Lparen
712 }
713 }
714 return y
715 }
716 // Call to "intrinsic" built-ins, e.g. new, make, panic.
717 if id, ok := ast.Unparen(e.Fun).(*ast.Ident); ok {
718 if obj, ok := fn.info.Uses[id].(*types.Builtin); ok {
719 if v := b.builtin(fn, obj, e.Args, fn.typ(tv.Type), e.Lparen); v != nil {
720 return v
721 }
722 }
723 }
724 // Regular function call.
725 var v Call
726 b.setCall(fn, e, &v.Call)
727 v.setType(fn.typ(tv.Type))
728 return emitCall(fn, &v)
729
730 case *ast.UnaryExpr:
731 switch e.Op {
732 case token.AND: // &X --- potentially escaping.
733 addr := b.addr(fn, e.X, true)
734 if _, ok := ast.Unparen(e.X).(*ast.StarExpr); ok {
735 // &*p must panic if p is nil (http://golang.org/s/go12nil).
736 // For simplicity, we'll just (suboptimally) rely
737 // on the side effects of a load.
738 // TODO(adonovan): emit dedicated nilcheck.
739 addr.load(fn)
740 }
741 return addr.address(fn)
742 case token.ADD:
743 return b.expr(fn, e.X)
744 case token.NOT, token.ARROW, token.SUB, token.XOR: // ! <- - ^
745 v := &UnOp{
746 Op: e.Op,
747 X: b.expr(fn, e.X),
748 }
749 v.setPos(e.OpPos)
750 v.setType(fn.typ(tv.Type))
751 return fn.emit(v)
752 default:
753 panic(e.Op)
754 }
755
756 case *ast.BinaryExpr:
757 switch e.Op {
758 case token.LAND, token.LOR:
759 return b.logicalBinop(fn, e)
760 case token.SHL, token.SHR:
761 fallthrough
762 case token.ADD, token.SUB, token.MUL, token.QUO, token.REM, token.AND, token.OR, token.XOR, token.AND_NOT:
763 return emitArith(fn, e.Op, b.expr(fn, e.X), b.expr(fn, e.Y), fn.typ(tv.Type), e.OpPos)
764
765 case token.EQL, token.NEQ, token.GTR, token.LSS, token.LEQ, token.GEQ:
766 cmp := emitCompare(fn, e.Op, b.expr(fn, e.X), b.expr(fn, e.Y), e.OpPos)
767 // The type of x==y may be UntypedBool.
768 return emitConv(fn, cmp, types.Default(fn.typ(tv.Type)))
769 default:
770 panic("illegal op in BinaryExpr: " + e.Op.String())
771 }
772
773 case *ast.SliceExpr:
774 var low, high, max Value
775 var x Value
776 xtyp := fn.typeOf(e.X)
777 switch typeparams.CoreType(xtyp).(type) {
778 case *types.Array:
779 // Potentially escaping.
780 x = b.addr(fn, e.X, true).address(fn)
781 case *types.Basic, *types.Slice, *types.Pointer: // *array
782 x = b.expr(fn, e.X)
783 default:
784 // core type exception?
785 if isBytestring(xtyp) {
786 x = b.expr(fn, e.X) // bytestring is handled as string and []byte.
787 } else {
788 panic("unexpected sequence type in SliceExpr")
789 }
790 }
791 if e.Low != nil {
792 low = b.expr(fn, e.Low)
793 }
794 if e.High != nil {
795 high = b.expr(fn, e.High)
796 }
797 if e.Slice3 {
798 max = b.expr(fn, e.Max)
799 }
800 v := &Slice{
801 X: x,
802 Low: low,
803 High: high,
804 Max: max,
805 }
806 v.setPos(e.Lbrack)
807 v.setType(fn.typ(tv.Type))
808 return fn.emit(v)
809
810 case *ast.Ident:
811 obj := fn.info.Uses[e]
812 // Universal built-in or nil?
813 switch obj := obj.(type) {
814 case *types.Builtin:
815 return &Builtin{name: obj.Name(), sig: fn.instanceType(e).(*types.Signature)}
816 case *types.Nil:
817 return zeroConst(fn.instanceType(e))
818 }
819
820 // Package-level func or var?
821 // (obj must belong to same package or a direct import.)
822 if v := fn.Prog.packageLevelMember(obj); v != nil {
823 if g, ok := v.(*Global); ok {
824 return emitLoad(fn, g) // var (address)
825 }
826 callee := v.(*Function) // (func)
827 if callee.typeparams.Len() > 0 {
828 targs := fn.subst.types(instanceArgs(fn.info, e))
829 callee = callee.instance(targs, b)
830 }
831 return callee
832 }
833 // Local var.
834 return emitLoad(fn, fn.lookup(obj.(*types.Var), false)) // var (address)
835
836 case *ast.SelectorExpr:
837 sel := fn.selection(e)
838 if sel == nil {
839 // builtin unsafe.{Add,Slice}
840 if obj, ok := fn.info.Uses[e.Sel].(*types.Builtin); ok {
841 return &Builtin{name: obj.Name(), sig: fn.typ(tv.Type).(*types.Signature)}
842 }
843 // qualified identifier
844 return b.expr(fn, e.Sel)
845 }
846 switch sel.kind {
847 case types.MethodExpr:
848 // (*T).f or T.f, the method f from the method-set of type T.
849 // The result is a "thunk".
850 thunk := createThunk(fn.Prog, sel)
851 b.enqueue(thunk)
852 return emitConv(fn, thunk, fn.typ(tv.Type))
853
854 case types.MethodVal:
855 // e.f where e is an expression and f is a method.
856 // The result is a "bound".
857 obj := sel.obj.(*types.Func)
858 rt := fn.typ(recvType(obj))
859 wantAddr := isPointer(rt)
860 escaping := true
861 v := b.receiver(fn, e.X, wantAddr, escaping, sel)
862
863 if types.IsInterface(rt) {
864 // If v may be an interface type I (after instantiating),
865 // we must emit a check that v is non-nil.
866 if recv, ok := types.Unalias(sel.recv).(*types.TypeParam); ok {
867 // Emit a nil check if any possible instantiation of the
868 // type parameter is an interface type.
869 if !typeSetIsEmpty(recv) {
870 // recv has a concrete term its typeset.
871 // So it cannot be instantiated as an interface.
872 //
873 // Example:
874 // func _[T interface{~int; Foo()}] () {
875 // var v T
876 // _ = v.Foo // <-- MethodVal
877 // }
878 } else {
879 // rt may be instantiated as an interface.
880 // Emit nil check: typeassert (any(v)).(any).
881 emitTypeAssert(fn, emitConv(fn, v, tEface), tEface, token.NoPos)
882 }
883 } else {
884 // non-type param interface
885 // Emit nil check: typeassert v.(I).
886 emitTypeAssert(fn, v, rt, e.Sel.Pos())
887 }
888 }
889 if targs := receiverTypeArgs(obj); len(targs) > 0 {
890 // obj is generic.
891 obj = fn.Prog.canon.instantiateMethod(obj, fn.subst.types(targs), fn.Prog.ctxt)
892 }
893 bound := createBound(fn.Prog, obj)
894 b.enqueue(bound)
895
896 // The assignment may widen a type parameter to its
897 // interface bound (case #3 of go.dev/issue.78110).
898 v = emitConv(fn, v, bound.FreeVars[0].Type())
899
900 c := &MakeClosure{
901 Fn: bound,
902 Bindings: []Value{v},
903 }
904 c.setPos(e.Sel.Pos())
905 c.setType(fn.typ(tv.Type))
906 return fn.emit(c)
907
908 case types.FieldVal:
909 indices := sel.index
910 last := len(indices) - 1
911 v := b.expr(fn, e.X)
912 v = emitImplicitSelections(fn, v, indices[:last], e.Pos())
913 v = emitFieldSelection(fn, v, indices[last], false, e.Sel)
914 return v
915 }
916
917 panic("unexpected expression-relative selector")
918
919 case *ast.IndexListExpr:
920 // f[X, Y] must be a generic function
921 if !instance(fn.info, e.X) {
922 panic("unexpected expression-could not match index list to instantiation")
923 }
924 return b.expr(fn, e.X) // Handle instantiation within the *Ident or *SelectorExpr cases.
925
926 case *ast.IndexExpr:
927 if instance(fn.info, e.X) {
928 return b.expr(fn, e.X) // Handle instantiation within the *Ident or *SelectorExpr cases.
929 }
930 // not a generic instantiation.
931 xt := fn.typeOf(e.X)
932 switch et, mode := indexType(xt); mode {
933 case ixVar:
934 // Addressable slice/array; use IndexAddr and Load.
935 return b.addr(fn, e, false).load(fn)
936
937 case ixArrVar, ixValue:
938 // An array in a register, a string or a combined type that contains
939 // either an [_]array (ixArrVar) or string (ixValue).
940
941 // Note: for ixArrVar and CoreType(xt)==nil can be IndexAddr and Load.
942 index := b.expr(fn, e.Index)
943 if isUntyped(index.Type()) {
944 index = emitConv(fn, index, tInt)
945 }
946 v := &Index{
947 X: b.expr(fn, e.X),
948 Index: index,
949 }
950 v.setPos(e.Lbrack)
951 v.setType(et)
952 return fn.emit(v)
953
954 case ixMap:
955 ct := typeparams.CoreType(xt).(*types.Map)
956 v := &Lookup{
957 X: b.expr(fn, e.X),
958 Index: emitConv(fn, b.expr(fn, e.Index), ct.Key()),
959 }
960 v.setPos(e.Lbrack)
961 v.setType(ct.Elem())
962 return fn.emit(v)
963 default:
964 panic("unexpected container type in IndexExpr: " + xt.String())
965 }
966
967 case *ast.CompositeLit, *ast.StarExpr:
968 // Addressable types (lvalues)
969 return b.addr(fn, e, false).load(fn)
970 }
971
972 panic(fmt.Sprintf("unexpected expr: %T", e))
973 }
974
975 // stmtList emits to fn code for all statements in list.
976 func (b *builder) stmtList(fn *Function, list []ast.Stmt) {
977 for _, s := range list {
978 b.stmt(fn, s)
979 }
980 }
981
982 // receiver emits to fn code for expression e in the "receiver"
983 // position of selection e.f (where f may be a field or a method) and
984 // returns the effective receiver after applying the implicit field
985 // selections of sel.
986 //
987 // wantAddr requests that the result is an address. If
988 // !sel.indirect, this may require that e be built in addr() mode; it
989 // must thus be addressable.
990 //
991 // escaping is defined as per builder.addr().
992 func (b *builder) receiver(fn *Function, e ast.Expr, wantAddr, escaping bool, sel *selection) Value {
993 var v Value
994 if wantAddr && !sel.indirect && !isPointerCore(fn.typeOf(e)) {
995 v = b.addr(fn, e, escaping).address(fn)
996 } else {
997 v = b.expr(fn, e)
998 }
999
1000 last := len(sel.index) - 1
1001 // The position of implicit selection is the position of the inducing receiver expression.
1002 v = emitImplicitSelections(fn, v, sel.index[:last], e.Pos())
1003 if types.IsInterface(v.Type()) {
1004 // When v is an interface, sel.Kind()==MethodValue and v.f is invoked.
1005 // So v is not loaded, even if v has a pointer core type.
1006 } else if !wantAddr && isPointerCore(v.Type()) {
1007 v = emitLoad(fn, v)
1008 }
1009 return v
1010 }
1011
1012 // setCallFunc populates the function parts of a CallCommon structure
1013 // (Func, Method, Recv, Args[0]) based on the kind of invocation
1014 // occurring in e.
1015 func (b *builder) setCallFunc(fn *Function, e *ast.CallExpr, c *CallCommon) {
1016 c.pos = e.Lparen
1017
1018 // Is this a method call?
1019 if selector, ok := ast.Unparen(e.Fun).(*ast.SelectorExpr); ok {
1020 sel := fn.selection(selector)
1021 if sel != nil && sel.kind == types.MethodVal {
1022 obj := sel.obj.(*types.Func)
1023 recv := recvType(obj)
1024
1025 wantAddr := isPointer(recv)
1026 escaping := true
1027 v := b.receiver(fn, selector.X, wantAddr, escaping, sel)
1028 if types.IsInterface(recv) {
1029 // Invoke-mode call.
1030 c.Value = v // possibly type param
1031 c.Method = obj
1032 } else {
1033 // "Call"-mode call.
1034 c.Value = fn.Prog.objectMethod(obj, b)
1035 c.Args = append(c.Args, v)
1036 }
1037 return
1038 }
1039
1040 // sel.kind==MethodExpr indicates T.f() or (*T).f():
1041 // a statically dispatched call to the method f in the
1042 // method-set of T or *T. T may be an interface.
1043 //
1044 // e.Fun would evaluate to a concrete method, interface
1045 // wrapper function, or promotion wrapper.
1046 //
1047 // For now, we evaluate it in the usual way.
1048 //
1049 // TODO(adonovan): opt: inline expr() here, to make the
1050 // call static and to avoid generation of wrappers.
1051 // It's somewhat tricky as it may consume the first
1052 // actual parameter if the call is "invoke" mode.
1053 //
1054 // Examples:
1055 // type T struct{}; func (T) f() {} // "call" mode
1056 // type T interface { f() } // "invoke" mode
1057 //
1058 // type S struct{ T }
1059 //
1060 // var s S
1061 // S.f(s)
1062 // (*S).f(&s)
1063 //
1064 // Suggested approach:
1065 // - consume the first actual parameter expression
1066 // and build it with b.expr().
1067 // - apply implicit field selections.
1068 // - use MethodVal logic to populate fields of c.
1069 }
1070
1071 // Evaluate the function operand in the usual way.
1072 c.Value = b.expr(fn, e.Fun)
1073 }
1074
1075 // emitCallArgs emits to f code for the actual parameters of call e to
1076 // a (possibly built-in) function of effective type sig.
1077 // The argument values are appended to args, which is then returned.
1078 func (b *builder) emitCallArgs(fn *Function, sig *types.Signature, e *ast.CallExpr, args []Value) []Value {
1079 // f(x, y, z...): pass slice z straight through.
1080 if e.Ellipsis != 0 {
1081 for i, arg := range e.Args {
1082 v := emitConv(fn, b.expr(fn, arg), sig.Params().At(i).Type())
1083 args = append(args, v)
1084 }
1085 return args
1086 }
1087
1088 offset := len(args) // 1 if call has receiver, 0 otherwise
1089
1090 // Evaluate actual parameter expressions.
1091 //
1092 // If this is a chained call of the form f(g()) where g has
1093 // multiple return values (MRV), they are flattened out into
1094 // args; a suffix of them may end up in a varargs slice.
1095 for _, arg := range e.Args {
1096 v := b.expr(fn, arg)
1097 if ttuple, ok := v.Type().(*types.Tuple); ok { // MRV chain
1098 for i, n := 0, ttuple.Len(); i < n; i++ {
1099 args = append(args, emitExtract(fn, v, i))
1100 }
1101 } else {
1102 args = append(args, v)
1103 }
1104 }
1105
1106 // Actual->formal assignability conversions for normal parameters.
1107 np := sig.Params().Len() // number of normal parameters
1108 if sig.Variadic() {
1109 np--
1110 }
1111 for i := 0; i < np; i++ {
1112 args[offset+i] = emitConv(fn, args[offset+i], sig.Params().At(i).Type())
1113 }
1114
1115 // Actual->formal assignability conversions for variadic parameter,
1116 // and construction of slice.
1117 if sig.Variadic() {
1118 varargs := args[offset+np:]
1119 st := sig.Params().At(np).Type().(*types.Slice)
1120 vt := st.Elem()
1121 if len(varargs) == 0 {
1122 args = append(args, zeroConst(st))
1123 } else {
1124 // Replace a suffix of args with a slice containing it.
1125 at := types.NewArray(vt, int64(len(varargs)))
1126 a := emitNew(fn, at, token.NoPos, "varargs")
1127 a.setPos(e.Rparen)
1128 for i, arg := range varargs {
1129 iaddr := &IndexAddr{
1130 X: a,
1131 Index: intConst(int64(i)),
1132 }
1133 iaddr.setType(types.NewPointer(vt))
1134 fn.emit(iaddr)
1135 emitStore(fn, iaddr, arg, arg.Pos())
1136 }
1137 s := &Slice{X: a}
1138 s.setType(st)
1139 args[offset+np] = fn.emit(s)
1140 args = args[:offset+np+1]
1141 }
1142 }
1143 return args
1144 }
1145
1146 // setCall emits to fn code to evaluate all the parameters of a function
1147 // call e, and populates *c with those values.
1148 func (b *builder) setCall(fn *Function, e *ast.CallExpr, c *CallCommon) {
1149 // First deal with the f(...) part and optional receiver.
1150 b.setCallFunc(fn, e, c)
1151
1152 // Then append the other actual parameters.
1153 sig, _ := typeparams.CoreType(fn.typeOf(e.Fun)).(*types.Signature)
1154 if sig == nil {
1155 panic(fmt.Sprintf("no signature for call of %s", e.Fun))
1156 }
1157 c.Args = b.emitCallArgs(fn, sig, e, c.Args)
1158 }
1159
1160 // assignOp emits to fn code to perform loc <op>= val.
1161 func (b *builder) assignOp(fn *Function, loc lvalue, val Value, op token.Token, pos token.Pos) {
1162 loc.store(fn, emitArith(fn, op, loc.load(fn), val, loc.typ(), pos))
1163 }
1164
1165 // localValueSpec emits to fn code to define all of the vars in the
1166 // function-local ValueSpec, spec.
1167 func (b *builder) localValueSpec(fn *Function, spec *ast.ValueSpec) {
1168 switch {
1169 case len(spec.Values) == len(spec.Names):
1170 // e.g. var x, y = 0, 1
1171 // 1:1 assignment
1172 for i, id := range spec.Names {
1173 if !isBlankIdent(id) {
1174 emitLocalVar(fn, identVar(fn, id))
1175 }
1176 lval := b.addr(fn, id, false) // non-escaping
1177 b.assign(fn, lval, spec.Values[i], true, nil)
1178 }
1179
1180 case len(spec.Values) == 0:
1181 // e.g. var x, y int
1182 // Locals are implicitly zero-initialized.
1183 for _, id := range spec.Names {
1184 if !isBlankIdent(id) {
1185 lhs := emitLocalVar(fn, identVar(fn, id))
1186 if fn.debugInfo() {
1187 emitDebugRef(fn, id, lhs, true)
1188 }
1189 }
1190 }
1191
1192 default:
1193 // e.g. var x, y = pos()
1194 tuple := b.exprN(fn, spec.Values[0])
1195 for i, id := range spec.Names {
1196 if !isBlankIdent(id) {
1197 emitLocalVar(fn, identVar(fn, id))
1198 lhs := b.addr(fn, id, false) // non-escaping
1199 lhs.store(fn, emitExtract(fn, tuple, i))
1200 }
1201 }
1202 }
1203 }
1204
1205 // assignStmt emits code to fn for a parallel assignment of rhss to lhss.
1206 // isDef is true if this is a short variable declaration (:=).
1207 //
1208 // Note the similarity with localValueSpec.
1209 func (b *builder) assignStmt(fn *Function, lhss, rhss []ast.Expr, isDef bool) {
1210 // Side effects of all LHSs and RHSs must occur in left-to-right order.
1211 lvals := make([]lvalue, len(lhss))
1212 isZero := make([]bool, len(lhss))
1213 for i, lhs := range lhss {
1214 var lval lvalue = blank{}
1215 if !isBlankIdent(lhs) {
1216 if isDef {
1217 if obj, ok := fn.info.Defs[lhs.(*ast.Ident)].(*types.Var); ok {
1218 emitLocalVar(fn, obj)
1219 isZero[i] = true
1220 }
1221 }
1222 lval = b.addr(fn, lhs, false) // non-escaping
1223 }
1224 lvals[i] = lval
1225 }
1226 if len(lhss) == len(rhss) {
1227 // Simple assignment: x = f() (!isDef)
1228 // Parallel assignment: x, y = f(), g() (!isDef)
1229 // or short var decl: x, y := f(), g() (isDef)
1230 //
1231 // In all cases, the RHSs may refer to the LHSs,
1232 // so we need a storebuf.
1233 var sb storebuf
1234 for i := range rhss {
1235 b.assign(fn, lvals[i], rhss[i], isZero[i], &sb)
1236 }
1237 sb.emit(fn)
1238 } else {
1239 // e.g. x, y = pos()
1240 tuple := b.exprN(fn, rhss[0])
1241 emitDebugRef(fn, rhss[0], tuple, false)
1242 for i, lval := range lvals {
1243 lval.store(fn, emitExtract(fn, tuple, i))
1244 }
1245 }
1246 }
1247
1248 // arrayLen returns the length of the array whose composite literal elements are elts.
1249 func (b *builder) arrayLen(fn *Function, elts []ast.Expr) int64 {
1250 var max int64 = -1
1251 var i int64 = -1
1252 for _, e := range elts {
1253 if kv, ok := e.(*ast.KeyValueExpr); ok {
1254 i = b.expr(fn, kv.Key).(*Const).Int64()
1255 } else {
1256 i++
1257 }
1258 if i > max {
1259 max = i
1260 }
1261 }
1262 return max + 1
1263 }
1264
1265 // compLit emits to fn code to initialize a composite literal e at
1266 // address addr with type typ.
1267 //
1268 // Nested composite literals are recursively initialized in place
1269 // where possible. If isZero is true, compLit assumes that addr
1270 // holds the zero value for typ.
1271 //
1272 // Because the elements of a composite literal may refer to the
1273 // variables being updated, as in the second line below,
1274 //
1275 // x := T{a: 1}
1276 // x = T{a: x.a}
1277 //
1278 // all the reads must occur before all the writes. Thus all stores to
1279 // loc are emitted to the storebuf sb for later execution.
1280 //
1281 // A CompositeLit may have pointer type only in the recursive (nested)
1282 // case when the type name is implicit. e.g. in []*T{{}}, the inner
1283 // literal has type *T behaves like &T{}.
1284 // In that case, addr must hold a T, not a *T.
1285 func (b *builder) compLit(fn *Function, addr Value, e *ast.CompositeLit, isZero bool, sb *storebuf) {
1286 typ := typeparams.Deref(fn.typeOf(e)) // retain the named/alias/param type, if any
1287 switch t := typeparams.CoreType(typ).(type) {
1288 case *types.Struct:
1289 if !isZero && len(e.Elts) != t.NumFields() {
1290 // memclear
1291 zt := typeparams.MustDeref(addr.Type())
1292 sb.store(&address{addr, e.Lbrace, nil}, zeroConst(zt))
1293 isZero = true
1294 }
1295 var fIndices []int
1296 for i, e := range e.Elts {
1297 var (
1298 pos token.Pos
1299 fType types.Type
1300 )
1301
1302 if kv, ok := e.(*ast.KeyValueExpr); ok { // tagged field
1303 fname := kv.Key.(*ast.Ident).Name
1304 obj, index, _ := types.LookupFieldOrMethod(t, true, fn.declaredPackage().Pkg, fname)
1305 fIndices = append(fIndices[:0], index...)
1306 pos = kv.Colon
1307 e = kv.Value
1308 fType = obj.Type()
1309 } else { // untagged field
1310 fIndices = append(fIndices[:0], i)
1311 pos = e.Pos()
1312 fType = t.Field(i).Type()
1313 }
1314
1315 last := len(fIndices) - 1
1316 v := emitImplicitSelections(fn, addr, fIndices[:last], pos)
1317
1318 faddr := &FieldAddr{
1319 X: v,
1320 Field: fIndices[last],
1321 }
1322 faddr.setPos(pos)
1323 faddr.setType(types.NewPointer(fType))
1324 fn.emit(faddr)
1325 b.assign(fn, &address{addr: faddr, pos: pos, expr: e}, e, isZero, sb)
1326 }
1327
1328 case *types.Array, *types.Slice:
1329 var at *types.Array
1330 var array Value
1331 switch t := t.(type) {
1332 case *types.Slice:
1333 at = types.NewArray(t.Elem(), b.arrayLen(fn, e.Elts))
1334 array = emitNew(fn, at, e.Lbrace, "slicelit")
1335 case *types.Array:
1336 at = t
1337 array = addr
1338
1339 if !isZero && int64(len(e.Elts)) != at.Len() {
1340 // memclear
1341 zt := typeparams.MustDeref(array.Type())
1342 sb.store(&address{array, e.Lbrace, nil}, zeroConst(zt))
1343 }
1344 }
1345
1346 var idx *Const
1347 for _, e := range e.Elts {
1348 pos := e.Pos()
1349 if kv, ok := e.(*ast.KeyValueExpr); ok {
1350 idx = b.expr(fn, kv.Key).(*Const)
1351 pos = kv.Colon
1352 e = kv.Value
1353 } else {
1354 var idxval int64
1355 if idx != nil {
1356 idxval = idx.Int64() + 1
1357 }
1358 idx = intConst(idxval)
1359 }
1360 iaddr := &IndexAddr{
1361 X: array,
1362 Index: idx,
1363 }
1364 iaddr.setType(types.NewPointer(at.Elem()))
1365 fn.emit(iaddr)
1366 if t != at { // slice
1367 // backing array is unaliased => storebuf not needed.
1368 b.assign(fn, &address{addr: iaddr, pos: pos, expr: e}, e, true, nil)
1369 } else {
1370 b.assign(fn, &address{addr: iaddr, pos: pos, expr: e}, e, true, sb)
1371 }
1372 }
1373
1374 if t != at { // slice
1375 s := &Slice{X: array}
1376 s.setPos(e.Lbrace)
1377 s.setType(typ)
1378 sb.store(&address{addr: addr, pos: e.Lbrace, expr: e}, fn.emit(s))
1379 }
1380
1381 case *types.Map:
1382 m := &MakeMap{Reserve: intConst(int64(len(e.Elts)))}
1383 m.setPos(e.Lbrace)
1384 m.setType(typ)
1385 fn.emit(m)
1386 for _, e := range e.Elts {
1387 e := e.(*ast.KeyValueExpr)
1388
1389 // If a key expression in a map literal is itself a
1390 // composite literal, the type may be omitted.
1391 // For example:
1392 // map[*struct{}]bool{{}: true}
1393 // An &-operation may be implied:
1394 // map[*struct{}]bool{&struct{}{}: true}
1395 wantAddr := false
1396 if _, ok := ast.Unparen(e.Key).(*ast.CompositeLit); ok {
1397 wantAddr = isPointerCore(t.Key())
1398 }
1399
1400 var key Value
1401 if wantAddr {
1402 // A CompositeLit never evaluates to a pointer,
1403 // so if the type of the location is a pointer,
1404 // an &-operation is implied.
1405 key = b.addr(fn, e.Key, true).address(fn)
1406 } else {
1407 key = b.expr(fn, e.Key)
1408 }
1409
1410 loc := element{
1411 m: m,
1412 k: emitConv(fn, key, t.Key()),
1413 t: t.Elem(),
1414 pos: e.Colon,
1415 }
1416
1417 // We call assign() only because it takes care
1418 // of any &-operation required in the recursive
1419 // case, e.g.,
1420 // map[int]*struct{}{0: {}} implies &struct{}{}.
1421 // In-place update is of course impossible,
1422 // and no storebuf is needed.
1423 b.assign(fn, &loc, e.Value, true, nil)
1424 }
1425 sb.store(&address{addr: addr, pos: e.Lbrace, expr: e}, m)
1426
1427 default:
1428 panic("unexpected CompositeLit type: " + typ.String())
1429 }
1430 }
1431
1432 // switchStmt emits to fn code for the switch statement s, optionally
1433 // labelled by label.
1434 func (b *builder) switchStmt(fn *Function, s *ast.SwitchStmt, label *lblock) {
1435 // We treat SwitchStmt like a sequential if-else chain.
1436 // Multiway dispatch can be recovered later by ssautil.Switches()
1437 // to those cases that are free of side effects.
1438 if s.Init != nil {
1439 b.stmt(fn, s.Init)
1440 }
1441 var tag Value = vTrue
1442 if s.Tag != nil {
1443 tag = b.expr(fn, s.Tag)
1444 }
1445 done := fn.newBasicBlock("switch.done")
1446 if label != nil {
1447 label._break = done
1448 }
1449 // We pull the default case (if present) down to the end.
1450 // But each fallthrough label must point to the next
1451 // body block in source order, so we preallocate a
1452 // body block (fallthru) for the next case.
1453 // Unfortunately this makes for a confusing block order.
1454 var dfltBody *[]ast.Stmt
1455 var dfltFallthrough *BasicBlock
1456 var fallthru, dfltBlock *BasicBlock
1457 ncases := len(s.Body.List)
1458 for i, clause := range s.Body.List {
1459 body := fallthru
1460 if body == nil {
1461 body = fn.newBasicBlock("switch.body") // first case only
1462 }
1463
1464 // Preallocate body block for the next case.
1465 fallthru = done
1466 if i+1 < ncases {
1467 fallthru = fn.newBasicBlock("switch.body")
1468 }
1469
1470 cc := clause.(*ast.CaseClause)
1471 if cc.List == nil {
1472 // Default case.
1473 dfltBody = &cc.Body
1474 dfltFallthrough = fallthru
1475 dfltBlock = body
1476 continue
1477 }
1478
1479 var nextCond *BasicBlock
1480 for _, cond := range cc.List {
1481 nextCond = fn.newBasicBlock("switch.next")
1482 // For boolean switches, emit short-circuit control flow,
1483 // just like an if/else-chain.
1484 if tag == vTrue && !isNonTypeParamInterface(fn.info.Types[cond].Type) {
1485 b.cond(fn, cond, body, nextCond)
1486 } else {
1487 c := emitCompare(fn, token.EQL, tag, b.expr(fn, cond), cond.Pos())
1488 emitIf(fn, c, body, nextCond)
1489 }
1490 fn.currentBlock = nextCond
1491 }
1492 fn.currentBlock = body
1493 fn.targets = &targets{
1494 tail: fn.targets,
1495 _break: done,
1496 _fallthrough: fallthru,
1497 }
1498 b.stmtList(fn, cc.Body)
1499 fn.targets = fn.targets.tail
1500 emitJump(fn, done)
1501 fn.currentBlock = nextCond
1502 }
1503 if dfltBlock != nil {
1504 emitJump(fn, dfltBlock)
1505 fn.currentBlock = dfltBlock
1506 fn.targets = &targets{
1507 tail: fn.targets,
1508 _break: done,
1509 _fallthrough: dfltFallthrough,
1510 }
1511 b.stmtList(fn, *dfltBody)
1512 fn.targets = fn.targets.tail
1513 }
1514 emitJump(fn, done)
1515 fn.currentBlock = done
1516 }
1517
1518 // typeSwitchStmt emits to fn code for the type switch statement s, optionally
1519 // labelled by label.
1520 func (b *builder) typeSwitchStmt(fn *Function, s *ast.TypeSwitchStmt, label *lblock) {
1521 // We treat TypeSwitchStmt like a sequential if-else chain.
1522 // Multiway dispatch can be recovered later by ssautil.Switches().
1523
1524 // Typeswitch lowering:
1525 //
1526 // var x X
1527 // switch y := x.(type) {
1528 // case T1, T2: S1 // >1 (y := x)
1529 // case nil: SN // nil (y := x)
1530 // default: SD // 0 types (y := x)
1531 // case T3: S3 // 1 type (y := x.(T3))
1532 // }
1533 //
1534 // ...s.Init...
1535 // x := eval x
1536 // .caseT1:
1537 // t1, ok1 := typeswitch,ok x <T1>
1538 // if ok1 then goto S1 else goto .caseT2
1539 // .caseT2:
1540 // t2, ok2 := typeswitch,ok x <T2>
1541 // if ok2 then goto S1 else goto .caseNil
1542 // .S1:
1543 // y := x
1544 // ...S1...
1545 // goto done
1546 // .caseNil:
1547 // if t2, ok2 := typeswitch,ok x <T2>
1548 // if x == nil then goto SN else goto .caseT3
1549 // .SN:
1550 // y := x
1551 // ...SN...
1552 // goto done
1553 // .caseT3:
1554 // t3, ok3 := typeswitch,ok x <T3>
1555 // if ok3 then goto S3 else goto default
1556 // .S3:
1557 // y := t3
1558 // ...S3...
1559 // goto done
1560 // .default:
1561 // y := x
1562 // ...SD...
1563 // goto done
1564 // .done:
1565 if s.Init != nil {
1566 b.stmt(fn, s.Init)
1567 }
1568
1569 var x Value
1570 switch ass := s.Assign.(type) {
1571 case *ast.ExprStmt: // x.(type)
1572 x = b.expr(fn, ast.Unparen(ass.X).(*ast.TypeAssertExpr).X)
1573 case *ast.AssignStmt: // y := x.(type)
1574 x = b.expr(fn, ast.Unparen(ass.Rhs[0]).(*ast.TypeAssertExpr).X)
1575 }
1576
1577 done := fn.newBasicBlock("typeswitch.done")
1578 if label != nil {
1579 label._break = done
1580 }
1581 var default_ *ast.CaseClause
1582 for _, clause := range s.Body.List {
1583 cc := clause.(*ast.CaseClause)
1584 if cc.List == nil {
1585 default_ = cc
1586 continue
1587 }
1588 body := fn.newBasicBlock("typeswitch.body")
1589 var next *BasicBlock
1590 var casetype types.Type
1591 var ti Value // ti, ok := typeassert,ok x <Ti>
1592 for _, cond := range cc.List {
1593 next = fn.newBasicBlock("typeswitch.next")
1594 casetype = fn.typeOf(cond)
1595 var condv Value
1596 if casetype == tUntypedNil {
1597 condv = emitCompare(fn, token.EQL, x, zeroConst(x.Type()), cond.Pos())
1598 ti = x
1599 } else {
1600 yok := emitTypeTest(fn, x, casetype, cc.Case)
1601 ti = emitExtract(fn, yok, 0)
1602 condv = emitExtract(fn, yok, 1)
1603 }
1604 emitIf(fn, condv, body, next)
1605 fn.currentBlock = next
1606 }
1607 if len(cc.List) != 1 {
1608 ti = x
1609 }
1610 fn.currentBlock = body
1611 b.typeCaseBody(fn, cc, ti, done)
1612 fn.currentBlock = next
1613 }
1614 if default_ != nil {
1615 b.typeCaseBody(fn, default_, x, done)
1616 } else {
1617 emitJump(fn, done)
1618 }
1619 fn.currentBlock = done
1620 }
1621
1622 func (b *builder) typeCaseBody(fn *Function, cc *ast.CaseClause, x Value, done *BasicBlock) {
1623 if obj, ok := fn.info.Implicits[cc].(*types.Var); ok {
1624 // In a switch y := x.(type), each case clause
1625 // implicitly declares a distinct object y.
1626 // In a single-type case, y has that type.
1627 // In multi-type cases, 'case nil' and default,
1628 // y has the same type as the interface operand.
1629 emitStore(fn, emitLocalVar(fn, obj), x, obj.Pos())
1630 }
1631 fn.targets = &targets{
1632 tail: fn.targets,
1633 _break: done,
1634 }
1635 b.stmtList(fn, cc.Body)
1636 fn.targets = fn.targets.tail
1637 emitJump(fn, done)
1638 }
1639
1640 // selectStmt emits to fn code for the select statement s, optionally
1641 // labelled by label.
1642 func (b *builder) selectStmt(fn *Function, s *ast.SelectStmt, label *lblock) {
1643 // A blocking select of a single case degenerates to a
1644 // simple send or receive.
1645 // TODO(adonovan): opt: is this optimization worth its weight?
1646 if len(s.Body.List) == 1 {
1647 clause := s.Body.List[0].(*ast.CommClause)
1648 if clause.Comm != nil {
1649 b.stmt(fn, clause.Comm)
1650 done := fn.newBasicBlock("select.done")
1651 if label != nil {
1652 label._break = done
1653 }
1654 fn.targets = &targets{
1655 tail: fn.targets,
1656 _break: done,
1657 }
1658 b.stmtList(fn, clause.Body)
1659 fn.targets = fn.targets.tail
1660 emitJump(fn, done)
1661 fn.currentBlock = done
1662 return
1663 }
1664 }
1665
1666 // First evaluate all channels in all cases, and find
1667 // the directions of each state.
1668 var states []*SelectState
1669 blocking := true
1670 debugInfo := fn.debugInfo()
1671 for _, clause := range s.Body.List {
1672 var st *SelectState
1673 switch comm := clause.(*ast.CommClause).Comm.(type) {
1674 case nil: // default case
1675 blocking = false
1676 continue
1677
1678 case *ast.SendStmt: // ch<- i
1679 ch := b.expr(fn, comm.Chan)
1680 chtyp := typeparams.CoreType(fn.typ(ch.Type())).(*types.Chan)
1681 st = &SelectState{
1682 Dir: types.SendOnly,
1683 Chan: ch,
1684 Send: emitConv(fn, b.expr(fn, comm.Value), chtyp.Elem()),
1685 Pos: comm.Arrow,
1686 }
1687 if debugInfo {
1688 st.DebugNode = comm
1689 }
1690
1691 case *ast.AssignStmt: // x := <-ch
1692 recv := ast.Unparen(comm.Rhs[0]).(*ast.UnaryExpr)
1693 st = &SelectState{
1694 Dir: types.RecvOnly,
1695 Chan: b.expr(fn, recv.X),
1696 Pos: recv.OpPos,
1697 }
1698 if debugInfo {
1699 st.DebugNode = recv
1700 }
1701
1702 case *ast.ExprStmt: // <-ch
1703 recv := ast.Unparen(comm.X).(*ast.UnaryExpr)
1704 st = &SelectState{
1705 Dir: types.RecvOnly,
1706 Chan: b.expr(fn, recv.X),
1707 Pos: recv.OpPos,
1708 }
1709 if debugInfo {
1710 st.DebugNode = recv
1711 }
1712 }
1713 states = append(states, st)
1714 }
1715
1716 // We dispatch on the (fair) result of Select using a
1717 // sequential if-else chain, in effect:
1718 //
1719 // idx, recvOk, r0...r_n-1 := select(...)
1720 // if idx == 0 { // receive on channel 0 (first receive => r0)
1721 // x, ok := r0, recvOk
1722 // ...state0...
1723 // } else if v == 1 { // send on channel 1
1724 // ...state1...
1725 // } else {
1726 // ...default...
1727 // }
1728 sel := &Select{
1729 States: states,
1730 Blocking: blocking,
1731 }
1732 sel.setPos(s.Select)
1733 var vars []*types.Var
1734 vars = append(vars, varIndex, varOk)
1735 for _, st := range states {
1736 if st.Dir == types.RecvOnly {
1737 chtyp := typeparams.CoreType(fn.typ(st.Chan.Type())).(*types.Chan)
1738 vars = append(vars, anonVar(chtyp.Elem()))
1739 }
1740 }
1741 sel.setType(types.NewTuple(vars...))
1742
1743 fn.emit(sel)
1744 idx := emitExtract(fn, sel, 0)
1745
1746 done := fn.newBasicBlock("select.done")
1747 if label != nil {
1748 label._break = done
1749 }
1750
1751 var defaultBody *[]ast.Stmt
1752 state := 0
1753 r := 2 // index in 'sel' tuple of value; increments if st.Dir==RECV
1754 for _, cc := range s.Body.List {
1755 clause := cc.(*ast.CommClause)
1756 if clause.Comm == nil {
1757 defaultBody = &clause.Body
1758 continue
1759 }
1760 body := fn.newBasicBlock("select.body")
1761 next := fn.newBasicBlock("select.next")
1762 emitIf(fn, emitCompare(fn, token.EQL, idx, intConst(int64(state)), token.NoPos), body, next)
1763 fn.currentBlock = body
1764 fn.targets = &targets{
1765 tail: fn.targets,
1766 _break: done,
1767 }
1768 switch comm := clause.Comm.(type) {
1769 case *ast.ExprStmt: // <-ch
1770 if debugInfo {
1771 v := emitExtract(fn, sel, r)
1772 emitDebugRef(fn, states[state].DebugNode.(ast.Expr), v, false)
1773 }
1774 r++
1775
1776 case *ast.AssignStmt: // x := <-states[state].Chan
1777 if comm.Tok == token.DEFINE {
1778 emitLocalVar(fn, identVar(fn, comm.Lhs[0].(*ast.Ident)))
1779 }
1780 x := b.addr(fn, comm.Lhs[0], false) // non-escaping
1781 v := emitExtract(fn, sel, r)
1782 if debugInfo {
1783 emitDebugRef(fn, states[state].DebugNode.(ast.Expr), v, false)
1784 }
1785 x.store(fn, v)
1786
1787 if len(comm.Lhs) == 2 { // x, ok := ...
1788 if comm.Tok == token.DEFINE {
1789 emitLocalVar(fn, identVar(fn, comm.Lhs[1].(*ast.Ident)))
1790 }
1791 ok := b.addr(fn, comm.Lhs[1], false) // non-escaping
1792 ok.store(fn, emitExtract(fn, sel, 1))
1793 }
1794 r++
1795 }
1796 b.stmtList(fn, clause.Body)
1797 fn.targets = fn.targets.tail
1798 emitJump(fn, done)
1799 fn.currentBlock = next
1800 state++
1801 }
1802 if defaultBody != nil {
1803 fn.targets = &targets{
1804 tail: fn.targets,
1805 _break: done,
1806 }
1807 b.stmtList(fn, *defaultBody)
1808 fn.targets = fn.targets.tail
1809 } else {
1810 // A blocking select must match some case.
1811 // (This should really be a runtime.errorString, not a string.)
1812 fn.emit(&Panic{
1813 X: emitConv(fn, stringConst("blocking select matched no case"), tEface),
1814 })
1815 fn.currentBlock = fn.newBasicBlock("unreachable")
1816 }
1817 emitJump(fn, done)
1818 fn.currentBlock = done
1819 }
1820
1821 // forStmt emits to fn code for the for statement s, optionally
1822 // labelled by label.
1823 func (b *builder) forStmt(fn *Function, s *ast.ForStmt, label *lblock) {
1824 // Use forStmtGo122 instead if it applies.
1825 if s.Init != nil {
1826 if assign, ok := s.Init.(*ast.AssignStmt); ok && assign.Tok == token.DEFINE {
1827 if versions.AtLeast(fn.goversion, versions.Go1_22) {
1828 b.forStmtGo122(fn, s, label)
1829 return
1830 }
1831 }
1832 }
1833
1834 // ...init...
1835 // jump loop
1836 // loop:
1837 // if cond goto body else done
1838 // body:
1839 // ...body...
1840 // jump post
1841 // post: (target of continue)
1842 // ...post...
1843 // jump loop
1844 // done: (target of break)
1845 if s.Init != nil {
1846 b.stmt(fn, s.Init)
1847 }
1848
1849 body := fn.newBasicBlock("for.body")
1850 done := fn.newBasicBlock("for.done") // target of 'break'
1851 loop := body // target of back-edge
1852 if s.Cond != nil {
1853 loop = fn.newBasicBlock("for.loop")
1854 }
1855 cont := loop // target of 'continue'
1856 if s.Post != nil {
1857 cont = fn.newBasicBlock("for.post")
1858 }
1859 if label != nil {
1860 label._break = done
1861 label._continue = cont
1862 }
1863 emitJump(fn, loop)
1864 fn.currentBlock = loop
1865 if loop != body {
1866 b.cond(fn, s.Cond, body, done)
1867 fn.currentBlock = body
1868 }
1869 fn.targets = &targets{
1870 tail: fn.targets,
1871 _break: done,
1872 _continue: cont,
1873 }
1874 b.stmt(fn, s.Body)
1875 fn.targets = fn.targets.tail
1876 emitJump(fn, cont)
1877
1878 if s.Post != nil {
1879 fn.currentBlock = cont
1880 b.stmt(fn, s.Post)
1881 emitJump(fn, loop) // back-edge
1882 }
1883 fn.currentBlock = done
1884 }
1885
1886 // forStmtGo122 emits to fn code for the for statement s, optionally
1887 // labelled by label. s must define its variables.
1888 //
1889 // This allocates once per loop iteration. This is only correct in
1890 // GoVersions >= go1.22.
1891 func (b *builder) forStmtGo122(fn *Function, s *ast.ForStmt, label *lblock) {
1892 // i_outer = alloc[T]
1893 // *i_outer = ...init... // under objects[i] = i_outer
1894 // jump loop
1895 // loop:
1896 // i = phi [head: i_outer, loop: i_next]
1897 // ...cond... // under objects[i] = i
1898 // if cond goto body else done
1899 // body:
1900 // ...body... // under objects[i] = i (same as loop)
1901 // jump post
1902 // post:
1903 // tmp = *i
1904 // i_next = alloc[T]
1905 // *i_next = tmp
1906 // ...post... // under objects[i] = i_next
1907 // goto loop
1908 // done:
1909
1910 init := s.Init.(*ast.AssignStmt)
1911 startingBlocks := len(fn.Blocks)
1912
1913 pre := fn.currentBlock // current block before starting
1914 loop := fn.newBasicBlock("for.loop") // target of back-edge
1915 body := fn.newBasicBlock("for.body")
1916 post := fn.newBasicBlock("for.post") // target of 'continue'
1917 done := fn.newBasicBlock("for.done") // target of 'break'
1918
1919 // For each of the n loop variables, we create five SSA values,
1920 // outer, phi, next, load, and store in pre, loop, and post.
1921 // There is no limit on n.
1922 type loopVar struct {
1923 obj *types.Var
1924 outer *Alloc
1925 phi *Phi
1926 load *UnOp
1927 next *Alloc
1928 store *Store
1929 }
1930 vars := make([]loopVar, len(init.Lhs))
1931 for i, lhs := range init.Lhs {
1932 v := identVar(fn, lhs.(*ast.Ident))
1933 typ := fn.typ(v.Type())
1934
1935 fn.currentBlock = pre
1936 outer := emitLocal(fn, typ, v.Pos(), v.Name())
1937
1938 fn.currentBlock = loop
1939 phi := &Phi{Comment: v.Name()}
1940 phi.pos = v.Pos()
1941 phi.typ = outer.Type()
1942 fn.emit(phi)
1943
1944 fn.currentBlock = post
1945 // If next is local, it reuses the address and zeroes the old value so
1946 // load before allocating next.
1947 load := emitLoad(fn, phi)
1948 next := emitLocal(fn, typ, v.Pos(), v.Name())
1949 store := emitStore(fn, next, load, token.NoPos)
1950
1951 phi.Edges = []Value{outer, next} // pre edge is emitted before post edge.
1952
1953 vars[i] = loopVar{v, outer, phi, load, next, store}
1954 }
1955
1956 // ...init... under fn.objects[v] = i_outer
1957 fn.currentBlock = pre
1958 for _, v := range vars {
1959 fn.vars[v.obj] = v.outer
1960 }
1961 const isDef = false // assign to already-allocated outers
1962 b.assignStmt(fn, init.Lhs, init.Rhs, isDef)
1963 if label != nil {
1964 label._break = done
1965 label._continue = post
1966 }
1967 emitJump(fn, loop)
1968
1969 // ...cond... under fn.objects[v] = i
1970 fn.currentBlock = loop
1971 for _, v := range vars {
1972 fn.vars[v.obj] = v.phi
1973 }
1974 if s.Cond != nil {
1975 b.cond(fn, s.Cond, body, done)
1976 } else {
1977 emitJump(fn, body)
1978 }
1979
1980 // ...body... under fn.objects[v] = i
1981 fn.currentBlock = body
1982 fn.targets = &targets{
1983 tail: fn.targets,
1984 _break: done,
1985 _continue: post,
1986 }
1987 b.stmt(fn, s.Body)
1988 fn.targets = fn.targets.tail
1989 emitJump(fn, post)
1990
1991 // ...post... under fn.objects[v] = i_next
1992 for _, v := range vars {
1993 fn.vars[v.obj] = v.next
1994 }
1995 fn.currentBlock = post
1996 if s.Post != nil {
1997 b.stmt(fn, s.Post)
1998 }
1999 emitJump(fn, loop) // back-edge
2000 fn.currentBlock = done
2001
2002 // For each loop variable that does not escape,
2003 // (the common case), fuse its next cells into its
2004 // (local) outer cell as they have disjoint live ranges.
2005 //
2006 // It is sufficient to test whether i_next escapes,
2007 // because its Heap flag will be marked true if either
2008 // the cond or post expression causes i to escape
2009 // (because escape distributes over phi).
2010 var nlocals int
2011 for _, v := range vars {
2012 if !v.next.Heap {
2013 nlocals++
2014 }
2015 }
2016 if nlocals > 0 {
2017 replace := make(map[Value]Value, 2*nlocals)
2018 dead := make(map[Instruction]bool, 4*nlocals)
2019 for _, v := range vars {
2020 if !v.next.Heap {
2021 replace[v.next] = v.outer
2022 replace[v.phi] = v.outer
2023 dead[v.phi], dead[v.next], dead[v.load], dead[v.store] = true, true, true, true
2024 }
2025 }
2026
2027 // Replace all uses of i_next and phi with i_outer.
2028 // Referrers have not been built for fn yet so only update Instruction operands.
2029 // We need only look within the blocks added by the loop.
2030 var operands []*Value // recycle storage
2031 for _, b := range fn.Blocks[startingBlocks:] {
2032 for _, instr := range b.Instrs {
2033 operands = instr.Operands(operands[:0])
2034 for _, ptr := range operands {
2035 k := *ptr
2036 if v := replace[k]; v != nil {
2037 *ptr = v
2038 }
2039 }
2040 }
2041 }
2042
2043 // Remove instructions for phi, load, and store.
2044 // lift() will remove the unused i_next *Alloc.
2045 isDead := func(i Instruction) bool { return dead[i] }
2046 loop.Instrs = slices.DeleteFunc(loop.Instrs, isDead)
2047 post.Instrs = slices.DeleteFunc(post.Instrs, isDead)
2048 }
2049 }
2050
2051 // rangeIndexed emits to fn the header for an integer-indexed loop
2052 // over array, *array or slice value x.
2053 // The v result is defined only if tv is non-nil.
2054 // forPos is the position of the "for" token.
2055 func (b *builder) rangeIndexed(fn *Function, x Value, tv types.Type, pos token.Pos) (k, v Value, loop, done *BasicBlock) {
2056 //
2057 // length = len(x)
2058 // index = -1
2059 // loop: (target of continue)
2060 // index++
2061 // if index < length goto body else done
2062 // body:
2063 // k = index
2064 // v = x[index]
2065 // ...body...
2066 // jump loop
2067 // done: (target of break)
2068
2069 // Determine number of iterations.
2070 var length Value
2071 dt := typeparams.Deref(x.Type())
2072 if arr, ok := typeparams.CoreType(dt).(*types.Array); ok {
2073 // For array or *array, the number of iterations is
2074 // known statically thanks to the type. We avoid a
2075 // data dependence upon x, permitting later dead-code
2076 // elimination if x is pure, static unrolling, etc.
2077 // Ranging over a nil *array may have >0 iterations.
2078 // We still generate code for x, in case it has effects.
2079 length = intConst(arr.Len())
2080 } else {
2081 // length = len(x).
2082 var c Call
2083 c.Call.Value = makeLen(x.Type())
2084 c.Call.Args = []Value{x}
2085 c.setType(tInt)
2086 length = fn.emit(&c)
2087 }
2088
2089 index := emitLocal(fn, tInt, token.NoPos, "rangeindex")
2090 emitStore(fn, index, intConst(-1), pos)
2091
2092 loop = fn.newBasicBlock("rangeindex.loop")
2093 emitJump(fn, loop)
2094 fn.currentBlock = loop
2095
2096 incr := &BinOp{
2097 Op: token.ADD,
2098 X: emitLoad(fn, index),
2099 Y: vOne,
2100 }
2101 incr.setType(tInt)
2102 emitStore(fn, index, fn.emit(incr), pos)
2103
2104 body := fn.newBasicBlock("rangeindex.body")
2105 done = fn.newBasicBlock("rangeindex.done")
2106 emitIf(fn, emitCompare(fn, token.LSS, incr, length, token.NoPos), body, done)
2107 fn.currentBlock = body
2108
2109 k = emitLoad(fn, index)
2110 if tv != nil {
2111 switch t := typeparams.CoreType(x.Type()).(type) {
2112 case *types.Array:
2113 instr := &Index{
2114 X: x,
2115 Index: k,
2116 }
2117 instr.setType(t.Elem())
2118 instr.setPos(x.Pos())
2119 v = fn.emit(instr)
2120
2121 case *types.Pointer: // *array
2122 instr := &IndexAddr{
2123 X: x,
2124 Index: k,
2125 }
2126 instr.setType(types.NewPointer(t.Elem().Underlying().(*types.Array).Elem()))
2127 instr.setPos(x.Pos())
2128 v = emitLoad(fn, fn.emit(instr))
2129
2130 case *types.Slice:
2131 instr := &IndexAddr{
2132 X: x,
2133 Index: k,
2134 }
2135 instr.setType(types.NewPointer(t.Elem()))
2136 instr.setPos(x.Pos())
2137 v = emitLoad(fn, fn.emit(instr))
2138
2139 default:
2140 panic("rangeIndexed x:" + t.String())
2141 }
2142 }
2143 return
2144 }
2145
2146 // rangeIter emits to fn the header for a loop using
2147 // Range/Next/Extract to iterate over map or string value x.
2148 // tk and tv are the types of the key/value results k and v, or nil
2149 // if the respective component is not wanted.
2150 func (b *builder) rangeIter(fn *Function, x Value, tk, tv types.Type, pos token.Pos) (k, v Value, loop, done *BasicBlock) {
2151 //
2152 // it = range x
2153 // loop: (target of continue)
2154 // okv = next it (ok, key, value)
2155 // ok = extract okv #0
2156 // if ok goto body else done
2157 // body:
2158 // k = extract okv #1
2159 // v = extract okv #2
2160 // ...body...
2161 // jump loop
2162 // done: (target of break)
2163 //
2164
2165 rng := &Range{X: x}
2166 rng.setPos(pos)
2167 rng.setType(tRangeIter)
2168 it := fn.emit(rng)
2169
2170 loop = fn.newBasicBlock("rangeiter.loop")
2171 emitJump(fn, loop)
2172 fn.currentBlock = loop
2173
2174 var ak, av types.Type
2175 isString := false
2176 if m, ok := typeparams.CoreType(x.Type()).(*types.Map); ok {
2177 ak, av = m.Key(), m.Elem()
2178 } else {
2179 isString = true
2180 ak, av = tInt, tRune
2181 }
2182 if tk == nil {
2183 ak = tInvalid
2184 }
2185 if tv == nil {
2186 av = tInvalid
2187 }
2188
2189 okv := &Next{
2190 Iter: it,
2191 IsString: isString,
2192 }
2193 okv.setType(types.NewTuple(
2194 varOk,
2195 newVar("k", ak),
2196 newVar("v", av),
2197 ))
2198 fn.emit(okv)
2199
2200 body := fn.newBasicBlock("rangeiter.body")
2201 done = fn.newBasicBlock("rangeiter.done")
2202 emitIf(fn, emitExtract(fn, okv, 0), body, done)
2203 fn.currentBlock = body
2204
2205 // The assignment may widen a map or string
2206 // key/value to a variable's interface type
2207 // (cases #1 and #2 of go.dev/issue/78110).
2208 if tk != nil {
2209 k = emitConv(fn, emitExtract(fn, okv, 1), tk)
2210 }
2211 if tv != nil {
2212 v = emitConv(fn, emitExtract(fn, okv, 2), tv)
2213 }
2214 return
2215 }
2216
2217 // rangeChan emits to fn the header for a loop that receives from
2218 // channel x until it fails.
2219 // tk is the channel's element type, or nil if the k result is
2220 // not wanted
2221 // pos is the position of the '=' or ':=' token.
2222 func (b *builder) rangeChan(fn *Function, x Value, tk types.Type, pos token.Pos) (k Value, loop, done *BasicBlock) {
2223 //
2224 // loop: (target of continue)
2225 // ko = <-x (key, ok)
2226 // ok = extract ko #1
2227 // if ok goto body else done
2228 // body:
2229 // k = extract ko #0
2230 // ...body...
2231 // goto loop
2232 // done: (target of break)
2233
2234 loop = fn.newBasicBlock("rangechan.loop")
2235 emitJump(fn, loop)
2236 fn.currentBlock = loop
2237 recv := &UnOp{
2238 Op: token.ARROW,
2239 X: x,
2240 CommaOk: true,
2241 }
2242 recv.setPos(pos)
2243 recv.setType(types.NewTuple(
2244 newVar("k", typeparams.CoreType(x.Type()).(*types.Chan).Elem()),
2245 varOk,
2246 ))
2247 ko := fn.emit(recv)
2248 body := fn.newBasicBlock("rangechan.body")
2249 done = fn.newBasicBlock("rangechan.done")
2250 emitIf(fn, emitExtract(fn, ko, 1), body, done)
2251 fn.currentBlock = body
2252 if tk != nil {
2253 k = emitExtract(fn, ko, 0)
2254 }
2255 return
2256 }
2257
2258 // rangeInt emits to fn the header for a range loop with an integer operand.
2259 // tk is the key value's type, or nil if the k result is not wanted.
2260 // pos is the position of the "for" token.
2261 func (b *builder) rangeInt(fn *Function, x Value, tk types.Type, pos token.Pos) (k Value, loop, done *BasicBlock) {
2262 //
2263 // iter = 0
2264 // if 0 < x goto body else done
2265 // loop: (target of continue)
2266 // iter++
2267 // if iter < x goto body else done
2268 // body:
2269 // k = x
2270 // ...body...
2271 // jump loop
2272 // done: (target of break)
2273
2274 if isUntyped(x.Type()) {
2275 x = emitConv(fn, x, tInt)
2276 }
2277
2278 T := x.Type()
2279 iter := emitLocal(fn, T, token.NoPos, "rangeint.iter")
2280 // x may be unsigned. Avoid initializing x to -1.
2281
2282 body := fn.newBasicBlock("rangeint.body")
2283 done = fn.newBasicBlock("rangeint.done")
2284 emitIf(fn, emitCompare(fn, token.LSS, zeroConst(T), x, token.NoPos), body, done)
2285
2286 loop = fn.newBasicBlock("rangeint.loop")
2287 fn.currentBlock = loop
2288
2289 incr := &BinOp{
2290 Op: token.ADD,
2291 X: emitLoad(fn, iter),
2292 Y: emitConv(fn, vOne, T),
2293 }
2294 incr.setType(T)
2295 emitStore(fn, iter, fn.emit(incr), pos)
2296 emitIf(fn, emitCompare(fn, token.LSS, incr, x, token.NoPos), body, done)
2297 fn.currentBlock = body
2298
2299 if tk != nil {
2300 // Integer types (int, uint8, etc.) are named and
2301 // we know that k is assignable to x when tk != nil.
2302 // This implies tk and T are identical so no conversion is needed.
2303 k = emitLoad(fn, iter)
2304 }
2305
2306 return
2307 }
2308
2309 // rangeStmt emits to fn code for the range statement s, optionally
2310 // labelled by label.
2311 func (b *builder) rangeStmt(fn *Function, s *ast.RangeStmt, label *lblock) {
2312 var tk, tv types.Type
2313 if s.Key != nil && !isBlankIdent(s.Key) {
2314 tk = fn.typeOf(s.Key)
2315 }
2316 if s.Value != nil && !isBlankIdent(s.Value) {
2317 tv = fn.typeOf(s.Value)
2318 }
2319
2320 // create locals for s.Key and s.Value.
2321 createVars := func() {
2322 // Unlike a short variable declaration, a RangeStmt
2323 // using := never redeclares an existing variable; it
2324 // always creates a new one.
2325 if tk != nil {
2326 emitLocalVar(fn, identVar(fn, s.Key.(*ast.Ident)))
2327 }
2328 if tv != nil {
2329 emitLocalVar(fn, identVar(fn, s.Value.(*ast.Ident)))
2330 }
2331 }
2332
2333 afterGo122 := versions.AtLeast(fn.goversion, versions.Go1_22)
2334 if s.Tok == token.DEFINE && !afterGo122 {
2335 // pre-go1.22: If iteration variables are defined (:=), this
2336 // occurs once outside the loop.
2337 createVars()
2338 }
2339
2340 x := b.expr(fn, s.X)
2341
2342 var k, v Value
2343 var loop, done *BasicBlock
2344 switch rt := typeparams.CoreType(x.Type()).(type) {
2345 case *types.Slice, *types.Array, *types.Pointer: // *array
2346 k, v, loop, done = b.rangeIndexed(fn, x, tv, s.For)
2347
2348 case *types.Chan:
2349 k, loop, done = b.rangeChan(fn, x, tk, s.For)
2350
2351 case *types.Map:
2352 k, v, loop, done = b.rangeIter(fn, x, tk, tv, s.For)
2353
2354 case *types.Basic:
2355 switch {
2356 case rt.Info()&types.IsString != 0:
2357 k, v, loop, done = b.rangeIter(fn, x, tk, tv, s.For)
2358
2359 case rt.Info()&types.IsInteger != 0:
2360 k, loop, done = b.rangeInt(fn, x, tk, s.For)
2361
2362 default:
2363 panic("Cannot range over basic type: " + rt.String())
2364 }
2365
2366 case *types.Signature:
2367 // Special case rewrite (fn.goversion >= go1.23):
2368 // for x := range f { ... }
2369 // into
2370 // f(func(x T) bool { ... })
2371 b.rangeFunc(fn, x, s, label)
2372 return
2373
2374 default:
2375 panic("Cannot range over: " + rt.String())
2376 }
2377
2378 if s.Tok == token.DEFINE && afterGo122 {
2379 // go1.22: If iteration variables are defined (:=), this occurs inside the loop.
2380 createVars()
2381 }
2382
2383 // Evaluate both LHS expressions before we update either.
2384 var kl, vl lvalue
2385 if tk != nil {
2386 kl = b.addr(fn, s.Key, false) // non-escaping
2387 }
2388 if tv != nil {
2389 vl = b.addr(fn, s.Value, false) // non-escaping
2390 }
2391 if tk != nil {
2392 kl.store(fn, k)
2393 }
2394 if tv != nil {
2395 vl.store(fn, v)
2396 }
2397
2398 if label != nil {
2399 label._break = done
2400 label._continue = loop
2401 }
2402
2403 fn.targets = &targets{
2404 tail: fn.targets,
2405 _break: done,
2406 _continue: loop,
2407 }
2408 b.stmt(fn, s.Body)
2409 fn.targets = fn.targets.tail
2410 emitJump(fn, loop) // back-edge
2411 fn.currentBlock = done
2412 }
2413
2414 // rangeFunc emits to fn code for the range-over-func rng.Body of the iterator
2415 // function x, optionally labelled by label. It creates a new anonymous function
2416 // yield for rng and builds the function.
2417 func (b *builder) rangeFunc(fn *Function, x Value, rng *ast.RangeStmt, label *lblock) {
2418 // Consider the SSA code for the outermost range-over-func in fn:
2419 //
2420 // func fn(...) (ret R) {
2421 // ...
2422 // for k, v = range x {
2423 // ...
2424 // }
2425 // ...
2426 // }
2427 //
2428 // The code emitted into fn will look something like this.
2429 //
2430 // loop:
2431 // jump := READY
2432 // y := make closure yield [ret, deferstack, jump, k, v]
2433 // x(y)
2434 // switch jump {
2435 // [see resuming execution]
2436 // }
2437 // goto done
2438 // done:
2439 // ...
2440 //
2441 // where yield is a new synthetic yield function:
2442 //
2443 // func yield(_k tk, _v tv) bool
2444 // free variables: [ret, stack, jump, k, v]
2445 // {
2446 // entry:
2447 // if jump != READY then goto invalid else valid
2448 // invalid:
2449 // panic("iterator called when it is not in a ready state")
2450 // valid:
2451 // jump = BUSY
2452 // k = _k
2453 // v = _v
2454 // ...
2455 // cont:
2456 // jump = READY
2457 // return true
2458 // }
2459 //
2460 // Yield state:
2461 //
2462 // Each range loop has an associated jump variable that records
2463 // the state of the iterator. A yield function is initially
2464 // in a READY (0) and callable state. If the yield function is called
2465 // and is not in READY state, it panics. When it is called in a callable
2466 // state, it becomes BUSY. When execution reaches the end of the body
2467 // of the loop (or a continue statement targeting the loop is executed),
2468 // the yield function returns true and resumes being in a READY state.
2469 // After the iterator function x(y) returns, then if the yield function
2470 // is in a READY state, the yield enters the DONE state.
2471 //
2472 // Each lowered control statement (break X, continue X, goto Z, or return)
2473 // that exits the loop sets the variable to a unique positive EXIT value,
2474 // before returning false from the yield function.
2475 //
2476 // If the yield function returns abruptly due to a panic or GoExit,
2477 // it remains in a BUSY state. The generated code asserts that, after
2478 // the iterator call x(y) returns normally, the jump variable state
2479 // is DONE.
2480 //
2481 // Resuming execution:
2482 //
2483 // The code generated for the range statement checks the jump
2484 // variable to determine how to resume execution.
2485 //
2486 // switch jump {
2487 // case BUSY: panic("...")
2488 // case DONE: goto done
2489 // case READY: state = DONE; goto done
2490 // case 123: ... // action for exit 123.
2491 // case 456: ... // action for exit 456.
2492 // ...
2493 // }
2494 //
2495 // Forward goto statements within a yield are jumps to labels that
2496 // have not yet been traversed in fn. They may be in the Body of the
2497 // function. What we emit for these is:
2498 //
2499 // goto target
2500 // target:
2501 // ...
2502 //
2503 // We leave an unresolved exit in yield.exits to check at the end
2504 // of building yield if it encountered target in the body. If it
2505 // encountered target, no additional work is required. Otherwise,
2506 // the yield emits a new early exit in the basic block for target.
2507 // We expect that blockopt will fuse the early exit into the case
2508 // block later. The unresolved exit is then added to yield.parent.exits.
2509
2510 loop := fn.newBasicBlock("rangefunc.loop")
2511 done := fn.newBasicBlock("rangefunc.done")
2512
2513 // These are targets within y.
2514 fn.targets = &targets{
2515 tail: fn.targets,
2516 _break: done,
2517 // _continue is within y.
2518 }
2519 if label != nil {
2520 label._break = done
2521 // _continue is within y
2522 }
2523
2524 emitJump(fn, loop)
2525 fn.currentBlock = loop
2526
2527 // loop:
2528 // jump := READY
2529
2530 anonIdx := len(fn.AnonFuncs)
2531
2532 jump := newVar(fmt.Sprintf("jump$%d", anonIdx+1), tInt)
2533 emitLocalVar(fn, jump) // zero value is READY
2534
2535 xsig := typeparams.CoreType(x.Type()).(*types.Signature)
2536 ysig := typeparams.CoreType(xsig.Params().At(0).Type()).(*types.Signature)
2537
2538 /* synthetic yield function for body of range-over-func loop */
2539 y := &Function{
2540 name: fmt.Sprintf("%s$%d", fn.Name(), anonIdx+1),
2541 Signature: ysig,
2542 Synthetic: "range-over-func yield",
2543 pos: rng.Range,
2544 parent: fn,
2545 anonIdx: int32(len(fn.AnonFuncs)),
2546 Pkg: fn.Pkg,
2547 Prog: fn.Prog,
2548 syntax: rng,
2549 info: fn.info,
2550 goversion: fn.goversion,
2551 build: (*builder).buildYieldFunc,
2552 topLevelOrigin: nil,
2553 typeparams: fn.typeparams,
2554 typeargs: fn.typeargs,
2555 subst: fn.subst,
2556 jump: jump,
2557 deferstack: fn.deferstack,
2558 returnVars: fn.returnVars, // use the parent's return variables
2559 uniq: fn.uniq, // start from parent's unique values
2560 }
2561
2562 // If the RangeStmt has a label, this is how it is passed to buildYieldFunc.
2563 if label != nil {
2564 y.lblocks = map[*types.Label]*lblock{label.label: nil}
2565 }
2566 fn.AnonFuncs = append(fn.AnonFuncs, y)
2567
2568 // Build y immediately. It may:
2569 // * cause fn's locals to escape, and
2570 // * create new exit nodes in exits.
2571 // (y is not marked 'built' until the end of the enclosing FuncDecl.)
2572 unresolved := len(fn.exits)
2573 y.build(b, y)
2574 fn.uniq = y.uniq // resume after y's unique values
2575
2576 // Emit the call of y.
2577 // c := MakeClosure y
2578 // x(c)
2579 c := &MakeClosure{Fn: y}
2580 c.setType(ysig)
2581 for _, fv := range y.FreeVars {
2582 c.Bindings = append(c.Bindings, fv.outer)
2583 fv.outer = nil
2584 }
2585 fn.emit(c)
2586 call := Call{
2587 Call: CallCommon{
2588 Value: x,
2589 Args: []Value{c},
2590 pos: token.NoPos,
2591 },
2592 }
2593 call.setType(xsig.Results())
2594 fn.emit(&call)
2595
2596 exits := fn.exits[unresolved:]
2597 b.buildYieldResume(fn, jump, exits, done)
2598
2599 emitJump(fn, done)
2600 fn.currentBlock = done
2601 // pop the stack for the range-over-func
2602 fn.targets = fn.targets.tail
2603 }
2604
2605 // buildYieldResume emits to fn code for how to resume execution once a call to
2606 // the iterator function over the yield function returns x(y). It does this by building
2607 // a switch over the value of jump for when it is READY, BUSY, or EXIT(id).
2608 func (b *builder) buildYieldResume(fn *Function, jump *types.Var, exits []*exit, done *BasicBlock) {
2609 // v := *jump
2610 // switch v {
2611 // case BUSY: panic("...")
2612 // case READY: jump = DONE; goto done
2613 // case EXIT(a): ...
2614 // case EXIT(b): ...
2615 // ...
2616 // }
2617 v := emitLoad(fn, fn.lookup(jump, false))
2618
2619 // case BUSY: panic("...")
2620 isbusy := fn.newBasicBlock("rangefunc.resume.busy")
2621 ifready := fn.newBasicBlock("rangefunc.resume.ready.check")
2622 emitIf(fn, emitCompare(fn, token.EQL, v, jBusy, token.NoPos), isbusy, ifready)
2623 fn.currentBlock = isbusy
2624 fn.emit(&Panic{
2625 X: emitConv(fn, stringConst("iterator call did not preserve panic"), tEface),
2626 })
2627 fn.currentBlock = ifready
2628
2629 // case READY: jump = DONE; goto done
2630 isready := fn.newBasicBlock("rangefunc.resume.ready")
2631 ifexit := fn.newBasicBlock("rangefunc.resume.exits")
2632 emitIf(fn, emitCompare(fn, token.EQL, v, jReady, token.NoPos), isready, ifexit)
2633 fn.currentBlock = isready
2634 storeVar(fn, jump, jDone, token.NoPos)
2635 emitJump(fn, done)
2636 fn.currentBlock = ifexit
2637
2638 for _, e := range exits {
2639 id := intConst(e.id)
2640
2641 // case EXIT(id): { /* do e */ }
2642 cond := emitCompare(fn, token.EQL, v, id, e.pos)
2643 matchb := fn.newBasicBlock("rangefunc.resume.match")
2644 cndb := fn.newBasicBlock("rangefunc.resume.cnd")
2645 emitIf(fn, cond, matchb, cndb)
2646 fn.currentBlock = matchb
2647
2648 // Cases to fill in the { /* do e */ } bit.
2649 switch {
2650 case e.label != nil: // forward goto?
2651 // case EXIT(id): goto lb // label
2652 lb := fn.lblockOf(e.label)
2653 // Do not mark lb as resolved.
2654 // If fn does not contain label, lb remains unresolved and
2655 // fn must itself be a range-over-func function. lb will be:
2656 // lb:
2657 // fn.jump = id
2658 // return false
2659 emitJump(fn, lb._goto)
2660
2661 case e.to != fn: // e jumps to an ancestor of fn?
2662 // case EXIT(id): { fn.jump = id; return false }
2663 // fn is a range-over-func function.
2664 storeVar(fn, fn.jump, id, token.NoPos)
2665 fn.emit(&Return{Results: []Value{vFalse}, pos: e.pos})
2666
2667 case e.block == nil && e.label == nil: // return from fn?
2668 // case EXIT(id): { return ... }
2669 fn.emit(new(RunDefers))
2670 results := make([]Value, len(fn.results))
2671 for i, r := range fn.results {
2672 results[i] = emitLoad(fn, r)
2673 }
2674 fn.emit(&Return{Results: results, pos: e.pos})
2675
2676 case e.block != nil:
2677 // case EXIT(id): goto block
2678 emitJump(fn, e.block)
2679
2680 default:
2681 panic("unreachable")
2682 }
2683 fn.currentBlock = cndb
2684 }
2685 }
2686
2687 // stmt lowers statement s to SSA form, emitting code to fn.
2688 func (b *builder) stmt(fn *Function, _s ast.Stmt) {
2689 // The label of the current statement. If non-nil, its _goto
2690 // target is always set; its _break and _continue are set only
2691 // within the body of switch/typeswitch/select/for/range.
2692 // It is effectively an additional default-nil parameter of stmt().
2693 var label *lblock
2694 start:
2695 switch s := _s.(type) {
2696 case *ast.EmptyStmt:
2697 // ignore. (Usually removed by gofmt.)
2698
2699 case *ast.DeclStmt: // Con, Var or Typ
2700 d := s.Decl.(*ast.GenDecl)
2701 if d.Tok == token.VAR {
2702 for _, spec := range d.Specs {
2703 if vs, ok := spec.(*ast.ValueSpec); ok {
2704 b.localValueSpec(fn, vs)
2705 }
2706 }
2707 }
2708
2709 case *ast.LabeledStmt:
2710 if s.Label.Name == "_" {
2711 // Blank labels can't be the target of a goto, break,
2712 // or continue statement, so we don't need a new block.
2713 _s = s.Stmt
2714 goto start
2715 }
2716 label = fn.lblockOf(fn.label(s.Label))
2717 label.resolved = true
2718 emitJump(fn, label._goto)
2719 fn.currentBlock = label._goto
2720 _s = s.Stmt
2721 goto start // effectively: tailcall stmt(fn, s.Stmt, label)
2722
2723 case *ast.ExprStmt:
2724 b.expr(fn, s.X)
2725
2726 case *ast.SendStmt:
2727 chtyp := typeparams.CoreType(fn.typeOf(s.Chan)).(*types.Chan)
2728 fn.emit(&Send{
2729 Chan: b.expr(fn, s.Chan),
2730 X: emitConv(fn, b.expr(fn, s.Value), chtyp.Elem()),
2731 pos: s.Arrow,
2732 })
2733
2734 case *ast.IncDecStmt:
2735 op := token.ADD
2736 if s.Tok == token.DEC {
2737 op = token.SUB
2738 }
2739 loc := b.addr(fn, s.X, false)
2740 b.assignOp(fn, loc, NewConst(constant.MakeInt64(1), loc.typ()), op, s.Pos())
2741
2742 case *ast.AssignStmt:
2743 switch s.Tok {
2744 case token.ASSIGN, token.DEFINE:
2745 b.assignStmt(fn, s.Lhs, s.Rhs, s.Tok == token.DEFINE)
2746
2747 default: // +=, etc.
2748 op := s.Tok + token.ADD - token.ADD_ASSIGN
2749 b.assignOp(fn, b.addr(fn, s.Lhs[0], false), b.expr(fn, s.Rhs[0]), op, s.Pos())
2750 }
2751
2752 case *ast.GoStmt:
2753 // The "intrinsics" new/make/len/cap are forbidden here.
2754 // panic is treated like an ordinary function call.
2755 v := Go{pos: s.Go}
2756 b.setCall(fn, s.Call, &v.Call)
2757 fn.emit(&v)
2758
2759 case *ast.DeferStmt:
2760 // The "intrinsics" new/make/len/cap are forbidden here.
2761 // panic is treated like an ordinary function call.
2762 deferstack := emitLoad(fn, fn.lookup(fn.deferstack, false))
2763 v := Defer{pos: s.Defer, DeferStack: deferstack}
2764 b.setCall(fn, s.Call, &v.Call)
2765 fn.emit(&v)
2766
2767 // A deferred call can cause recovery from panic,
2768 // and control resumes at the Recover block.
2769 createRecoverBlock(fn.source)
2770
2771 case *ast.ReturnStmt:
2772 b.returnStmt(fn, s)
2773
2774 case *ast.BranchStmt:
2775 b.branchStmt(fn, s)
2776
2777 case *ast.BlockStmt:
2778 b.stmtList(fn, s.List)
2779
2780 case *ast.IfStmt:
2781 if s.Init != nil {
2782 b.stmt(fn, s.Init)
2783 }
2784 then := fn.newBasicBlock("if.then")
2785 done := fn.newBasicBlock("if.done")
2786 els := done
2787 if s.Else != nil {
2788 els = fn.newBasicBlock("if.else")
2789 }
2790 b.cond(fn, s.Cond, then, els)
2791 fn.currentBlock = then
2792 b.stmt(fn, s.Body)
2793 emitJump(fn, done)
2794
2795 if s.Else != nil {
2796 fn.currentBlock = els
2797 b.stmt(fn, s.Else)
2798 emitJump(fn, done)
2799 }
2800
2801 fn.currentBlock = done
2802
2803 case *ast.SwitchStmt:
2804 b.switchStmt(fn, s, label)
2805
2806 case *ast.TypeSwitchStmt:
2807 b.typeSwitchStmt(fn, s, label)
2808
2809 case *ast.SelectStmt:
2810 b.selectStmt(fn, s, label)
2811
2812 case *ast.ForStmt:
2813 b.forStmt(fn, s, label)
2814
2815 case *ast.RangeStmt:
2816 b.rangeStmt(fn, s, label)
2817
2818 default:
2819 panic(fmt.Sprintf("unexpected statement kind: %T", s))
2820 }
2821 }
2822
2823 func (b *builder) branchStmt(fn *Function, s *ast.BranchStmt) {
2824 var block *BasicBlock
2825 if s.Label == nil {
2826 block = targetedBlock(fn, s.Tok)
2827 } else {
2828 target := fn.label(s.Label)
2829 block = labelledBlock(fn, target, s.Tok)
2830 if block == nil { // forward goto
2831 lb := fn.lblockOf(target)
2832 block = lb._goto // jump to lb._goto
2833 if fn.jump != nil {
2834 // fn is a range-over-func and the goto may exit fn.
2835 // Create an exit and resolve it at the end of
2836 // builder.buildYieldFunc.
2837 labelExit(fn, target, s.Pos())
2838 }
2839 }
2840 }
2841 to := block.parent
2842
2843 if to == fn {
2844 emitJump(fn, block)
2845 } else { // break outside of fn.
2846 // fn must be a range-over-func
2847 e := blockExit(fn, block, s.Pos())
2848 storeVar(fn, fn.jump, intConst(e.id), e.pos)
2849 fn.emit(&Return{Results: []Value{vFalse}, pos: e.pos})
2850 }
2851 fn.currentBlock = fn.newBasicBlock("unreachable")
2852 }
2853
2854 func (b *builder) returnStmt(fn *Function, s *ast.ReturnStmt) {
2855 var results []Value
2856
2857 sig := fn.source.Signature // signature of the enclosing source function
2858
2859 // Convert return operands to result type.
2860 if len(s.Results) == 1 && sig.Results().Len() > 1 {
2861 // Return of one expression in a multi-valued function.
2862 tuple := b.exprN(fn, s.Results[0])
2863 ttuple := tuple.Type().(*types.Tuple)
2864 for i, n := 0, ttuple.Len(); i < n; i++ {
2865 results = append(results,
2866 emitConv(fn, emitExtract(fn, tuple, i),
2867 sig.Results().At(i).Type()))
2868 }
2869 } else {
2870 // 1:1 return, or no-arg return in non-void function.
2871 for i, r := range s.Results {
2872 v := emitConv(fn, b.expr(fn, r), sig.Results().At(i).Type())
2873 results = append(results, v)
2874 }
2875 }
2876
2877 // Store the results.
2878 for i, r := range results {
2879 var result Value // fn.source.result[i] conceptually
2880 if fn == fn.source {
2881 result = fn.results[i]
2882 } else { // lookup needed?
2883 result = fn.lookup(fn.returnVars[i], false)
2884 }
2885 emitStore(fn, result, r, s.Return)
2886 }
2887
2888 if fn.jump != nil {
2889 // Return from body of a range-over-func.
2890 // The return statement is syntactically within the loop,
2891 // but the generated code is in the 'switch jump {...}' after it.
2892 e := returnExit(fn, s.Pos())
2893 storeVar(fn, fn.jump, intConst(e.id), e.pos)
2894 fn.emit(&Return{Results: []Value{vFalse}, pos: e.pos})
2895 fn.currentBlock = fn.newBasicBlock("unreachable")
2896 return
2897 }
2898
2899 // Run function calls deferred in this
2900 // function when explicitly returning from it.
2901 fn.emit(new(RunDefers))
2902 // Reload (potentially) named result variables to form the result tuple.
2903 results = results[:0]
2904 for _, nr := range fn.results {
2905 results = append(results, emitLoad(fn, nr))
2906 }
2907 fn.emit(&Return{Results: results, pos: s.Return})
2908 fn.currentBlock = fn.newBasicBlock("unreachable")
2909 }
2910
2911 // A buildFunc is a strategy for building the SSA body for a function.
2912 type buildFunc = func(*builder, *Function)
2913
2914 // iterate causes all created but unbuilt functions to be built. As
2915 // this may create new methods, the process is iterated until it
2916 // converges.
2917 //
2918 // Waits for any dependencies to finish building.
2919 func (b *builder) iterate() {
2920 for ; b.finished < len(b.fns); b.finished++ {
2921 fn := b.fns[b.finished]
2922 b.buildFunction(fn)
2923 }
2924
2925 b.buildshared.markDone()
2926 b.buildshared.wait()
2927 }
2928
2929 // buildFunction builds SSA code for the body of function fn. Idempotent.
2930 func (b *builder) buildFunction(fn *Function) {
2931 if fn.build != nil {
2932 assert(fn.parent == nil, "anonymous functions should not be built by buildFunction()")
2933
2934 if fn.Prog.mode&LogSource != 0 {
2935 defer logStack("build %s @ %s", fn, fn.Prog.Fset.Position(fn.pos))()
2936 }
2937 fn.build(b, fn)
2938 fn.done()
2939 }
2940 }
2941
2942 // buildParamsOnly builds fn.Params from fn.Signature, but does not build fn.Body.
2943 func (b *builder) buildParamsOnly(fn *Function) {
2944 // For external (C, asm) functions or functions loaded from
2945 // export data, we must set fn.Params even though there is no
2946 // body code to reference them.
2947 if recv := fn.Signature.Recv(); recv != nil {
2948 fn.addParamVar(recv)
2949 }
2950 params := fn.Signature.Params()
2951 for i, n := 0, params.Len(); i < n; i++ {
2952 fn.addParamVar(params.At(i))
2953 }
2954
2955 // clear out other function state (keep consistent with finishBody)
2956 fn.subst = nil
2957 }
2958
2959 // buildFromSyntax builds fn.Body from fn.syntax, which must be non-nil.
2960 func (b *builder) buildFromSyntax(fn *Function) {
2961 var (
2962 recvField *ast.FieldList
2963 body *ast.BlockStmt
2964 functype *ast.FuncType
2965 )
2966 switch syntax := fn.syntax.(type) {
2967 case *ast.FuncDecl:
2968 functype = syntax.Type
2969 recvField = syntax.Recv
2970 body = syntax.Body
2971 if body == nil {
2972 b.buildParamsOnly(fn) // no body (non-Go function)
2973 return
2974 }
2975 case *ast.FuncLit:
2976 functype = syntax.Type
2977 body = syntax.Body
2978 case nil:
2979 panic("no syntax")
2980 default:
2981 panic(syntax) // unexpected syntax
2982 }
2983 fn.source = fn
2984 fn.startBody()
2985 fn.createSyntacticParams(recvField, functype)
2986 fn.createDeferStack()
2987 b.stmt(fn, body)
2988 if cb := fn.currentBlock; cb != nil && (cb == fn.Blocks[0] || cb == fn.Recover || cb.Preds != nil) {
2989 // Control fell off the end of the function's body block.
2990 //
2991 // Block optimizations eliminate the current block, if
2992 // unreachable. It is a builder invariant that
2993 // if this no-arg return is ill-typed for
2994 // fn.Signature.Results, this block must be
2995 // unreachable. The sanity checker checks this.
2996 fn.emit(new(RunDefers))
2997 fn.emit(new(Return))
2998 }
2999 fn.finishBody()
3000 }
3001
3002 // buildYieldFunc builds the body of the yield function created
3003 // from a range-over-func *ast.RangeStmt.
3004 func (b *builder) buildYieldFunc(fn *Function) {
3005 // See builder.rangeFunc for detailed documentation on how fn is set up.
3006 //
3007 // In pseudo-Go this roughly builds:
3008 // func yield(_k tk, _v tv) bool {
3009 // if jump != READY { panic("yield function called after range loop exit") }
3010 // jump = BUSY
3011 // k, v = _k, _v // assign the iterator variable (if needed)
3012 // ... // rng.Body
3013 // continue:
3014 // jump = READY
3015 // return true
3016 // }
3017 s := fn.syntax.(*ast.RangeStmt)
3018 fn.source = fn.parent.source
3019 fn.startBody()
3020 params := fn.Signature.Params()
3021 for v := range params.Variables() {
3022 fn.addParamVar(v)
3023 }
3024
3025 // Initial targets
3026 ycont := fn.newBasicBlock("yield-continue")
3027 // lblocks is either {} or is {label: nil} where label is the label of syntax.
3028 for label := range fn.lblocks {
3029 fn.lblocks[label] = &lblock{
3030 label: label,
3031 resolved: true,
3032 _goto: ycont,
3033 _continue: ycont,
3034 // `break label` statement targets fn.parent.targets._break
3035 }
3036 }
3037 fn.targets = &targets{
3038 tail: fn.targets,
3039 _continue: ycont,
3040 // `break` statement targets fn.parent.targets._break.
3041 }
3042
3043 // continue:
3044 // jump = READY
3045 // return true
3046 saved := fn.currentBlock
3047 fn.currentBlock = ycont
3048 storeVar(fn, fn.jump, jReady, s.Body.Rbrace)
3049 // A yield function's own deferstack is always empty, so rundefers is not needed.
3050 fn.emit(&Return{Results: []Value{vTrue}, pos: token.NoPos})
3051
3052 // Emit header:
3053 //
3054 // if jump != READY { panic("yield iterator accessed after exit") }
3055 // jump = BUSY
3056 // k, v = _k, _v
3057 fn.currentBlock = saved
3058 yloop := fn.newBasicBlock("yield-loop")
3059 invalid := fn.newBasicBlock("yield-invalid")
3060
3061 jumpVal := emitLoad(fn, fn.lookup(fn.jump, true))
3062 emitIf(fn, emitCompare(fn, token.EQL, jumpVal, jReady, token.NoPos), yloop, invalid)
3063 fn.currentBlock = invalid
3064 fn.emit(&Panic{
3065 X: emitConv(fn, stringConst("yield function called after range loop exit"), tEface),
3066 })
3067
3068 fn.currentBlock = yloop
3069 storeVar(fn, fn.jump, jBusy, s.Body.Rbrace)
3070
3071 // Initialize k and v from params.
3072 var tk, tv types.Type
3073 if s.Key != nil && !isBlankIdent(s.Key) {
3074 tk = fn.typeOf(s.Key) // fn.parent.typeOf is identical
3075 }
3076 if s.Value != nil && !isBlankIdent(s.Value) {
3077 tv = fn.typeOf(s.Value)
3078 }
3079 if s.Tok == token.DEFINE {
3080 if tk != nil {
3081 emitLocalVar(fn, identVar(fn, s.Key.(*ast.Ident)))
3082 }
3083 if tv != nil {
3084 emitLocalVar(fn, identVar(fn, s.Value.(*ast.Ident)))
3085 }
3086 }
3087 var k, v Value
3088 if len(fn.Params) > 0 {
3089 k = fn.Params[0]
3090 }
3091 if len(fn.Params) > 1 {
3092 v = fn.Params[1]
3093 }
3094 var kl, vl lvalue
3095 if tk != nil {
3096 kl = b.addr(fn, s.Key, false) // non-escaping
3097 }
3098 if tv != nil {
3099 vl = b.addr(fn, s.Value, false) // non-escaping
3100 }
3101 if tk != nil {
3102 kl.store(fn, k)
3103 }
3104 if tv != nil {
3105 vl.store(fn, v)
3106 }
3107
3108 // Build the body of the range loop.
3109 b.stmt(fn, s.Body)
3110 if cb := fn.currentBlock; cb != nil && (cb == fn.Blocks[0] || cb == fn.Recover || cb.Preds != nil) {
3111 // Control fell off the end of the function's body block.
3112 // Block optimizations eliminate the current block, if
3113 // unreachable.
3114 emitJump(fn, ycont)
3115 }
3116 // pop the stack for the yield function
3117 fn.targets = fn.targets.tail
3118
3119 // Clean up exits and promote any unresolved exits to fn.parent.
3120 for _, e := range fn.exits {
3121 if e.label != nil {
3122 lb := fn.lblocks[e.label]
3123 if lb.resolved {
3124 // label was resolved. Do not turn lb into an exit.
3125 // e does not need to be handled by the parent.
3126 continue
3127 }
3128
3129 // _goto becomes an exit.
3130 // _goto:
3131 // jump = id
3132 // return false
3133 fn.currentBlock = lb._goto
3134 id := intConst(e.id)
3135 storeVar(fn, fn.jump, id, e.pos)
3136 fn.emit(&Return{Results: []Value{vFalse}, pos: e.pos})
3137 }
3138
3139 if e.to != fn { // e needs to be handled by the parent too.
3140 fn.parent.exits = append(fn.parent.exits, e)
3141 }
3142 }
3143
3144 fn.finishBody()
3145 }
3146
3147 // addMakeInterfaceType records non-interface type t as the type of
3148 // the operand a MakeInterface operation, for [Program.RuntimeTypes].
3149 //
3150 // Acquires prog.makeInterfaceTypesMu.
3151 func addMakeInterfaceType(prog *Program, t types.Type) {
3152 prog.makeInterfaceTypesMu.Lock()
3153 defer prog.makeInterfaceTypesMu.Unlock()
3154 if prog.makeInterfaceTypes == nil {
3155 prog.makeInterfaceTypes = make(map[types.Type]unit)
3156 }
3157 prog.makeInterfaceTypes[t] = unit{}
3158 }
3159
3160 // Build calls Package.Build for each package in prog.
3161 // Building occurs in parallel unless the BuildSerially mode flag was set.
3162 //
3163 // Build is intended for whole-program analysis; a typical compiler
3164 // need only build a single package.
3165 //
3166 // Build is idempotent and thread-safe.
3167 func (prog *Program) Build() {
3168 var wg sync.WaitGroup
3169 for _, p := range prog.packages {
3170 if prog.mode&BuildSerially != 0 {
3171 p.Build()
3172 } else {
3173 wg.Add(1)
3174 cpuLimit <- unit{} // acquire a token
3175 go func(p *Package) {
3176 p.Build()
3177 wg.Done()
3178 <-cpuLimit // release a token
3179 }(p)
3180 }
3181 }
3182 wg.Wait()
3183 }
3184
3185 // cpuLimit is a counting semaphore to limit CPU parallelism.
3186 var cpuLimit = make(chan unit, runtime.GOMAXPROCS(0))
3187
3188 // Build builds SSA code for all functions and vars in package p.
3189 //
3190 // CreatePackage must have been called for all of p's direct imports
3191 // (and hence its direct imports must have been error-free). It is not
3192 // necessary to call CreatePackage for indirect dependencies.
3193 // Functions will be created for all necessary methods in those
3194 // packages on demand.
3195 //
3196 // Build is idempotent and thread-safe.
3197 func (p *Package) Build() { p.buildOnce.Do(p.build) }
3198
3199 func (p *Package) build() {
3200 if p.info == nil {
3201 return // synthetic package, e.g. "testmain"
3202 }
3203 if p.Prog.mode&LogSource != 0 {
3204 defer logStack("build %s", p)()
3205 }
3206
3207 b := builder{fns: p.created}
3208 b.iterate()
3209
3210 // We no longer need transient information: ASTs or go/types deductions.
3211 p.info = nil
3212 p.created = nil
3213 p.files = nil
3214 p.initVersion = nil
3215
3216 if p.Prog.mode&SanityCheckFunctions != 0 {
3217 sanityCheckPackage(p)
3218 }
3219 }
3220
3221 // buildPackageInit builds fn.Body for the synthetic package initializer.
3222 func (b *builder) buildPackageInit(fn *Function) {
3223 p := fn.Pkg
3224 fn.startBody()
3225
3226 var done *BasicBlock
3227
3228 if p.Prog.mode&BareInits == 0 {
3229 // Make init() skip if package is already initialized.
3230 initguard := p.Var("init$guard")
3231 doinit := fn.newBasicBlock("init.start")
3232 done = fn.newBasicBlock("init.done")
3233 emitIf(fn, emitLoad(fn, initguard), done, doinit)
3234 fn.currentBlock = doinit
3235 emitStore(fn, initguard, vTrue, token.NoPos)
3236
3237 // Call the init() function of each package we import.
3238 for _, pkg := range p.Pkg.Imports() {
3239 prereq := p.Prog.packages[pkg]
3240 if prereq == nil {
3241 panic(fmt.Sprintf("Package(%q).Build(): unsatisfied import: Program.CreatePackage(%q) was not called", p.Pkg.Path(), pkg.Path()))
3242 }
3243 var v Call
3244 v.Call.Value = prereq.init
3245 v.Call.pos = fn.pos
3246 v.setType(types.NewTuple())
3247 fn.emit(&v)
3248 }
3249 }
3250
3251 // Initialize package-level vars in correct order.
3252 if len(p.info.InitOrder) > 0 && len(p.files) == 0 {
3253 panic("no source files provided for package. cannot initialize globals")
3254 }
3255
3256 for _, varinit := range p.info.InitOrder {
3257 if fn.Prog.mode&LogSource != 0 {
3258 fmt.Fprintf(os.Stderr, "build global initializer %v @ %s\n",
3259 varinit.Lhs, p.Prog.Fset.Position(varinit.Rhs.Pos()))
3260 }
3261 // Initializers for global vars are evaluated in dependency
3262 // order, but may come from arbitrary files of the package
3263 // with different versions, so we transiently update
3264 // fn.goversion for each one. (Since init is a synthetic
3265 // function it has no syntax of its own that needs a version.)
3266 fn.goversion = p.initVersion[varinit.Rhs]
3267 if len(varinit.Lhs) == 1 {
3268 // 1:1 initialization: var x, y = a(), b()
3269 var lval lvalue
3270 if v := varinit.Lhs[0]; v.Name() != "_" {
3271 lval = &address{addr: p.objects[v].(*Global), pos: v.Pos()}
3272 } else {
3273 lval = blank{}
3274 }
3275 b.assign(fn, lval, varinit.Rhs, true, nil)
3276 } else {
3277 // n:1 initialization: var x, y := f()
3278 tuple := b.exprN(fn, varinit.Rhs)
3279 for i, v := range varinit.Lhs {
3280 if v.Name() == "_" {
3281 continue
3282 }
3283 emitStore(fn, p.objects[v].(*Global), emitExtract(fn, tuple, i), v.Pos())
3284 }
3285 }
3286 }
3287
3288 // The rest of the init function is synthetic:
3289 // no syntax, info, goversion.
3290 fn.info = nil
3291 fn.goversion = ""
3292
3293 // Call all of the declared init() functions in source order.
3294 for _, file := range p.files {
3295 for _, decl := range file.Decls {
3296 if decl, ok := decl.(*ast.FuncDecl); ok {
3297 id := decl.Name
3298 if !isBlankIdent(id) && id.Name == "init" && decl.Recv == nil {
3299 declaredInit := p.objects[p.info.Defs[id]].(*Function)
3300 var v Call
3301 v.Call.Value = declaredInit
3302 v.setType(types.NewTuple())
3303 p.init.emit(&v)
3304 }
3305 }
3306 }
3307 }
3308
3309 // Finish up init().
3310 if p.Prog.mode&BareInits == 0 {
3311 emitJump(fn, done)
3312 fn.currentBlock = done
3313 }
3314 fn.emit(new(Return))
3315 fn.finishBody()
3316 }