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