github.com/powerman/golang-tools@v0.1.11-0.20220410185822-5ad214d8d803/go/ssa/ssa.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 package defines a high-level intermediate representation for
     8  // Go programs using static single-assignment (SSA) form.
     9  
    10  import (
    11  	"fmt"
    12  	"go/ast"
    13  	"go/constant"
    14  	"go/token"
    15  	"go/types"
    16  	"sync"
    17  
    18  	"github.com/powerman/golang-tools/go/types/typeutil"
    19  	"github.com/powerman/golang-tools/internal/typeparams"
    20  )
    21  
    22  // A Program is a partial or complete Go program converted to SSA form.
    23  type Program struct {
    24  	Fset       *token.FileSet              // position information for the files of this Program
    25  	imported   map[string]*Package         // all importable Packages, keyed by import path
    26  	packages   map[*types.Package]*Package // all loaded Packages, keyed by object
    27  	mode       BuilderMode                 // set of mode bits for SSA construction
    28  	MethodSets typeutil.MethodSetCache     // cache of type-checker's method-sets
    29  
    30  	canon *canonizer          // type canonicalization map
    31  	ctxt  *typeparams.Context // cache for type checking instantiations
    32  
    33  	methodsMu    sync.Mutex                 // guards the following maps:
    34  	methodSets   typeutil.Map               // maps type to its concrete methodSet
    35  	runtimeTypes typeutil.Map               // types for which rtypes are needed
    36  	bounds       map[boundsKey]*Function    // bounds for curried x.Method closures
    37  	thunks       map[selectionKey]*Function // thunks for T.Method expressions
    38  	instances    map[*Function]*instanceSet // instances of generic functions
    39  }
    40  
    41  // A Package is a single analyzed Go package containing Members for
    42  // all package-level functions, variables, constants and types it
    43  // declares.  These may be accessed directly via Members, or via the
    44  // type-specific accessor methods Func, Type, Var and Const.
    45  //
    46  // Members also contains entries for "init" (the synthetic package
    47  // initializer) and "init#%d", the nth declared init function,
    48  // and unspecified other things too.
    49  //
    50  type Package struct {
    51  	Prog    *Program                // the owning program
    52  	Pkg     *types.Package          // the corresponding go/types.Package
    53  	Members map[string]Member       // all package members keyed by name (incl. init and init#%d)
    54  	objects map[types.Object]Member // mapping of package objects to members (incl. methods). Contains *NamedConst, *Global, *Function.
    55  	init    *Function               // Func("init"); the package's init function
    56  	debug   bool                    // include full debug info in this package
    57  
    58  	// The following fields are set transiently, then cleared
    59  	// after building.
    60  	buildOnce sync.Once   // ensures package building occurs once
    61  	ninit     int32       // number of init functions
    62  	info      *types.Info // package type information
    63  	files     []*ast.File // package ASTs
    64  	created   creator     // members created as a result of building this package (includes declared functions, wrappers)
    65  }
    66  
    67  // A Member is a member of a Go package, implemented by *NamedConst,
    68  // *Global, *Function, or *Type; they are created by package-level
    69  // const, var, func and type declarations respectively.
    70  //
    71  type Member interface {
    72  	Name() string                    // declared name of the package member
    73  	String() string                  // package-qualified name of the package member
    74  	RelString(*types.Package) string // like String, but relative refs are unqualified
    75  	Object() types.Object            // typechecker's object for this member, if any
    76  	Pos() token.Pos                  // position of member's declaration, if known
    77  	Type() types.Type                // type of the package member
    78  	Token() token.Token              // token.{VAR,FUNC,CONST,TYPE}
    79  	Package() *Package               // the containing package
    80  }
    81  
    82  // A Type is a Member of a Package representing a package-level named type.
    83  type Type struct {
    84  	object *types.TypeName
    85  	pkg    *Package
    86  }
    87  
    88  // A NamedConst is a Member of a Package representing a package-level
    89  // named constant.
    90  //
    91  // Pos() returns the position of the declaring ast.ValueSpec.Names[*]
    92  // identifier.
    93  //
    94  // NB: a NamedConst is not a Value; it contains a constant Value, which
    95  // it augments with the name and position of its 'const' declaration.
    96  //
    97  type NamedConst struct {
    98  	object *types.Const
    99  	Value  *Const
   100  	pkg    *Package
   101  }
   102  
   103  // A Value is an SSA value that can be referenced by an instruction.
   104  type Value interface {
   105  	// Name returns the name of this value, and determines how
   106  	// this Value appears when used as an operand of an
   107  	// Instruction.
   108  	//
   109  	// This is the same as the source name for Parameters,
   110  	// Builtins, Functions, FreeVars, Globals.
   111  	// For constants, it is a representation of the constant's value
   112  	// and type.  For all other Values this is the name of the
   113  	// virtual register defined by the instruction.
   114  	//
   115  	// The name of an SSA Value is not semantically significant,
   116  	// and may not even be unique within a function.
   117  	Name() string
   118  
   119  	// If this value is an Instruction, String returns its
   120  	// disassembled form; otherwise it returns unspecified
   121  	// human-readable information about the Value, such as its
   122  	// kind, name and type.
   123  	String() string
   124  
   125  	// Type returns the type of this value.  Many instructions
   126  	// (e.g. IndexAddr) change their behaviour depending on the
   127  	// types of their operands.
   128  	Type() types.Type
   129  
   130  	// Parent returns the function to which this Value belongs.
   131  	// It returns nil for named Functions, Builtin, Const and Global.
   132  	Parent() *Function
   133  
   134  	// Referrers returns the list of instructions that have this
   135  	// value as one of their operands; it may contain duplicates
   136  	// if an instruction has a repeated operand.
   137  	//
   138  	// Referrers actually returns a pointer through which the
   139  	// caller may perform mutations to the object's state.
   140  	//
   141  	// Referrers is currently only defined if Parent()!=nil,
   142  	// i.e. for the function-local values FreeVar, Parameter,
   143  	// Functions (iff anonymous) and all value-defining instructions.
   144  	// It returns nil for named Functions, Builtin, Const and Global.
   145  	//
   146  	// Instruction.Operands contains the inverse of this relation.
   147  	Referrers() *[]Instruction
   148  
   149  	// Pos returns the location of the AST token most closely
   150  	// associated with the operation that gave rise to this value,
   151  	// or token.NoPos if it was not explicit in the source.
   152  	//
   153  	// For each ast.Node type, a particular token is designated as
   154  	// the closest location for the expression, e.g. the Lparen
   155  	// for an *ast.CallExpr.  This permits a compact but
   156  	// approximate mapping from Values to source positions for use
   157  	// in diagnostic messages, for example.
   158  	//
   159  	// (Do not use this position to determine which Value
   160  	// corresponds to an ast.Expr; use Function.ValueForExpr
   161  	// instead.  NB: it requires that the function was built with
   162  	// debug information.)
   163  	Pos() token.Pos
   164  }
   165  
   166  // An Instruction is an SSA instruction that computes a new Value or
   167  // has some effect.
   168  //
   169  // An Instruction that defines a value (e.g. BinOp) also implements
   170  // the Value interface; an Instruction that only has an effect (e.g. Store)
   171  // does not.
   172  //
   173  type Instruction interface {
   174  	// String returns the disassembled form of this value.
   175  	//
   176  	// Examples of Instructions that are Values:
   177  	//       "x + y"     (BinOp)
   178  	//       "len([])"   (Call)
   179  	// Note that the name of the Value is not printed.
   180  	//
   181  	// Examples of Instructions that are not Values:
   182  	//       "return x"  (Return)
   183  	//       "*y = x"    (Store)
   184  	//
   185  	// (The separation Value.Name() from Value.String() is useful
   186  	// for some analyses which distinguish the operation from the
   187  	// value it defines, e.g., 'y = local int' is both an allocation
   188  	// of memory 'local int' and a definition of a pointer y.)
   189  	String() string
   190  
   191  	// Parent returns the function to which this instruction
   192  	// belongs.
   193  	Parent() *Function
   194  
   195  	// Block returns the basic block to which this instruction
   196  	// belongs.
   197  	Block() *BasicBlock
   198  
   199  	// setBlock sets the basic block to which this instruction belongs.
   200  	setBlock(*BasicBlock)
   201  
   202  	// Operands returns the operands of this instruction: the
   203  	// set of Values it references.
   204  	//
   205  	// Specifically, it appends their addresses to rands, a
   206  	// user-provided slice, and returns the resulting slice,
   207  	// permitting avoidance of memory allocation.
   208  	//
   209  	// The operands are appended in undefined order, but the order
   210  	// is consistent for a given Instruction; the addresses are
   211  	// always non-nil but may point to a nil Value.  Clients may
   212  	// store through the pointers, e.g. to effect a value
   213  	// renaming.
   214  	//
   215  	// Value.Referrers is a subset of the inverse of this
   216  	// relation.  (Referrers are not tracked for all types of
   217  	// Values.)
   218  	Operands(rands []*Value) []*Value
   219  
   220  	// Pos returns the location of the AST token most closely
   221  	// associated with the operation that gave rise to this
   222  	// instruction, or token.NoPos if it was not explicit in the
   223  	// source.
   224  	//
   225  	// For each ast.Node type, a particular token is designated as
   226  	// the closest location for the expression, e.g. the Go token
   227  	// for an *ast.GoStmt.  This permits a compact but approximate
   228  	// mapping from Instructions to source positions for use in
   229  	// diagnostic messages, for example.
   230  	//
   231  	// (Do not use this position to determine which Instruction
   232  	// corresponds to an ast.Expr; see the notes for Value.Pos.
   233  	// This position may be used to determine which non-Value
   234  	// Instruction corresponds to some ast.Stmts, but not all: If
   235  	// and Jump instructions have no Pos(), for example.)
   236  	Pos() token.Pos
   237  }
   238  
   239  // A Node is a node in the SSA value graph.  Every concrete type that
   240  // implements Node is also either a Value, an Instruction, or both.
   241  //
   242  // Node contains the methods common to Value and Instruction, plus the
   243  // Operands and Referrers methods generalized to return nil for
   244  // non-Instructions and non-Values, respectively.
   245  //
   246  // Node is provided to simplify SSA graph algorithms.  Clients should
   247  // use the more specific and informative Value or Instruction
   248  // interfaces where appropriate.
   249  //
   250  type Node interface {
   251  	// Common methods:
   252  	String() string
   253  	Pos() token.Pos
   254  	Parent() *Function
   255  
   256  	// Partial methods:
   257  	Operands(rands []*Value) []*Value // nil for non-Instructions
   258  	Referrers() *[]Instruction        // nil for non-Values
   259  }
   260  
   261  // Function represents the parameters, results, and code of a function
   262  // or method.
   263  //
   264  // If Blocks is nil, this indicates an external function for which no
   265  // Go source code is available.  In this case, FreeVars and Locals
   266  // are nil too.  Clients performing whole-program analysis must
   267  // handle external functions specially.
   268  //
   269  // Blocks contains the function's control-flow graph (CFG).
   270  // Blocks[0] is the function entry point; block order is not otherwise
   271  // semantically significant, though it may affect the readability of
   272  // the disassembly.
   273  // To iterate over the blocks in dominance order, use DomPreorder().
   274  //
   275  // Recover is an optional second entry point to which control resumes
   276  // after a recovered panic.  The Recover block may contain only a return
   277  // statement, preceded by a load of the function's named return
   278  // parameters, if any.
   279  //
   280  // A nested function (Parent()!=nil) that refers to one or more
   281  // lexically enclosing local variables ("free variables") has FreeVars.
   282  // Such functions cannot be called directly but require a
   283  // value created by MakeClosure which, via its Bindings, supplies
   284  // values for these parameters.
   285  //
   286  // If the function is a method (Signature.Recv() != nil) then the first
   287  // element of Params is the receiver parameter.
   288  //
   289  // A Go package may declare many functions called "init".
   290  // For each one, Object().Name() returns "init" but Name() returns
   291  // "init#1", etc, in declaration order.
   292  //
   293  // Pos() returns the declaring ast.FuncLit.Type.Func or the position
   294  // of the ast.FuncDecl.Name, if the function was explicit in the
   295  // source.  Synthetic wrappers, for which Synthetic != "", may share
   296  // the same position as the function they wrap.
   297  // Syntax.Pos() always returns the position of the declaring "func" token.
   298  //
   299  // Type() returns the function's Signature.
   300  //
   301  type Function struct {
   302  	name      string
   303  	object    types.Object     // a declared *types.Func or one of its wrappers
   304  	method    *types.Selection // info about provenance of synthetic methods
   305  	Signature *types.Signature
   306  	pos       token.Pos
   307  
   308  	Synthetic string        // provenance of synthetic function; "" for true source functions
   309  	syntax    ast.Node      // *ast.Func{Decl,Lit}; replaced with simple ast.Node after build, unless debug mode
   310  	parent    *Function     // enclosing function if anon; nil if global
   311  	Pkg       *Package      // enclosing package; nil for shared funcs (wrappers and error.Error)
   312  	Prog      *Program      // enclosing program
   313  	Params    []*Parameter  // function parameters; for methods, includes receiver
   314  	FreeVars  []*FreeVar    // free variables whose values must be supplied by closure
   315  	Locals    []*Alloc      // local variables of this function
   316  	Blocks    []*BasicBlock // basic blocks of the function; nil => external
   317  	Recover   *BasicBlock   // optional; control transfers here after recovered panic
   318  	AnonFuncs []*Function   // anonymous functions directly beneath this one
   319  	referrers []Instruction // referring instructions (iff Parent() != nil)
   320  	built     bool          // function has completed both CREATE and BUILD phase.
   321  
   322  	_Origin     *Function               // the origin function if this the instantiation of a generic function. nil if Parent() != nil.
   323  	_TypeParams []*typeparams.TypeParam // the type paramaters of this function. len(TypeParams) == len(_TypeArgs) => runtime function
   324  	_TypeArgs   []types.Type            // type arguments for for an instantiation. len(_TypeArgs) != 0 => instantiation
   325  
   326  	// The following fields are set transiently during building,
   327  	// then cleared.
   328  	currentBlock *BasicBlock             // where to emit code
   329  	objects      map[types.Object]Value  // addresses of local variables
   330  	namedResults []*Alloc                // tuple of named results
   331  	targets      *targets                // linked stack of branch targets
   332  	lblocks      map[*ast.Object]*lblock // labelled blocks
   333  	info         *types.Info             // *types.Info to build from. nil for wrappers.
   334  	subst        *subster                // type substitution cache
   335  }
   336  
   337  // BasicBlock represents an SSA basic block.
   338  //
   339  // The final element of Instrs is always an explicit transfer of
   340  // control (If, Jump, Return, or Panic).
   341  //
   342  // A block may contain no Instructions only if it is unreachable,
   343  // i.e., Preds is nil.  Empty blocks are typically pruned.
   344  //
   345  // BasicBlocks and their Preds/Succs relation form a (possibly cyclic)
   346  // graph independent of the SSA Value graph: the control-flow graph or
   347  // CFG.  It is illegal for multiple edges to exist between the same
   348  // pair of blocks.
   349  //
   350  // Each BasicBlock is also a node in the dominator tree of the CFG.
   351  // The tree may be navigated using Idom()/Dominees() and queried using
   352  // Dominates().
   353  //
   354  // The order of Preds and Succs is significant (to Phi and If
   355  // instructions, respectively).
   356  //
   357  type BasicBlock struct {
   358  	Index        int            // index of this block within Parent().Blocks
   359  	Comment      string         // optional label; no semantic significance
   360  	parent       *Function      // parent function
   361  	Instrs       []Instruction  // instructions in order
   362  	Preds, Succs []*BasicBlock  // predecessors and successors
   363  	succs2       [2]*BasicBlock // initial space for Succs
   364  	dom          domInfo        // dominator tree info
   365  	gaps         int            // number of nil Instrs (transient)
   366  	rundefers    int            // number of rundefers (transient)
   367  }
   368  
   369  // Pure values ----------------------------------------
   370  
   371  // A FreeVar represents a free variable of the function to which it
   372  // belongs.
   373  //
   374  // FreeVars are used to implement anonymous functions, whose free
   375  // variables are lexically captured in a closure formed by
   376  // MakeClosure.  The value of such a free var is an Alloc or another
   377  // FreeVar and is considered a potentially escaping heap address, with
   378  // pointer type.
   379  //
   380  // FreeVars are also used to implement bound method closures.  Such a
   381  // free var represents the receiver value and may be of any type that
   382  // has concrete methods.
   383  //
   384  // Pos() returns the position of the value that was captured, which
   385  // belongs to an enclosing function.
   386  //
   387  type FreeVar struct {
   388  	name      string
   389  	typ       types.Type
   390  	pos       token.Pos
   391  	parent    *Function
   392  	referrers []Instruction
   393  
   394  	// Transiently needed during building.
   395  	outer Value // the Value captured from the enclosing context.
   396  }
   397  
   398  // A Parameter represents an input parameter of a function.
   399  //
   400  type Parameter struct {
   401  	name      string
   402  	object    types.Object // a *types.Var; nil for non-source locals
   403  	typ       types.Type
   404  	pos       token.Pos
   405  	parent    *Function
   406  	referrers []Instruction
   407  }
   408  
   409  // A Const represents the value of a constant expression.
   410  //
   411  // The underlying type of a constant may be any boolean, numeric, or
   412  // string type.  In addition, a Const may represent the nil value of
   413  // any reference type---interface, map, channel, pointer, slice, or
   414  // function---but not "untyped nil".
   415  //
   416  // All source-level constant expressions are represented by a Const
   417  // of the same type and value.
   418  //
   419  // Value holds the value of the constant, independent of its Type(),
   420  // using go/constant representation, or nil for a typed nil value.
   421  //
   422  // Pos() returns token.NoPos.
   423  //
   424  // Example printed form:
   425  // 	42:int
   426  //	"hello":untyped string
   427  //	3+4i:MyComplex
   428  //
   429  type Const struct {
   430  	typ   types.Type
   431  	Value constant.Value
   432  }
   433  
   434  // A Global is a named Value holding the address of a package-level
   435  // variable.
   436  //
   437  // Pos() returns the position of the ast.ValueSpec.Names[*]
   438  // identifier.
   439  //
   440  type Global struct {
   441  	name   string
   442  	object types.Object // a *types.Var; may be nil for synthetics e.g. init$guard
   443  	typ    types.Type
   444  	pos    token.Pos
   445  
   446  	Pkg *Package
   447  }
   448  
   449  // A Builtin represents a specific use of a built-in function, e.g. len.
   450  //
   451  // Builtins are immutable values.  Builtins do not have addresses.
   452  // Builtins can only appear in CallCommon.Value.
   453  //
   454  // Name() indicates the function: one of the built-in functions from the
   455  // Go spec (excluding "make" and "new") or one of these ssa-defined
   456  // intrinsics:
   457  //
   458  //   // wrapnilchk returns ptr if non-nil, panics otherwise.
   459  //   // (For use in indirection wrappers.)
   460  //   func ssa:wrapnilchk(ptr *T, recvType, methodName string) *T
   461  //
   462  // Object() returns a *types.Builtin for built-ins defined by the spec,
   463  // nil for others.
   464  //
   465  // Type() returns a *types.Signature representing the effective
   466  // signature of the built-in for this call.
   467  //
   468  type Builtin struct {
   469  	name string
   470  	sig  *types.Signature
   471  }
   472  
   473  // Value-defining instructions  ----------------------------------------
   474  
   475  // The Alloc instruction reserves space for a variable of the given type,
   476  // zero-initializes it, and yields its address.
   477  //
   478  // Alloc values are always addresses, and have pointer types, so the
   479  // type of the allocated variable is actually
   480  // Type().Underlying().(*types.Pointer).Elem().
   481  //
   482  // If Heap is false, Alloc allocates space in the function's
   483  // activation record (frame); we refer to an Alloc(Heap=false) as a
   484  // "local" alloc.  Each local Alloc returns the same address each time
   485  // it is executed within the same activation; the space is
   486  // re-initialized to zero.
   487  //
   488  // If Heap is true, Alloc allocates space in the heap; we
   489  // refer to an Alloc(Heap=true) as a "new" alloc.  Each new Alloc
   490  // returns a different address each time it is executed.
   491  //
   492  // When Alloc is applied to a channel, map or slice type, it returns
   493  // the address of an uninitialized (nil) reference of that kind; store
   494  // the result of MakeSlice, MakeMap or MakeChan in that location to
   495  // instantiate these types.
   496  //
   497  // Pos() returns the ast.CompositeLit.Lbrace for a composite literal,
   498  // or the ast.CallExpr.Rparen for a call to new() or for a call that
   499  // allocates a varargs slice.
   500  //
   501  // Example printed form:
   502  // 	t0 = local int
   503  // 	t1 = new int
   504  //
   505  type Alloc struct {
   506  	register
   507  	Comment string
   508  	Heap    bool
   509  	index   int // dense numbering; for lifting
   510  }
   511  
   512  // The Phi instruction represents an SSA φ-node, which combines values
   513  // that differ across incoming control-flow edges and yields a new
   514  // value.  Within a block, all φ-nodes must appear before all non-φ
   515  // nodes.
   516  //
   517  // Pos() returns the position of the && or || for short-circuit
   518  // control-flow joins, or that of the *Alloc for φ-nodes inserted
   519  // during SSA renaming.
   520  //
   521  // Example printed form:
   522  // 	t2 = phi [0: t0, 1: t1]
   523  //
   524  type Phi struct {
   525  	register
   526  	Comment string  // a hint as to its purpose
   527  	Edges   []Value // Edges[i] is value for Block().Preds[i]
   528  }
   529  
   530  // The Call instruction represents a function or method call.
   531  //
   532  // The Call instruction yields the function result if there is exactly
   533  // one.  Otherwise it returns a tuple, the components of which are
   534  // accessed via Extract.
   535  //
   536  // See CallCommon for generic function call documentation.
   537  //
   538  // Pos() returns the ast.CallExpr.Lparen, if explicit in the source.
   539  //
   540  // Example printed form:
   541  // 	t2 = println(t0, t1)
   542  // 	t4 = t3()
   543  // 	t7 = invoke t5.Println(...t6)
   544  //
   545  type Call struct {
   546  	register
   547  	Call CallCommon
   548  }
   549  
   550  // The BinOp instruction yields the result of binary operation X Op Y.
   551  //
   552  // Pos() returns the ast.BinaryExpr.OpPos, if explicit in the source.
   553  //
   554  // Example printed form:
   555  // 	t1 = t0 + 1:int
   556  //
   557  type BinOp struct {
   558  	register
   559  	// One of:
   560  	// ADD SUB MUL QUO REM          + - * / %
   561  	// AND OR XOR SHL SHR AND_NOT   & | ^ << >> &^
   562  	// EQL NEQ LSS LEQ GTR GEQ      == != < <= < >=
   563  	Op   token.Token
   564  	X, Y Value
   565  }
   566  
   567  // The UnOp instruction yields the result of Op X.
   568  // ARROW is channel receive.
   569  // MUL is pointer indirection (load).
   570  // XOR is bitwise complement.
   571  // SUB is negation.
   572  // NOT is logical negation.
   573  //
   574  // If CommaOk and Op=ARROW, the result is a 2-tuple of the value above
   575  // and a boolean indicating the success of the receive.  The
   576  // components of the tuple are accessed using Extract.
   577  //
   578  // Pos() returns the ast.UnaryExpr.OpPos, if explicit in the source.
   579  // For receive operations (ARROW) implicit in ranging over a channel,
   580  // Pos() returns the ast.RangeStmt.For.
   581  // For implicit memory loads (STAR), Pos() returns the position of the
   582  // most closely associated source-level construct; the details are not
   583  // specified.
   584  //
   585  // Example printed form:
   586  // 	t0 = *x
   587  // 	t2 = <-t1,ok
   588  //
   589  type UnOp struct {
   590  	register
   591  	Op      token.Token // One of: NOT SUB ARROW MUL XOR ! - <- * ^
   592  	X       Value
   593  	CommaOk bool
   594  }
   595  
   596  // The ChangeType instruction applies to X a value-preserving type
   597  // change to Type().
   598  //
   599  // Type changes are permitted:
   600  //    - between a named type and its underlying type.
   601  //    - between two named types of the same underlying type.
   602  //    - between (possibly named) pointers to identical base types.
   603  //    - from a bidirectional channel to a read- or write-channel,
   604  //      optionally adding/removing a name.
   605  //
   606  // This operation cannot fail dynamically.
   607  //
   608  // Pos() returns the ast.CallExpr.Lparen, if the instruction arose
   609  // from an explicit conversion in the source.
   610  //
   611  // Example printed form:
   612  // 	t1 = changetype *int <- IntPtr (t0)
   613  //
   614  type ChangeType struct {
   615  	register
   616  	X Value
   617  }
   618  
   619  // The Convert instruction yields the conversion of value X to type
   620  // Type().  One or both of those types is basic (but possibly named).
   621  //
   622  // A conversion may change the value and representation of its operand.
   623  // Conversions are permitted:
   624  //    - between real numeric types.
   625  //    - between complex numeric types.
   626  //    - between string and []byte or []rune.
   627  //    - between pointers and unsafe.Pointer.
   628  //    - between unsafe.Pointer and uintptr.
   629  //    - from (Unicode) integer to (UTF-8) string.
   630  // A conversion may imply a type name change also.
   631  //
   632  // This operation cannot fail dynamically.
   633  //
   634  // Conversions of untyped string/number/bool constants to a specific
   635  // representation are eliminated during SSA construction.
   636  //
   637  // Pos() returns the ast.CallExpr.Lparen, if the instruction arose
   638  // from an explicit conversion in the source.
   639  //
   640  // Example printed form:
   641  // 	t1 = convert []byte <- string (t0)
   642  //
   643  type Convert struct {
   644  	register
   645  	X Value
   646  }
   647  
   648  // ChangeInterface constructs a value of one interface type from a
   649  // value of another interface type known to be assignable to it.
   650  // This operation cannot fail.
   651  //
   652  // Pos() returns the ast.CallExpr.Lparen if the instruction arose from
   653  // an explicit T(e) conversion; the ast.TypeAssertExpr.Lparen if the
   654  // instruction arose from an explicit e.(T) operation; or token.NoPos
   655  // otherwise.
   656  //
   657  // Example printed form:
   658  // 	t1 = change interface interface{} <- I (t0)
   659  //
   660  type ChangeInterface struct {
   661  	register
   662  	X Value
   663  }
   664  
   665  // The SliceToArrayPointer instruction yields the conversion of slice X to
   666  // array pointer.
   667  //
   668  // Pos() returns the ast.CallExpr.Lparen, if the instruction arose
   669  // from an explicit conversion in the source.
   670  //
   671  // Example printed form:
   672  // 	t1 = slice to array pointer *[4]byte <- []byte (t0)
   673  //
   674  type SliceToArrayPointer struct {
   675  	register
   676  	X Value
   677  }
   678  
   679  // MakeInterface constructs an instance of an interface type from a
   680  // value of a concrete type.
   681  //
   682  // Use Program.MethodSets.MethodSet(X.Type()) to find the method-set
   683  // of X, and Program.MethodValue(m) to find the implementation of a method.
   684  //
   685  // To construct the zero value of an interface type T, use:
   686  // 	NewConst(constant.MakeNil(), T, pos)
   687  //
   688  // Pos() returns the ast.CallExpr.Lparen, if the instruction arose
   689  // from an explicit conversion in the source.
   690  //
   691  // Example printed form:
   692  // 	t1 = make interface{} <- int (42:int)
   693  // 	t2 = make Stringer <- t0
   694  //
   695  type MakeInterface struct {
   696  	register
   697  	X Value
   698  }
   699  
   700  // The MakeClosure instruction yields a closure value whose code is
   701  // Fn and whose free variables' values are supplied by Bindings.
   702  //
   703  // Type() returns a (possibly named) *types.Signature.
   704  //
   705  // Pos() returns the ast.FuncLit.Type.Func for a function literal
   706  // closure or the ast.SelectorExpr.Sel for a bound method closure.
   707  //
   708  // Example printed form:
   709  // 	t0 = make closure anon@1.2 [x y z]
   710  // 	t1 = make closure bound$(main.I).add [i]
   711  //
   712  type MakeClosure struct {
   713  	register
   714  	Fn       Value   // always a *Function
   715  	Bindings []Value // values for each free variable in Fn.FreeVars
   716  }
   717  
   718  // The MakeMap instruction creates a new hash-table-based map object
   719  // and yields a value of kind map.
   720  //
   721  // Type() returns a (possibly named) *types.Map.
   722  //
   723  // Pos() returns the ast.CallExpr.Lparen, if created by make(map), or
   724  // the ast.CompositeLit.Lbrack if created by a literal.
   725  //
   726  // Example printed form:
   727  // 	t1 = make map[string]int t0
   728  // 	t1 = make StringIntMap t0
   729  //
   730  type MakeMap struct {
   731  	register
   732  	Reserve Value // initial space reservation; nil => default
   733  }
   734  
   735  // The MakeChan instruction creates a new channel object and yields a
   736  // value of kind chan.
   737  //
   738  // Type() returns a (possibly named) *types.Chan.
   739  //
   740  // Pos() returns the ast.CallExpr.Lparen for the make(chan) that
   741  // created it.
   742  //
   743  // Example printed form:
   744  // 	t0 = make chan int 0
   745  // 	t0 = make IntChan 0
   746  //
   747  type MakeChan struct {
   748  	register
   749  	Size Value // int; size of buffer; zero => synchronous.
   750  }
   751  
   752  // The MakeSlice instruction yields a slice of length Len backed by a
   753  // newly allocated array of length Cap.
   754  //
   755  // Both Len and Cap must be non-nil Values of integer type.
   756  //
   757  // (Alloc(types.Array) followed by Slice will not suffice because
   758  // Alloc can only create arrays of constant length.)
   759  //
   760  // Type() returns a (possibly named) *types.Slice.
   761  //
   762  // Pos() returns the ast.CallExpr.Lparen for the make([]T) that
   763  // created it.
   764  //
   765  // Example printed form:
   766  // 	t1 = make []string 1:int t0
   767  // 	t1 = make StringSlice 1:int t0
   768  //
   769  type MakeSlice struct {
   770  	register
   771  	Len Value
   772  	Cap Value
   773  }
   774  
   775  // The Slice instruction yields a slice of an existing string, slice
   776  // or *array X between optional integer bounds Low and High.
   777  //
   778  // Dynamically, this instruction panics if X evaluates to a nil *array
   779  // pointer.
   780  //
   781  // Type() returns string if the type of X was string, otherwise a
   782  // *types.Slice with the same element type as X.
   783  //
   784  // Pos() returns the ast.SliceExpr.Lbrack if created by a x[:] slice
   785  // operation, the ast.CompositeLit.Lbrace if created by a literal, or
   786  // NoPos if not explicit in the source (e.g. a variadic argument slice).
   787  //
   788  // Example printed form:
   789  // 	t1 = slice t0[1:]
   790  //
   791  type Slice struct {
   792  	register
   793  	X              Value // slice, string, or *array
   794  	Low, High, Max Value // each may be nil
   795  }
   796  
   797  // The FieldAddr instruction yields the address of Field of *struct X.
   798  //
   799  // The field is identified by its index within the field list of the
   800  // struct type of X.
   801  //
   802  // Dynamically, this instruction panics if X evaluates to a nil
   803  // pointer.
   804  //
   805  // Type() returns a (possibly named) *types.Pointer.
   806  //
   807  // Pos() returns the position of the ast.SelectorExpr.Sel for the
   808  // field, if explicit in the source. For implicit selections, returns
   809  // the position of the inducing explicit selection.
   810  //
   811  // Example printed form:
   812  // 	t1 = &t0.name [#1]
   813  //
   814  type FieldAddr struct {
   815  	register
   816  	X     Value // *struct
   817  	Field int   // field is X.Type().Underlying().(*types.Pointer).Elem().Underlying().(*types.Struct).Field(Field)
   818  }
   819  
   820  // The Field instruction yields the Field of struct X.
   821  //
   822  // The field is identified by its index within the field list of the
   823  // struct type of X; by using numeric indices we avoid ambiguity of
   824  // package-local identifiers and permit compact representations.
   825  //
   826  // Pos() returns the position of the ast.SelectorExpr.Sel for the
   827  // field, if explicit in the source. For implicit selections, returns
   828  // the position of the inducing explicit selection.
   829  
   830  //
   831  // Example printed form:
   832  // 	t1 = t0.name [#1]
   833  //
   834  type Field struct {
   835  	register
   836  	X     Value // struct
   837  	Field int   // index into X.Type().(*types.Struct).Fields
   838  }
   839  
   840  // The IndexAddr instruction yields the address of the element at
   841  // index Index of collection X.  Index is an integer expression.
   842  //
   843  // The elements of maps and strings are not addressable; use Lookup or
   844  // MapUpdate instead.
   845  //
   846  // Dynamically, this instruction panics if X evaluates to a nil *array
   847  // pointer.
   848  //
   849  // Type() returns a (possibly named) *types.Pointer.
   850  //
   851  // Pos() returns the ast.IndexExpr.Lbrack for the index operation, if
   852  // explicit in the source.
   853  //
   854  // Example printed form:
   855  // 	t2 = &t0[t1]
   856  //
   857  type IndexAddr struct {
   858  	register
   859  	X     Value // slice or *array,
   860  	Index Value // numeric index
   861  }
   862  
   863  // The Index instruction yields element Index of array X.
   864  //
   865  // Pos() returns the ast.IndexExpr.Lbrack for the index operation, if
   866  // explicit in the source.
   867  //
   868  // Example printed form:
   869  // 	t2 = t0[t1]
   870  //
   871  type Index struct {
   872  	register
   873  	X     Value // array
   874  	Index Value // integer index
   875  }
   876  
   877  // The Lookup instruction yields element Index of collection X, a map
   878  // or string.  Index is an integer expression if X is a string or the
   879  // appropriate key type if X is a map.
   880  //
   881  // If CommaOk, the result is a 2-tuple of the value above and a
   882  // boolean indicating the result of a map membership test for the key.
   883  // The components of the tuple are accessed using Extract.
   884  //
   885  // Pos() returns the ast.IndexExpr.Lbrack, if explicit in the source.
   886  //
   887  // Example printed form:
   888  // 	t2 = t0[t1]
   889  // 	t5 = t3[t4],ok
   890  //
   891  type Lookup struct {
   892  	register
   893  	X       Value // string or map
   894  	Index   Value // numeric or key-typed index
   895  	CommaOk bool  // return a value,ok pair
   896  }
   897  
   898  // SelectState is a helper for Select.
   899  // It represents one goal state and its corresponding communication.
   900  //
   901  type SelectState struct {
   902  	Dir       types.ChanDir // direction of case (SendOnly or RecvOnly)
   903  	Chan      Value         // channel to use (for send or receive)
   904  	Send      Value         // value to send (for send)
   905  	Pos       token.Pos     // position of token.ARROW
   906  	DebugNode ast.Node      // ast.SendStmt or ast.UnaryExpr(<-) [debug mode]
   907  }
   908  
   909  // The Select instruction tests whether (or blocks until) one
   910  // of the specified sent or received states is entered.
   911  //
   912  // Let n be the number of States for which Dir==RECV and T_i (0<=i<n)
   913  // be the element type of each such state's Chan.
   914  // Select returns an n+2-tuple
   915  //    (index int, recvOk bool, r_0 T_0, ... r_n-1 T_n-1)
   916  // The tuple's components, described below, must be accessed via the
   917  // Extract instruction.
   918  //
   919  // If Blocking, select waits until exactly one state holds, i.e. a
   920  // channel becomes ready for the designated operation of sending or
   921  // receiving; select chooses one among the ready states
   922  // pseudorandomly, performs the send or receive operation, and sets
   923  // 'index' to the index of the chosen channel.
   924  //
   925  // If !Blocking, select doesn't block if no states hold; instead it
   926  // returns immediately with index equal to -1.
   927  //
   928  // If the chosen channel was used for a receive, the r_i component is
   929  // set to the received value, where i is the index of that state among
   930  // all n receive states; otherwise r_i has the zero value of type T_i.
   931  // Note that the receive index i is not the same as the state
   932  // index index.
   933  //
   934  // The second component of the triple, recvOk, is a boolean whose value
   935  // is true iff the selected operation was a receive and the receive
   936  // successfully yielded a value.
   937  //
   938  // Pos() returns the ast.SelectStmt.Select.
   939  //
   940  // Example printed form:
   941  // 	t3 = select nonblocking [<-t0, t1<-t2]
   942  // 	t4 = select blocking []
   943  //
   944  type Select struct {
   945  	register
   946  	States   []*SelectState
   947  	Blocking bool
   948  }
   949  
   950  // The Range instruction yields an iterator over the domain and range
   951  // of X, which must be a string or map.
   952  //
   953  // Elements are accessed via Next.
   954  //
   955  // Type() returns an opaque and degenerate "rangeIter" type.
   956  //
   957  // Pos() returns the ast.RangeStmt.For.
   958  //
   959  // Example printed form:
   960  // 	t0 = range "hello":string
   961  //
   962  type Range struct {
   963  	register
   964  	X Value // string or map
   965  }
   966  
   967  // The Next instruction reads and advances the (map or string)
   968  // iterator Iter and returns a 3-tuple value (ok, k, v).  If the
   969  // iterator is not exhausted, ok is true and k and v are the next
   970  // elements of the domain and range, respectively.  Otherwise ok is
   971  // false and k and v are undefined.
   972  //
   973  // Components of the tuple are accessed using Extract.
   974  //
   975  // The IsString field distinguishes iterators over strings from those
   976  // over maps, as the Type() alone is insufficient: consider
   977  // map[int]rune.
   978  //
   979  // Type() returns a *types.Tuple for the triple (ok, k, v).
   980  // The types of k and/or v may be types.Invalid.
   981  //
   982  // Example printed form:
   983  // 	t1 = next t0
   984  //
   985  type Next struct {
   986  	register
   987  	Iter     Value
   988  	IsString bool // true => string iterator; false => map iterator.
   989  }
   990  
   991  // The TypeAssert instruction tests whether interface value X has type
   992  // AssertedType.
   993  //
   994  // If !CommaOk, on success it returns v, the result of the conversion
   995  // (defined below); on failure it panics.
   996  //
   997  // If CommaOk: on success it returns a pair (v, true) where v is the
   998  // result of the conversion; on failure it returns (z, false) where z
   999  // is AssertedType's zero value.  The components of the pair must be
  1000  // accessed using the Extract instruction.
  1001  //
  1002  // If AssertedType is a concrete type, TypeAssert checks whether the
  1003  // dynamic type in interface X is equal to it, and if so, the result
  1004  // of the conversion is a copy of the value in the interface.
  1005  //
  1006  // If AssertedType is an interface, TypeAssert checks whether the
  1007  // dynamic type of the interface is assignable to it, and if so, the
  1008  // result of the conversion is a copy of the interface value X.
  1009  // If AssertedType is a superinterface of X.Type(), the operation will
  1010  // fail iff the operand is nil.  (Contrast with ChangeInterface, which
  1011  // performs no nil-check.)
  1012  //
  1013  // Type() reflects the actual type of the result, possibly a
  1014  // 2-types.Tuple; AssertedType is the asserted type.
  1015  //
  1016  // Pos() returns the ast.CallExpr.Lparen if the instruction arose from
  1017  // an explicit T(e) conversion; the ast.TypeAssertExpr.Lparen if the
  1018  // instruction arose from an explicit e.(T) operation; or the
  1019  // ast.CaseClause.Case if the instruction arose from a case of a
  1020  // type-switch statement.
  1021  //
  1022  // Example printed form:
  1023  // 	t1 = typeassert t0.(int)
  1024  // 	t3 = typeassert,ok t2.(T)
  1025  //
  1026  type TypeAssert struct {
  1027  	register
  1028  	X            Value
  1029  	AssertedType types.Type
  1030  	CommaOk      bool
  1031  }
  1032  
  1033  // The Extract instruction yields component Index of Tuple.
  1034  //
  1035  // This is used to access the results of instructions with multiple
  1036  // return values, such as Call, TypeAssert, Next, UnOp(ARROW) and
  1037  // IndexExpr(Map).
  1038  //
  1039  // Example printed form:
  1040  // 	t1 = extract t0 #1
  1041  //
  1042  type Extract struct {
  1043  	register
  1044  	Tuple Value
  1045  	Index int
  1046  }
  1047  
  1048  // Instructions executed for effect.  They do not yield a value. --------------------
  1049  
  1050  // The Jump instruction transfers control to the sole successor of its
  1051  // owning block.
  1052  //
  1053  // A Jump must be the last instruction of its containing BasicBlock.
  1054  //
  1055  // Pos() returns NoPos.
  1056  //
  1057  // Example printed form:
  1058  // 	jump done
  1059  //
  1060  type Jump struct {
  1061  	anInstruction
  1062  }
  1063  
  1064  // The If instruction transfers control to one of the two successors
  1065  // of its owning block, depending on the boolean Cond: the first if
  1066  // true, the second if false.
  1067  //
  1068  // An If instruction must be the last instruction of its containing
  1069  // BasicBlock.
  1070  //
  1071  // Pos() returns NoPos.
  1072  //
  1073  // Example printed form:
  1074  // 	if t0 goto done else body
  1075  //
  1076  type If struct {
  1077  	anInstruction
  1078  	Cond Value
  1079  }
  1080  
  1081  // The Return instruction returns values and control back to the calling
  1082  // function.
  1083  //
  1084  // len(Results) is always equal to the number of results in the
  1085  // function's signature.
  1086  //
  1087  // If len(Results) > 1, Return returns a tuple value with the specified
  1088  // components which the caller must access using Extract instructions.
  1089  //
  1090  // There is no instruction to return a ready-made tuple like those
  1091  // returned by a "value,ok"-mode TypeAssert, Lookup or UnOp(ARROW) or
  1092  // a tail-call to a function with multiple result parameters.
  1093  //
  1094  // Return must be the last instruction of its containing BasicBlock.
  1095  // Such a block has no successors.
  1096  //
  1097  // Pos() returns the ast.ReturnStmt.Return, if explicit in the source.
  1098  //
  1099  // Example printed form:
  1100  // 	return
  1101  // 	return nil:I, 2:int
  1102  //
  1103  type Return struct {
  1104  	anInstruction
  1105  	Results []Value
  1106  	pos     token.Pos
  1107  }
  1108  
  1109  // The RunDefers instruction pops and invokes the entire stack of
  1110  // procedure calls pushed by Defer instructions in this function.
  1111  //
  1112  // It is legal to encounter multiple 'rundefers' instructions in a
  1113  // single control-flow path through a function; this is useful in
  1114  // the combined init() function, for example.
  1115  //
  1116  // Pos() returns NoPos.
  1117  //
  1118  // Example printed form:
  1119  //	rundefers
  1120  //
  1121  type RunDefers struct {
  1122  	anInstruction
  1123  }
  1124  
  1125  // The Panic instruction initiates a panic with value X.
  1126  //
  1127  // A Panic instruction must be the last instruction of its containing
  1128  // BasicBlock, which must have no successors.
  1129  //
  1130  // NB: 'go panic(x)' and 'defer panic(x)' do not use this instruction;
  1131  // they are treated as calls to a built-in function.
  1132  //
  1133  // Pos() returns the ast.CallExpr.Lparen if this panic was explicit
  1134  // in the source.
  1135  //
  1136  // Example printed form:
  1137  // 	panic t0
  1138  //
  1139  type Panic struct {
  1140  	anInstruction
  1141  	X   Value // an interface{}
  1142  	pos token.Pos
  1143  }
  1144  
  1145  // The Go instruction creates a new goroutine and calls the specified
  1146  // function within it.
  1147  //
  1148  // See CallCommon for generic function call documentation.
  1149  //
  1150  // Pos() returns the ast.GoStmt.Go.
  1151  //
  1152  // Example printed form:
  1153  // 	go println(t0, t1)
  1154  // 	go t3()
  1155  // 	go invoke t5.Println(...t6)
  1156  //
  1157  type Go struct {
  1158  	anInstruction
  1159  	Call CallCommon
  1160  	pos  token.Pos
  1161  }
  1162  
  1163  // The Defer instruction pushes the specified call onto a stack of
  1164  // functions to be called by a RunDefers instruction or by a panic.
  1165  //
  1166  // See CallCommon for generic function call documentation.
  1167  //
  1168  // Pos() returns the ast.DeferStmt.Defer.
  1169  //
  1170  // Example printed form:
  1171  // 	defer println(t0, t1)
  1172  // 	defer t3()
  1173  // 	defer invoke t5.Println(...t6)
  1174  //
  1175  type Defer struct {
  1176  	anInstruction
  1177  	Call CallCommon
  1178  	pos  token.Pos
  1179  }
  1180  
  1181  // The Send instruction sends X on channel Chan.
  1182  //
  1183  // Pos() returns the ast.SendStmt.Arrow, if explicit in the source.
  1184  //
  1185  // Example printed form:
  1186  // 	send t0 <- t1
  1187  //
  1188  type Send struct {
  1189  	anInstruction
  1190  	Chan, X Value
  1191  	pos     token.Pos
  1192  }
  1193  
  1194  // The Store instruction stores Val at address Addr.
  1195  // Stores can be of arbitrary types.
  1196  //
  1197  // Pos() returns the position of the source-level construct most closely
  1198  // associated with the memory store operation.
  1199  // Since implicit memory stores are numerous and varied and depend upon
  1200  // implementation choices, the details are not specified.
  1201  //
  1202  // Example printed form:
  1203  // 	*x = y
  1204  //
  1205  type Store struct {
  1206  	anInstruction
  1207  	Addr Value
  1208  	Val  Value
  1209  	pos  token.Pos
  1210  }
  1211  
  1212  // The MapUpdate instruction updates the association of Map[Key] to
  1213  // Value.
  1214  //
  1215  // Pos() returns the ast.KeyValueExpr.Colon or ast.IndexExpr.Lbrack,
  1216  // if explicit in the source.
  1217  //
  1218  // Example printed form:
  1219  //	t0[t1] = t2
  1220  //
  1221  type MapUpdate struct {
  1222  	anInstruction
  1223  	Map   Value
  1224  	Key   Value
  1225  	Value Value
  1226  	pos   token.Pos
  1227  }
  1228  
  1229  // A DebugRef instruction maps a source-level expression Expr to the
  1230  // SSA value X that represents the value (!IsAddr) or address (IsAddr)
  1231  // of that expression.
  1232  //
  1233  // DebugRef is a pseudo-instruction: it has no dynamic effect.
  1234  //
  1235  // Pos() returns Expr.Pos(), the start position of the source-level
  1236  // expression.  This is not the same as the "designated" token as
  1237  // documented at Value.Pos(). e.g. CallExpr.Pos() does not return the
  1238  // position of the ("designated") Lparen token.
  1239  //
  1240  // If Expr is an *ast.Ident denoting a var or func, Object() returns
  1241  // the object; though this information can be obtained from the type
  1242  // checker, including it here greatly facilitates debugging.
  1243  // For non-Ident expressions, Object() returns nil.
  1244  //
  1245  // DebugRefs are generated only for functions built with debugging
  1246  // enabled; see Package.SetDebugMode() and the GlobalDebug builder
  1247  // mode flag.
  1248  //
  1249  // DebugRefs are not emitted for ast.Idents referring to constants or
  1250  // predeclared identifiers, since they are trivial and numerous.
  1251  // Nor are they emitted for ast.ParenExprs.
  1252  //
  1253  // (By representing these as instructions, rather than out-of-band,
  1254  // consistency is maintained during transformation passes by the
  1255  // ordinary SSA renaming machinery.)
  1256  //
  1257  // Example printed form:
  1258  //      ; *ast.CallExpr @ 102:9 is t5
  1259  //      ; var x float64 @ 109:72 is x
  1260  //      ; address of *ast.CompositeLit @ 216:10 is t0
  1261  //
  1262  type DebugRef struct {
  1263  	anInstruction
  1264  	Expr   ast.Expr     // the referring expression (never *ast.ParenExpr)
  1265  	object types.Object // the identity of the source var/func
  1266  	IsAddr bool         // Expr is addressable and X is the address it denotes
  1267  	X      Value        // the value or address of Expr
  1268  }
  1269  
  1270  // Embeddable mix-ins and helpers for common parts of other structs. -----------
  1271  
  1272  // register is a mix-in embedded by all SSA values that are also
  1273  // instructions, i.e. virtual registers, and provides a uniform
  1274  // implementation of most of the Value interface: Value.Name() is a
  1275  // numbered register (e.g. "t0"); the other methods are field accessors.
  1276  //
  1277  // Temporary names are automatically assigned to each register on
  1278  // completion of building a function in SSA form.
  1279  //
  1280  // Clients must not assume that the 'id' value (and the Name() derived
  1281  // from it) is unique within a function.  As always in this API,
  1282  // semantics are determined only by identity; names exist only to
  1283  // facilitate debugging.
  1284  //
  1285  type register struct {
  1286  	anInstruction
  1287  	num       int        // "name" of virtual register, e.g. "t0".  Not guaranteed unique.
  1288  	typ       types.Type // type of virtual register
  1289  	pos       token.Pos  // position of source expression, or NoPos
  1290  	referrers []Instruction
  1291  }
  1292  
  1293  // anInstruction is a mix-in embedded by all Instructions.
  1294  // It provides the implementations of the Block and setBlock methods.
  1295  type anInstruction struct {
  1296  	block *BasicBlock // the basic block of this instruction
  1297  }
  1298  
  1299  // CallCommon is contained by Go, Defer and Call to hold the
  1300  // common parts of a function or method call.
  1301  //
  1302  // Each CallCommon exists in one of two modes, function call and
  1303  // interface method invocation, or "call" and "invoke" for short.
  1304  //
  1305  // 1. "call" mode: when Method is nil (!IsInvoke), a CallCommon
  1306  // represents an ordinary function call of the value in Value,
  1307  // which may be a *Builtin, a *Function or any other value of kind
  1308  // 'func'.
  1309  //
  1310  // Value may be one of:
  1311  //    (a) a *Function, indicating a statically dispatched call
  1312  //        to a package-level function, an anonymous function, or
  1313  //        a method of a named type.
  1314  //    (b) a *MakeClosure, indicating an immediately applied
  1315  //        function literal with free variables.
  1316  //    (c) a *Builtin, indicating a statically dispatched call
  1317  //        to a built-in function.
  1318  //    (d) any other value, indicating a dynamically dispatched
  1319  //        function call.
  1320  // StaticCallee returns the identity of the callee in cases
  1321  // (a) and (b), nil otherwise.
  1322  //
  1323  // Args contains the arguments to the call.  If Value is a method,
  1324  // Args[0] contains the receiver parameter.
  1325  //
  1326  // Example printed form:
  1327  // 	t2 = println(t0, t1)
  1328  // 	go t3()
  1329  //	defer t5(...t6)
  1330  //
  1331  // 2. "invoke" mode: when Method is non-nil (IsInvoke), a CallCommon
  1332  // represents a dynamically dispatched call to an interface method.
  1333  // In this mode, Value is the interface value and Method is the
  1334  // interface's abstract method.  Note: an abstract method may be
  1335  // shared by multiple interfaces due to embedding; Value.Type()
  1336  // provides the specific interface used for this call.
  1337  //
  1338  // Value is implicitly supplied to the concrete method implementation
  1339  // as the receiver parameter; in other words, Args[0] holds not the
  1340  // receiver but the first true argument.
  1341  //
  1342  // Example printed form:
  1343  // 	t1 = invoke t0.String()
  1344  // 	go invoke t3.Run(t2)
  1345  // 	defer invoke t4.Handle(...t5)
  1346  //
  1347  // For all calls to variadic functions (Signature().Variadic()),
  1348  // the last element of Args is a slice.
  1349  //
  1350  type CallCommon struct {
  1351  	Value  Value       // receiver (invoke mode) or func value (call mode)
  1352  	Method *types.Func // abstract method (invoke mode)
  1353  	Args   []Value     // actual parameters (in static method call, includes receiver)
  1354  	pos    token.Pos   // position of CallExpr.Lparen, iff explicit in source
  1355  }
  1356  
  1357  // IsInvoke returns true if this call has "invoke" (not "call") mode.
  1358  func (c *CallCommon) IsInvoke() bool {
  1359  	return c.Method != nil
  1360  }
  1361  
  1362  func (c *CallCommon) Pos() token.Pos { return c.pos }
  1363  
  1364  // Signature returns the signature of the called function.
  1365  //
  1366  // For an "invoke"-mode call, the signature of the interface method is
  1367  // returned.
  1368  //
  1369  // In either "call" or "invoke" mode, if the callee is a method, its
  1370  // receiver is represented by sig.Recv, not sig.Params().At(0).
  1371  //
  1372  func (c *CallCommon) Signature() *types.Signature {
  1373  	if c.Method != nil {
  1374  		return c.Method.Type().(*types.Signature)
  1375  	}
  1376  	return c.Value.Type().Underlying().(*types.Signature)
  1377  }
  1378  
  1379  // StaticCallee returns the callee if this is a trivially static
  1380  // "call"-mode call to a function.
  1381  func (c *CallCommon) StaticCallee() *Function {
  1382  	switch fn := c.Value.(type) {
  1383  	case *Function:
  1384  		return fn
  1385  	case *MakeClosure:
  1386  		return fn.Fn.(*Function)
  1387  	}
  1388  	return nil
  1389  }
  1390  
  1391  // Description returns a description of the mode of this call suitable
  1392  // for a user interface, e.g., "static method call".
  1393  func (c *CallCommon) Description() string {
  1394  	switch fn := c.Value.(type) {
  1395  	case *Builtin:
  1396  		return "built-in function call"
  1397  	case *MakeClosure:
  1398  		return "static function closure call"
  1399  	case *Function:
  1400  		if fn.Signature.Recv() != nil {
  1401  			return "static method call"
  1402  		}
  1403  		return "static function call"
  1404  	}
  1405  	if c.IsInvoke() {
  1406  		return "dynamic method call" // ("invoke" mode)
  1407  	}
  1408  	return "dynamic function call"
  1409  }
  1410  
  1411  // The CallInstruction interface, implemented by *Go, *Defer and *Call,
  1412  // exposes the common parts of function-calling instructions,
  1413  // yet provides a way back to the Value defined by *Call alone.
  1414  //
  1415  type CallInstruction interface {
  1416  	Instruction
  1417  	Common() *CallCommon // returns the common parts of the call
  1418  	Value() *Call        // returns the result value of the call (*Call) or nil (*Go, *Defer)
  1419  }
  1420  
  1421  func (s *Call) Common() *CallCommon  { return &s.Call }
  1422  func (s *Defer) Common() *CallCommon { return &s.Call }
  1423  func (s *Go) Common() *CallCommon    { return &s.Call }
  1424  
  1425  func (s *Call) Value() *Call  { return s }
  1426  func (s *Defer) Value() *Call { return nil }
  1427  func (s *Go) Value() *Call    { return nil }
  1428  
  1429  func (v *Builtin) Type() types.Type        { return v.sig }
  1430  func (v *Builtin) Name() string            { return v.name }
  1431  func (*Builtin) Referrers() *[]Instruction { return nil }
  1432  func (v *Builtin) Pos() token.Pos          { return token.NoPos }
  1433  func (v *Builtin) Object() types.Object    { return types.Universe.Lookup(v.name) }
  1434  func (v *Builtin) Parent() *Function       { return nil }
  1435  
  1436  func (v *FreeVar) Type() types.Type          { return v.typ }
  1437  func (v *FreeVar) Name() string              { return v.name }
  1438  func (v *FreeVar) Referrers() *[]Instruction { return &v.referrers }
  1439  func (v *FreeVar) Pos() token.Pos            { return v.pos }
  1440  func (v *FreeVar) Parent() *Function         { return v.parent }
  1441  
  1442  func (v *Global) Type() types.Type                     { return v.typ }
  1443  func (v *Global) Name() string                         { return v.name }
  1444  func (v *Global) Parent() *Function                    { return nil }
  1445  func (v *Global) Pos() token.Pos                       { return v.pos }
  1446  func (v *Global) Referrers() *[]Instruction            { return nil }
  1447  func (v *Global) Token() token.Token                   { return token.VAR }
  1448  func (v *Global) Object() types.Object                 { return v.object }
  1449  func (v *Global) String() string                       { return v.RelString(nil) }
  1450  func (v *Global) Package() *Package                    { return v.Pkg }
  1451  func (v *Global) RelString(from *types.Package) string { return relString(v, from) }
  1452  
  1453  func (v *Function) Name() string         { return v.name }
  1454  func (v *Function) Type() types.Type     { return v.Signature }
  1455  func (v *Function) Pos() token.Pos       { return v.pos }
  1456  func (v *Function) Token() token.Token   { return token.FUNC }
  1457  func (v *Function) Object() types.Object { return v.object }
  1458  func (v *Function) String() string       { return v.RelString(nil) }
  1459  func (v *Function) Package() *Package    { return v.Pkg }
  1460  func (v *Function) Parent() *Function    { return v.parent }
  1461  func (v *Function) Referrers() *[]Instruction {
  1462  	if v.parent != nil {
  1463  		return &v.referrers
  1464  	}
  1465  	return nil
  1466  }
  1467  
  1468  func (v *Parameter) Type() types.Type          { return v.typ }
  1469  func (v *Parameter) Name() string              { return v.name }
  1470  func (v *Parameter) Object() types.Object      { return v.object }
  1471  func (v *Parameter) Referrers() *[]Instruction { return &v.referrers }
  1472  func (v *Parameter) Pos() token.Pos            { return v.pos }
  1473  func (v *Parameter) Parent() *Function         { return v.parent }
  1474  
  1475  func (v *Alloc) Type() types.Type          { return v.typ }
  1476  func (v *Alloc) Referrers() *[]Instruction { return &v.referrers }
  1477  func (v *Alloc) Pos() token.Pos            { return v.pos }
  1478  
  1479  func (v *register) Type() types.Type          { return v.typ }
  1480  func (v *register) setType(typ types.Type)    { v.typ = typ }
  1481  func (v *register) Name() string              { return fmt.Sprintf("t%d", v.num) }
  1482  func (v *register) setNum(num int)            { v.num = num }
  1483  func (v *register) Referrers() *[]Instruction { return &v.referrers }
  1484  func (v *register) Pos() token.Pos            { return v.pos }
  1485  func (v *register) setPos(pos token.Pos)      { v.pos = pos }
  1486  
  1487  func (v *anInstruction) Parent() *Function          { return v.block.parent }
  1488  func (v *anInstruction) Block() *BasicBlock         { return v.block }
  1489  func (v *anInstruction) setBlock(block *BasicBlock) { v.block = block }
  1490  func (v *anInstruction) Referrers() *[]Instruction  { return nil }
  1491  
  1492  func (t *Type) Name() string                         { return t.object.Name() }
  1493  func (t *Type) Pos() token.Pos                       { return t.object.Pos() }
  1494  func (t *Type) Type() types.Type                     { return t.object.Type() }
  1495  func (t *Type) Token() token.Token                   { return token.TYPE }
  1496  func (t *Type) Object() types.Object                 { return t.object }
  1497  func (t *Type) String() string                       { return t.RelString(nil) }
  1498  func (t *Type) Package() *Package                    { return t.pkg }
  1499  func (t *Type) RelString(from *types.Package) string { return relString(t, from) }
  1500  
  1501  func (c *NamedConst) Name() string                         { return c.object.Name() }
  1502  func (c *NamedConst) Pos() token.Pos                       { return c.object.Pos() }
  1503  func (c *NamedConst) String() string                       { return c.RelString(nil) }
  1504  func (c *NamedConst) Type() types.Type                     { return c.object.Type() }
  1505  func (c *NamedConst) Token() token.Token                   { return token.CONST }
  1506  func (c *NamedConst) Object() types.Object                 { return c.object }
  1507  func (c *NamedConst) Package() *Package                    { return c.pkg }
  1508  func (c *NamedConst) RelString(from *types.Package) string { return relString(c, from) }
  1509  
  1510  func (d *DebugRef) Object() types.Object { return d.object }
  1511  
  1512  // Func returns the package-level function of the specified name,
  1513  // or nil if not found.
  1514  //
  1515  func (p *Package) Func(name string) (f *Function) {
  1516  	f, _ = p.Members[name].(*Function)
  1517  	return
  1518  }
  1519  
  1520  // Var returns the package-level variable of the specified name,
  1521  // or nil if not found.
  1522  //
  1523  func (p *Package) Var(name string) (g *Global) {
  1524  	g, _ = p.Members[name].(*Global)
  1525  	return
  1526  }
  1527  
  1528  // Const returns the package-level constant of the specified name,
  1529  // or nil if not found.
  1530  //
  1531  func (p *Package) Const(name string) (c *NamedConst) {
  1532  	c, _ = p.Members[name].(*NamedConst)
  1533  	return
  1534  }
  1535  
  1536  // Type returns the package-level type of the specified name,
  1537  // or nil if not found.
  1538  //
  1539  func (p *Package) Type(name string) (t *Type) {
  1540  	t, _ = p.Members[name].(*Type)
  1541  	return
  1542  }
  1543  
  1544  func (v *Call) Pos() token.Pos      { return v.Call.pos }
  1545  func (s *Defer) Pos() token.Pos     { return s.pos }
  1546  func (s *Go) Pos() token.Pos        { return s.pos }
  1547  func (s *MapUpdate) Pos() token.Pos { return s.pos }
  1548  func (s *Panic) Pos() token.Pos     { return s.pos }
  1549  func (s *Return) Pos() token.Pos    { return s.pos }
  1550  func (s *Send) Pos() token.Pos      { return s.pos }
  1551  func (s *Store) Pos() token.Pos     { return s.pos }
  1552  func (s *If) Pos() token.Pos        { return token.NoPos }
  1553  func (s *Jump) Pos() token.Pos      { return token.NoPos }
  1554  func (s *RunDefers) Pos() token.Pos { return token.NoPos }
  1555  func (s *DebugRef) Pos() token.Pos  { return s.Expr.Pos() }
  1556  
  1557  // Operands.
  1558  
  1559  func (v *Alloc) Operands(rands []*Value) []*Value {
  1560  	return rands
  1561  }
  1562  
  1563  func (v *BinOp) Operands(rands []*Value) []*Value {
  1564  	return append(rands, &v.X, &v.Y)
  1565  }
  1566  
  1567  func (c *CallCommon) Operands(rands []*Value) []*Value {
  1568  	rands = append(rands, &c.Value)
  1569  	for i := range c.Args {
  1570  		rands = append(rands, &c.Args[i])
  1571  	}
  1572  	return rands
  1573  }
  1574  
  1575  func (s *Go) Operands(rands []*Value) []*Value {
  1576  	return s.Call.Operands(rands)
  1577  }
  1578  
  1579  func (s *Call) Operands(rands []*Value) []*Value {
  1580  	return s.Call.Operands(rands)
  1581  }
  1582  
  1583  func (s *Defer) Operands(rands []*Value) []*Value {
  1584  	return s.Call.Operands(rands)
  1585  }
  1586  
  1587  func (v *ChangeInterface) Operands(rands []*Value) []*Value {
  1588  	return append(rands, &v.X)
  1589  }
  1590  
  1591  func (v *ChangeType) Operands(rands []*Value) []*Value {
  1592  	return append(rands, &v.X)
  1593  }
  1594  
  1595  func (v *Convert) Operands(rands []*Value) []*Value {
  1596  	return append(rands, &v.X)
  1597  }
  1598  
  1599  func (v *SliceToArrayPointer) Operands(rands []*Value) []*Value {
  1600  	return append(rands, &v.X)
  1601  }
  1602  
  1603  func (s *DebugRef) Operands(rands []*Value) []*Value {
  1604  	return append(rands, &s.X)
  1605  }
  1606  
  1607  func (v *Extract) Operands(rands []*Value) []*Value {
  1608  	return append(rands, &v.Tuple)
  1609  }
  1610  
  1611  func (v *Field) Operands(rands []*Value) []*Value {
  1612  	return append(rands, &v.X)
  1613  }
  1614  
  1615  func (v *FieldAddr) Operands(rands []*Value) []*Value {
  1616  	return append(rands, &v.X)
  1617  }
  1618  
  1619  func (s *If) Operands(rands []*Value) []*Value {
  1620  	return append(rands, &s.Cond)
  1621  }
  1622  
  1623  func (v *Index) Operands(rands []*Value) []*Value {
  1624  	return append(rands, &v.X, &v.Index)
  1625  }
  1626  
  1627  func (v *IndexAddr) Operands(rands []*Value) []*Value {
  1628  	return append(rands, &v.X, &v.Index)
  1629  }
  1630  
  1631  func (*Jump) Operands(rands []*Value) []*Value {
  1632  	return rands
  1633  }
  1634  
  1635  func (v *Lookup) Operands(rands []*Value) []*Value {
  1636  	return append(rands, &v.X, &v.Index)
  1637  }
  1638  
  1639  func (v *MakeChan) Operands(rands []*Value) []*Value {
  1640  	return append(rands, &v.Size)
  1641  }
  1642  
  1643  func (v *MakeClosure) Operands(rands []*Value) []*Value {
  1644  	rands = append(rands, &v.Fn)
  1645  	for i := range v.Bindings {
  1646  		rands = append(rands, &v.Bindings[i])
  1647  	}
  1648  	return rands
  1649  }
  1650  
  1651  func (v *MakeInterface) Operands(rands []*Value) []*Value {
  1652  	return append(rands, &v.X)
  1653  }
  1654  
  1655  func (v *MakeMap) Operands(rands []*Value) []*Value {
  1656  	return append(rands, &v.Reserve)
  1657  }
  1658  
  1659  func (v *MakeSlice) Operands(rands []*Value) []*Value {
  1660  	return append(rands, &v.Len, &v.Cap)
  1661  }
  1662  
  1663  func (v *MapUpdate) Operands(rands []*Value) []*Value {
  1664  	return append(rands, &v.Map, &v.Key, &v.Value)
  1665  }
  1666  
  1667  func (v *Next) Operands(rands []*Value) []*Value {
  1668  	return append(rands, &v.Iter)
  1669  }
  1670  
  1671  func (s *Panic) Operands(rands []*Value) []*Value {
  1672  	return append(rands, &s.X)
  1673  }
  1674  
  1675  func (v *Phi) Operands(rands []*Value) []*Value {
  1676  	for i := range v.Edges {
  1677  		rands = append(rands, &v.Edges[i])
  1678  	}
  1679  	return rands
  1680  }
  1681  
  1682  func (v *Range) Operands(rands []*Value) []*Value {
  1683  	return append(rands, &v.X)
  1684  }
  1685  
  1686  func (s *Return) Operands(rands []*Value) []*Value {
  1687  	for i := range s.Results {
  1688  		rands = append(rands, &s.Results[i])
  1689  	}
  1690  	return rands
  1691  }
  1692  
  1693  func (*RunDefers) Operands(rands []*Value) []*Value {
  1694  	return rands
  1695  }
  1696  
  1697  func (v *Select) Operands(rands []*Value) []*Value {
  1698  	for i := range v.States {
  1699  		rands = append(rands, &v.States[i].Chan, &v.States[i].Send)
  1700  	}
  1701  	return rands
  1702  }
  1703  
  1704  func (s *Send) Operands(rands []*Value) []*Value {
  1705  	return append(rands, &s.Chan, &s.X)
  1706  }
  1707  
  1708  func (v *Slice) Operands(rands []*Value) []*Value {
  1709  	return append(rands, &v.X, &v.Low, &v.High, &v.Max)
  1710  }
  1711  
  1712  func (s *Store) Operands(rands []*Value) []*Value {
  1713  	return append(rands, &s.Addr, &s.Val)
  1714  }
  1715  
  1716  func (v *TypeAssert) Operands(rands []*Value) []*Value {
  1717  	return append(rands, &v.X)
  1718  }
  1719  
  1720  func (v *UnOp) Operands(rands []*Value) []*Value {
  1721  	return append(rands, &v.X)
  1722  }
  1723  
  1724  // Non-Instruction Values:
  1725  func (v *Builtin) Operands(rands []*Value) []*Value   { return rands }
  1726  func (v *FreeVar) Operands(rands []*Value) []*Value   { return rands }
  1727  func (v *Const) Operands(rands []*Value) []*Value     { return rands }
  1728  func (v *Function) Operands(rands []*Value) []*Value  { return rands }
  1729  func (v *Global) Operands(rands []*Value) []*Value    { return rands }
  1730  func (v *Parameter) Operands(rands []*Value) []*Value { return rands }