gitee.com/lonely0422/gometalinter.git@v3.0.1-0.20190307123442-32416ab75314+incompatible/_linters/src/honnef.co/go/tools/ssa/func.go (about)

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