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

1696 lines
55 KiB

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