github.com/megatontech/mynoteforgo@v0.0.0-20200507084910-5d0c6ea6e890/源码/cmd/compile/internal/gc/sinit.go (about) 1 // Copyright 2009 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 gc 6 7 import ( 8 "cmd/compile/internal/types" 9 "fmt" 10 ) 11 12 // Static initialization ordering state. 13 // These values are stored in two bits in Node.flags. 14 const ( 15 InitNotStarted = iota 16 InitDone 17 InitPending 18 ) 19 20 type InitEntry struct { 21 Xoffset int64 // struct, array only 22 Expr *Node // bytes of run-time computed expressions 23 } 24 25 type InitPlan struct { 26 E []InitEntry 27 } 28 29 var ( 30 initlist []*Node 31 initplans map[*Node]*InitPlan 32 inittemps = make(map[*Node]*Node) 33 ) 34 35 // init1 walks the AST starting at n, and accumulates in out 36 // the list of definitions needing init code in dependency order. 37 func init1(n *Node, out *[]*Node) { 38 if n == nil { 39 return 40 } 41 init1(n.Left, out) 42 init1(n.Right, out) 43 for _, n1 := range n.List.Slice() { 44 init1(n1, out) 45 } 46 47 if n.isMethodExpression() { 48 // Methods called as Type.Method(receiver, ...). 49 // Definitions for method expressions are stored in type->nname. 50 init1(asNode(n.Type.FuncType().Nname), out) 51 } 52 53 if n.Op != ONAME { 54 return 55 } 56 switch n.Class() { 57 case PEXTERN, PFUNC: 58 default: 59 if n.isBlank() && n.Name.Curfn == nil && n.Name.Defn != nil && n.Name.Defn.Initorder() == InitNotStarted { 60 // blank names initialization is part of init() but not 61 // when they are inside a function. 62 break 63 } 64 return 65 } 66 67 if n.Initorder() == InitDone { 68 return 69 } 70 if n.Initorder() == InitPending { 71 // Since mutually recursive sets of functions are allowed, 72 // we don't necessarily raise an error if n depends on a node 73 // which is already waiting for its dependencies to be visited. 74 // 75 // initlist contains a cycle of identifiers referring to each other. 76 // If this cycle contains a variable, then this variable refers to itself. 77 // Conversely, if there exists an initialization cycle involving 78 // a variable in the program, the tree walk will reach a cycle 79 // involving that variable. 80 if n.Class() != PFUNC { 81 foundinitloop(n, n) 82 } 83 84 for i := len(initlist) - 1; i >= 0; i-- { 85 x := initlist[i] 86 if x == n { 87 break 88 } 89 if x.Class() != PFUNC { 90 foundinitloop(n, x) 91 } 92 } 93 94 // The loop involves only functions, ok. 95 return 96 } 97 98 // reached a new unvisited node. 99 n.SetInitorder(InitPending) 100 initlist = append(initlist, n) 101 102 // make sure that everything n depends on is initialized. 103 // n->defn is an assignment to n 104 if defn := n.Name.Defn; defn != nil { 105 switch defn.Op { 106 default: 107 Dump("defn", defn) 108 Fatalf("init1: bad defn") 109 110 case ODCLFUNC: 111 init2list(defn.Nbody, out) 112 113 case OAS: 114 if defn.Left != n { 115 Dump("defn", defn) 116 Fatalf("init1: bad defn") 117 } 118 if defn.Left.isBlank() && candiscard(defn.Right) { 119 defn.Op = OEMPTY 120 defn.Left = nil 121 defn.Right = nil 122 break 123 } 124 125 init2(defn.Right, out) 126 if Debug['j'] != 0 { 127 fmt.Printf("%v\n", n.Sym) 128 } 129 if n.isBlank() || !staticinit(n, out) { 130 if Debug['%'] != 0 { 131 Dump("nonstatic", defn) 132 } 133 *out = append(*out, defn) 134 } 135 136 case OAS2FUNC, OAS2MAPR, OAS2DOTTYPE, OAS2RECV: 137 if defn.Initorder() == InitDone { 138 break 139 } 140 defn.SetInitorder(InitPending) 141 for _, n2 := range defn.Rlist.Slice() { 142 init1(n2, out) 143 } 144 if Debug['%'] != 0 { 145 Dump("nonstatic", defn) 146 } 147 *out = append(*out, defn) 148 defn.SetInitorder(InitDone) 149 } 150 } 151 152 last := len(initlist) - 1 153 if initlist[last] != n { 154 Fatalf("bad initlist %v", initlist) 155 } 156 initlist[last] = nil // allow GC 157 initlist = initlist[:last] 158 159 n.SetInitorder(InitDone) 160 } 161 162 // foundinitloop prints an init loop error and exits. 163 func foundinitloop(node, visited *Node) { 164 // If there have already been errors printed, 165 // those errors probably confused us and 166 // there might not be a loop. Let the user 167 // fix those first. 168 flusherrors() 169 if nerrors > 0 { 170 errorexit() 171 } 172 173 // Find the index of node and visited in the initlist. 174 var nodeindex, visitedindex int 175 for ; initlist[nodeindex] != node; nodeindex++ { 176 } 177 for ; initlist[visitedindex] != visited; visitedindex++ { 178 } 179 180 // There is a loop involving visited. We know about node and 181 // initlist = n1 <- ... <- visited <- ... <- node <- ... 182 fmt.Printf("%v: initialization loop:\n", visited.Line()) 183 184 // Print visited -> ... -> n1 -> node. 185 for _, n := range initlist[visitedindex:] { 186 fmt.Printf("\t%v %v refers to\n", n.Line(), n.Sym) 187 } 188 189 // Print node -> ... -> visited. 190 for _, n := range initlist[nodeindex:visitedindex] { 191 fmt.Printf("\t%v %v refers to\n", n.Line(), n.Sym) 192 } 193 194 fmt.Printf("\t%v %v\n", visited.Line(), visited.Sym) 195 errorexit() 196 } 197 198 // recurse over n, doing init1 everywhere. 199 func init2(n *Node, out *[]*Node) { 200 if n == nil || n.Initorder() == InitDone { 201 return 202 } 203 204 if n.Op == ONAME && n.Ninit.Len() != 0 { 205 Fatalf("name %v with ninit: %+v\n", n.Sym, n) 206 } 207 208 init1(n, out) 209 init2(n.Left, out) 210 init2(n.Right, out) 211 init2list(n.Ninit, out) 212 init2list(n.List, out) 213 init2list(n.Rlist, out) 214 init2list(n.Nbody, out) 215 216 switch n.Op { 217 case OCLOSURE: 218 init2list(n.Func.Closure.Nbody, out) 219 case ODOTMETH, OCALLPART: 220 init2(asNode(n.Type.FuncType().Nname), out) 221 } 222 } 223 224 func init2list(l Nodes, out *[]*Node) { 225 for _, n := range l.Slice() { 226 init2(n, out) 227 } 228 } 229 230 func initreorder(l []*Node, out *[]*Node) { 231 for _, n := range l { 232 switch n.Op { 233 case ODCLFUNC, ODCLCONST, ODCLTYPE: 234 continue 235 } 236 237 initreorder(n.Ninit.Slice(), out) 238 n.Ninit.Set(nil) 239 init1(n, out) 240 } 241 } 242 243 // initfix computes initialization order for a list l of top-level 244 // declarations and outputs the corresponding list of statements 245 // to include in the init() function body. 246 func initfix(l []*Node) []*Node { 247 var lout []*Node 248 initplans = make(map[*Node]*InitPlan) 249 lno := lineno 250 initreorder(l, &lout) 251 lineno = lno 252 initplans = nil 253 return lout 254 } 255 256 // compilation of top-level (static) assignments 257 // into DATA statements if at all possible. 258 func staticinit(n *Node, out *[]*Node) bool { 259 if n.Op != ONAME || n.Class() != PEXTERN || n.Name.Defn == nil || n.Name.Defn.Op != OAS { 260 Fatalf("staticinit") 261 } 262 263 lineno = n.Pos 264 l := n.Name.Defn.Left 265 r := n.Name.Defn.Right 266 return staticassign(l, r, out) 267 } 268 269 // like staticassign but we are copying an already 270 // initialized value r. 271 func staticcopy(l *Node, r *Node, out *[]*Node) bool { 272 if r.Op != ONAME { 273 return false 274 } 275 if r.Class() == PFUNC { 276 gdata(l, r, Widthptr) 277 return true 278 } 279 if r.Class() != PEXTERN || r.Sym.Pkg != localpkg { 280 return false 281 } 282 if r.Name.Defn == nil { // probably zeroed but perhaps supplied externally and of unknown value 283 return false 284 } 285 if r.Name.Defn.Op != OAS { 286 return false 287 } 288 orig := r 289 r = r.Name.Defn.Right 290 291 for r.Op == OCONVNOP && !types.Identical(r.Type, l.Type) { 292 r = r.Left 293 } 294 295 switch r.Op { 296 case ONAME: 297 if staticcopy(l, r, out) { 298 return true 299 } 300 // We may have skipped past one or more OCONVNOPs, so 301 // use conv to ensure r is assignable to l (#13263). 302 *out = append(*out, nod(OAS, l, conv(r, l.Type))) 303 return true 304 305 case OLITERAL: 306 if isZero(r) { 307 return true 308 } 309 gdata(l, r, int(l.Type.Width)) 310 return true 311 312 case OADDR: 313 switch r.Left.Op { 314 case ONAME: 315 gdata(l, r, int(l.Type.Width)) 316 return true 317 } 318 319 case OPTRLIT: 320 switch r.Left.Op { 321 case OARRAYLIT, OSLICELIT, OSTRUCTLIT, OMAPLIT: 322 // copy pointer 323 gdata(l, nod(OADDR, inittemps[r], nil), int(l.Type.Width)) 324 return true 325 } 326 327 case OSLICELIT: 328 // copy slice 329 a := inittemps[r] 330 331 n := l.copy() 332 n.Xoffset = l.Xoffset + int64(array_array) 333 gdata(n, nod(OADDR, a, nil), Widthptr) 334 n.Xoffset = l.Xoffset + int64(array_nel) 335 gdata(n, r.Right, Widthptr) 336 n.Xoffset = l.Xoffset + int64(array_cap) 337 gdata(n, r.Right, Widthptr) 338 return true 339 340 case OARRAYLIT, OSTRUCTLIT: 341 p := initplans[r] 342 343 n := l.copy() 344 for i := range p.E { 345 e := &p.E[i] 346 n.Xoffset = l.Xoffset + e.Xoffset 347 n.Type = e.Expr.Type 348 if e.Expr.Op == OLITERAL { 349 gdata(n, e.Expr, int(n.Type.Width)) 350 continue 351 } 352 ll := n.sepcopy() 353 if staticcopy(ll, e.Expr, out) { 354 continue 355 } 356 // Requires computation, but we're 357 // copying someone else's computation. 358 rr := orig.sepcopy() 359 rr.Type = ll.Type 360 rr.Xoffset += e.Xoffset 361 setlineno(rr) 362 *out = append(*out, nod(OAS, ll, rr)) 363 } 364 365 return true 366 } 367 368 return false 369 } 370 371 func staticassign(l *Node, r *Node, out *[]*Node) bool { 372 for r.Op == OCONVNOP { 373 r = r.Left 374 } 375 376 switch r.Op { 377 case ONAME: 378 return staticcopy(l, r, out) 379 380 case OLITERAL: 381 if isZero(r) { 382 return true 383 } 384 gdata(l, r, int(l.Type.Width)) 385 return true 386 387 case OADDR: 388 var nam Node 389 if stataddr(&nam, r.Left) { 390 n := *r 391 n.Left = &nam 392 gdata(l, &n, int(l.Type.Width)) 393 return true 394 } 395 fallthrough 396 397 case OPTRLIT: 398 switch r.Left.Op { 399 case OARRAYLIT, OSLICELIT, OMAPLIT, OSTRUCTLIT: 400 // Init pointer. 401 a := staticname(r.Left.Type) 402 403 inittemps[r] = a 404 gdata(l, nod(OADDR, a, nil), int(l.Type.Width)) 405 406 // Init underlying literal. 407 if !staticassign(a, r.Left, out) { 408 *out = append(*out, nod(OAS, a, r.Left)) 409 } 410 return true 411 } 412 //dump("not static ptrlit", r); 413 414 case OSTR2BYTES: 415 if l.Class() == PEXTERN && r.Left.Op == OLITERAL { 416 sval := r.Left.Val().U.(string) 417 slicebytes(l, sval, len(sval)) 418 return true 419 } 420 421 case OSLICELIT: 422 initplan(r) 423 // Init slice. 424 bound := r.Right.Int64() 425 ta := types.NewArray(r.Type.Elem(), bound) 426 a := staticname(ta) 427 inittemps[r] = a 428 n := l.copy() 429 n.Xoffset = l.Xoffset + int64(array_array) 430 gdata(n, nod(OADDR, a, nil), Widthptr) 431 n.Xoffset = l.Xoffset + int64(array_nel) 432 gdata(n, r.Right, Widthptr) 433 n.Xoffset = l.Xoffset + int64(array_cap) 434 gdata(n, r.Right, Widthptr) 435 436 // Fall through to init underlying array. 437 l = a 438 fallthrough 439 440 case OARRAYLIT, OSTRUCTLIT: 441 initplan(r) 442 443 p := initplans[r] 444 n := l.copy() 445 for i := range p.E { 446 e := &p.E[i] 447 n.Xoffset = l.Xoffset + e.Xoffset 448 n.Type = e.Expr.Type 449 if e.Expr.Op == OLITERAL { 450 gdata(n, e.Expr, int(n.Type.Width)) 451 continue 452 } 453 setlineno(e.Expr) 454 a := n.sepcopy() 455 if !staticassign(a, e.Expr, out) { 456 *out = append(*out, nod(OAS, a, e.Expr)) 457 } 458 } 459 460 return true 461 462 case OMAPLIT: 463 break 464 465 case OCLOSURE: 466 if hasemptycvars(r) { 467 if Debug_closure > 0 { 468 Warnl(r.Pos, "closure converted to global") 469 } 470 // Closures with no captured variables are globals, 471 // so the assignment can be done at link time. 472 gdata(l, r.Func.Closure.Func.Nname, Widthptr) 473 return true 474 } 475 closuredebugruntimecheck(r) 476 477 case OCONVIFACE: 478 // This logic is mirrored in isStaticCompositeLiteral. 479 // If you change something here, change it there, and vice versa. 480 481 // Determine the underlying concrete type and value we are converting from. 482 val := r 483 for val.Op == OCONVIFACE { 484 val = val.Left 485 } 486 if val.Type.IsInterface() { 487 // val is an interface type. 488 // If val is nil, we can statically initialize l; 489 // both words are zero and so there no work to do, so report success. 490 // If val is non-nil, we have no concrete type to record, 491 // and we won't be able to statically initialize its value, so report failure. 492 return Isconst(val, CTNIL) 493 } 494 495 var itab *Node 496 if l.Type.IsEmptyInterface() { 497 itab = typename(val.Type) 498 } else { 499 itab = itabname(val.Type, l.Type) 500 } 501 502 // Create a copy of l to modify while we emit data. 503 n := l.copy() 504 505 // Emit itab, advance offset. 506 gdata(n, itab, Widthptr) 507 n.Xoffset += int64(Widthptr) 508 509 // Emit data. 510 if isdirectiface(val.Type) { 511 if Isconst(val, CTNIL) { 512 // Nil is zero, nothing to do. 513 return true 514 } 515 // Copy val directly into n. 516 n.Type = val.Type 517 setlineno(val) 518 a := n.sepcopy() 519 if !staticassign(a, val, out) { 520 *out = append(*out, nod(OAS, a, val)) 521 } 522 } else { 523 // Construct temp to hold val, write pointer to temp into n. 524 a := staticname(val.Type) 525 inittemps[val] = a 526 if !staticassign(a, val, out) { 527 *out = append(*out, nod(OAS, a, val)) 528 } 529 ptr := nod(OADDR, a, nil) 530 n.Type = types.NewPtr(val.Type) 531 gdata(n, ptr, Widthptr) 532 } 533 534 return true 535 } 536 537 //dump("not static", r); 538 return false 539 } 540 541 // initContext is the context in which static data is populated. 542 // It is either in an init function or in any other function. 543 // Static data populated in an init function will be written either 544 // zero times (as a readonly, static data symbol) or 545 // one time (during init function execution). 546 // Either way, there is no opportunity for races or further modification, 547 // so the data can be written to a (possibly readonly) data symbol. 548 // Static data populated in any other function needs to be local to 549 // that function to allow multiple instances of that function 550 // to execute concurrently without clobbering each others' data. 551 type initContext uint8 552 553 const ( 554 inInitFunction initContext = iota 555 inNonInitFunction 556 ) 557 558 // from here down is the walk analysis 559 // of composite literals. 560 // most of the work is to generate 561 // data statements for the constant 562 // part of the composite literal. 563 564 var statuniqgen int // name generator for static temps 565 566 // staticname returns a name backed by a static data symbol. 567 // Callers should call n.Name.SetReadonly(true) on the 568 // returned node for readonly nodes. 569 func staticname(t *types.Type) *Node { 570 // Don't use lookupN; it interns the resulting string, but these are all unique. 571 n := newname(lookup(fmt.Sprintf("statictmp_%d", statuniqgen))) 572 statuniqgen++ 573 addvar(n, t, PEXTERN) 574 return n 575 } 576 577 func isLiteral(n *Node) bool { 578 // Treat nils as zeros rather than literals. 579 return n.Op == OLITERAL && n.Val().Ctype() != CTNIL 580 } 581 582 func (n *Node) isSimpleName() bool { 583 return n.Op == ONAME && n.Addable() && n.Class() != PAUTOHEAP && n.Class() != PEXTERN 584 } 585 586 func litas(l *Node, r *Node, init *Nodes) { 587 a := nod(OAS, l, r) 588 a = typecheck(a, ctxStmt) 589 a = walkexpr(a, init) 590 init.Append(a) 591 } 592 593 // initGenType is a bitmap indicating the types of generation that will occur for a static value. 594 type initGenType uint8 595 596 const ( 597 initDynamic initGenType = 1 << iota // contains some dynamic values, for which init code will be generated 598 initConst // contains some constant values, which may be written into data symbols 599 ) 600 601 // getdyn calculates the initGenType for n. 602 // If top is false, getdyn is recursing. 603 func getdyn(n *Node, top bool) initGenType { 604 switch n.Op { 605 default: 606 if isLiteral(n) { 607 return initConst 608 } 609 return initDynamic 610 611 case OSLICELIT: 612 if !top { 613 return initDynamic 614 } 615 if n.Right.Int64()/4 > int64(n.List.Len()) { 616 // <25% of entries have explicit values. 617 // Very rough estimation, it takes 4 bytes of instructions 618 // to initialize 1 byte of result. So don't use a static 619 // initializer if the dynamic initialization code would be 620 // smaller than the static value. 621 // See issue 23780. 622 return initDynamic 623 } 624 625 case OARRAYLIT, OSTRUCTLIT: 626 } 627 628 var mode initGenType 629 for _, n1 := range n.List.Slice() { 630 switch n1.Op { 631 case OKEY: 632 n1 = n1.Right 633 case OSTRUCTKEY: 634 n1 = n1.Left 635 } 636 mode |= getdyn(n1, false) 637 if mode == initDynamic|initConst { 638 break 639 } 640 } 641 return mode 642 } 643 644 // isStaticCompositeLiteral reports whether n is a compile-time constant. 645 func isStaticCompositeLiteral(n *Node) bool { 646 switch n.Op { 647 case OSLICELIT: 648 return false 649 case OARRAYLIT: 650 for _, r := range n.List.Slice() { 651 if r.Op == OKEY { 652 r = r.Right 653 } 654 if !isStaticCompositeLiteral(r) { 655 return false 656 } 657 } 658 return true 659 case OSTRUCTLIT: 660 for _, r := range n.List.Slice() { 661 if r.Op != OSTRUCTKEY { 662 Fatalf("isStaticCompositeLiteral: rhs not OSTRUCTKEY: %v", r) 663 } 664 if !isStaticCompositeLiteral(r.Left) { 665 return false 666 } 667 } 668 return true 669 case OLITERAL: 670 return true 671 case OCONVIFACE: 672 // See staticassign's OCONVIFACE case for comments. 673 val := n 674 for val.Op == OCONVIFACE { 675 val = val.Left 676 } 677 if val.Type.IsInterface() { 678 return Isconst(val, CTNIL) 679 } 680 if isdirectiface(val.Type) && Isconst(val, CTNIL) { 681 return true 682 } 683 return isStaticCompositeLiteral(val) 684 } 685 return false 686 } 687 688 // initKind is a kind of static initialization: static, dynamic, or local. 689 // Static initialization represents literals and 690 // literal components of composite literals. 691 // Dynamic initialization represents non-literals and 692 // non-literal components of composite literals. 693 // LocalCode initializion represents initialization 694 // that occurs purely in generated code local to the function of use. 695 // Initialization code is sometimes generated in passes, 696 // first static then dynamic. 697 type initKind uint8 698 699 const ( 700 initKindStatic initKind = iota + 1 701 initKindDynamic 702 initKindLocalCode 703 ) 704 705 // fixedlit handles struct, array, and slice literals. 706 // TODO: expand documentation. 707 func fixedlit(ctxt initContext, kind initKind, n *Node, var_ *Node, init *Nodes) { 708 var splitnode func(*Node) (a *Node, value *Node) 709 switch n.Op { 710 case OARRAYLIT, OSLICELIT: 711 var k int64 712 splitnode = func(r *Node) (*Node, *Node) { 713 if r.Op == OKEY { 714 k = indexconst(r.Left) 715 if k < 0 { 716 Fatalf("fixedlit: invalid index %v", r.Left) 717 } 718 r = r.Right 719 } 720 a := nod(OINDEX, var_, nodintconst(k)) 721 k++ 722 return a, r 723 } 724 case OSTRUCTLIT: 725 splitnode = func(r *Node) (*Node, *Node) { 726 if r.Op != OSTRUCTKEY { 727 Fatalf("fixedlit: rhs not OSTRUCTKEY: %v", r) 728 } 729 if r.Sym.IsBlank() { 730 return nblank, r.Left 731 } 732 return nodSym(ODOT, var_, r.Sym), r.Left 733 } 734 default: 735 Fatalf("fixedlit bad op: %v", n.Op) 736 } 737 738 for _, r := range n.List.Slice() { 739 a, value := splitnode(r) 740 741 switch value.Op { 742 case OSLICELIT: 743 if (kind == initKindStatic && ctxt == inNonInitFunction) || (kind == initKindDynamic && ctxt == inInitFunction) { 744 slicelit(ctxt, value, a, init) 745 continue 746 } 747 748 case OARRAYLIT, OSTRUCTLIT: 749 fixedlit(ctxt, kind, value, a, init) 750 continue 751 } 752 753 islit := isLiteral(value) 754 if (kind == initKindStatic && !islit) || (kind == initKindDynamic && islit) { 755 continue 756 } 757 758 // build list of assignments: var[index] = expr 759 setlineno(value) 760 a = nod(OAS, a, value) 761 a = typecheck(a, ctxStmt) 762 switch kind { 763 case initKindStatic: 764 genAsStatic(a) 765 case initKindDynamic, initKindLocalCode: 766 a = orderStmtInPlace(a, map[string][]*Node{}) 767 a = walkstmt(a) 768 init.Append(a) 769 default: 770 Fatalf("fixedlit: bad kind %d", kind) 771 } 772 773 } 774 } 775 776 func slicelit(ctxt initContext, n *Node, var_ *Node, init *Nodes) { 777 // make an array type corresponding the number of elements we have 778 t := types.NewArray(n.Type.Elem(), n.Right.Int64()) 779 dowidth(t) 780 781 if ctxt == inNonInitFunction { 782 // put everything into static array 783 vstat := staticname(t) 784 785 fixedlit(ctxt, initKindStatic, n, vstat, init) 786 fixedlit(ctxt, initKindDynamic, n, vstat, init) 787 788 // copy static to slice 789 var_ = typecheck(var_, ctxExpr|ctxAssign) 790 var nam Node 791 if !stataddr(&nam, var_) || nam.Class() != PEXTERN { 792 Fatalf("slicelit: %v", var_) 793 } 794 795 var v Node 796 v.Type = types.Types[TINT] 797 setintconst(&v, t.NumElem()) 798 799 nam.Xoffset += int64(array_array) 800 gdata(&nam, nod(OADDR, vstat, nil), Widthptr) 801 nam.Xoffset += int64(array_nel) - int64(array_array) 802 gdata(&nam, &v, Widthptr) 803 nam.Xoffset += int64(array_cap) - int64(array_nel) 804 gdata(&nam, &v, Widthptr) 805 806 return 807 } 808 809 // recipe for var = []t{...} 810 // 1. make a static array 811 // var vstat [...]t 812 // 2. assign (data statements) the constant part 813 // vstat = constpart{} 814 // 3. make an auto pointer to array and allocate heap to it 815 // var vauto *[...]t = new([...]t) 816 // 4. copy the static array to the auto array 817 // *vauto = vstat 818 // 5. for each dynamic part assign to the array 819 // vauto[i] = dynamic part 820 // 6. assign slice of allocated heap to var 821 // var = vauto[:] 822 // 823 // an optimization is done if there is no constant part 824 // 3. var vauto *[...]t = new([...]t) 825 // 5. vauto[i] = dynamic part 826 // 6. var = vauto[:] 827 828 // if the literal contains constants, 829 // make static initialized array (1),(2) 830 var vstat *Node 831 832 mode := getdyn(n, true) 833 if mode&initConst != 0 { 834 vstat = staticname(t) 835 if ctxt == inInitFunction { 836 vstat.Name.SetReadonly(true) 837 } 838 fixedlit(ctxt, initKindStatic, n, vstat, init) 839 } 840 841 // make new auto *array (3 declare) 842 vauto := temp(types.NewPtr(t)) 843 844 // set auto to point at new temp or heap (3 assign) 845 var a *Node 846 if x := prealloc[n]; x != nil { 847 // temp allocated during order.go for dddarg 848 if !types.Identical(t, x.Type) { 849 panic("dotdotdot base type does not match order's assigned type") 850 } 851 852 if vstat == nil { 853 a = nod(OAS, x, nil) 854 a = typecheck(a, ctxStmt) 855 init.Append(a) // zero new temp 856 } else { 857 // Declare that we're about to initialize all of x. 858 // (Which happens at the *vauto = vstat below.) 859 init.Append(nod(OVARDEF, x, nil)) 860 } 861 862 a = nod(OADDR, x, nil) 863 } else if n.Esc == EscNone { 864 a = temp(t) 865 if vstat == nil { 866 a = nod(OAS, temp(t), nil) 867 a = typecheck(a, ctxStmt) 868 init.Append(a) // zero new temp 869 a = a.Left 870 } else { 871 init.Append(nod(OVARDEF, a, nil)) 872 } 873 874 a = nod(OADDR, a, nil) 875 } else { 876 a = nod(ONEW, nil, nil) 877 a.List.Set1(typenod(t)) 878 } 879 880 a = nod(OAS, vauto, a) 881 a = typecheck(a, ctxStmt) 882 a = walkexpr(a, init) 883 init.Append(a) 884 885 if vstat != nil { 886 // copy static to heap (4) 887 a = nod(ODEREF, vauto, nil) 888 889 a = nod(OAS, a, vstat) 890 a = typecheck(a, ctxStmt) 891 a = walkexpr(a, init) 892 init.Append(a) 893 } 894 895 // put dynamics into array (5) 896 var index int64 897 for _, value := range n.List.Slice() { 898 if value.Op == OKEY { 899 index = indexconst(value.Left) 900 if index < 0 { 901 Fatalf("slicelit: invalid index %v", value.Left) 902 } 903 value = value.Right 904 } 905 a := nod(OINDEX, vauto, nodintconst(index)) 906 a.SetBounded(true) 907 index++ 908 909 // TODO need to check bounds? 910 911 switch value.Op { 912 case OSLICELIT: 913 break 914 915 case OARRAYLIT, OSTRUCTLIT: 916 fixedlit(ctxt, initKindDynamic, value, a, init) 917 continue 918 } 919 920 if vstat != nil && isLiteral(value) { // already set by copy from static value 921 continue 922 } 923 924 // build list of vauto[c] = expr 925 setlineno(value) 926 a = nod(OAS, a, value) 927 928 a = typecheck(a, ctxStmt) 929 a = orderStmtInPlace(a, map[string][]*Node{}) 930 a = walkstmt(a) 931 init.Append(a) 932 } 933 934 // make slice out of heap (6) 935 a = nod(OAS, var_, nod(OSLICE, vauto, nil)) 936 937 a = typecheck(a, ctxStmt) 938 a = orderStmtInPlace(a, map[string][]*Node{}) 939 a = walkstmt(a) 940 init.Append(a) 941 } 942 943 func maplit(n *Node, m *Node, init *Nodes) { 944 // make the map var 945 a := nod(OMAKE, nil, nil) 946 a.Esc = n.Esc 947 a.List.Set2(typenod(n.Type), nodintconst(int64(n.List.Len()))) 948 litas(m, a, init) 949 950 // Split the initializers into static and dynamic. 951 var stat, dyn []*Node 952 for _, r := range n.List.Slice() { 953 if r.Op != OKEY { 954 Fatalf("maplit: rhs not OKEY: %v", r) 955 } 956 if isStaticCompositeLiteral(r.Left) && isStaticCompositeLiteral(r.Right) { 957 stat = append(stat, r) 958 } else { 959 dyn = append(dyn, r) 960 } 961 } 962 963 // Add static entries. 964 if len(stat) > 25 { 965 // For a large number of static entries, put them in an array and loop. 966 967 // build types [count]Tindex and [count]Tvalue 968 tk := types.NewArray(n.Type.Key(), int64(len(stat))) 969 tv := types.NewArray(n.Type.Elem(), int64(len(stat))) 970 971 // TODO(josharian): suppress alg generation for these types? 972 dowidth(tk) 973 dowidth(tv) 974 975 // make and initialize static arrays 976 vstatk := staticname(tk) 977 vstatk.Name.SetReadonly(true) 978 vstatv := staticname(tv) 979 vstatv.Name.SetReadonly(true) 980 981 datak := nod(OARRAYLIT, nil, nil) 982 datav := nod(OARRAYLIT, nil, nil) 983 for _, r := range stat { 984 datak.List.Append(r.Left) 985 datav.List.Append(r.Right) 986 } 987 fixedlit(inInitFunction, initKindStatic, datak, vstatk, init) 988 fixedlit(inInitFunction, initKindStatic, datav, vstatv, init) 989 990 // loop adding structure elements to map 991 // for i = 0; i < len(vstatk); i++ { 992 // map[vstatk[i]] = vstatv[i] 993 // } 994 i := temp(types.Types[TINT]) 995 rhs := nod(OINDEX, vstatv, i) 996 rhs.SetBounded(true) 997 998 kidx := nod(OINDEX, vstatk, i) 999 kidx.SetBounded(true) 1000 lhs := nod(OINDEX, m, kidx) 1001 1002 zero := nod(OAS, i, nodintconst(0)) 1003 cond := nod(OLT, i, nodintconst(tk.NumElem())) 1004 incr := nod(OAS, i, nod(OADD, i, nodintconst(1))) 1005 body := nod(OAS, lhs, rhs) 1006 1007 loop := nod(OFOR, cond, incr) 1008 loop.Nbody.Set1(body) 1009 loop.Ninit.Set1(zero) 1010 1011 loop = typecheck(loop, ctxStmt) 1012 loop = walkstmt(loop) 1013 init.Append(loop) 1014 } else { 1015 // For a small number of static entries, just add them directly. 1016 addMapEntries(m, stat, init) 1017 } 1018 1019 // Add dynamic entries. 1020 addMapEntries(m, dyn, init) 1021 } 1022 1023 func addMapEntries(m *Node, dyn []*Node, init *Nodes) { 1024 if len(dyn) == 0 { 1025 return 1026 } 1027 1028 nerr := nerrors 1029 1030 // Build list of var[c] = expr. 1031 // Use temporaries so that mapassign1 can have addressable key, val. 1032 // TODO(josharian): avoid map key temporaries for mapfast_* assignments with literal keys. 1033 key := temp(m.Type.Key()) 1034 val := temp(m.Type.Elem()) 1035 1036 for _, r := range dyn { 1037 index, value := r.Left, r.Right 1038 1039 setlineno(index) 1040 a := nod(OAS, key, index) 1041 a = typecheck(a, ctxStmt) 1042 a = walkstmt(a) 1043 init.Append(a) 1044 1045 setlineno(value) 1046 a = nod(OAS, val, value) 1047 a = typecheck(a, ctxStmt) 1048 a = walkstmt(a) 1049 init.Append(a) 1050 1051 setlineno(val) 1052 a = nod(OAS, nod(OINDEX, m, key), val) 1053 a = typecheck(a, ctxStmt) 1054 a = walkstmt(a) 1055 init.Append(a) 1056 1057 if nerr != nerrors { 1058 break 1059 } 1060 } 1061 1062 a := nod(OVARKILL, key, nil) 1063 a = typecheck(a, ctxStmt) 1064 init.Append(a) 1065 a = nod(OVARKILL, val, nil) 1066 a = typecheck(a, ctxStmt) 1067 init.Append(a) 1068 } 1069 1070 func anylit(n *Node, var_ *Node, init *Nodes) { 1071 t := n.Type 1072 switch n.Op { 1073 default: 1074 Fatalf("anylit: not lit, op=%v node=%v", n.Op, n) 1075 1076 case OPTRLIT: 1077 if !t.IsPtr() { 1078 Fatalf("anylit: not ptr") 1079 } 1080 1081 var r *Node 1082 if n.Right != nil { 1083 // n.Right is stack temporary used as backing store. 1084 init.Append(nod(OAS, n.Right, nil)) // zero backing store, just in case (#18410) 1085 r = nod(OADDR, n.Right, nil) 1086 r = typecheck(r, ctxExpr) 1087 } else { 1088 r = nod(ONEW, nil, nil) 1089 r.SetTypecheck(1) 1090 r.Type = t 1091 r.Esc = n.Esc 1092 } 1093 1094 r = walkexpr(r, init) 1095 a := nod(OAS, var_, r) 1096 1097 a = typecheck(a, ctxStmt) 1098 init.Append(a) 1099 1100 var_ = nod(ODEREF, var_, nil) 1101 var_ = typecheck(var_, ctxExpr|ctxAssign) 1102 anylit(n.Left, var_, init) 1103 1104 case OSTRUCTLIT, OARRAYLIT: 1105 if !t.IsStruct() && !t.IsArray() { 1106 Fatalf("anylit: not struct/array") 1107 } 1108 1109 if var_.isSimpleName() && n.List.Len() > 4 { 1110 // lay out static data 1111 vstat := staticname(t) 1112 vstat.Name.SetReadonly(true) 1113 1114 ctxt := inInitFunction 1115 if n.Op == OARRAYLIT { 1116 ctxt = inNonInitFunction 1117 } 1118 fixedlit(ctxt, initKindStatic, n, vstat, init) 1119 1120 // copy static to var 1121 a := nod(OAS, var_, vstat) 1122 1123 a = typecheck(a, ctxStmt) 1124 a = walkexpr(a, init) 1125 init.Append(a) 1126 1127 // add expressions to automatic 1128 fixedlit(inInitFunction, initKindDynamic, n, var_, init) 1129 break 1130 } 1131 1132 var components int64 1133 if n.Op == OARRAYLIT { 1134 components = t.NumElem() 1135 } else { 1136 components = int64(t.NumFields()) 1137 } 1138 // initialization of an array or struct with unspecified components (missing fields or arrays) 1139 if var_.isSimpleName() || int64(n.List.Len()) < components { 1140 a := nod(OAS, var_, nil) 1141 a = typecheck(a, ctxStmt) 1142 a = walkexpr(a, init) 1143 init.Append(a) 1144 } 1145 1146 fixedlit(inInitFunction, initKindLocalCode, n, var_, init) 1147 1148 case OSLICELIT: 1149 slicelit(inInitFunction, n, var_, init) 1150 1151 case OMAPLIT: 1152 if !t.IsMap() { 1153 Fatalf("anylit: not map") 1154 } 1155 maplit(n, var_, init) 1156 } 1157 } 1158 1159 func oaslit(n *Node, init *Nodes) bool { 1160 if n.Left == nil || n.Right == nil { 1161 // not a special composite literal assignment 1162 return false 1163 } 1164 if n.Left.Type == nil || n.Right.Type == nil { 1165 // not a special composite literal assignment 1166 return false 1167 } 1168 if !n.Left.isSimpleName() { 1169 // not a special composite literal assignment 1170 return false 1171 } 1172 if !types.Identical(n.Left.Type, n.Right.Type) { 1173 // not a special composite literal assignment 1174 return false 1175 } 1176 1177 switch n.Right.Op { 1178 default: 1179 // not a special composite literal assignment 1180 return false 1181 1182 case OSTRUCTLIT, OARRAYLIT, OSLICELIT, OMAPLIT: 1183 if vmatch1(n.Left, n.Right) { 1184 // not a special composite literal assignment 1185 return false 1186 } 1187 anylit(n.Right, n.Left, init) 1188 } 1189 1190 n.Op = OEMPTY 1191 n.Right = nil 1192 return true 1193 } 1194 1195 func getlit(lit *Node) int { 1196 if smallintconst(lit) { 1197 return int(lit.Int64()) 1198 } 1199 return -1 1200 } 1201 1202 // stataddr sets nam to the static address of n and reports whether it succeeded. 1203 func stataddr(nam *Node, n *Node) bool { 1204 if n == nil { 1205 return false 1206 } 1207 1208 switch n.Op { 1209 case ONAME: 1210 *nam = *n 1211 return n.Addable() 1212 1213 case ODOT: 1214 if !stataddr(nam, n.Left) { 1215 break 1216 } 1217 nam.Xoffset += n.Xoffset 1218 nam.Type = n.Type 1219 return true 1220 1221 case OINDEX: 1222 if n.Left.Type.IsSlice() { 1223 break 1224 } 1225 if !stataddr(nam, n.Left) { 1226 break 1227 } 1228 l := getlit(n.Right) 1229 if l < 0 { 1230 break 1231 } 1232 1233 // Check for overflow. 1234 if n.Type.Width != 0 && thearch.MAXWIDTH/n.Type.Width <= int64(l) { 1235 break 1236 } 1237 nam.Xoffset += int64(l) * n.Type.Width 1238 nam.Type = n.Type 1239 return true 1240 } 1241 1242 return false 1243 } 1244 1245 func initplan(n *Node) { 1246 if initplans[n] != nil { 1247 return 1248 } 1249 p := new(InitPlan) 1250 initplans[n] = p 1251 switch n.Op { 1252 default: 1253 Fatalf("initplan") 1254 1255 case OARRAYLIT, OSLICELIT: 1256 var k int64 1257 for _, a := range n.List.Slice() { 1258 if a.Op == OKEY { 1259 k = indexconst(a.Left) 1260 if k < 0 { 1261 Fatalf("initplan arraylit: invalid index %v", a.Left) 1262 } 1263 a = a.Right 1264 } 1265 addvalue(p, k*n.Type.Elem().Width, a) 1266 k++ 1267 } 1268 1269 case OSTRUCTLIT: 1270 for _, a := range n.List.Slice() { 1271 if a.Op != OSTRUCTKEY { 1272 Fatalf("initplan structlit") 1273 } 1274 addvalue(p, a.Xoffset, a.Left) 1275 } 1276 1277 case OMAPLIT: 1278 for _, a := range n.List.Slice() { 1279 if a.Op != OKEY { 1280 Fatalf("initplan maplit") 1281 } 1282 addvalue(p, -1, a.Right) 1283 } 1284 } 1285 } 1286 1287 func addvalue(p *InitPlan, xoffset int64, n *Node) { 1288 // special case: zero can be dropped entirely 1289 if isZero(n) { 1290 return 1291 } 1292 1293 // special case: inline struct and array (not slice) literals 1294 if isvaluelit(n) { 1295 initplan(n) 1296 q := initplans[n] 1297 for _, qe := range q.E { 1298 // qe is a copy; we are not modifying entries in q.E 1299 qe.Xoffset += xoffset 1300 p.E = append(p.E, qe) 1301 } 1302 return 1303 } 1304 1305 // add to plan 1306 p.E = append(p.E, InitEntry{Xoffset: xoffset, Expr: n}) 1307 } 1308 1309 func isZero(n *Node) bool { 1310 switch n.Op { 1311 case OLITERAL: 1312 switch u := n.Val().U.(type) { 1313 default: 1314 Dump("unexpected literal", n) 1315 Fatalf("isZero") 1316 case *NilVal: 1317 return true 1318 case string: 1319 return u == "" 1320 case bool: 1321 return !u 1322 case *Mpint: 1323 return u.CmpInt64(0) == 0 1324 case *Mpflt: 1325 return u.CmpFloat64(0) == 0 1326 case *Mpcplx: 1327 return u.Real.CmpFloat64(0) == 0 && u.Imag.CmpFloat64(0) == 0 1328 } 1329 1330 case OARRAYLIT: 1331 for _, n1 := range n.List.Slice() { 1332 if n1.Op == OKEY { 1333 n1 = n1.Right 1334 } 1335 if !isZero(n1) { 1336 return false 1337 } 1338 } 1339 return true 1340 1341 case OSTRUCTLIT: 1342 for _, n1 := range n.List.Slice() { 1343 if !isZero(n1.Left) { 1344 return false 1345 } 1346 } 1347 return true 1348 } 1349 1350 return false 1351 } 1352 1353 func isvaluelit(n *Node) bool { 1354 return n.Op == OARRAYLIT || n.Op == OSTRUCTLIT 1355 } 1356 1357 func genAsStatic(as *Node) { 1358 if as.Left.Type == nil { 1359 Fatalf("genAsStatic as.Left not typechecked") 1360 } 1361 1362 var nam Node 1363 if !stataddr(&nam, as.Left) || (nam.Class() != PEXTERN && as.Left != nblank) { 1364 Fatalf("genAsStatic: lhs %v", as.Left) 1365 } 1366 1367 switch { 1368 case as.Right.Op == OLITERAL: 1369 case as.Right.Op == ONAME && as.Right.Class() == PFUNC: 1370 default: 1371 Fatalf("genAsStatic: rhs %v", as.Right) 1372 } 1373 1374 gdata(&nam, as.Right, int(as.Right.Type.Width)) 1375 }