func.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  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 Function and BasicBlock types.
  6. import (
  7. "bytes"
  8. "fmt"
  9. "go/ast"
  10. "go/token"
  11. "go/types"
  12. "io"
  13. "os"
  14. "strings"
  15. )
  16. // addEdge adds a control-flow graph edge from from to to.
  17. func addEdge(from, to *BasicBlock) {
  18. from.Succs = append(from.Succs, to)
  19. to.Preds = append(to.Preds, from)
  20. }
  21. // Parent returns the function that contains block b.
  22. func (b *BasicBlock) Parent() *Function { return b.parent }
  23. // String returns a human-readable label of this block.
  24. // It is not guaranteed unique within the function.
  25. //
  26. func (b *BasicBlock) String() string {
  27. return fmt.Sprintf("%d", b.Index)
  28. }
  29. // emit appends an instruction to the current basic block.
  30. // If the instruction defines a Value, it is returned.
  31. //
  32. func (b *BasicBlock) emit(i Instruction) Value {
  33. i.setBlock(b)
  34. b.Instrs = append(b.Instrs, i)
  35. v, _ := i.(Value)
  36. return v
  37. }
  38. // predIndex returns the i such that b.Preds[i] == c or panics if
  39. // there is none.
  40. func (b *BasicBlock) predIndex(c *BasicBlock) int {
  41. for i, pred := range b.Preds {
  42. if pred == c {
  43. return i
  44. }
  45. }
  46. panic(fmt.Sprintf("no edge %s -> %s", c, b))
  47. }
  48. // hasPhi returns true if b.Instrs contains φ-nodes.
  49. func (b *BasicBlock) hasPhi() bool {
  50. _, ok := b.Instrs[0].(*Phi)
  51. return ok
  52. }
  53. func (b *BasicBlock) Phis() []Instruction {
  54. return b.phis()
  55. }
  56. // phis returns the prefix of b.Instrs containing all the block's φ-nodes.
  57. func (b *BasicBlock) phis() []Instruction {
  58. for i, instr := range b.Instrs {
  59. if _, ok := instr.(*Phi); !ok {
  60. return b.Instrs[:i]
  61. }
  62. }
  63. return nil // unreachable in well-formed blocks
  64. }
  65. // replacePred replaces all occurrences of p in b's predecessor list with q.
  66. // Ordinarily there should be at most one.
  67. //
  68. func (b *BasicBlock) replacePred(p, q *BasicBlock) {
  69. for i, pred := range b.Preds {
  70. if pred == p {
  71. b.Preds[i] = q
  72. }
  73. }
  74. }
  75. // replaceSucc replaces all occurrences of p in b's successor list with q.
  76. // Ordinarily there should be at most one.
  77. //
  78. func (b *BasicBlock) replaceSucc(p, q *BasicBlock) {
  79. for i, succ := range b.Succs {
  80. if succ == p {
  81. b.Succs[i] = q
  82. }
  83. }
  84. }
  85. func (b *BasicBlock) RemovePred(p *BasicBlock) {
  86. b.removePred(p)
  87. }
  88. // removePred removes all occurrences of p in b's
  89. // predecessor list and φ-nodes.
  90. // Ordinarily there should be at most one.
  91. //
  92. func (b *BasicBlock) removePred(p *BasicBlock) {
  93. phis := b.phis()
  94. // We must preserve edge order for φ-nodes.
  95. j := 0
  96. for i, pred := range b.Preds {
  97. if pred != p {
  98. b.Preds[j] = b.Preds[i]
  99. // Strike out φ-edge too.
  100. for _, instr := range phis {
  101. phi := instr.(*Phi)
  102. phi.Edges[j] = phi.Edges[i]
  103. }
  104. j++
  105. }
  106. }
  107. // Nil out b.Preds[j:] and φ-edges[j:] to aid GC.
  108. for i := j; i < len(b.Preds); i++ {
  109. b.Preds[i] = nil
  110. for _, instr := range phis {
  111. instr.(*Phi).Edges[i] = nil
  112. }
  113. }
  114. b.Preds = b.Preds[:j]
  115. for _, instr := range phis {
  116. phi := instr.(*Phi)
  117. phi.Edges = phi.Edges[:j]
  118. }
  119. }
  120. // Destinations associated with unlabelled for/switch/select stmts.
  121. // We push/pop one of these as we enter/leave each construct and for
  122. // each BranchStmt we scan for the innermost target of the right type.
  123. //
  124. type targets struct {
  125. tail *targets // rest of stack
  126. _break *BasicBlock
  127. _continue *BasicBlock
  128. _fallthrough *BasicBlock
  129. }
  130. // Destinations associated with a labelled block.
  131. // We populate these as labels are encountered in forward gotos or
  132. // labelled statements.
  133. //
  134. type lblock struct {
  135. _goto *BasicBlock
  136. _break *BasicBlock
  137. _continue *BasicBlock
  138. }
  139. // labelledBlock returns the branch target associated with the
  140. // specified label, creating it if needed.
  141. //
  142. func (f *Function) labelledBlock(label *ast.Ident) *lblock {
  143. lb := f.lblocks[label.Obj]
  144. if lb == nil {
  145. lb = &lblock{_goto: f.newBasicBlock(label.Name)}
  146. if f.lblocks == nil {
  147. f.lblocks = make(map[*ast.Object]*lblock)
  148. }
  149. f.lblocks[label.Obj] = lb
  150. }
  151. return lb
  152. }
  153. // addParam adds a (non-escaping) parameter to f.Params of the
  154. // specified name, type and source position.
  155. //
  156. func (f *Function) addParam(name string, typ types.Type, pos token.Pos) *Parameter {
  157. v := &Parameter{
  158. name: name,
  159. typ: typ,
  160. pos: pos,
  161. parent: f,
  162. }
  163. f.Params = append(f.Params, v)
  164. return v
  165. }
  166. func (f *Function) addParamObj(obj types.Object) *Parameter {
  167. name := obj.Name()
  168. if name == "" {
  169. name = fmt.Sprintf("arg%d", len(f.Params))
  170. }
  171. param := f.addParam(name, obj.Type(), obj.Pos())
  172. param.object = obj
  173. return param
  174. }
  175. // addSpilledParam declares a parameter that is pre-spilled to the
  176. // stack; the function body will load/store the spilled location.
  177. // Subsequent lifting will eliminate spills where possible.
  178. //
  179. func (f *Function) addSpilledParam(obj types.Object) {
  180. param := f.addParamObj(obj)
  181. spill := &Alloc{Comment: obj.Name()}
  182. spill.setType(types.NewPointer(obj.Type()))
  183. spill.setPos(obj.Pos())
  184. f.objects[obj] = spill
  185. f.Locals = append(f.Locals, spill)
  186. f.emit(spill)
  187. f.emit(&Store{Addr: spill, Val: param})
  188. }
  189. // startBody initializes the function prior to generating SSA code for its body.
  190. // Precondition: f.Type() already set.
  191. //
  192. func (f *Function) startBody() {
  193. f.currentBlock = f.newBasicBlock("entry")
  194. f.objects = make(map[types.Object]Value) // needed for some synthetics, e.g. init
  195. }
  196. // createSyntacticParams populates f.Params and generates code (spills
  197. // and named result locals) for all the parameters declared in the
  198. // syntax. In addition it populates the f.objects mapping.
  199. //
  200. // Preconditions:
  201. // f.startBody() was called.
  202. // Postcondition:
  203. // len(f.Params) == len(f.Signature.Params) + (f.Signature.Recv() ? 1 : 0)
  204. //
  205. func (f *Function) createSyntacticParams(recv *ast.FieldList, functype *ast.FuncType) {
  206. // Receiver (at most one inner iteration).
  207. if recv != nil {
  208. for _, field := range recv.List {
  209. for _, n := range field.Names {
  210. f.addSpilledParam(f.Pkg.info.Defs[n])
  211. }
  212. // Anonymous receiver? No need to spill.
  213. if field.Names == nil {
  214. f.addParamObj(f.Signature.Recv())
  215. }
  216. }
  217. }
  218. // Parameters.
  219. if functype.Params != nil {
  220. n := len(f.Params) // 1 if has recv, 0 otherwise
  221. for _, field := range functype.Params.List {
  222. for _, n := range field.Names {
  223. f.addSpilledParam(f.Pkg.info.Defs[n])
  224. }
  225. // Anonymous parameter? No need to spill.
  226. if field.Names == nil {
  227. f.addParamObj(f.Signature.Params().At(len(f.Params) - n))
  228. }
  229. }
  230. }
  231. // Named results.
  232. if functype.Results != nil {
  233. for _, field := range functype.Results.List {
  234. // Implicit "var" decl of locals for named results.
  235. for _, n := range field.Names {
  236. f.namedResults = append(f.namedResults, f.addLocalForIdent(n))
  237. }
  238. }
  239. }
  240. }
  241. // numberRegisters assigns numbers to all SSA registers
  242. // (value-defining Instructions) in f, to aid debugging.
  243. // (Non-Instruction Values are named at construction.)
  244. //
  245. func numberRegisters(f *Function) {
  246. v := 0
  247. for _, b := range f.Blocks {
  248. for _, instr := range b.Instrs {
  249. switch instr.(type) {
  250. case Value:
  251. instr.(interface {
  252. setNum(int)
  253. }).setNum(v)
  254. v++
  255. }
  256. }
  257. }
  258. }
  259. // buildReferrers populates the def/use information in all non-nil
  260. // Value.Referrers slice.
  261. // Precondition: all such slices are initially empty.
  262. func buildReferrers(f *Function) {
  263. var rands []*Value
  264. for _, b := range f.Blocks {
  265. for _, instr := range b.Instrs {
  266. rands = instr.Operands(rands[:0]) // recycle storage
  267. for _, rand := range rands {
  268. if r := *rand; r != nil {
  269. if ref := r.Referrers(); ref != nil {
  270. *ref = append(*ref, instr)
  271. }
  272. }
  273. }
  274. }
  275. }
  276. }
  277. // finishBody() finalizes the function after SSA code generation of its body.
  278. func (f *Function) finishBody() {
  279. f.objects = nil
  280. f.currentBlock = nil
  281. f.lblocks = nil
  282. // Don't pin the AST in memory (except in debug mode).
  283. if n := f.syntax; n != nil && !f.debugInfo() {
  284. f.syntax = extentNode{n.Pos(), n.End()}
  285. }
  286. // Remove from f.Locals any Allocs that escape to the heap.
  287. j := 0
  288. for _, l := range f.Locals {
  289. if !l.Heap {
  290. f.Locals[j] = l
  291. j++
  292. }
  293. }
  294. // Nil out f.Locals[j:] to aid GC.
  295. for i := j; i < len(f.Locals); i++ {
  296. f.Locals[i] = nil
  297. }
  298. f.Locals = f.Locals[:j]
  299. // comma-ok receiving from a time.Tick channel will never return
  300. // ok == false, so any branching on the value of ok can be
  301. // replaced with an unconditional jump. This will primarily match
  302. // `for range time.Tick(x)` loops, but it can also match
  303. // user-written code.
  304. for _, block := range f.Blocks {
  305. if len(block.Instrs) < 3 {
  306. continue
  307. }
  308. if len(block.Succs) != 2 {
  309. continue
  310. }
  311. var instrs []*Instruction
  312. for i, ins := range block.Instrs {
  313. if _, ok := ins.(*DebugRef); ok {
  314. continue
  315. }
  316. instrs = append(instrs, &block.Instrs[i])
  317. }
  318. for i, ins := range instrs {
  319. unop, ok := (*ins).(*UnOp)
  320. if !ok || unop.Op != token.ARROW {
  321. continue
  322. }
  323. call, ok := unop.X.(*Call)
  324. if !ok {
  325. continue
  326. }
  327. if call.Common().IsInvoke() {
  328. continue
  329. }
  330. // OPT(dh): surely there is a more efficient way of doing
  331. // this, than using FullName. We should already have
  332. // resolved time.Tick somewhere?
  333. v, ok := call.Common().Value.(*Function)
  334. if !ok {
  335. continue
  336. }
  337. t, ok := v.Object().(*types.Func)
  338. if !ok {
  339. continue
  340. }
  341. if t.FullName() != "time.Tick" {
  342. continue
  343. }
  344. ex, ok := (*instrs[i+1]).(*Extract)
  345. if !ok || ex.Tuple != unop || ex.Index != 1 {
  346. continue
  347. }
  348. ifstmt, ok := (*instrs[i+2]).(*If)
  349. if !ok || ifstmt.Cond != ex {
  350. continue
  351. }
  352. *instrs[i+2] = NewJump(block)
  353. succ := block.Succs[1]
  354. block.Succs = block.Succs[0:1]
  355. succ.RemovePred(block)
  356. }
  357. }
  358. optimizeBlocks(f)
  359. buildReferrers(f)
  360. buildDomTree(f)
  361. if f.Prog.mode&NaiveForm == 0 {
  362. // For debugging pre-state of lifting pass:
  363. // numberRegisters(f)
  364. // f.WriteTo(os.Stderr)
  365. lift(f)
  366. }
  367. f.namedResults = nil // (used by lifting)
  368. numberRegisters(f)
  369. if f.Prog.mode&PrintFunctions != 0 {
  370. printMu.Lock()
  371. f.WriteTo(os.Stdout)
  372. printMu.Unlock()
  373. }
  374. if f.Prog.mode&SanityCheckFunctions != 0 {
  375. mustSanityCheck(f, nil)
  376. }
  377. }
  378. func (f *Function) RemoveNilBlocks() {
  379. f.removeNilBlocks()
  380. }
  381. // removeNilBlocks eliminates nils from f.Blocks and updates each
  382. // BasicBlock.Index. Use this after any pass that may delete blocks.
  383. //
  384. func (f *Function) removeNilBlocks() {
  385. j := 0
  386. for _, b := range f.Blocks {
  387. if b != nil {
  388. b.Index = j
  389. f.Blocks[j] = b
  390. j++
  391. }
  392. }
  393. // Nil out f.Blocks[j:] to aid GC.
  394. for i := j; i < len(f.Blocks); i++ {
  395. f.Blocks[i] = nil
  396. }
  397. f.Blocks = f.Blocks[:j]
  398. }
  399. // SetDebugMode sets the debug mode for package pkg. If true, all its
  400. // functions will include full debug info. This greatly increases the
  401. // size of the instruction stream, and causes Functions to depend upon
  402. // the ASTs, potentially keeping them live in memory for longer.
  403. //
  404. func (pkg *Package) SetDebugMode(debug bool) {
  405. // TODO(adonovan): do we want ast.File granularity?
  406. pkg.debug = debug
  407. }
  408. // debugInfo reports whether debug info is wanted for this function.
  409. func (f *Function) debugInfo() bool {
  410. return f.Pkg != nil && f.Pkg.debug
  411. }
  412. // addNamedLocal creates a local variable, adds it to function f and
  413. // returns it. Its name and type are taken from obj. Subsequent
  414. // calls to f.lookup(obj) will return the same local.
  415. //
  416. func (f *Function) addNamedLocal(obj types.Object) *Alloc {
  417. l := f.addLocal(obj.Type(), obj.Pos())
  418. l.Comment = obj.Name()
  419. f.objects[obj] = l
  420. return l
  421. }
  422. func (f *Function) addLocalForIdent(id *ast.Ident) *Alloc {
  423. return f.addNamedLocal(f.Pkg.info.Defs[id])
  424. }
  425. // addLocal creates an anonymous local variable of type typ, adds it
  426. // to function f and returns it. pos is the optional source location.
  427. //
  428. func (f *Function) addLocal(typ types.Type, pos token.Pos) *Alloc {
  429. v := &Alloc{}
  430. v.setType(types.NewPointer(typ))
  431. v.setPos(pos)
  432. f.Locals = append(f.Locals, v)
  433. f.emit(v)
  434. return v
  435. }
  436. // lookup returns the address of the named variable identified by obj
  437. // that is local to function f or one of its enclosing functions.
  438. // If escaping, the reference comes from a potentially escaping pointer
  439. // expression and the referent must be heap-allocated.
  440. //
  441. func (f *Function) lookup(obj types.Object, escaping bool) Value {
  442. if v, ok := f.objects[obj]; ok {
  443. if alloc, ok := v.(*Alloc); ok && escaping {
  444. alloc.Heap = true
  445. }
  446. return v // function-local var (address)
  447. }
  448. // Definition must be in an enclosing function;
  449. // plumb it through intervening closures.
  450. if f.parent == nil {
  451. panic("no ssa.Value for " + obj.String())
  452. }
  453. outer := f.parent.lookup(obj, true) // escaping
  454. v := &FreeVar{
  455. name: obj.Name(),
  456. typ: outer.Type(),
  457. pos: outer.Pos(),
  458. outer: outer,
  459. parent: f,
  460. }
  461. f.objects[obj] = v
  462. f.FreeVars = append(f.FreeVars, v)
  463. return v
  464. }
  465. // emit emits the specified instruction to function f.
  466. func (f *Function) emit(instr Instruction) Value {
  467. return f.currentBlock.emit(instr)
  468. }
  469. // RelString returns the full name of this function, qualified by
  470. // package name, receiver type, etc.
  471. //
  472. // The specific formatting rules are not guaranteed and may change.
  473. //
  474. // Examples:
  475. // "math.IsNaN" // a package-level function
  476. // "(*bytes.Buffer).Bytes" // a declared method or a wrapper
  477. // "(*bytes.Buffer).Bytes$thunk" // thunk (func wrapping method; receiver is param 0)
  478. // "(*bytes.Buffer).Bytes$bound" // bound (func wrapping method; receiver supplied by closure)
  479. // "main.main$1" // an anonymous function in main
  480. // "main.init#1" // a declared init function
  481. // "main.init" // the synthesized package initializer
  482. //
  483. // When these functions are referred to from within the same package
  484. // (i.e. from == f.Pkg.Object), they are rendered without the package path.
  485. // For example: "IsNaN", "(*Buffer).Bytes", etc.
  486. //
  487. // All non-synthetic functions have distinct package-qualified names.
  488. // (But two methods may have the same name "(T).f" if one is a synthetic
  489. // wrapper promoting a non-exported method "f" from another package; in
  490. // that case, the strings are equal but the identifiers "f" are distinct.)
  491. //
  492. func (f *Function) RelString(from *types.Package) string {
  493. // Anonymous?
  494. if f.parent != nil {
  495. // An anonymous function's Name() looks like "parentName$1",
  496. // but its String() should include the type/package/etc.
  497. parent := f.parent.RelString(from)
  498. for i, anon := range f.parent.AnonFuncs {
  499. if anon == f {
  500. return fmt.Sprintf("%s$%d", parent, 1+i)
  501. }
  502. }
  503. return f.name // should never happen
  504. }
  505. // Method (declared or wrapper)?
  506. if recv := f.Signature.Recv(); recv != nil {
  507. return f.relMethod(from, recv.Type())
  508. }
  509. // Thunk?
  510. if f.method != nil {
  511. return f.relMethod(from, f.method.Recv())
  512. }
  513. // Bound?
  514. if len(f.FreeVars) == 1 && strings.HasSuffix(f.name, "$bound") {
  515. return f.relMethod(from, f.FreeVars[0].Type())
  516. }
  517. // Package-level function?
  518. // Prefix with package name for cross-package references only.
  519. if p := f.pkg(); p != nil && p != from {
  520. return fmt.Sprintf("%s.%s", p.Path(), f.name)
  521. }
  522. // Unknown.
  523. return f.name
  524. }
  525. func (f *Function) relMethod(from *types.Package, recv types.Type) string {
  526. return fmt.Sprintf("(%s).%s", relType(recv, from), f.name)
  527. }
  528. // writeSignature writes to buf the signature sig in declaration syntax.
  529. func writeSignature(buf *bytes.Buffer, from *types.Package, name string, sig *types.Signature, params []*Parameter) {
  530. buf.WriteString("func ")
  531. if recv := sig.Recv(); recv != nil {
  532. buf.WriteString("(")
  533. if n := params[0].Name(); n != "" {
  534. buf.WriteString(n)
  535. buf.WriteString(" ")
  536. }
  537. types.WriteType(buf, params[0].Type(), types.RelativeTo(from))
  538. buf.WriteString(") ")
  539. }
  540. buf.WriteString(name)
  541. types.WriteSignature(buf, sig, types.RelativeTo(from))
  542. }
  543. func (f *Function) pkg() *types.Package {
  544. if f.Pkg != nil {
  545. return f.Pkg.Pkg
  546. }
  547. return nil
  548. }
  549. var _ io.WriterTo = (*Function)(nil) // *Function implements io.Writer
  550. func (f *Function) WriteTo(w io.Writer) (int64, error) {
  551. var buf bytes.Buffer
  552. WriteFunction(&buf, f)
  553. n, err := w.Write(buf.Bytes())
  554. return int64(n), err
  555. }
  556. // WriteFunction writes to buf a human-readable "disassembly" of f.
  557. func WriteFunction(buf *bytes.Buffer, f *Function) {
  558. fmt.Fprintf(buf, "# Name: %s\n", f.String())
  559. if f.Pkg != nil {
  560. fmt.Fprintf(buf, "# Package: %s\n", f.Pkg.Pkg.Path())
  561. }
  562. if syn := f.Synthetic; syn != "" {
  563. fmt.Fprintln(buf, "# Synthetic:", syn)
  564. }
  565. if pos := f.Pos(); pos.IsValid() {
  566. fmt.Fprintf(buf, "# Location: %s\n", f.Prog.Fset.Position(pos))
  567. }
  568. if f.parent != nil {
  569. fmt.Fprintf(buf, "# Parent: %s\n", f.parent.Name())
  570. }
  571. if f.Recover != nil {
  572. fmt.Fprintf(buf, "# Recover: %s\n", f.Recover)
  573. }
  574. from := f.pkg()
  575. if f.FreeVars != nil {
  576. buf.WriteString("# Free variables:\n")
  577. for i, fv := range f.FreeVars {
  578. fmt.Fprintf(buf, "# % 3d:\t%s %s\n", i, fv.Name(), relType(fv.Type(), from))
  579. }
  580. }
  581. if len(f.Locals) > 0 {
  582. buf.WriteString("# Locals:\n")
  583. for i, l := range f.Locals {
  584. fmt.Fprintf(buf, "# % 3d:\t%s %s\n", i, l.Name(), relType(deref(l.Type()), from))
  585. }
  586. }
  587. writeSignature(buf, from, f.Name(), f.Signature, f.Params)
  588. buf.WriteString(":\n")
  589. if f.Blocks == nil {
  590. buf.WriteString("\t(external)\n")
  591. }
  592. // NB. column calculations are confused by non-ASCII
  593. // characters and assume 8-space tabs.
  594. const punchcard = 80 // for old time's sake.
  595. const tabwidth = 8
  596. for _, b := range f.Blocks {
  597. if b == nil {
  598. // Corrupt CFG.
  599. fmt.Fprintf(buf, ".nil:\n")
  600. continue
  601. }
  602. n, _ := fmt.Fprintf(buf, "%d:", b.Index)
  603. bmsg := fmt.Sprintf("%s P:%d S:%d", b.Comment, len(b.Preds), len(b.Succs))
  604. fmt.Fprintf(buf, "%*s%s\n", punchcard-1-n-len(bmsg), "", bmsg)
  605. if false { // CFG debugging
  606. fmt.Fprintf(buf, "\t# CFG: %s --> %s --> %s\n", b.Preds, b, b.Succs)
  607. }
  608. for _, instr := range b.Instrs {
  609. buf.WriteString("\t")
  610. switch v := instr.(type) {
  611. case Value:
  612. l := punchcard - tabwidth
  613. // Left-align the instruction.
  614. if name := v.Name(); name != "" {
  615. n, _ := fmt.Fprintf(buf, "%s = ", name)
  616. l -= n
  617. }
  618. n, _ := buf.WriteString(instr.String())
  619. l -= n
  620. // Right-align the type if there's space.
  621. if t := v.Type(); t != nil {
  622. buf.WriteByte(' ')
  623. ts := relType(t, from)
  624. l -= len(ts) + len(" ") // (spaces before and after type)
  625. if l > 0 {
  626. fmt.Fprintf(buf, "%*s", l, "")
  627. }
  628. buf.WriteString(ts)
  629. }
  630. case nil:
  631. // Be robust against bad transforms.
  632. buf.WriteString("<deleted>")
  633. default:
  634. buf.WriteString(instr.String())
  635. }
  636. buf.WriteString("\n")
  637. }
  638. }
  639. fmt.Fprintf(buf, "\n")
  640. }
  641. // newBasicBlock adds to f a new basic block and returns it. It does
  642. // not automatically become the current block for subsequent calls to emit.
  643. // comment is an optional string for more readable debugging output.
  644. //
  645. func (f *Function) newBasicBlock(comment string) *BasicBlock {
  646. b := &BasicBlock{
  647. Index: len(f.Blocks),
  648. Comment: comment,
  649. parent: f,
  650. }
  651. b.Succs = b.succs2[:0]
  652. f.Blocks = append(f.Blocks, b)
  653. return b
  654. }
  655. // NewFunction returns a new synthetic Function instance belonging to
  656. // prog, with its name and signature fields set as specified.
  657. //
  658. // The caller is responsible for initializing the remaining fields of
  659. // the function object, e.g. Pkg, Params, Blocks.
  660. //
  661. // It is practically impossible for clients to construct well-formed
  662. // SSA functions/packages/programs directly, so we assume this is the
  663. // job of the Builder alone. NewFunction exists to provide clients a
  664. // little flexibility. For example, analysis tools may wish to
  665. // construct fake Functions for the root of the callgraph, a fake
  666. // "reflect" package, etc.
  667. //
  668. // TODO(adonovan): think harder about the API here.
  669. //
  670. func (prog *Program) NewFunction(name string, sig *types.Signature, provenance string) *Function {
  671. return &Function{Prog: prog, name: name, Signature: sig, Synthetic: provenance}
  672. }
  673. type extentNode [2]token.Pos
  674. func (n extentNode) Pos() token.Pos { return n[0] }
  675. func (n extentNode) End() token.Pos { return n[1] }
  676. // Syntax returns an ast.Node whose Pos/End methods provide the
  677. // lexical extent of the function if it was defined by Go source code
  678. // (f.Synthetic==""), or nil otherwise.
  679. //
  680. // If f was built with debug information (see Package.SetDebugRef),
  681. // the result is the *ast.FuncDecl or *ast.FuncLit that declared the
  682. // function. Otherwise, it is an opaque Node providing only position
  683. // information; this avoids pinning the AST in memory.
  684. //
  685. func (f *Function) Syntax() ast.Node { return f.syntax }