Debian Codegraph @

go/ir/builder.go

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