Debian Codegraph @

go/ssa/ssa.go

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