golang.org/x/tools@v0.21.1-0.20240520172518-788d39e776b1/go/ssa/func.go (about) 1 // Copyright 2013 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package ssa 6 7 // This file implements the Function type. 8 9 import ( 10 "bytes" 11 "fmt" 12 "go/ast" 13 "go/token" 14 "go/types" 15 "io" 16 "os" 17 "strings" 18 19 "golang.org/x/tools/internal/typeparams" 20 ) 21 22 // Like ObjectOf, but panics instead of returning nil. 23 // Only valid during f's create and build phases. 24 func (f *Function) objectOf(id *ast.Ident) types.Object { 25 if o := f.info.ObjectOf(id); o != nil { 26 return o 27 } 28 panic(fmt.Sprintf("no types.Object for ast.Ident %s @ %s", 29 id.Name, f.Prog.Fset.Position(id.Pos()))) 30 } 31 32 // Like TypeOf, but panics instead of returning nil. 33 // Only valid during f's create and build phases. 34 func (f *Function) typeOf(e ast.Expr) types.Type { 35 if T := f.info.TypeOf(e); T != nil { 36 return f.typ(T) 37 } 38 panic(fmt.Sprintf("no type for %T @ %s", e, f.Prog.Fset.Position(e.Pos()))) 39 } 40 41 // typ is the locally instantiated type of T. 42 // If f is not an instantiation, then f.typ(T)==T. 43 func (f *Function) typ(T types.Type) types.Type { 44 return f.subst.typ(T) 45 } 46 47 // If id is an Instance, returns info.Instances[id].Type. 48 // Otherwise returns f.typeOf(id). 49 func (f *Function) instanceType(id *ast.Ident) types.Type { 50 if t, ok := f.info.Instances[id]; ok { 51 return t.Type 52 } 53 return f.typeOf(id) 54 } 55 56 // selection returns a *selection corresponding to f.info.Selections[selector] 57 // with potential updates for type substitution. 58 func (f *Function) selection(selector *ast.SelectorExpr) *selection { 59 sel := f.info.Selections[selector] 60 if sel == nil { 61 return nil 62 } 63 64 switch sel.Kind() { 65 case types.MethodExpr, types.MethodVal: 66 if recv := f.typ(sel.Recv()); recv != sel.Recv() { 67 // recv changed during type substitution. 68 pkg := f.declaredPackage().Pkg 69 obj, index, indirect := types.LookupFieldOrMethod(recv, true, pkg, sel.Obj().Name()) 70 71 // sig replaces sel.Type(). See (types.Selection).Typ() for details. 72 sig := obj.Type().(*types.Signature) 73 sig = changeRecv(sig, newVar(sig.Recv().Name(), recv)) 74 if sel.Kind() == types.MethodExpr { 75 sig = recvAsFirstArg(sig) 76 } 77 return &selection{ 78 kind: sel.Kind(), 79 recv: recv, 80 typ: sig, 81 obj: obj, 82 index: index, 83 indirect: indirect, 84 } 85 } 86 } 87 return toSelection(sel) 88 } 89 90 // Destinations associated with unlabelled for/switch/select stmts. 91 // We push/pop one of these as we enter/leave each construct and for 92 // each BranchStmt we scan for the innermost target of the right type. 93 type targets struct { 94 tail *targets // rest of stack 95 _break *BasicBlock 96 _continue *BasicBlock 97 _fallthrough *BasicBlock 98 } 99 100 // Destinations associated with a labelled block. 101 // We populate these as labels are encountered in forward gotos or 102 // labelled statements. 103 // Forward gotos are resolved once it is known which statement they 104 // are associated with inside the Function. 105 type lblock struct { 106 label *types.Label // Label targeted by the blocks. 107 resolved bool // _goto block encountered (back jump or resolved fwd jump) 108 _goto *BasicBlock 109 _break *BasicBlock 110 _continue *BasicBlock 111 } 112 113 // label returns the symbol denoted by a label identifier. 114 // 115 // label should be a non-blank identifier (label.Name != "_"). 116 func (f *Function) label(label *ast.Ident) *types.Label { 117 return f.objectOf(label).(*types.Label) 118 } 119 120 // lblockOf returns the branch target associated with the 121 // specified label, creating it if needed. 122 func (f *Function) lblockOf(label *types.Label) *lblock { 123 lb := f.lblocks[label] 124 if lb == nil { 125 lb = &lblock{ 126 label: label, 127 _goto: f.newBasicBlock(label.Name()), 128 } 129 if f.lblocks == nil { 130 f.lblocks = make(map[*types.Label]*lblock) 131 } 132 f.lblocks[label] = lb 133 } 134 return lb 135 } 136 137 // labelledBlock searches f for the block of the specified label. 138 // 139 // If f is a yield function, it additionally searches ancestor Functions 140 // corresponding to enclosing range-over-func statements within the 141 // same source function, so the returned block may belong to a different Function. 142 func labelledBlock(f *Function, label *types.Label, tok token.Token) *BasicBlock { 143 if lb := f.lblocks[label]; lb != nil { 144 var block *BasicBlock 145 switch tok { 146 case token.BREAK: 147 block = lb._break 148 case token.CONTINUE: 149 block = lb._continue 150 case token.GOTO: 151 block = lb._goto 152 } 153 if block != nil { 154 return block 155 } 156 } 157 // Search ancestors if this is a yield function. 158 if f.jump != nil { 159 return labelledBlock(f.parent, label, tok) 160 } 161 return nil 162 } 163 164 // targetedBlock looks for the nearest block in f.targets 165 // (and f's ancestors) that matches tok's type, and returns 166 // the block and function it was found in. 167 func targetedBlock(f *Function, tok token.Token) *BasicBlock { 168 if f == nil { 169 return nil 170 } 171 for t := f.targets; t != nil; t = t.tail { 172 var block *BasicBlock 173 switch tok { 174 case token.BREAK: 175 block = t._break 176 case token.CONTINUE: 177 block = t._continue 178 case token.FALLTHROUGH: 179 block = t._fallthrough 180 } 181 if block != nil { 182 return block 183 } 184 } 185 // Search f's ancestors (in case f is a yield function). 186 return targetedBlock(f.parent, tok) 187 } 188 189 // addResultVar adds a result for a variable v to f.results and v to f.returnVars. 190 func (f *Function) addResultVar(v *types.Var) { 191 name := v.Name() 192 if name == "" { 193 name = fmt.Sprintf("res%d", len(f.results)) 194 } 195 result := emitLocalVar(f, v) 196 f.results = append(f.results, result) 197 f.returnVars = append(f.returnVars, v) 198 } 199 200 // addParamVar adds a parameter to f.Params. 201 func (f *Function) addParamVar(v *types.Var) *Parameter { 202 name := v.Name() 203 if name == "" { 204 name = fmt.Sprintf("arg%d", len(f.Params)) 205 } 206 param := &Parameter{ 207 name: name, 208 object: v, 209 typ: f.typ(v.Type()), 210 parent: f, 211 } 212 f.Params = append(f.Params, param) 213 return param 214 } 215 216 // addSpilledParam declares a parameter that is pre-spilled to the 217 // stack; the function body will load/store the spilled location. 218 // Subsequent lifting will eliminate spills where possible. 219 func (f *Function) addSpilledParam(obj *types.Var) { 220 param := f.addParamVar(obj) 221 spill := emitLocalVar(f, obj) 222 f.emit(&Store{Addr: spill, Val: param}) 223 } 224 225 // startBody initializes the function prior to generating SSA code for its body. 226 // Precondition: f.Type() already set. 227 func (f *Function) startBody() { 228 f.currentBlock = f.newBasicBlock("entry") 229 f.vars = make(map[*types.Var]Value) // needed for some synthetics, e.g. init 230 } 231 232 // createSyntacticParams populates f.Params and generates code (spills 233 // and named result locals) for all the parameters declared in the 234 // syntax. In addition it populates the f.objects mapping. 235 // 236 // Preconditions: 237 // f.startBody() was called. f.info != nil. 238 // Postcondition: 239 // len(f.Params) == len(f.Signature.Params) + (f.Signature.Recv() ? 1 : 0) 240 func (f *Function) createSyntacticParams(recv *ast.FieldList, functype *ast.FuncType) { 241 // Receiver (at most one inner iteration). 242 if recv != nil { 243 for _, field := range recv.List { 244 for _, n := range field.Names { 245 f.addSpilledParam(identVar(f, n)) 246 } 247 // Anonymous receiver? No need to spill. 248 if field.Names == nil { 249 f.addParamVar(f.Signature.Recv()) 250 } 251 } 252 } 253 254 // Parameters. 255 if functype.Params != nil { 256 n := len(f.Params) // 1 if has recv, 0 otherwise 257 for _, field := range functype.Params.List { 258 for _, n := range field.Names { 259 f.addSpilledParam(identVar(f, n)) 260 } 261 // Anonymous parameter? No need to spill. 262 if field.Names == nil { 263 f.addParamVar(f.Signature.Params().At(len(f.Params) - n)) 264 } 265 } 266 } 267 268 // Results. 269 if functype.Results != nil { 270 for _, field := range functype.Results.List { 271 // Implicit "var" decl of locals for named results. 272 for _, n := range field.Names { 273 v := identVar(f, n) 274 f.addResultVar(v) 275 } 276 // Implicit "var" decl of local for an unnamed result. 277 if field.Names == nil { 278 v := f.Signature.Results().At(len(f.results)) 279 f.addResultVar(v) 280 } 281 } 282 } 283 } 284 285 // createDeferStack initializes fn.deferstack to local variable 286 // initialized to a ssa:deferstack() call. 287 func (fn *Function) createDeferStack() { 288 // Each syntactic function makes a call to ssa:deferstack, 289 // which is spilled to a local. Unused ones are later removed. 290 fn.deferstack = newVar("defer$stack", tDeferStack) 291 call := &Call{Call: CallCommon{Value: vDeferStack}} 292 call.setType(tDeferStack) 293 deferstack := fn.emit(call) 294 spill := emitLocalVar(fn, fn.deferstack) 295 emitStore(fn, spill, deferstack, token.NoPos) 296 } 297 298 type setNumable interface { 299 setNum(int) 300 } 301 302 // numberRegisters assigns numbers to all SSA registers 303 // (value-defining Instructions) in f, to aid debugging. 304 // (Non-Instruction Values are named at construction.) 305 func numberRegisters(f *Function) { 306 v := 0 307 for _, b := range f.Blocks { 308 for _, instr := range b.Instrs { 309 switch instr.(type) { 310 case Value: 311 instr.(setNumable).setNum(v) 312 v++ 313 } 314 } 315 } 316 } 317 318 // buildReferrers populates the def/use information in all non-nil 319 // Value.Referrers slice. 320 // Precondition: all such slices are initially empty. 321 func buildReferrers(f *Function) { 322 var rands []*Value 323 for _, b := range f.Blocks { 324 for _, instr := range b.Instrs { 325 rands = instr.Operands(rands[:0]) // recycle storage 326 for _, rand := range rands { 327 if r := *rand; r != nil { 328 if ref := r.Referrers(); ref != nil { 329 *ref = append(*ref, instr) 330 } 331 } 332 } 333 } 334 } 335 } 336 337 // finishBody() finalizes the contents of the function after SSA code generation of its body. 338 // 339 // The function is not done being built until done() is called. 340 func (f *Function) finishBody() { 341 f.currentBlock = nil 342 f.lblocks = nil 343 f.returnVars = nil 344 f.jump = nil 345 f.source = nil 346 f.exits = nil 347 348 // Remove from f.Locals any Allocs that escape to the heap. 349 j := 0 350 for _, l := range f.Locals { 351 if !l.Heap { 352 f.Locals[j] = l 353 j++ 354 } 355 } 356 // Nil out f.Locals[j:] to aid GC. 357 for i := j; i < len(f.Locals); i++ { 358 f.Locals[i] = nil 359 } 360 f.Locals = f.Locals[:j] 361 362 optimizeBlocks(f) 363 364 buildReferrers(f) 365 366 buildDomTree(f) 367 368 if f.Prog.mode&NaiveForm == 0 { 369 // For debugging pre-state of lifting pass: 370 // numberRegisters(f) 371 // f.WriteTo(os.Stderr) 372 lift(f) 373 } 374 375 // clear remaining builder state 376 f.results = nil // (used by lifting) 377 f.deferstack = nil // (used by lifting) 378 f.vars = nil // (used by lifting) 379 f.subst = nil 380 381 numberRegisters(f) // uses f.namedRegisters 382 } 383 384 // done marks the building of f's SSA body complete, 385 // along with any nested functions, and optionally prints them. 386 func (f *Function) done() { 387 assert(f.parent == nil, "done called on an anonymous function") 388 389 var visit func(*Function) 390 visit = func(f *Function) { 391 for _, anon := range f.AnonFuncs { 392 visit(anon) // anon is done building before f. 393 } 394 395 f.uniq = 0 // done with uniq 396 f.build = nil // function is built 397 398 if f.Prog.mode&PrintFunctions != 0 { 399 printMu.Lock() 400 f.WriteTo(os.Stdout) 401 printMu.Unlock() 402 } 403 404 if f.Prog.mode&SanityCheckFunctions != 0 { 405 mustSanityCheck(f, nil) 406 } 407 } 408 visit(f) 409 } 410 411 // removeNilBlocks eliminates nils from f.Blocks and updates each 412 // BasicBlock.Index. Use this after any pass that may delete blocks. 413 func (f *Function) removeNilBlocks() { 414 j := 0 415 for _, b := range f.Blocks { 416 if b != nil { 417 b.Index = j 418 f.Blocks[j] = b 419 j++ 420 } 421 } 422 // Nil out f.Blocks[j:] to aid GC. 423 for i := j; i < len(f.Blocks); i++ { 424 f.Blocks[i] = nil 425 } 426 f.Blocks = f.Blocks[:j] 427 } 428 429 // SetDebugMode sets the debug mode for package pkg. If true, all its 430 // functions will include full debug info. This greatly increases the 431 // size of the instruction stream, and causes Functions to depend upon 432 // the ASTs, potentially keeping them live in memory for longer. 433 func (pkg *Package) SetDebugMode(debug bool) { 434 pkg.debug = debug 435 } 436 437 // debugInfo reports whether debug info is wanted for this function. 438 func (f *Function) debugInfo() bool { 439 // debug info for instantiations follows the debug info of their origin. 440 p := f.declaredPackage() 441 return p != nil && p.debug 442 } 443 444 // lookup returns the address of the named variable identified by obj 445 // that is local to function f or one of its enclosing functions. 446 // If escaping, the reference comes from a potentially escaping pointer 447 // expression and the referent must be heap-allocated. 448 // We assume the referent is a *Alloc or *Phi. 449 // (The only Phis at this stage are those created directly by go1.22 "for" loops.) 450 func (f *Function) lookup(obj *types.Var, escaping bool) Value { 451 if v, ok := f.vars[obj]; ok { 452 if escaping { 453 switch v := v.(type) { 454 case *Alloc: 455 v.Heap = true 456 case *Phi: 457 for _, edge := range v.Edges { 458 if alloc, ok := edge.(*Alloc); ok { 459 alloc.Heap = true 460 } 461 } 462 } 463 } 464 return v // function-local var (address) 465 } 466 467 // Definition must be in an enclosing function; 468 // plumb it through intervening closures. 469 if f.parent == nil { 470 panic("no ssa.Value for " + obj.String()) 471 } 472 outer := f.parent.lookup(obj, true) // escaping 473 v := &FreeVar{ 474 name: obj.Name(), 475 typ: outer.Type(), 476 pos: outer.Pos(), 477 outer: outer, 478 parent: f, 479 } 480 f.vars[obj] = v 481 f.FreeVars = append(f.FreeVars, v) 482 return v 483 } 484 485 // emit emits the specified instruction to function f. 486 func (f *Function) emit(instr Instruction) Value { 487 return f.currentBlock.emit(instr) 488 } 489 490 // RelString returns the full name of this function, qualified by 491 // package name, receiver type, etc. 492 // 493 // The specific formatting rules are not guaranteed and may change. 494 // 495 // Examples: 496 // 497 // "math.IsNaN" // a package-level function 498 // "(*bytes.Buffer).Bytes" // a declared method or a wrapper 499 // "(*bytes.Buffer).Bytes$thunk" // thunk (func wrapping method; receiver is param 0) 500 // "(*bytes.Buffer).Bytes$bound" // bound (func wrapping method; receiver supplied by closure) 501 // "main.main$1" // an anonymous function in main 502 // "main.init#1" // a declared init function 503 // "main.init" // the synthesized package initializer 504 // 505 // When these functions are referred to from within the same package 506 // (i.e. from == f.Pkg.Object), they are rendered without the package path. 507 // For example: "IsNaN", "(*Buffer).Bytes", etc. 508 // 509 // All non-synthetic functions have distinct package-qualified names. 510 // (But two methods may have the same name "(T).f" if one is a synthetic 511 // wrapper promoting a non-exported method "f" from another package; in 512 // that case, the strings are equal but the identifiers "f" are distinct.) 513 func (f *Function) RelString(from *types.Package) string { 514 // Anonymous? 515 if f.parent != nil { 516 // An anonymous function's Name() looks like "parentName$1", 517 // but its String() should include the type/package/etc. 518 parent := f.parent.RelString(from) 519 for i, anon := range f.parent.AnonFuncs { 520 if anon == f { 521 return fmt.Sprintf("%s$%d", parent, 1+i) 522 } 523 } 524 525 return f.name // should never happen 526 } 527 528 // Method (declared or wrapper)? 529 if recv := f.Signature.Recv(); recv != nil { 530 return f.relMethod(from, recv.Type()) 531 } 532 533 // Thunk? 534 if f.method != nil { 535 return f.relMethod(from, f.method.recv) 536 } 537 538 // Bound? 539 if len(f.FreeVars) == 1 && strings.HasSuffix(f.name, "$bound") { 540 return f.relMethod(from, f.FreeVars[0].Type()) 541 } 542 543 // Package-level function? 544 // Prefix with package name for cross-package references only. 545 if p := f.relPkg(); p != nil && p != from { 546 return fmt.Sprintf("%s.%s", p.Path(), f.name) 547 } 548 549 // Unknown. 550 return f.name 551 } 552 553 func (f *Function) relMethod(from *types.Package, recv types.Type) string { 554 return fmt.Sprintf("(%s).%s", relType(recv, from), f.name) 555 } 556 557 // writeSignature writes to buf the signature sig in declaration syntax. 558 func writeSignature(buf *bytes.Buffer, from *types.Package, name string, sig *types.Signature) { 559 buf.WriteString("func ") 560 if recv := sig.Recv(); recv != nil { 561 buf.WriteString("(") 562 if name := recv.Name(); name != "" { 563 buf.WriteString(name) 564 buf.WriteString(" ") 565 } 566 types.WriteType(buf, recv.Type(), types.RelativeTo(from)) 567 buf.WriteString(") ") 568 } 569 buf.WriteString(name) 570 types.WriteSignature(buf, sig, types.RelativeTo(from)) 571 } 572 573 // declaredPackage returns the package fn is declared in or nil if the 574 // function is not declared in a package. 575 func (fn *Function) declaredPackage() *Package { 576 switch { 577 case fn.Pkg != nil: 578 return fn.Pkg // non-generic function (does that follow??) 579 case fn.topLevelOrigin != nil: 580 return fn.topLevelOrigin.Pkg // instance of a named generic function 581 case fn.parent != nil: 582 return fn.parent.declaredPackage() // instance of an anonymous [generic] function 583 default: 584 return nil // function is not declared in a package, e.g. a wrapper. 585 } 586 } 587 588 // relPkg returns types.Package fn is printed in relationship to. 589 func (fn *Function) relPkg() *types.Package { 590 if p := fn.declaredPackage(); p != nil { 591 return p.Pkg 592 } 593 return nil 594 } 595 596 var _ io.WriterTo = (*Function)(nil) // *Function implements io.Writer 597 598 func (f *Function) WriteTo(w io.Writer) (int64, error) { 599 var buf bytes.Buffer 600 WriteFunction(&buf, f) 601 n, err := w.Write(buf.Bytes()) 602 return int64(n), err 603 } 604 605 // WriteFunction writes to buf a human-readable "disassembly" of f. 606 func WriteFunction(buf *bytes.Buffer, f *Function) { 607 fmt.Fprintf(buf, "# Name: %s\n", f.String()) 608 if f.Pkg != nil { 609 fmt.Fprintf(buf, "# Package: %s\n", f.Pkg.Pkg.Path()) 610 } 611 if syn := f.Synthetic; syn != "" { 612 fmt.Fprintln(buf, "# Synthetic:", syn) 613 } 614 if pos := f.Pos(); pos.IsValid() { 615 fmt.Fprintf(buf, "# Location: %s\n", f.Prog.Fset.Position(pos)) 616 } 617 618 if f.parent != nil { 619 fmt.Fprintf(buf, "# Parent: %s\n", f.parent.Name()) 620 } 621 622 if f.Recover != nil { 623 fmt.Fprintf(buf, "# Recover: %s\n", f.Recover) 624 } 625 626 from := f.relPkg() 627 628 if f.FreeVars != nil { 629 buf.WriteString("# Free variables:\n") 630 for i, fv := range f.FreeVars { 631 fmt.Fprintf(buf, "# % 3d:\t%s %s\n", i, fv.Name(), relType(fv.Type(), from)) 632 } 633 } 634 635 if len(f.Locals) > 0 { 636 buf.WriteString("# Locals:\n") 637 for i, l := range f.Locals { 638 fmt.Fprintf(buf, "# % 3d:\t%s %s\n", i, l.Name(), relType(typeparams.MustDeref(l.Type()), from)) 639 } 640 } 641 writeSignature(buf, from, f.Name(), f.Signature) 642 buf.WriteString(":\n") 643 644 if f.Blocks == nil { 645 buf.WriteString("\t(external)\n") 646 } 647 648 // NB. column calculations are confused by non-ASCII 649 // characters and assume 8-space tabs. 650 const punchcard = 80 // for old time's sake. 651 const tabwidth = 8 652 for _, b := range f.Blocks { 653 if b == nil { 654 // Corrupt CFG. 655 fmt.Fprintf(buf, ".nil:\n") 656 continue 657 } 658 n, _ := fmt.Fprintf(buf, "%d:", b.Index) 659 bmsg := fmt.Sprintf("%s P:%d S:%d", b.Comment, len(b.Preds), len(b.Succs)) 660 fmt.Fprintf(buf, "%*s%s\n", punchcard-1-n-len(bmsg), "", bmsg) 661 662 if false { // CFG debugging 663 fmt.Fprintf(buf, "\t# CFG: %s --> %s --> %s\n", b.Preds, b, b.Succs) 664 } 665 for _, instr := range b.Instrs { 666 buf.WriteString("\t") 667 switch v := instr.(type) { 668 case Value: 669 l := punchcard - tabwidth 670 // Left-align the instruction. 671 if name := v.Name(); name != "" { 672 n, _ := fmt.Fprintf(buf, "%s = ", name) 673 l -= n 674 } 675 n, _ := buf.WriteString(instr.String()) 676 l -= n 677 // Right-align the type if there's space. 678 if t := v.Type(); t != nil { 679 buf.WriteByte(' ') 680 ts := relType(t, from) 681 l -= len(ts) + len(" ") // (spaces before and after type) 682 if l > 0 { 683 fmt.Fprintf(buf, "%*s", l, "") 684 } 685 buf.WriteString(ts) 686 } 687 case nil: 688 // Be robust against bad transforms. 689 buf.WriteString("<deleted>") 690 default: 691 buf.WriteString(instr.String()) 692 } 693 // -mode=S: show line numbers 694 if f.Prog.mode&LogSource != 0 { 695 if pos := instr.Pos(); pos.IsValid() { 696 fmt.Fprintf(buf, " L%d", f.Prog.Fset.Position(pos).Line) 697 } 698 } 699 buf.WriteString("\n") 700 } 701 } 702 fmt.Fprintf(buf, "\n") 703 } 704 705 // newBasicBlock adds to f a new basic block and returns it. It does 706 // not automatically become the current block for subsequent calls to emit. 707 // comment is an optional string for more readable debugging output. 708 func (f *Function) newBasicBlock(comment string) *BasicBlock { 709 b := &BasicBlock{ 710 Index: len(f.Blocks), 711 Comment: comment, 712 parent: f, 713 } 714 b.Succs = b.succs2[:0] 715 f.Blocks = append(f.Blocks, b) 716 return b 717 } 718 719 // NewFunction returns a new synthetic Function instance belonging to 720 // prog, with its name and signature fields set as specified. 721 // 722 // The caller is responsible for initializing the remaining fields of 723 // the function object, e.g. Pkg, Params, Blocks. 724 // 725 // It is practically impossible for clients to construct well-formed 726 // SSA functions/packages/programs directly, so we assume this is the 727 // job of the Builder alone. NewFunction exists to provide clients a 728 // little flexibility. For example, analysis tools may wish to 729 // construct fake Functions for the root of the callgraph, a fake 730 // "reflect" package, etc. 731 // 732 // TODO(adonovan): think harder about the API here. 733 func (prog *Program) NewFunction(name string, sig *types.Signature, provenance string) *Function { 734 return &Function{Prog: prog, name: name, Signature: sig, Synthetic: provenance} 735 } 736 737 // Syntax returns the function's syntax (*ast.Func{Decl,Lit}) 738 // if it was produced from syntax or an *ast.RangeStmt if 739 // it is a range-over-func yield function. 740 func (f *Function) Syntax() ast.Node { return f.syntax } 741 742 // identVar returns the variable defined by id. 743 func identVar(fn *Function, id *ast.Ident) *types.Var { 744 return fn.info.Defs[id].(*types.Var) 745 } 746 747 // unique returns a unique positive int within the source tree of f. 748 // The source tree of f includes all of f's ancestors by parent and all 749 // of the AnonFuncs contained within these. 750 func unique(f *Function) int64 { 751 f.uniq++ 752 return f.uniq 753 } 754 755 // exit is a change of control flow going from a range-over-func 756 // yield function to an ancestor function caused by a break, continue, 757 // goto, or return statement. 758 // 759 // There are 3 types of exits: 760 // * return from the source function (from ReturnStmt), 761 // * jump to a block (from break and continue statements [labelled/unlabelled]), 762 // * go to a label (from goto statements). 763 // 764 // As the builder does one pass over the ast, it is unclear whether 765 // a forward goto statement will leave a range-over-func body. 766 // The function being exited to is unresolved until the end 767 // of building the range-over-func body. 768 type exit struct { 769 id int64 // unique value for exit within from and to 770 from *Function // the function the exit starts from 771 to *Function // the function being exited to (nil if unresolved) 772 pos token.Pos 773 774 block *BasicBlock // basic block within to being jumped to. 775 label *types.Label // forward label being jumped to via goto. 776 // block == nil && label == nil => return 777 } 778 779 // storeVar emits to function f code to store a value v to a *types.Var x. 780 func storeVar(f *Function, x *types.Var, v Value, pos token.Pos) { 781 emitStore(f, f.lookup(x, true), v, pos) 782 } 783 784 // labelExit creates a new exit to a yield fn to exit the function using a label. 785 func labelExit(fn *Function, label *types.Label, pos token.Pos) *exit { 786 e := &exit{ 787 id: unique(fn), 788 from: fn, 789 to: nil, 790 pos: pos, 791 label: label, 792 } 793 fn.exits = append(fn.exits, e) 794 return e 795 } 796 797 // blockExit creates a new exit to a yield fn that jumps to a basic block. 798 func blockExit(fn *Function, block *BasicBlock, pos token.Pos) *exit { 799 e := &exit{ 800 id: unique(fn), 801 from: fn, 802 to: block.parent, 803 pos: pos, 804 block: block, 805 } 806 fn.exits = append(fn.exits, e) 807 return e 808 } 809 810 // blockExit creates a new exit to a yield fn that returns the source function. 811 func returnExit(fn *Function, pos token.Pos) *exit { 812 e := &exit{ 813 id: unique(fn), 814 from: fn, 815 to: fn.source, 816 pos: pos, 817 } 818 fn.exits = append(fn.exits, e) 819 return e 820 }