You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2379 lines
62 KiB

  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. package ssa
  5. // This file implements the BUILD phase of SSA construction.
  6. //
  7. // SSA construction has two phases, CREATE and BUILD. In the CREATE phase
  8. // (create.go), all packages are constructed and type-checked and
  9. // definitions of all package members are created, method-sets are
  10. // computed, and wrapper methods are synthesized.
  11. // ssa.Packages are created in arbitrary order.
  12. //
  13. // In the BUILD phase (builder.go), the builder traverses the AST of
  14. // each Go source function and generates SSA instructions for the
  15. // function body. Initializer expressions for package-level variables
  16. // are emitted to the package's init() function in the order specified
  17. // by go/types.Info.InitOrder, then code for each function in the
  18. // package is generated in lexical order.
  19. // The BUILD phases for distinct packages are independent and are
  20. // executed in parallel.
  21. //
  22. // TODO(adonovan): indeed, building functions is now embarrassingly parallel.
  23. // Audit for concurrency then benchmark using more goroutines.
  24. //
  25. // The builder's and Program's indices (maps) are populated and
  26. // mutated during the CREATE phase, but during the BUILD phase they
  27. // remain constant. The sole exception is Prog.methodSets and its
  28. // related maps, which are protected by a dedicated mutex.
  29. import (
  30. "fmt"
  31. "go/ast"
  32. exact "go/constant"
  33. "go/token"
  34. "go/types"
  35. "os"
  36. "sync"
  37. )
  38. type opaqueType struct {
  39. types.Type
  40. name string
  41. }
  42. func (t *opaqueType) String() string { return t.name }
  43. var (
  44. varOk = newVar("ok", tBool)
  45. varIndex = newVar("index", tInt)
  46. // Type constants.
  47. tBool = types.Typ[types.Bool]
  48. tByte = types.Typ[types.Byte]
  49. tInt = types.Typ[types.Int]
  50. tInvalid = types.Typ[types.Invalid]
  51. tString = types.Typ[types.String]
  52. tUntypedNil = types.Typ[types.UntypedNil]
  53. tRangeIter = &opaqueType{nil, "iter"} // the type of all "range" iterators
  54. tEface = types.NewInterface(nil, nil).Complete()
  55. // SSA Value constants.
  56. vZero = intConst(0)
  57. vOne = intConst(1)
  58. vTrue = NewConst(exact.MakeBool(true), tBool)
  59. )
  60. // builder holds state associated with the package currently being built.
  61. // Its methods contain all the logic for AST-to-SSA conversion.
  62. type builder struct{}
  63. // cond emits to fn code to evaluate boolean condition e and jump
  64. // to t or f depending on its value, performing various simplifications.
  65. //
  66. // Postcondition: fn.currentBlock is nil.
  67. //
  68. func (b *builder) cond(fn *Function, e ast.Expr, t, f *BasicBlock) {
  69. switch e := e.(type) {
  70. case *ast.ParenExpr:
  71. b.cond(fn, e.X, t, f)
  72. return
  73. case *ast.BinaryExpr:
  74. switch e.Op {
  75. case token.LAND:
  76. ltrue := fn.newBasicBlock("cond.true")
  77. b.cond(fn, e.X, ltrue, f)
  78. fn.currentBlock = ltrue
  79. b.cond(fn, e.Y, t, f)
  80. return
  81. case token.LOR:
  82. lfalse := fn.newBasicBlock("cond.false")
  83. b.cond(fn, e.X, t, lfalse)
  84. fn.currentBlock = lfalse
  85. b.cond(fn, e.Y, t, f)
  86. return
  87. }
  88. case *ast.UnaryExpr:
  89. if e.Op == token.NOT {
  90. b.cond(fn, e.X, f, t)
  91. return
  92. }
  93. }
  94. // A traditional compiler would simplify "if false" (etc) here
  95. // but we do not, for better fidelity to the source code.
  96. //
  97. // The value of a constant condition may be platform-specific,
  98. // and may cause blocks that are reachable in some configuration
  99. // to be hidden from subsequent analyses such as bug-finding tools.
  100. emitIf(fn, b.expr(fn, e), t, f)
  101. }
  102. // logicalBinop emits code to fn to evaluate e, a &&- or
  103. // ||-expression whose reified boolean value is wanted.
  104. // The value is returned.
  105. //
  106. func (b *builder) logicalBinop(fn *Function, e *ast.BinaryExpr) Value {
  107. rhs := fn.newBasicBlock("binop.rhs")
  108. done := fn.newBasicBlock("binop.done")
  109. // T(e) = T(e.X) = T(e.Y) after untyped constants have been
  110. // eliminated.
  111. // TODO(adonovan): not true; MyBool==MyBool yields UntypedBool.
  112. t := fn.Pkg.typeOf(e)
  113. var short Value // value of the short-circuit path
  114. switch e.Op {
  115. case token.LAND:
  116. b.cond(fn, e.X, rhs, done)
  117. short = NewConst(exact.MakeBool(false), t)
  118. case token.LOR:
  119. b.cond(fn, e.X, done, rhs)
  120. short = NewConst(exact.MakeBool(true), t)
  121. }
  122. // Is rhs unreachable?
  123. if rhs.Preds == nil {
  124. // Simplify false&&y to false, true||y to true.
  125. fn.currentBlock = done
  126. return short
  127. }
  128. // Is done unreachable?
  129. if done.Preds == nil {
  130. // Simplify true&&y (or false||y) to y.
  131. fn.currentBlock = rhs
  132. return b.expr(fn, e.Y)
  133. }
  134. // All edges from e.X to done carry the short-circuit value.
  135. var edges []Value
  136. for range done.Preds {
  137. edges = append(edges, short)
  138. }
  139. // The edge from e.Y to done carries the value of e.Y.
  140. fn.currentBlock = rhs
  141. edges = append(edges, b.expr(fn, e.Y))
  142. emitJump(fn, done)
  143. fn.currentBlock = done
  144. phi := &Phi{Edges: edges, Comment: e.Op.String()}
  145. phi.pos = e.OpPos
  146. phi.typ = t
  147. return done.emit(phi)
  148. }
  149. // exprN lowers a multi-result expression e to SSA form, emitting code
  150. // to fn and returning a single Value whose type is a *types.Tuple.
  151. // The caller must access the components via Extract.
  152. //
  153. // Multi-result expressions include CallExprs in a multi-value
  154. // assignment or return statement, and "value,ok" uses of
  155. // TypeAssertExpr, IndexExpr (when X is a map), and UnaryExpr (when Op
  156. // is token.ARROW).
  157. //
  158. func (b *builder) exprN(fn *Function, e ast.Expr) Value {
  159. typ := fn.Pkg.typeOf(e).(*types.Tuple)
  160. switch e := e.(type) {
  161. case *ast.ParenExpr:
  162. return b.exprN(fn, e.X)
  163. case *ast.CallExpr:
  164. // Currently, no built-in function nor type conversion
  165. // has multiple results, so we can avoid some of the
  166. // cases for single-valued CallExpr.
  167. var c Call
  168. b.setCall(fn, e, &c.Call)
  169. c.typ = typ
  170. return fn.emit(&c)
  171. case *ast.IndexExpr:
  172. mapt := fn.Pkg.typeOf(e.X).Underlying().(*types.Map)
  173. lookup := &Lookup{
  174. X: b.expr(fn, e.X),
  175. Index: emitConv(fn, b.expr(fn, e.Index), mapt.Key()),
  176. CommaOk: true,
  177. }
  178. lookup.setType(typ)
  179. lookup.setPos(e.Lbrack)
  180. return fn.emit(lookup)
  181. case *ast.TypeAssertExpr:
  182. return emitTypeTest(fn, b.expr(fn, e.X), typ.At(0).Type(), e.Lparen)
  183. case *ast.UnaryExpr: // must be receive <-
  184. unop := &UnOp{
  185. Op: token.ARROW,
  186. X: b.expr(fn, e.X),
  187. CommaOk: true,
  188. }
  189. unop.setType(typ)
  190. unop.setPos(e.OpPos)
  191. return fn.emit(unop)
  192. }
  193. panic(fmt.Sprintf("exprN(%T) in %s", e, fn))
  194. }
  195. // builtin emits to fn SSA instructions to implement a call to the
  196. // built-in function obj with the specified arguments
  197. // and return type. It returns the value defined by the result.
  198. //
  199. // The result is nil if no special handling was required; in this case
  200. // the caller should treat this like an ordinary library function
  201. // call.
  202. //
  203. func (b *builder) builtin(fn *Function, obj *types.Builtin, args []ast.Expr, typ types.Type, pos token.Pos) Value {
  204. switch obj.Name() {
  205. case "make":
  206. switch typ.Underlying().(type) {
  207. case *types.Slice:
  208. n := b.expr(fn, args[1])
  209. m := n
  210. if len(args) == 3 {
  211. m = b.expr(fn, args[2])
  212. }
  213. if m, ok := m.(*Const); ok {
  214. // treat make([]T, n, m) as new([m]T)[:n]
  215. cap := m.Int64()
  216. at := types.NewArray(typ.Underlying().(*types.Slice).Elem(), cap)
  217. alloc := emitNew(fn, at, pos)
  218. alloc.Comment = "makeslice"
  219. v := &Slice{
  220. X: alloc,
  221. High: n,
  222. }
  223. v.setPos(pos)
  224. v.setType(typ)
  225. return fn.emit(v)
  226. }
  227. v := &MakeSlice{
  228. Len: n,
  229. Cap: m,
  230. }
  231. v.setPos(pos)
  232. v.setType(typ)
  233. return fn.emit(v)
  234. case *types.Map:
  235. var res Value
  236. if len(args) == 2 {
  237. res = b.expr(fn, args[1])
  238. }
  239. v := &MakeMap{Reserve: res}
  240. v.setPos(pos)
  241. v.setType(typ)
  242. return fn.emit(v)
  243. case *types.Chan:
  244. var sz Value = vZero
  245. if len(args) == 2 {
  246. sz = b.expr(fn, args[1])
  247. }
  248. v := &MakeChan{Size: sz}
  249. v.setPos(pos)
  250. v.setType(typ)
  251. return fn.emit(v)
  252. }
  253. case "new":
  254. alloc := emitNew(fn, deref(typ), pos)
  255. alloc.Comment = "new"
  256. return alloc
  257. case "len", "cap":
  258. // Special case: len or cap of an array or *array is
  259. // based on the type, not the value which may be nil.
  260. // We must still evaluate the value, though. (If it
  261. // was side-effect free, the whole call would have
  262. // been constant-folded.)
  263. t := deref(fn.Pkg.typeOf(args[0])).Underlying()
  264. if at, ok := t.(*types.Array); ok {
  265. b.expr(fn, args[0]) // for effects only
  266. return intConst(at.Len())
  267. }
  268. // Otherwise treat as normal.
  269. case "panic":
  270. fn.emit(&Panic{
  271. X: emitConv(fn, b.expr(fn, args[0]), tEface),
  272. pos: pos,
  273. })
  274. fn.currentBlock = fn.newBasicBlock("unreachable")
  275. return vTrue // any non-nil Value will do
  276. }
  277. return nil // treat all others as a regular function call
  278. }
  279. // addr lowers a single-result addressable expression e to SSA form,
  280. // emitting code to fn and returning the location (an lvalue) defined
  281. // by the expression.
  282. //
  283. // If escaping is true, addr marks the base variable of the
  284. // addressable expression e as being a potentially escaping pointer
  285. // value. For example, in this code:
  286. //
  287. // a := A{
  288. // b: [1]B{B{c: 1}}
  289. // }
  290. // return &a.b[0].c
  291. //
  292. // the application of & causes a.b[0].c to have its address taken,
  293. // which means that ultimately the local variable a must be
  294. // heap-allocated. This is a simple but very conservative escape
  295. // analysis.
  296. //
  297. // Operations forming potentially escaping pointers include:
  298. // - &x, including when implicit in method call or composite literals.
  299. // - a[:] iff a is an array (not *array)
  300. // - references to variables in lexically enclosing functions.
  301. //
  302. func (b *builder) addr(fn *Function, e ast.Expr, escaping bool) lvalue {
  303. switch e := e.(type) {
  304. case *ast.Ident:
  305. if isBlankIdent(e) {
  306. return blank{}
  307. }
  308. obj := fn.Pkg.objectOf(e)
  309. v := fn.Prog.packageLevelValue(obj) // var (address)
  310. if v == nil {
  311. v = fn.lookup(obj, escaping)
  312. }
  313. return &address{addr: v, pos: e.Pos(), expr: e}
  314. case *ast.CompositeLit:
  315. t := deref(fn.Pkg.typeOf(e))
  316. var v *Alloc
  317. if escaping {
  318. v = emitNew(fn, t, e.Lbrace)
  319. } else {
  320. v = fn.addLocal(t, e.Lbrace)
  321. }
  322. v.Comment = "complit"
  323. var sb storebuf
  324. b.compLit(fn, v, e, true, &sb)
  325. sb.emit(fn)
  326. return &address{addr: v, pos: e.Lbrace, expr: e}
  327. case *ast.ParenExpr:
  328. return b.addr(fn, e.X, escaping)
  329. case *ast.SelectorExpr:
  330. sel, ok := fn.Pkg.info.Selections[e]
  331. if !ok {
  332. // qualified identifier
  333. return b.addr(fn, e.Sel, escaping)
  334. }
  335. if sel.Kind() != types.FieldVal {
  336. panic(sel)
  337. }
  338. wantAddr := true
  339. v := b.receiver(fn, e.X, wantAddr, escaping, sel)
  340. last := len(sel.Index()) - 1
  341. return &address{
  342. addr: emitFieldSelection(fn, v, sel.Index()[last], true, e.Sel),
  343. pos: e.Sel.Pos(),
  344. expr: e.Sel,
  345. }
  346. case *ast.IndexExpr:
  347. var x Value
  348. var et types.Type
  349. switch t := fn.Pkg.typeOf(e.X).Underlying().(type) {
  350. case *types.Array:
  351. x = b.addr(fn, e.X, escaping).address(fn)
  352. et = types.NewPointer(t.Elem())
  353. case *types.Pointer: // *array
  354. x = b.expr(fn, e.X)
  355. et = types.NewPointer(t.Elem().Underlying().(*types.Array).Elem())
  356. case *types.Slice:
  357. x = b.expr(fn, e.X)
  358. et = types.NewPointer(t.Elem())
  359. case *types.Map:
  360. return &element{
  361. m: b.expr(fn, e.X),
  362. k: emitConv(fn, b.expr(fn, e.Index), t.Key()),
  363. t: t.Elem(),
  364. pos: e.Lbrack,
  365. }
  366. default:
  367. panic("unexpected container type in IndexExpr: " + t.String())
  368. }
  369. v := &IndexAddr{
  370. X: x,
  371. Index: emitConv(fn, b.expr(fn, e.Index), tInt),
  372. }
  373. v.setPos(e.Lbrack)
  374. v.setType(et)
  375. return &address{addr: fn.emit(v), pos: e.Lbrack, expr: e}
  376. case *ast.StarExpr:
  377. return &address{addr: b.expr(fn, e.X), pos: e.Star, expr: e}
  378. }
  379. panic(fmt.Sprintf("unexpected address expression: %T", e))
  380. }
  381. type store struct {
  382. lhs lvalue
  383. rhs Value
  384. }
  385. type storebuf struct{ stores []store }
  386. func (sb *storebuf) store(lhs lvalue, rhs Value) {
  387. sb.stores = append(sb.stores, store{lhs, rhs})
  388. }
  389. func (sb *storebuf) emit(fn *Function) {
  390. for _, s := range sb.stores {
  391. s.lhs.store(fn, s.rhs)
  392. }
  393. }
  394. // assign emits to fn code to initialize the lvalue loc with the value
  395. // of expression e. If isZero is true, assign assumes that loc holds
  396. // the zero value for its type.
  397. //
  398. // This is equivalent to loc.store(fn, b.expr(fn, e)), but may generate
  399. // better code in some cases, e.g., for composite literals in an
  400. // addressable location.
  401. //
  402. // If sb is not nil, assign generates code to evaluate expression e, but
  403. // not to update loc. Instead, the necessary stores are appended to the
  404. // storebuf sb so that they can be executed later. This allows correct
  405. // in-place update of existing variables when the RHS is a composite
  406. // literal that may reference parts of the LHS.
  407. //
  408. func (b *builder) assign(fn *Function, loc lvalue, e ast.Expr, isZero bool, sb *storebuf) {
  409. // Can we initialize it in place?
  410. if e, ok := unparen(e).(*ast.CompositeLit); ok {
  411. // A CompositeLit never evaluates to a pointer,
  412. // so if the type of the location is a pointer,
  413. // an &-operation is implied.
  414. if _, ok := loc.(blank); !ok { // avoid calling blank.typ()
  415. if isPointer(loc.typ()) {
  416. ptr := b.addr(fn, e, true).address(fn)
  417. // copy address
  418. if sb != nil {
  419. sb.store(loc, ptr)
  420. } else {
  421. loc.store(fn, ptr)
  422. }
  423. return
  424. }
  425. }
  426. if _, ok := loc.(*address); ok {
  427. if isInterface(loc.typ()) {
  428. // e.g. var x interface{} = T{...}
  429. // Can't in-place initialize an interface value.
  430. // Fall back to copying.
  431. } else {
  432. // x = T{...} or x := T{...}
  433. addr := loc.address(fn)
  434. if sb != nil {
  435. b.compLit(fn, addr, e, isZero, sb)
  436. } else {
  437. var sb storebuf
  438. b.compLit(fn, addr, e, isZero, &sb)
  439. sb.emit(fn)
  440. }
  441. // Subtle: emit debug ref for aggregate types only;
  442. // slice and map are handled by store ops in compLit.
  443. switch loc.typ().Underlying().(type) {
  444. case *types.Struct, *types.Array:
  445. emitDebugRef(fn, e, addr, true)
  446. }
  447. return
  448. }
  449. }
  450. }
  451. // simple case: just copy
  452. rhs := b.expr(fn, e)
  453. if sb != nil {
  454. sb.store(loc, rhs)
  455. } else {
  456. loc.store(fn, rhs)
  457. }
  458. }
  459. // expr lowers a single-result expression e to SSA form, emitting code
  460. // to fn and returning the Value defined by the expression.
  461. //
  462. func (b *builder) expr(fn *Function, e ast.Expr) Value {
  463. e = unparen(e)
  464. tv := fn.Pkg.info.Types[e]
  465. // Is expression a constant?
  466. if tv.Value != nil {
  467. return NewConst(tv.Value, tv.Type)
  468. }
  469. var v Value
  470. if tv.Addressable() {
  471. // Prefer pointer arithmetic ({Index,Field}Addr) followed
  472. // by Load over subelement extraction (e.g. Index, Field),
  473. // to avoid large copies.
  474. v = b.addr(fn, e, false).load(fn)
  475. } else {
  476. v = b.expr0(fn, e, tv)
  477. }
  478. if fn.debugInfo() {
  479. emitDebugRef(fn, e, v, false)
  480. }
  481. return v
  482. }
  483. func (b *builder) expr0(fn *Function, e ast.Expr, tv types.TypeAndValue) Value {
  484. switch e := e.(type) {
  485. case *ast.BasicLit:
  486. panic("non-constant BasicLit") // unreachable
  487. case *ast.FuncLit:
  488. fn2 := &Function{
  489. name: fmt.Sprintf("%s$%d", fn.Name(), 1+len(fn.AnonFuncs)),
  490. Signature: fn.Pkg.typeOf(e.Type).Underlying().(*types.Signature),
  491. pos: e.Type.Func,
  492. parent: fn,
  493. Pkg: fn.Pkg,
  494. Prog: fn.Prog,
  495. syntax: e,
  496. }
  497. fn.AnonFuncs = append(fn.AnonFuncs, fn2)
  498. b.buildFunction(fn2)
  499. if fn2.FreeVars == nil {
  500. return fn2
  501. }
  502. v := &MakeClosure{Fn: fn2}
  503. v.setType(tv.Type)
  504. for _, fv := range fn2.FreeVars {
  505. v.Bindings = append(v.Bindings, fv.outer)
  506. fv.outer = nil
  507. }
  508. return fn.emit(v)
  509. case *ast.TypeAssertExpr: // single-result form only
  510. return emitTypeAssert(fn, b.expr(fn, e.X), tv.Type, e.Lparen)
  511. case *ast.CallExpr:
  512. if fn.Pkg.info.Types[e.Fun].IsType() {
  513. // Explicit type conversion, e.g. string(x) or big.Int(x)
  514. x := b.expr(fn, e.Args[0])
  515. y := emitConv(fn, x, tv.Type)
  516. if y != x {
  517. switch y := y.(type) {
  518. case *Convert:
  519. y.pos = e.Lparen
  520. case *ChangeType:
  521. y.pos = e.Lparen
  522. case *MakeInterface:
  523. y.pos = e.Lparen
  524. }
  525. }
  526. return y
  527. }
  528. // Call to "intrinsic" built-ins, e.g. new, make, panic.
  529. if id, ok := unparen(e.Fun).(*ast.Ident); ok {
  530. if obj, ok := fn.Pkg.info.Uses[id].(*types.Builtin); ok {
  531. if v := b.builtin(fn, obj, e.Args, tv.Type, e.Lparen); v != nil {
  532. return v
  533. }
  534. }
  535. }
  536. // Regular function call.
  537. var v Call
  538. b.setCall(fn, e, &v.Call)
  539. v.setType(tv.Type)
  540. return fn.emit(&v)
  541. case *ast.UnaryExpr:
  542. switch e.Op {
  543. case token.AND: // &X --- potentially escaping.
  544. addr := b.addr(fn, e.X, true)
  545. if _, ok := unparen(e.X).(*ast.StarExpr); ok {
  546. // &*p must panic if p is nil (http://golang.org/s/go12nil).
  547. // For simplicity, we'll just (suboptimally) rely
  548. // on the side effects of a load.
  549. // TODO(adonovan): emit dedicated nilcheck.
  550. addr.load(fn)
  551. }
  552. return addr.address(fn)
  553. case token.ADD:
  554. return b.expr(fn, e.X)
  555. case token.NOT, token.ARROW, token.SUB, token.XOR: // ! <- - ^
  556. v := &UnOp{
  557. Op: e.Op,
  558. X: b.expr(fn, e.X),
  559. }
  560. v.setPos(e.OpPos)
  561. v.setType(tv.Type)
  562. return fn.emit(v)
  563. default:
  564. panic(e.Op)
  565. }
  566. case *ast.BinaryExpr:
  567. switch e.Op {
  568. case token.LAND, token.LOR:
  569. return b.logicalBinop(fn, e)
  570. case token.SHL, token.SHR:
  571. fallthrough
  572. case token.ADD, token.SUB, token.MUL, token.QUO, token.REM, token.AND, token.OR, token.XOR, token.AND_NOT:
  573. return emitArith(fn, e.Op, b.expr(fn, e.X), b.expr(fn, e.Y), tv.Type, e.OpPos)
  574. case token.EQL, token.NEQ, token.GTR, token.LSS, token.LEQ, token.GEQ:
  575. cmp := emitCompare(fn, e.Op, b.expr(fn, e.X), b.expr(fn, e.Y), e.OpPos)
  576. // The type of x==y may be UntypedBool.
  577. return emitConv(fn, cmp, DefaultType(tv.Type))
  578. default:
  579. panic("illegal op in BinaryExpr: " + e.Op.String())
  580. }
  581. case *ast.SliceExpr:
  582. var low, high, max Value
  583. var x Value
  584. switch fn.Pkg.typeOf(e.X).Underlying().(type) {
  585. case *types.Array:
  586. // Potentially escaping.
  587. x = b.addr(fn, e.X, true).address(fn)
  588. case *types.Basic, *types.Slice, *types.Pointer: // *array
  589. x = b.expr(fn, e.X)
  590. default:
  591. panic("unreachable")
  592. }
  593. if e.High != nil {
  594. high = b.expr(fn, e.High)
  595. }
  596. if e.Low != nil {
  597. low = b.expr(fn, e.Low)
  598. }
  599. if e.Slice3 {
  600. max = b.expr(fn, e.Max)
  601. }
  602. v := &Slice{
  603. X: x,
  604. Low: low,
  605. High: high,
  606. Max: max,
  607. }
  608. v.setPos(e.Lbrack)
  609. v.setType(tv.Type)
  610. return fn.emit(v)
  611. case *ast.Ident:
  612. obj := fn.Pkg.info.Uses[e]
  613. // Universal built-in or nil?
  614. switch obj := obj.(type) {
  615. case *types.Builtin:
  616. return &Builtin{name: obj.Name(), sig: tv.Type.(*types.Signature)}
  617. case *types.Nil:
  618. return nilConst(tv.Type)
  619. }
  620. // Package-level func or var?
  621. if v := fn.Prog.packageLevelValue(obj); v != nil {
  622. if _, ok := obj.(*types.Var); ok {
  623. return emitLoad(fn, v) // var (address)
  624. }
  625. return v // (func)
  626. }
  627. // Local var.
  628. return emitLoad(fn, fn.lookup(obj, false)) // var (address)
  629. case *ast.SelectorExpr:
  630. sel, ok := fn.Pkg.info.Selections[e]
  631. if !ok {
  632. // qualified identifier
  633. return b.expr(fn, e.Sel)
  634. }
  635. switch sel.Kind() {
  636. case types.MethodExpr:
  637. // (*T).f or T.f, the method f from the method-set of type T.
  638. // The result is a "thunk".
  639. return emitConv(fn, makeThunk(fn.Prog, sel), tv.Type)
  640. case types.MethodVal:
  641. // e.f where e is an expression and f is a method.
  642. // The result is a "bound".
  643. obj := sel.Obj().(*types.Func)
  644. rt := recvType(obj)
  645. wantAddr := isPointer(rt)
  646. escaping := true
  647. v := b.receiver(fn, e.X, wantAddr, escaping, sel)
  648. if isInterface(rt) {
  649. // If v has interface type I,
  650. // we must emit a check that v is non-nil.
  651. // We use: typeassert v.(I).
  652. emitTypeAssert(fn, v, rt, token.NoPos)
  653. }
  654. c := &MakeClosure{
  655. Fn: makeBound(fn.Prog, obj),
  656. Bindings: []Value{v},
  657. }
  658. c.setPos(e.Sel.Pos())
  659. c.setType(tv.Type)
  660. return fn.emit(c)
  661. case types.FieldVal:
  662. indices := sel.Index()
  663. last := len(indices) - 1
  664. v := b.expr(fn, e.X)
  665. v = emitImplicitSelections(fn, v, indices[:last])
  666. v = emitFieldSelection(fn, v, indices[last], false, e.Sel)
  667. return v
  668. }
  669. panic("unexpected expression-relative selector")
  670. case *ast.IndexExpr:
  671. switch t := fn.Pkg.typeOf(e.X).Underlying().(type) {
  672. case *types.Array:
  673. // Non-addressable array (in a register).
  674. v := &Index{
  675. X: b.expr(fn, e.X),
  676. Index: emitConv(fn, b.expr(fn, e.Index), tInt),
  677. }
  678. v.setPos(e.Lbrack)
  679. v.setType(t.Elem())
  680. return fn.emit(v)
  681. case *types.Map:
  682. // Maps are not addressable.
  683. mapt := fn.Pkg.typeOf(e.X).Underlying().(*types.Map)
  684. v := &Lookup{
  685. X: b.expr(fn, e.X),
  686. Index: emitConv(fn, b.expr(fn, e.Index), mapt.Key()),
  687. }
  688. v.setPos(e.Lbrack)
  689. v.setType(mapt.Elem())
  690. return fn.emit(v)
  691. case *types.Basic: // => string
  692. // Strings are not addressable.
  693. v := &Lookup{
  694. X: b.expr(fn, e.X),
  695. Index: b.expr(fn, e.Index),
  696. }
  697. v.setPos(e.Lbrack)
  698. v.setType(tByte)
  699. return fn.emit(v)
  700. case *types.Slice, *types.Pointer: // *array
  701. // Addressable slice/array; use IndexAddr and Load.
  702. return b.addr(fn, e, false).load(fn)
  703. default:
  704. panic("unexpected container type in IndexExpr: " + t.String())
  705. }
  706. case *ast.CompositeLit, *ast.StarExpr:
  707. // Addressable types (lvalues)
  708. return b.addr(fn, e, false).load(fn)
  709. }
  710. panic(fmt.Sprintf("unexpected expr: %T", e))
  711. }
  712. // stmtList emits to fn code for all statements in list.
  713. func (b *builder) stmtList(fn *Function, list []ast.Stmt) {
  714. for _, s := range list {
  715. b.stmt(fn, s)
  716. }
  717. }
  718. // receiver emits to fn code for expression e in the "receiver"
  719. // position of selection e.f (where f may be a field or a method) and
  720. // returns the effective receiver after applying the implicit field
  721. // selections of sel.
  722. //
  723. // wantAddr requests that the result is an an address. If
  724. // !sel.Indirect(), this may require that e be built in addr() mode; it
  725. // must thus be addressable.
  726. //
  727. // escaping is defined as per builder.addr().
  728. //
  729. func (b *builder) receiver(fn *Function, e ast.Expr, wantAddr, escaping bool, sel *types.Selection) Value {
  730. var v Value
  731. if wantAddr && !sel.Indirect() && !isPointer(fn.Pkg.typeOf(e)) {
  732. v = b.addr(fn, e, escaping).address(fn)
  733. } else {
  734. v = b.expr(fn, e)
  735. }
  736. last := len(sel.Index()) - 1
  737. v = emitImplicitSelections(fn, v, sel.Index()[:last])
  738. if !wantAddr && isPointer(v.Type()) {
  739. v = emitLoad(fn, v)
  740. }
  741. return v
  742. }
  743. // setCallFunc populates the function parts of a CallCommon structure
  744. // (Func, Method, Recv, Args[0]) based on the kind of invocation
  745. // occurring in e.
  746. //
  747. func (b *builder) setCallFunc(fn *Function, e *ast.CallExpr, c *CallCommon) {
  748. c.pos = e.Lparen
  749. // Is this a method call?
  750. if selector, ok := unparen(e.Fun).(*ast.SelectorExpr); ok {
  751. sel, ok := fn.Pkg.info.Selections[selector]
  752. if ok && sel.Kind() == types.MethodVal {
  753. obj := sel.Obj().(*types.Func)
  754. recv := recvType(obj)
  755. wantAddr := isPointer(recv)
  756. escaping := true
  757. v := b.receiver(fn, selector.X, wantAddr, escaping, sel)
  758. if isInterface(recv) {
  759. // Invoke-mode call.
  760. c.Value = v
  761. c.Method = obj
  762. } else {
  763. // "Call"-mode call.
  764. c.Value = fn.Prog.declaredFunc(obj)
  765. c.Args = append(c.Args, v)
  766. }
  767. return
  768. }
  769. // sel.Kind()==MethodExpr indicates T.f() or (*T).f():
  770. // a statically dispatched call to the method f in the
  771. // method-set of T or *T. T may be an interface.
  772. //
  773. // e.Fun would evaluate to a concrete method, interface
  774. // wrapper function, or promotion wrapper.
  775. //
  776. // For now, we evaluate it in the usual way.
  777. //
  778. // TODO(adonovan): opt: inline expr() here, to make the
  779. // call static and to avoid generation of wrappers.
  780. // It's somewhat tricky as it may consume the first
  781. // actual parameter if the call is "invoke" mode.
  782. //
  783. // Examples:
  784. // type T struct{}; func (T) f() {} // "call" mode
  785. // type T interface { f() } // "invoke" mode
  786. //
  787. // type S struct{ T }
  788. //
  789. // var s S
  790. // S.f(s)
  791. // (*S).f(&s)
  792. //
  793. // Suggested approach:
  794. // - consume the first actual parameter expression
  795. // and build it with b.expr().
  796. // - apply implicit field selections.
  797. // - use MethodVal logic to populate fields of c.
  798. }
  799. // Evaluate the function operand in the usual way.
  800. c.Value = b.expr(fn, e.Fun)
  801. }
  802. // emitCallArgs emits to f code for the actual parameters of call e to
  803. // a (possibly built-in) function of effective type sig.
  804. // The argument values are appended to args, which is then returned.
  805. //
  806. func (b *builder) emitCallArgs(fn *Function, sig *types.Signature, e *ast.CallExpr, args []Value) []Value {
  807. // f(x, y, z...): pass slice z straight through.
  808. if e.Ellipsis != 0 {
  809. for i, arg := range e.Args {
  810. v := emitConv(fn, b.expr(fn, arg), sig.Params().At(i).Type())
  811. args = append(args, v)
  812. }
  813. return args
  814. }
  815. offset := len(args) // 1 if call has receiver, 0 otherwise
  816. // Evaluate actual parameter expressions.
  817. //
  818. // If this is a chained call of the form f(g()) where g has
  819. // multiple return values (MRV), they are flattened out into
  820. // args; a suffix of them may end up in a varargs slice.
  821. for _, arg := range e.Args {
  822. v := b.expr(fn, arg)
  823. if ttuple, ok := v.Type().(*types.Tuple); ok { // MRV chain
  824. for i, n := 0, ttuple.Len(); i < n; i++ {
  825. args = append(args, emitExtract(fn, v, i))
  826. }
  827. } else {
  828. args = append(args, v)
  829. }
  830. }
  831. // Actual->formal assignability conversions for normal parameters.
  832. np := sig.Params().Len() // number of normal parameters
  833. if sig.Variadic() {
  834. np--
  835. }
  836. for i := 0; i < np; i++ {
  837. args[offset+i] = emitConv(fn, args[offset+i], sig.Params().At(i).Type())
  838. }
  839. // Actual->formal assignability conversions for variadic parameter,
  840. // and construction of slice.
  841. if sig.Variadic() {
  842. varargs := args[offset+np:]
  843. st := sig.Params().At(np).Type().(*types.Slice)
  844. vt := st.Elem()
  845. if len(varargs) == 0 {
  846. args = append(args, nilConst(st))
  847. } else {
  848. // Replace a suffix of args with a slice containing it.
  849. at := types.NewArray(vt, int64(len(varargs)))
  850. a := emitNew(fn, at, token.NoPos)
  851. a.setPos(e.Rparen)
  852. a.Comment = "varargs"
  853. for i, arg := range varargs {
  854. iaddr := &IndexAddr{
  855. X: a,
  856. Index: intConst(int64(i)),
  857. }
  858. iaddr.setType(types.NewPointer(vt))
  859. fn.emit(iaddr)
  860. emitStore(fn, iaddr, arg, arg.Pos())
  861. }
  862. s := &Slice{X: a}
  863. s.setType(st)
  864. args[offset+np] = fn.emit(s)
  865. args = args[:offset+np+1]
  866. }
  867. }
  868. return args
  869. }
  870. // setCall emits to fn code to evaluate all the parameters of a function
  871. // call e, and populates *c with those values.
  872. //
  873. func (b *builder) setCall(fn *Function, e *ast.CallExpr, c *CallCommon) {
  874. // First deal with the f(...) part and optional receiver.
  875. b.setCallFunc(fn, e, c)
  876. // Then append the other actual parameters.
  877. sig, _ := fn.Pkg.typeOf(e.Fun).Underlying().(*types.Signature)
  878. if sig == nil {
  879. panic(fmt.Sprintf("no signature for call of %s", e.Fun))
  880. }
  881. c.Args = b.emitCallArgs(fn, sig, e, c.Args)
  882. }
  883. // assignOp emits to fn code to perform loc += incr or loc -= incr.
  884. func (b *builder) assignOp(fn *Function, loc lvalue, incr Value, op token.Token) {
  885. oldv := loc.load(fn)
  886. loc.store(fn, emitArith(fn, op, oldv, emitConv(fn, incr, oldv.Type()), loc.typ(), token.NoPos))
  887. }
  888. // localValueSpec emits to fn code to define all of the vars in the
  889. // function-local ValueSpec, spec.
  890. //
  891. func (b *builder) localValueSpec(fn *Function, spec *ast.ValueSpec) {
  892. switch {
  893. case len(spec.Values) == len(spec.Names):
  894. // e.g. var x, y = 0, 1
  895. // 1:1 assignment
  896. for i, id := range spec.Names {
  897. if !isBlankIdent(id) {
  898. fn.addLocalForIdent(id)
  899. }
  900. lval := b.addr(fn, id, false) // non-escaping
  901. b.assign(fn, lval, spec.Values[i], true, nil)
  902. }
  903. case len(spec.Values) == 0:
  904. // e.g. var x, y int
  905. // Locals are implicitly zero-initialized.
  906. for _, id := range spec.Names {
  907. if !isBlankIdent(id) {
  908. lhs := fn.addLocalForIdent(id)
  909. if fn.debugInfo() {
  910. emitDebugRef(fn, id, lhs, true)
  911. }
  912. }
  913. }
  914. default:
  915. // e.g. var x, y = pos()
  916. tuple := b.exprN(fn, spec.Values[0])
  917. for i, id := range spec.Names {
  918. if !isBlankIdent(id) {
  919. fn.addLocalForIdent(id)
  920. lhs := b.addr(fn, id, false) // non-escaping
  921. lhs.store(fn, emitExtract(fn, tuple, i))
  922. }
  923. }
  924. }
  925. }
  926. // assignStmt emits code to fn for a parallel assignment of rhss to lhss.
  927. // isDef is true if this is a short variable declaration (:=).
  928. //
  929. // Note the similarity with localValueSpec.
  930. //
  931. func (b *builder) assignStmt(fn *Function, lhss, rhss []ast.Expr, isDef bool) {
  932. // Side effects of all LHSs and RHSs must occur in left-to-right order.
  933. lvals := make([]lvalue, len(lhss))
  934. isZero := make([]bool, len(lhss))
  935. for i, lhs := range lhss {
  936. var lval lvalue = blank{}
  937. if !isBlankIdent(lhs) {
  938. if isDef {
  939. if obj := fn.Pkg.info.Defs[lhs.(*ast.Ident)]; obj != nil {
  940. fn.addNamedLocal(obj)
  941. isZero[i] = true
  942. }
  943. }
  944. lval = b.addr(fn, lhs, false) // non-escaping
  945. }
  946. lvals[i] = lval
  947. }
  948. if len(lhss) == len(rhss) {
  949. // Simple assignment: x = f() (!isDef)
  950. // Parallel assignment: x, y = f(), g() (!isDef)
  951. // or short var decl: x, y := f(), g() (isDef)
  952. //
  953. // In all cases, the RHSs may refer to the LHSs,
  954. // so we need a storebuf.
  955. var sb storebuf
  956. for i := range rhss {
  957. b.assign(fn, lvals[i], rhss[i], isZero[i], &sb)
  958. }
  959. sb.emit(fn)
  960. } else {
  961. // e.g. x, y = pos()
  962. tuple := b.exprN(fn, rhss[0])
  963. emitDebugRef(fn, rhss[0], tuple, false)
  964. for i, lval := range lvals {
  965. lval.store(fn, emitExtract(fn, tuple, i))
  966. }
  967. }
  968. }
  969. // arrayLen returns the length of the array whose composite literal elements are elts.
  970. func (b *builder) arrayLen(fn *Function, elts []ast.Expr) int64 {
  971. var max int64 = -1
  972. var i int64 = -1
  973. for _, e := range elts {
  974. if kv, ok := e.(*ast.KeyValueExpr); ok {
  975. i = b.expr(fn, kv.Key).(*Const).Int64()
  976. } else {
  977. i++
  978. }
  979. if i > max {
  980. max = i
  981. }
  982. }
  983. return max + 1
  984. }
  985. // compLit emits to fn code to initialize a composite literal e at
  986. // address addr with type typ.
  987. //
  988. // Nested composite literals are recursively initialized in place
  989. // where possible. If isZero is true, compLit assumes that addr
  990. // holds the zero value for typ.
  991. //
  992. // Because the elements of a composite literal may refer to the
  993. // variables being updated, as in the second line below,
  994. // x := T{a: 1}
  995. // x = T{a: x.a}
  996. // all the reads must occur before all the writes. Thus all stores to
  997. // loc are emitted to the storebuf sb for later execution.
  998. //
  999. // A CompositeLit may have pointer type only in the recursive (nested)
  1000. // case when the type name is implicit. e.g. in []*T{{}}, the inner
  1001. // literal has type *T behaves like &T{}.
  1002. // In that case, addr must hold a T, not a *T.
  1003. //
  1004. func (b *builder) compLit(fn *Function, addr Value, e *ast.CompositeLit, isZero bool, sb *storebuf) {
  1005. typ := deref(fn.Pkg.typeOf(e))
  1006. switch t := typ.Underlying().(type) {
  1007. case *types.Struct:
  1008. if !isZero && len(e.Elts) != t.NumFields() {
  1009. // memclear
  1010. sb.store(&address{addr, e.Lbrace, nil},
  1011. zeroValue(fn, deref(addr.Type())))
  1012. isZero = true
  1013. }
  1014. for i, e := range e.Elts {
  1015. fieldIndex := i
  1016. pos := e.Pos()
  1017. if kv, ok := e.(*ast.KeyValueExpr); ok {
  1018. fname := kv.Key.(*ast.Ident).Name
  1019. for i, n := 0, t.NumFields(); i < n; i++ {
  1020. sf := t.Field(i)
  1021. if sf.Name() == fname {
  1022. fieldIndex = i
  1023. pos = kv.Colon
  1024. e = kv.Value
  1025. break
  1026. }
  1027. }
  1028. }
  1029. sf := t.Field(fieldIndex)
  1030. faddr := &FieldAddr{
  1031. X: addr,
  1032. Field: fieldIndex,
  1033. }
  1034. faddr.setType(types.NewPointer(sf.Type()))
  1035. fn.emit(faddr)
  1036. b.assign(fn, &address{addr: faddr, pos: pos, expr: e}, e, isZero, sb)
  1037. }
  1038. case *types.Array, *types.Slice:
  1039. var at *types.Array
  1040. var array Value
  1041. switch t := t.(type) {
  1042. case *types.Slice:
  1043. at = types.NewArray(t.Elem(), b.arrayLen(fn, e.Elts))
  1044. alloc := emitNew(fn, at, e.Lbrace)
  1045. alloc.Comment = "slicelit"
  1046. array = alloc
  1047. case *types.Array:
  1048. at = t
  1049. array = addr
  1050. if !isZero && int64(len(e.Elts)) != at.Len() {
  1051. // memclear
  1052. sb.store(&address{array, e.Lbrace, nil},
  1053. zeroValue(fn, deref(array.Type())))
  1054. }
  1055. }
  1056. var idx *Const
  1057. for _, e := range e.Elts {
  1058. pos := e.Pos()
  1059. if kv, ok := e.(*ast.KeyValueExpr); ok {
  1060. idx = b.expr(fn, kv.Key).(*Const)
  1061. pos = kv.Colon
  1062. e = kv.Value
  1063. } else {
  1064. var idxval int64
  1065. if idx != nil {
  1066. idxval = idx.Int64() + 1
  1067. }
  1068. idx = intConst(idxval)
  1069. }
  1070. iaddr := &IndexAddr{
  1071. X: array,
  1072. Index: idx,
  1073. }
  1074. iaddr.setType(types.NewPointer(at.Elem()))
  1075. fn.emit(iaddr)
  1076. if t != at { // slice
  1077. // backing array is unaliased => storebuf not needed.
  1078. b.assign(fn, &address{addr: iaddr, pos: pos, expr: e}, e, true, nil)
  1079. } else {
  1080. b.assign(fn, &address{addr: iaddr, pos: pos, expr: e}, e, true, sb)
  1081. }
  1082. }
  1083. if t != at { // slice
  1084. s := &Slice{X: array}
  1085. s.setPos(e.Lbrace)
  1086. s.setType(typ)
  1087. sb.store(&address{addr: addr, pos: e.Lbrace, expr: e}, fn.emit(s))
  1088. }
  1089. case *types.Map:
  1090. m := &MakeMap{Reserve: intConst(int64(len(e.Elts)))}
  1091. m.setPos(e.Lbrace)
  1092. m.setType(typ)
  1093. fn.emit(m)
  1094. for _, e := range e.Elts {
  1095. e := e.(*ast.KeyValueExpr)
  1096. // If a key expression in a map literal is itself a
  1097. // composite literal, the type may be omitted.
  1098. // For example:
  1099. // map[*struct{}]bool{{}: true}
  1100. // An &-operation may be implied:
  1101. // map[*struct{}]bool{&struct{}{}: true}
  1102. var key Value
  1103. if _, ok := unparen(e.Key).(*ast.CompositeLit); ok && isPointer(t.Key()) {
  1104. // A CompositeLit never evaluates to a pointer,
  1105. // so if the type of the location is a pointer,
  1106. // an &-operation is implied.
  1107. key = b.addr(fn, e.Key, true).address(fn)
  1108. } else {
  1109. key = b.expr(fn, e.Key)
  1110. }
  1111. loc := element{
  1112. m: m,
  1113. k: emitConv(fn, key, t.Key()),
  1114. t: t.Elem(),
  1115. pos: e.Colon,
  1116. }
  1117. // We call assign() only because it takes care
  1118. // of any &-operation required in the recursive
  1119. // case, e.g.,
  1120. // map[int]*struct{}{0: {}} implies &struct{}{}.
  1121. // In-place update is of course impossible,
  1122. // and no storebuf is needed.
  1123. b.assign(fn, &loc, e.Value, true, nil)
  1124. }
  1125. sb.store(&address{addr: addr, pos: e.Lbrace, expr: e}, m)
  1126. default:
  1127. panic("unexpected CompositeLit type: " + t.String())
  1128. }
  1129. }
  1130. // switchStmt emits to fn code for the switch statement s, optionally
  1131. // labelled by label.
  1132. //
  1133. func (b *builder) switchStmt(fn *Function, s *ast.SwitchStmt, label *lblock) {
  1134. // We treat SwitchStmt like a sequential if-else chain.
  1135. // Multiway dispatch can be recovered later by ssautil.Switches()
  1136. // to those cases that are free of side effects.
  1137. if s.Init != nil {
  1138. b.stmt(fn, s.Init)
  1139. }
  1140. var tag Value = vTrue
  1141. if s.Tag != nil {
  1142. tag = b.expr(fn, s.Tag)
  1143. }
  1144. done := fn.newBasicBlock("switch.done")
  1145. if label != nil {
  1146. label._break = done
  1147. }
  1148. // We pull the default case (if present) down to the end.
  1149. // But each fallthrough label must point to the next
  1150. // body block in source order, so we preallocate a
  1151. // body block (fallthru) for the next case.
  1152. // Unfortunately this makes for a confusing block order.
  1153. var dfltBody *[]ast.Stmt
  1154. var dfltFallthrough *BasicBlock
  1155. var fallthru, dfltBlock *BasicBlock
  1156. ncases := len(s.Body.List)
  1157. for i, clause := range s.Body.List {
  1158. body := fallthru
  1159. if body == nil {
  1160. body = fn.newBasicBlock("switch.body") // first case only
  1161. }
  1162. // Preallocate body block for the next case.
  1163. fallthru = done
  1164. if i+1 < ncases {
  1165. fallthru = fn.newBasicBlock("switch.body")
  1166. }
  1167. cc := clause.(*ast.CaseClause)
  1168. if cc.List == nil {
  1169. // Default case.
  1170. dfltBody = &cc.Body
  1171. dfltFallthrough = fallthru
  1172. dfltBlock = body
  1173. continue
  1174. }
  1175. var nextCond *BasicBlock
  1176. for _, cond := range cc.List {
  1177. nextCond = fn.newBasicBlock("switch.next")
  1178. // TODO(adonovan): opt: when tag==vTrue, we'd
  1179. // get better code if we use b.cond(cond)
  1180. // instead of BinOp(EQL, tag, b.expr(cond))
  1181. // followed by If. Don't forget conversions
  1182. // though.
  1183. cond := emitCompare(fn, token.EQL, tag, b.expr(fn, cond), token.NoPos)
  1184. emitIf(fn, cond, body, nextCond)
  1185. fn.currentBlock = nextCond
  1186. }
  1187. fn.currentBlock = body
  1188. fn.targets = &targets{
  1189. tail: fn.targets,
  1190. _break: done,
  1191. _fallthrough: fallthru,
  1192. }
  1193. b.stmtList(fn, cc.Body)
  1194. fn.targets = fn.targets.tail
  1195. emitJump(fn, done)
  1196. fn.currentBlock = nextCond
  1197. }
  1198. if dfltBlock != nil {
  1199. emitJump(fn, dfltBlock)
  1200. fn.currentBlock = dfltBlock
  1201. fn.targets = &targets{
  1202. tail: fn.targets,
  1203. _break: done,
  1204. _fallthrough: dfltFallthrough,
  1205. }
  1206. b.stmtList(fn, *dfltBody)
  1207. fn.targets = fn.targets.tail
  1208. }
  1209. emitJump(fn, done)
  1210. fn.currentBlock = done
  1211. }
  1212. // typeSwitchStmt emits to fn code for the type switch statement s, optionally
  1213. // labelled by label.
  1214. //
  1215. func (b *builder) typeSwitchStmt(fn *Function, s *ast.TypeSwitchStmt, label *lblock) {
  1216. // We treat TypeSwitchStmt like a sequential if-else chain.
  1217. // Multiway dispatch can be recovered later by ssautil.Switches().
  1218. // Typeswitch lowering:
  1219. //
  1220. // var x X
  1221. // switch y := x.(type) {
  1222. // case T1, T2: S1 // >1 (y := x)
  1223. // case nil: SN // nil (y := x)
  1224. // default: SD // 0 types (y := x)
  1225. // case T3: S3 // 1 type (y := x.(T3))
  1226. // }
  1227. //
  1228. // ...s.Init...
  1229. // x := eval x
  1230. // .caseT1:
  1231. // t1, ok1 := typeswitch,ok x <T1>
  1232. // if ok1 then goto S1 else goto .caseT2
  1233. // .caseT2:
  1234. // t2, ok2 := typeswitch,ok x <T2>
  1235. // if ok2 then goto S1 else goto .caseNil
  1236. // .S1:
  1237. // y := x
  1238. // ...S1...
  1239. // goto done
  1240. // .caseNil:
  1241. // if t2, ok2 := typeswitch,ok x <T2>
  1242. // if x == nil then goto SN else goto .caseT3
  1243. // .SN:
  1244. // y := x
  1245. // ...SN...
  1246. // goto done
  1247. // .caseT3:
  1248. // t3, ok3 := typeswitch,ok x <T3>
  1249. // if ok3 then goto S3 else goto default
  1250. // .S3:
  1251. // y := t3
  1252. // ...S3...
  1253. // goto done
  1254. // .default:
  1255. // y := x
  1256. // ...SD...
  1257. // goto done
  1258. // .done:
  1259. if s.Init != nil {
  1260. b.stmt(fn, s.Init)
  1261. }
  1262. var x Value
  1263. switch ass := s.Assign.(type) {
  1264. case *ast.ExprStmt: // x.(type)
  1265. x = b.expr(fn, unparen(ass.X).(*ast.TypeAssertExpr).X)
  1266. case *ast.AssignStmt: // y := x.(type)
  1267. x = b.expr(fn, unparen(ass.Rhs[0]).(*ast.TypeAssertExpr).X)
  1268. }
  1269. done := fn.newBasicBlock("typeswitch.done")
  1270. if label != nil {
  1271. label._break = done
  1272. }
  1273. var default_ *ast.CaseClause
  1274. for _, clause := range s.Body.List {
  1275. cc := clause.(*ast.CaseClause)
  1276. if cc.List == nil {
  1277. default_ = cc
  1278. continue
  1279. }
  1280. body := fn.newBasicBlock("typeswitch.body")
  1281. var next *BasicBlock
  1282. var casetype types.Type
  1283. var ti Value // ti, ok := typeassert,ok x <Ti>
  1284. for _, cond := range cc.List {
  1285. next = fn.newBasicBlock("typeswitch.next")
  1286. casetype = fn.Pkg.typeOf(cond)
  1287. var condv Value
  1288. if casetype == tUntypedNil {
  1289. condv = emitCompare(fn, token.EQL, x, nilConst(x.Type()), token.NoPos)
  1290. ti = x
  1291. } else {
  1292. yok := emitTypeTest(fn, x, casetype, cc.Case)
  1293. ti = emitExtract(fn, yok, 0)
  1294. condv = emitExtract(fn, yok, 1)
  1295. }
  1296. emitIf(fn, condv, body, next)
  1297. fn.currentBlock = next
  1298. }
  1299. if len(cc.List) != 1 {
  1300. ti = x
  1301. }
  1302. fn.currentBlock = body
  1303. b.typeCaseBody(fn, cc, ti, done)
  1304. fn.currentBlock = next
  1305. }
  1306. if default_ != nil {
  1307. b.typeCaseBody(fn, default_, x, done)
  1308. } else {
  1309. emitJump(fn, done)
  1310. }
  1311. fn.currentBlock = done
  1312. }
  1313. func (b *builder) typeCaseBody(fn *Function, cc *ast.CaseClause, x Value, done *BasicBlock) {
  1314. if obj := fn.Pkg.info.Implicits[cc]; obj != nil {
  1315. // In a switch y := x.(type), each case clause
  1316. // implicitly declares a distinct object y.
  1317. // In a single-type case, y has that type.
  1318. // In multi-type cases, 'case nil' and default,
  1319. // y has the same type as the interface operand.
  1320. emitStore(fn, fn.addNamedLocal(obj), x, obj.Pos())
  1321. }
  1322. fn.targets = &targets{
  1323. tail: fn.targets,
  1324. _break: done,
  1325. }
  1326. b.stmtList(fn, cc.Body)
  1327. fn.targets = fn.targets.tail
  1328. emitJump(fn, done)
  1329. }
  1330. // selectStmt emits to fn code for the select statement s, optionally
  1331. // labelled by label.
  1332. //
  1333. func (b *builder) selectStmt(fn *Function, s *ast.SelectStmt, label *lblock) {
  1334. // A blocking select of a single case degenerates to a
  1335. // simple send or receive.
  1336. // TODO(adonovan): opt: is this optimization worth its weight?
  1337. if len(s.Body.List) == 1 {
  1338. clause := s.Body.List[0].(*ast.CommClause)
  1339. if clause.Comm != nil {
  1340. b.stmt(fn, clause.Comm)
  1341. done := fn.newBasicBlock("select.done")
  1342. if label != nil {
  1343. label._break = done
  1344. }
  1345. fn.targets = &targets{
  1346. tail: fn.targets,
  1347. _break: done,
  1348. }
  1349. b.stmtList(fn, clause.Body)
  1350. fn.targets = fn.targets.tail
  1351. emitJump(fn, done)
  1352. fn.currentBlock = done
  1353. return
  1354. }
  1355. }
  1356. // First evaluate all channels in all cases, and find
  1357. // the directions of each state.
  1358. var states []*SelectState
  1359. blocking := true
  1360. debugInfo := fn.debugInfo()
  1361. for _, clause := range s.Body.List {
  1362. var st *SelectState
  1363. switch comm := clause.(*ast.CommClause).Comm.(type) {
  1364. case nil: // default case
  1365. blocking = false
  1366. continue
  1367. case *ast.SendStmt: // ch<- i
  1368. ch := b.expr(fn, comm.Chan)
  1369. st = &SelectState{
  1370. Dir: types.SendOnly,
  1371. Chan: ch,
  1372. Send: emitConv(fn, b.expr(fn, comm.Value),
  1373. ch.Type().Underlying().(*types.Chan).Elem()),
  1374. Pos: comm.Arrow,
  1375. }
  1376. if debugInfo {
  1377. st.DebugNode = comm
  1378. }
  1379. case *ast.AssignStmt: // x := <-ch
  1380. recv := unparen(comm.Rhs[0]).(*ast.UnaryExpr)
  1381. st = &SelectState{
  1382. Dir: types.RecvOnly,
  1383. Chan: b.expr(fn, recv.X),
  1384. Pos: recv.OpPos,
  1385. }
  1386. if debugInfo {
  1387. st.DebugNode = recv
  1388. }
  1389. case *ast.ExprStmt: // <-ch
  1390. recv := unparen(comm.X).(*ast.UnaryExpr)
  1391. st = &SelectState{
  1392. Dir: types.RecvOnly,
  1393. Chan: b.expr(fn, recv.X),
  1394. Pos: recv.OpPos,
  1395. }
  1396. if debugInfo {
  1397. st.DebugNode = recv
  1398. }
  1399. }
  1400. states = append(states, st)
  1401. }
  1402. // We dispatch on the (fair) result of Select using a
  1403. // sequential if-else chain, in effect:
  1404. //
  1405. // idx, recvOk, r0...r_n-1 := select(...)
  1406. // if idx == 0 { // receive on channel 0 (first receive => r0)
  1407. // x, ok := r0, recvOk
  1408. // ...state0...
  1409. // } else if v == 1 { // send on channel 1
  1410. // ...state1...
  1411. // } else {
  1412. // ...default...
  1413. // }
  1414. sel := &Select{
  1415. States: states,
  1416. Blocking: blocking,
  1417. }
  1418. sel.setPos(s.Select)
  1419. var vars []*types.Var
  1420. vars = append(vars, varIndex, varOk)
  1421. for _, st := range states {
  1422. if st.Dir == types.RecvOnly {
  1423. tElem := st.Chan.Type().Underlying().(*types.Chan).Elem()
  1424. vars = append(vars, anonVar(tElem))
  1425. }
  1426. }
  1427. sel.setType(types.NewTuple(vars...))
  1428. fn.emit(sel)
  1429. idx := emitExtract(fn, sel, 0)
  1430. done := fn.newBasicBlock("select.done")
  1431. if label != nil {
  1432. label._break = done
  1433. }
  1434. var defaultBody *[]ast.Stmt
  1435. state := 0
  1436. r := 2 // index in 'sel' tuple of value; increments if st.Dir==RECV
  1437. for _, cc := range s.Body.List {
  1438. clause := cc.(*ast.CommClause)
  1439. if clause.Comm == nil {
  1440. defaultBody = &clause.Body
  1441. continue
  1442. }
  1443. body := fn.newBasicBlock("select.body")
  1444. next := fn.newBasicBlock("select.next")
  1445. emitIf(fn, emitCompare(fn, token.EQL, idx, intConst(int64(state)), token.NoPos), body, next)
  1446. fn.currentBlock = body
  1447. fn.targets = &targets{
  1448. tail: fn.targets,
  1449. _break: done,
  1450. }
  1451. switch comm := clause.Comm.(type) {
  1452. case *ast.ExprStmt: // <-ch
  1453. if debugInfo {
  1454. v := emitExtract(fn, sel, r)
  1455. emitDebugRef(fn, states[state].DebugNode.(ast.Expr), v, false)
  1456. }
  1457. r++
  1458. case *ast.AssignStmt: // x := <-states[state].Chan
  1459. if comm.Tok == token.DEFINE {
  1460. fn.addLocalForIdent(comm.Lhs[0].(*ast.Ident))
  1461. }
  1462. x := b.addr(fn, comm.Lhs[0], false) // non-escaping
  1463. v := emitExtract(fn, sel, r)
  1464. if debugInfo {
  1465. emitDebugRef(fn, states[state].DebugNode.(ast.Expr), v, false)
  1466. }
  1467. x.store(fn, v)
  1468. if len(comm.Lhs) == 2 { // x, ok := ...
  1469. if comm.Tok == token.DEFINE {
  1470. fn.addLocalForIdent(comm.Lhs[1].(*ast.Ident))
  1471. }
  1472. ok := b.addr(fn, comm.Lhs[1], false) // non-escaping
  1473. ok.store(fn, emitExtract(fn, sel, 1))
  1474. }
  1475. r++
  1476. }
  1477. b.stmtList(fn, clause.Body)
  1478. fn.targets = fn.targets.tail
  1479. emitJump(fn, done)
  1480. fn.currentBlock = next
  1481. state++
  1482. }
  1483. if defaultBody != nil {
  1484. fn.targets = &targets{
  1485. tail: fn.targets,
  1486. _break: done,
  1487. }
  1488. b.stmtList(fn, *defaultBody)
  1489. fn.targets = fn.targets.tail
  1490. } else {
  1491. // A blocking select must match some case.
  1492. // (This should really be a runtime.errorString, not a string.)
  1493. fn.emit(&Panic{
  1494. X: emitConv(fn, stringConst("blocking select matched no case"), tEface),
  1495. })
  1496. fn.currentBlock = fn.newBasicBlock("unreachable")
  1497. }
  1498. emitJump(fn, done)
  1499. fn.currentBlock = done
  1500. }
  1501. // forStmt emits to fn code for the for statement s, optionally
  1502. // labelled by label.
  1503. //
  1504. func (b *builder) forStmt(fn *Function, s *ast.ForStmt, label *lblock) {
  1505. // ...init...
  1506. // jump loop
  1507. // loop:
  1508. // if cond goto body else done
  1509. // body:
  1510. // ...body...
  1511. // jump post
  1512. // post: (target of continue)
  1513. // ...post...
  1514. // jump loop
  1515. // done: (target of break)
  1516. if s.Init != nil {
  1517. b.stmt(fn, s.Init)
  1518. }
  1519. body := fn.newBasicBlock("for.body")
  1520. done := fn.newBasicBlock("for.done") // target of 'break'
  1521. loop := body // target of back-edge
  1522. if s.Cond != nil {
  1523. loop = fn.newBasicBlock("for.loop")
  1524. }
  1525. cont := loop // target of 'continue'
  1526. if s.Post != nil {
  1527. cont = fn.newBasicBlock("for.post")
  1528. }
  1529. if label != nil {
  1530. label._break = done
  1531. label._continue = cont
  1532. }
  1533. emitJump(fn, loop)
  1534. fn.currentBlock = loop
  1535. if loop != body {
  1536. b.cond(fn, s.Cond, body, done)
  1537. fn.currentBlock = body
  1538. }
  1539. fn.targets = &targets{
  1540. tail: fn.targets,
  1541. _break: done,
  1542. _continue: cont,
  1543. }
  1544. b.stmt(fn, s.Body)
  1545. fn.targets = fn.targets.tail
  1546. emitJump(fn, cont)
  1547. if s.Post != nil {
  1548. fn.currentBlock = cont
  1549. b.stmt(fn, s.Post)
  1550. emitJump(fn, loop) // back-edge
  1551. }
  1552. fn.currentBlock = done
  1553. }
  1554. // rangeIndexed emits to fn the header for an integer-indexed loop
  1555. // over array, *array or slice value x.
  1556. // The v result is defined only if tv is non-nil.
  1557. // forPos is the position of the "for" token.
  1558. //
  1559. func (b *builder) rangeIndexed(fn *Function, x Value, tv types.Type, pos token.Pos) (k, v Value, loop, done *BasicBlock) {
  1560. //
  1561. // length = len(x)
  1562. // index = -1
  1563. // loop: (target of continue)
  1564. // index++
  1565. // if index < length goto body else done
  1566. // body:
  1567. // k = index
  1568. // v = x[index]
  1569. // ...body...
  1570. // jump loop
  1571. // done: (target of break)
  1572. // Determine number of iterations.
  1573. var length Value
  1574. if arr, ok := deref(x.Type()).Underlying().(*types.Array); ok {
  1575. // For array or *array, the number of iterations is
  1576. // known statically thanks to the type. We avoid a
  1577. // data dependence upon x, permitting later dead-code
  1578. // elimination if x is pure, static unrolling, etc.
  1579. // Ranging over a nil *array may have >0 iterations.
  1580. // We still generate code for x, in case it has effects.
  1581. length = intConst(arr.Len())
  1582. } else {
  1583. // length = len(x).
  1584. var c Call
  1585. c.Call.Value = makeLen(x.Type())
  1586. c.Call.Args = []Value{x}
  1587. c.setType(tInt)
  1588. length = fn.emit(&c)
  1589. }
  1590. index := fn.addLocal(tInt, token.NoPos)
  1591. emitStore(fn, index, intConst(-1), pos)
  1592. loop = fn.newBasicBlock("rangeindex.loop")
  1593. emitJump(fn, loop)
  1594. fn.currentBlock = loop
  1595. incr := &BinOp{
  1596. Op: token.ADD,
  1597. X: emitLoad(fn, index),
  1598. Y: vOne,
  1599. }
  1600. incr.setType(tInt)
  1601. emitStore(fn, index, fn.emit(incr), pos)
  1602. body := fn.newBasicBlock("rangeindex.body")
  1603. done = fn.newBasicBlock("rangeindex.done")
  1604. emitIf(fn, emitCompare(fn, token.LSS, incr, length, token.NoPos), body, done)
  1605. fn.currentBlock = body
  1606. k = emitLoad(fn, index)
  1607. if tv != nil {
  1608. switch t := x.Type().Underlying().(type) {
  1609. case *types.Array:
  1610. instr := &Index{
  1611. X: x,
  1612. Index: k,
  1613. }
  1614. instr.setType(t.Elem())
  1615. v = fn.emit(instr)
  1616. case *types.Pointer: // *array
  1617. instr := &IndexAddr{
  1618. X: x,
  1619. Index: k,
  1620. }
  1621. instr.setType(types.NewPointer(t.Elem().Underlying().(*types.Array).Elem()))
  1622. v = emitLoad(fn, fn.emit(instr))
  1623. case *types.Slice:
  1624. instr := &IndexAddr{
  1625. X: x,
  1626. Index: k,
  1627. }
  1628. instr.setType(types.NewPointer(t.Elem()))
  1629. v = emitLoad(fn, fn.emit(instr))
  1630. default:
  1631. panic("rangeIndexed x:" + t.String())
  1632. }
  1633. }
  1634. return
  1635. }
  1636. // rangeIter emits to fn the header for a loop using
  1637. // Range/Next/Extract to iterate over map or string value x.
  1638. // tk and tv are the types of the key/value results k and v, or nil
  1639. // if the respective component is not wanted.
  1640. //
  1641. func (b *builder) rangeIter(fn *Function, x Value, tk, tv types.Type, pos token.Pos) (k, v Value, loop, done *BasicBlock) {
  1642. //
  1643. // it = range x
  1644. // loop: (target of continue)
  1645. // okv = next it (ok, key, value)
  1646. // ok = extract okv #0
  1647. // if ok goto body else done
  1648. // body:
  1649. // k = extract okv #1
  1650. // v = extract okv #2
  1651. // ...body...
  1652. // jump loop
  1653. // done: (target of break)
  1654. //
  1655. if tk == nil {
  1656. tk = tInvalid
  1657. }
  1658. if tv == nil {
  1659. tv = tInvalid
  1660. }
  1661. rng := &Range{X: x}
  1662. rng.setPos(pos)
  1663. rng.setType(tRangeIter)
  1664. it := fn.emit(rng)
  1665. loop = fn.newBasicBlock("rangeiter.loop")
  1666. emitJump(fn, loop)
  1667. fn.currentBlock = loop
  1668. _, isString := x.Type().Underlying().(*types.Basic)
  1669. okv := &Next{
  1670. Iter: it,
  1671. IsString: isString,
  1672. }
  1673. okv.setType(types.NewTuple(
  1674. varOk,
  1675. newVar("k", tk),
  1676. newVar("v", tv),
  1677. ))
  1678. fn.emit(okv)
  1679. body := fn.newBasicBlock("rangeiter.body")
  1680. done = fn.newBasicBlock("rangeiter.done")
  1681. emitIf(fn, emitExtract(fn, okv, 0), body, done)
  1682. fn.currentBlock = body
  1683. if tk != tInvalid {
  1684. k = emitExtract(fn, okv, 1)
  1685. }
  1686. if tv != tInvalid {
  1687. v = emitExtract(fn, okv, 2)
  1688. }
  1689. return
  1690. }
  1691. // rangeChan emits to fn the header for a loop that receives from
  1692. // channel x until it fails.
  1693. // tk is the channel's element type, or nil if the k result is
  1694. // not wanted
  1695. // pos is the position of the '=' or ':=' token.
  1696. //
  1697. func (b *builder) rangeChan(fn *Function, x Value, tk types.Type, pos token.Pos) (k Value, loop, done *BasicBlock) {
  1698. //
  1699. // loop: (target of continue)
  1700. // ko = <-x (key, ok)
  1701. // ok = extract ko #1
  1702. // if ok goto body else done
  1703. // body:
  1704. // k = extract ko #0
  1705. // ...
  1706. // goto loop
  1707. // done: (target of break)
  1708. loop = fn.newBasicBlock("rangechan.loop")
  1709. emitJump(fn, loop)
  1710. fn.currentBlock = loop
  1711. recv := &UnOp{
  1712. Op: token.ARROW,
  1713. X: x,
  1714. CommaOk: true,
  1715. }
  1716. recv.setPos(pos)
  1717. recv.setType(types.NewTuple(
  1718. newVar("k", x.Type().Underlying().(*types.Chan).Elem()),
  1719. varOk,
  1720. ))
  1721. ko := fn.emit(recv)
  1722. body := fn.newBasicBlock("rangechan.body")
  1723. done = fn.newBasicBlock("rangechan.done")
  1724. emitIf(fn, emitExtract(fn, ko, 1), body, done)
  1725. fn.currentBlock = body
  1726. if tk != nil {
  1727. k = emitExtract(fn, ko, 0)
  1728. }
  1729. return
  1730. }
  1731. // rangeStmt emits to fn code for the range statement s, optionally
  1732. // labelled by label.
  1733. //
  1734. func (b *builder) rangeStmt(fn *Function, s *ast.RangeStmt, label *lblock) {
  1735. var tk, tv types.Type
  1736. if s.Key != nil && !isBlankIdent(s.Key) {
  1737. tk = fn.Pkg.typeOf(s.Key)
  1738. }
  1739. if s.Value != nil && !isBlankIdent(s.Value) {
  1740. tv = fn.Pkg.typeOf(s.Value)
  1741. }
  1742. // If iteration variables are defined (:=), this
  1743. // occurs once outside the loop.
  1744. //
  1745. // Unlike a short variable declaration, a RangeStmt
  1746. // using := never redeclares an existing variable; it
  1747. // always creates a new one.
  1748. if s.Tok == token.DEFINE {
  1749. if tk != nil {
  1750. fn.addLocalForIdent(s.Key.(*ast.Ident))
  1751. }
  1752. if tv != nil {
  1753. fn.addLocalForIdent(s.Value.(*ast.Ident))
  1754. }
  1755. }
  1756. x := b.expr(fn, s.X)
  1757. var k, v Value
  1758. var loop, done *BasicBlock
  1759. switch rt := x.Type().Underlying().(type) {
  1760. case *types.Slice, *types.Array, *types.Pointer: // *array
  1761. k, v, loop, done = b.rangeIndexed(fn, x, tv, s.For)
  1762. case *types.Chan:
  1763. k, loop, done = b.rangeChan(fn, x, tk, s.For)
  1764. case *types.Map, *types.Basic: // string
  1765. k, v, loop, done = b.rangeIter(fn, x, tk, tv, s.For)
  1766. default:
  1767. panic("Cannot range over: " + rt.String())
  1768. }
  1769. // Evaluate both LHS expressions before we update either.
  1770. var kl, vl lvalue
  1771. if tk != nil {
  1772. kl = b.addr(fn, s.Key, false) // non-escaping
  1773. }
  1774. if tv != nil {
  1775. vl = b.addr(fn, s.Value, false) // non-escaping
  1776. }
  1777. if tk != nil {
  1778. kl.store(fn, k)
  1779. }
  1780. if tv != nil {
  1781. vl.store(fn, v)
  1782. }
  1783. if label != nil {
  1784. label._break = done
  1785. label._continue = loop
  1786. }
  1787. fn.targets = &targets{
  1788. tail: fn.targets,
  1789. _break: done,
  1790. _continue: loop,
  1791. }
  1792. b.stmt(fn, s.Body)
  1793. fn.targets = fn.targets.tail
  1794. emitJump(fn, loop) // back-edge
  1795. fn.currentBlock = done
  1796. }
  1797. // stmt lowers statement s to SSA form, emitting code to fn.
  1798. func (b *builder) stmt(fn *Function, _s ast.Stmt) {
  1799. // The label of the current statement. If non-nil, its _goto
  1800. // target is always set; its _break and _continue are set only
  1801. // within the body of switch/typeswitch/select/for/range.
  1802. // It is effectively an additional default-nil parameter of stmt().
  1803. var label *lblock
  1804. start:
  1805. switch s := _s.(type) {
  1806. case *ast.EmptyStmt:
  1807. // ignore. (Usually removed by gofmt.)
  1808. case *ast.DeclStmt: // Con, Var or Typ
  1809. d := s.Decl.(*ast.GenDecl)
  1810. if d.Tok == token.VAR {
  1811. for _, spec := range d.Specs {
  1812. if vs, ok := spec.(*ast.ValueSpec); ok {
  1813. b.localValueSpec(fn, vs)
  1814. }
  1815. }
  1816. }
  1817. case *ast.LabeledStmt:
  1818. label = fn.labelledBlock(s.Label)
  1819. emitJump(fn, label._goto)
  1820. fn.currentBlock = label._goto
  1821. _s = s.Stmt
  1822. goto start // effectively: tailcall stmt(fn, s.Stmt, label)
  1823. case *ast.ExprStmt:
  1824. b.expr(fn, s.X)
  1825. case *ast.SendStmt:
  1826. fn.emit(&Send{
  1827. Chan: b.expr(fn, s.Chan),
  1828. X: emitConv(fn, b.expr(fn, s.Value),
  1829. fn.Pkg.typeOf(s.Chan).Underlying().(*types.Chan).Elem()),
  1830. pos: s.Arrow,
  1831. })
  1832. case *ast.IncDecStmt:
  1833. op := token.ADD
  1834. if s.Tok == token.DEC {
  1835. op = token.SUB
  1836. }
  1837. loc := b.addr(fn, s.X, false)
  1838. b.assignOp(fn, loc, NewConst(exact.MakeInt64(1), loc.typ()), op)
  1839. case *ast.AssignStmt:
  1840. switch s.Tok {
  1841. case token.ASSIGN, token.DEFINE:
  1842. b.assignStmt(fn, s.Lhs, s.Rhs, s.Tok == token.DEFINE)
  1843. default: // +=, etc.
  1844. op := s.Tok + token.ADD - token.ADD_ASSIGN
  1845. b.assignOp(fn, b.addr(fn, s.Lhs[0], false), b.expr(fn, s.Rhs[0]), op)
  1846. }
  1847. case *ast.GoStmt:
  1848. // The "intrinsics" new/make/len/cap are forbidden here.
  1849. // panic is treated like an ordinary function call.
  1850. v := Go{pos: s.Go}
  1851. b.setCall(fn, s.Call, &v.Call)
  1852. fn.emit(&v)
  1853. case *ast.DeferStmt:
  1854. // The "intrinsics" new/make/len/cap are forbidden here.
  1855. // panic is treated like an ordinary function call.
  1856. v := Defer{pos: s.Defer}
  1857. b.setCall(fn, s.Call, &v.Call)
  1858. fn.emit(&v)
  1859. // A deferred call can cause recovery from panic,
  1860. // and control resumes at the Recover block.
  1861. createRecoverBlock(fn)
  1862. case *ast.ReturnStmt:
  1863. var results []Value
  1864. if len(s.Results) == 1 && fn.Signature.Results().Len() > 1 {
  1865. // Return of one expression in a multi-valued function.
  1866. tuple := b.exprN(fn, s.Results[0])
  1867. ttuple := tuple.Type().(*types.Tuple)
  1868. for i, n := 0, ttuple.Len(); i < n; i++ {
  1869. results = append(results,
  1870. emitConv(fn, emitExtract(fn, tuple, i),
  1871. fn.Signature.Results().At(i).Type()))
  1872. }
  1873. } else {
  1874. // 1:1 return, or no-arg return in non-void function.
  1875. for i, r := range s.Results {
  1876. v := emitConv(fn, b.expr(fn, r), fn.Signature.Results().At(i).Type())
  1877. results = append(results, v)
  1878. }
  1879. }
  1880. if fn.namedResults != nil {
  1881. // Function has named result parameters (NRPs).
  1882. // Perform parallel assignment of return operands to NRPs.
  1883. for i, r := range results {
  1884. emitStore(fn, fn.namedResults[i], r, s.Return)
  1885. }
  1886. }
  1887. // Run function calls deferred in this
  1888. // function when explicitly returning from it.
  1889. fn.emit(new(RunDefers))
  1890. if fn.namedResults != nil {
  1891. // Reload NRPs to form the result tuple.
  1892. results = results[:0]
  1893. for _, r := range fn.namedResults {
  1894. results = append(results, emitLoad(fn, r))
  1895. }
  1896. }
  1897. fn.emit(&Return{Results: results, pos: s.Return})
  1898. fn.currentBlock = fn.newBasicBlock("unreachable")
  1899. case *ast.BranchStmt:
  1900. var block *BasicBlock
  1901. switch s.Tok {
  1902. case token.BREAK:
  1903. if s.Label != nil {
  1904. block = fn.labelledBlock(s.Label)._break
  1905. } else {
  1906. for t := fn.targets; t != nil && block == nil; t = t.tail {
  1907. block = t._break
  1908. }
  1909. }
  1910. case token.CONTINUE:
  1911. if s.Label != nil {
  1912. block = fn.labelledBlock(s.Label)._continue
  1913. } else {
  1914. for t := fn.targets; t != nil && block == nil; t = t.tail {
  1915. block = t._continue
  1916. }
  1917. }
  1918. case token.FALLTHROUGH:
  1919. for t := fn.targets; t != nil && block == nil; t = t.tail {
  1920. block = t._fallthrough
  1921. }
  1922. case token.GOTO:
  1923. block = fn.labelledBlock(s.Label)._goto
  1924. }
  1925. emitJump(fn, block)
  1926. fn.currentBlock = fn.newBasicBlock("unreachable")
  1927. case *ast.BlockStmt:
  1928. b.stmtList(fn, s.List)
  1929. case *ast.IfStmt:
  1930. if s.Init != nil {
  1931. b.stmt(fn, s.Init)
  1932. }
  1933. then := fn.newBasicBlock("if.then")
  1934. done := fn.newBasicBlock("if.done")
  1935. els := done
  1936. if s.Else != nil {
  1937. els = fn.newBasicBlock("if.else")
  1938. }
  1939. b.cond(fn, s.Cond, then, els)
  1940. fn.currentBlock = then
  1941. b.stmt(fn, s.Body)
  1942. emitJump(fn, done)
  1943. if s.Else != nil {
  1944. fn.currentBlock = els
  1945. b.stmt(fn, s.Else)
  1946. emitJump(fn, done)
  1947. }
  1948. fn.currentBlock = done
  1949. case *ast.SwitchStmt:
  1950. b.switchStmt(fn, s, label)
  1951. case *ast.TypeSwitchStmt:
  1952. b.typeSwitchStmt(fn, s, label)
  1953. case *ast.SelectStmt:
  1954. b.selectStmt(fn, s, label)
  1955. case *ast.ForStmt:
  1956. b.forStmt(fn, s, label)
  1957. case *ast.RangeStmt:
  1958. b.rangeStmt(fn, s, label)
  1959. default:
  1960. panic(fmt.Sprintf("unexpected statement kind: %T", s))
  1961. }
  1962. }
  1963. // buildFunction builds SSA code for the body of function fn. Idempotent.
  1964. func (b *builder) buildFunction(fn *Function) {
  1965. if fn.Blocks != nil {
  1966. return // building already started
  1967. }
  1968. var recvField *ast.FieldList
  1969. var body *ast.BlockStmt
  1970. var functype *ast.FuncType
  1971. switch n := fn.syntax.(type) {
  1972. case nil:
  1973. return // not a Go source function. (Synthetic, or from object file.)
  1974. case *ast.FuncDecl:
  1975. functype = n.Type
  1976. recvField = n.Recv
  1977. body = n.Body
  1978. case *ast.FuncLit:
  1979. functype = n.Type
  1980. body = n.Body
  1981. default:
  1982. panic(n)
  1983. }
  1984. if body == nil {
  1985. // External function.
  1986. if fn.Params == nil {
  1987. // This condition ensures we add a non-empty
  1988. // params list once only, but we may attempt
  1989. // the degenerate empty case repeatedly.
  1990. // TODO(adonovan): opt: don't do that.
  1991. // We set Function.Params even though there is no body
  1992. // code to reference them. This simplifies clients.
  1993. if recv := fn.Signature.Recv(); recv != nil {
  1994. fn.addParamObj(recv)
  1995. }
  1996. params := fn.Signature.Params()
  1997. for i, n := 0, params.Len(); i < n; i++ {
  1998. fn.addParamObj(params.At(i))
  1999. }
  2000. }
  2001. return
  2002. }
  2003. if fn.Prog.mode&LogSource != 0 {
  2004. defer logStack("build function %s @ %s", fn, fn.Prog.Fset.Position(fn.pos))()
  2005. }
  2006. fn.startBody()
  2007. fn.createSyntacticParams(recvField, functype)
  2008. b.stmt(fn, body)
  2009. if cb := fn.currentBlock; cb != nil && (cb == fn.Blocks[0] || cb == fn.Recover || cb.Preds != nil) {
  2010. // Control fell off the end of the function's body block.
  2011. //
  2012. // Block optimizations eliminate the current block, if
  2013. // unreachable. It is a builder invariant that
  2014. // if this no-arg return is ill-typed for
  2015. // fn.Signature.Results, this block must be
  2016. // unreachable. The sanity checker checks this.
  2017. fn.emit(new(RunDefers))
  2018. fn.emit(new(Return))
  2019. }
  2020. fn.finishBody()
  2021. }
  2022. // buildFuncDecl builds SSA code for the function or method declared
  2023. // by decl in package pkg.
  2024. //
  2025. func (b *builder) buildFuncDecl(pkg *Package, decl *ast.FuncDecl) {
  2026. id := decl.Name
  2027. if isBlankIdent(id) {
  2028. return // discard
  2029. }
  2030. fn := pkg.values[pkg.info.Defs[id]].(*Function)
  2031. if decl.Recv == nil && id.Name == "init" {
  2032. var v Call
  2033. v.Call.Value = fn
  2034. v.setType(types.NewTuple())
  2035. pkg.init.emit(&v)
  2036. }
  2037. b.buildFunction(fn)
  2038. }
  2039. // Build calls Package.Build for each package in prog.
  2040. // Building occurs in parallel unless the BuildSerially mode flag was set.
  2041. //
  2042. // Build is intended for whole-program analysis; a typical compiler
  2043. // need only build a single package.
  2044. //
  2045. // Build is idempotent and thread-safe.
  2046. //
  2047. func (prog *Program) Build() {
  2048. var wg sync.WaitGroup
  2049. for _, p := range prog.packages {
  2050. if prog.mode&BuildSerially != 0 {
  2051. p.Build()
  2052. } else {
  2053. wg.Add(1)
  2054. go func(p *Package) {
  2055. p.Build()
  2056. wg.Done()
  2057. }(p)
  2058. }
  2059. }
  2060. wg.Wait()
  2061. }
  2062. // Build builds SSA code for all functions and vars in package p.
  2063. //
  2064. // Precondition: CreatePackage must have been called for all of p's
  2065. // direct imports (and hence its direct imports must have been
  2066. // error-free).
  2067. //
  2068. // Build is idempotent and thread-safe.
  2069. //
  2070. func (p *Package) Build() { p.buildOnce.Do(p.build) }
  2071. func (p *Package) build() {
  2072. if p.info == nil {
  2073. return // synthetic package, e.g. "testmain"
  2074. }
  2075. // Ensure we have runtime type info for all exported members.
  2076. // TODO(adonovan): ideally belongs in memberFromObject, but
  2077. // that would require package creation in topological order.
  2078. for name, mem := range p.Members {
  2079. if ast.IsExported(name) {
  2080. p.Prog.needMethodsOf(mem.Type())
  2081. }
  2082. }
  2083. if p.Prog.mode&LogSource != 0 {
  2084. defer logStack("build %s", p)()
  2085. }
  2086. init := p.init
  2087. init.startBody()
  2088. var done *BasicBlock
  2089. if p.Prog.mode&BareInits == 0 {
  2090. // Make init() skip if package is already initialized.
  2091. initguard := p.Var("init$guard")
  2092. doinit := init.newBasicBlock("init.start")
  2093. done = init.newBasicBlock("init.done")
  2094. emitIf(init, emitLoad(init, initguard), done, doinit)
  2095. init.currentBlock = doinit
  2096. emitStore(init, initguard, vTrue, token.NoPos)
  2097. // Call the init() function of each package we import.
  2098. for _, pkg := range p.Pkg.Imports() {
  2099. prereq := p.Prog.packages[pkg]
  2100. if prereq == nil {
  2101. panic(fmt.Sprintf("Package(%q).Build(): unsatisfied import: Program.CreatePackage(%q) was not called", p.Pkg.Path(), pkg.Path()))
  2102. }
  2103. var v Call
  2104. v.Call.Value = prereq.init
  2105. v.Call.pos = init.pos
  2106. v.setType(types.NewTuple())
  2107. init.emit(&v)
  2108. }
  2109. }
  2110. var b builder
  2111. // Initialize package-level vars in correct order.
  2112. for _, varinit := range p.info.InitOrder {
  2113. if init.Prog.mode&LogSource != 0 {
  2114. fmt.Fprintf(os.Stderr, "build global initializer %v @ %s\n",
  2115. varinit.Lhs, p.Prog.Fset.Position(varinit.Rhs.Pos()))
  2116. }
  2117. if len(varinit.Lhs) == 1 {
  2118. // 1:1 initialization: var x, y = a(), b()
  2119. var lval lvalue
  2120. if v := varinit.Lhs[0]; v.Name() != "_" {
  2121. lval = &address{addr: p.values[v].(*Global), pos: v.Pos()}
  2122. } else {
  2123. lval = blank{}
  2124. }
  2125. b.assign(init, lval, varinit.Rhs, true, nil)
  2126. } else {
  2127. // n:1 initialization: var x, y := f()
  2128. tuple := b.exprN(init, varinit.Rhs)
  2129. for i, v := range varinit.Lhs {
  2130. if v.Name() == "_" {
  2131. continue
  2132. }
  2133. emitStore(init, p.values[v].(*Global), emitExtract(init, tuple, i), v.Pos())
  2134. }
  2135. }
  2136. }
  2137. // Build all package-level functions, init functions
  2138. // and methods, including unreachable/blank ones.
  2139. // We build them in source order, but it's not significant.
  2140. for _, file := range p.files {
  2141. for _, decl := range file.Decls {
  2142. if decl, ok := decl.(*ast.FuncDecl); ok {
  2143. b.buildFuncDecl(p, decl)
  2144. }
  2145. }
  2146. }
  2147. // Finish up init().
  2148. if p.Prog.mode&BareInits == 0 {
  2149. emitJump(init, done)
  2150. init.currentBlock = done
  2151. }
  2152. init.emit(new(Return))
  2153. init.finishBody()
  2154. p.info = nil // We no longer need ASTs or go/types deductions.
  2155. if p.Prog.mode&SanityCheckFunctions != 0 {
  2156. sanityCheckPackage(p)
  2157. }
  2158. }
  2159. // Like ObjectOf, but panics instead of returning nil.
  2160. // Only valid during p's create and build phases.
  2161. func (p *Package) objectOf(id *ast.Ident) types.Object {
  2162. if o := p.info.ObjectOf(id); o != nil {
  2163. return o
  2164. }
  2165. panic(fmt.Sprintf("no types.Object for ast.Ident %s @ %s",
  2166. id.Name, p.Prog.Fset.Position(id.Pos())))
  2167. }
  2168. // Like TypeOf, but panics instead of returning nil.
  2169. // Only valid during p's create and build phases.
  2170. func (p *Package) typeOf(e ast.Expr) types.Type {
  2171. if T := p.info.TypeOf(e); T != nil {
  2172. return T
  2173. }
  2174. panic(fmt.Sprintf("no type for %T @ %s",
  2175. e, p.Prog.Fset.Position(e.Pos())))
  2176. }