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