Source file src/cmd/compile/internal/walk/builtin.go

     1  // Copyright 2009 The Go Authors. All rights reserved.walk/bui
     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 walk
     6  
     7  import (
     8  	"fmt"
     9  	"go/constant"
    10  	"go/token"
    11  	"internal/abi"
    12  	"internal/buildcfg"
    13  	"strings"
    14  
    15  	"cmd/compile/internal/base"
    16  	"cmd/compile/internal/escape"
    17  	"cmd/compile/internal/ir"
    18  	"cmd/compile/internal/reflectdata"
    19  	"cmd/compile/internal/typecheck"
    20  	"cmd/compile/internal/types"
    21  )
    22  
    23  // Rewrite append(src, x, y, z) so that any side effects in
    24  // x, y, z (including runtime panics) are evaluated in
    25  // initialization statements before the append.
    26  // For normal code generation, stop there and leave the
    27  // rest to ssagen.
    28  //
    29  // For race detector, expand append(src, a [, b]* ) to
    30  //
    31  //	init {
    32  //	  s := src
    33  //	  const argc = len(args) - 1
    34  //	  newLen := s.len + argc
    35  //	  if uint(newLen) <= uint(s.cap) {
    36  //	    s = s[:newLen]
    37  //	  } else {
    38  //	    s = growslice(s.ptr, newLen, s.cap, argc, elemType)
    39  //	  }
    40  //	  s[s.len - argc] = a
    41  //	  s[s.len - argc + 1] = b
    42  //	  ...
    43  //	}
    44  //	s
    45  func walkAppend(n *ir.CallExpr, init *ir.Nodes, dst ir.Node) ir.Node {
    46  	if !ir.SameSafeExpr(dst, n.Args[0]) {
    47  		n.Args[0] = safeExpr(n.Args[0], init)
    48  		n.Args[0] = walkExpr(n.Args[0], init)
    49  	}
    50  	walkExprListSafe(n.Args[1:], init)
    51  
    52  	nsrc := n.Args[0]
    53  
    54  	// walkExprListSafe will leave OINDEX (s[n]) alone if both s
    55  	// and n are name or literal, but those may index the slice we're
    56  	// modifying here. Fix explicitly.
    57  	// Using cheapExpr also makes sure that the evaluation
    58  	// of all arguments (and especially any panics) happen
    59  	// before we begin to modify the slice in a visible way.
    60  	ls := n.Args[1:]
    61  	for i, n := range ls {
    62  		n = cheapExpr(n, init)
    63  		if !types.Identical(n.Type(), nsrc.Type().Elem()) {
    64  			n = typecheck.AssignConv(n, nsrc.Type().Elem(), "append")
    65  			n = walkExpr(n, init)
    66  		}
    67  		ls[i] = n
    68  	}
    69  
    70  	argc := len(n.Args) - 1
    71  	if argc < 1 {
    72  		return nsrc
    73  	}
    74  
    75  	// General case, with no function calls left as arguments.
    76  	// Leave for ssagen, except that instrumentation requires the old form.
    77  	if !base.Flag.Cfg.Instrumenting || base.Flag.CompilingRuntime {
    78  		return n
    79  	}
    80  
    81  	var l []ir.Node
    82  
    83  	// s = slice to append to
    84  	s := typecheck.TempAt(base.Pos, ir.CurFunc, nsrc.Type())
    85  	l = append(l, ir.NewAssignStmt(base.Pos, s, nsrc))
    86  
    87  	// num = number of things to append
    88  	num := ir.NewInt(base.Pos, int64(argc))
    89  
    90  	// newLen := s.len + num
    91  	newLen := typecheck.TempAt(base.Pos, ir.CurFunc, types.Types[types.TINT])
    92  	l = append(l, ir.NewAssignStmt(base.Pos, newLen, ir.NewBinaryExpr(base.Pos, ir.OADD, ir.NewUnaryExpr(base.Pos, ir.OLEN, s), num)))
    93  
    94  	// if uint(newLen) <= uint(s.cap)
    95  	nif := ir.NewIfStmt(base.Pos, nil, nil, nil)
    96  	nif.Cond = ir.NewBinaryExpr(base.Pos, ir.OLE, typecheck.Conv(newLen, types.Types[types.TUINT]), typecheck.Conv(ir.NewUnaryExpr(base.Pos, ir.OCAP, s), types.Types[types.TUINT]))
    97  	nif.Likely = true
    98  
    99  	// then { s = s[:n] }
   100  	slice := ir.NewSliceExpr(base.Pos, ir.OSLICE, s, nil, newLen, nil)
   101  	slice.SetBounded(true)
   102  	nif.Body = []ir.Node{
   103  		ir.NewAssignStmt(base.Pos, s, slice),
   104  	}
   105  
   106  	// else { s = growslice(s.ptr, n, s.cap, a, T) }
   107  	nif.Else = []ir.Node{
   108  		ir.NewAssignStmt(base.Pos, s, walkGrowslice(s, nif.PtrInit(),
   109  			ir.NewUnaryExpr(base.Pos, ir.OSPTR, s),
   110  			newLen,
   111  			ir.NewUnaryExpr(base.Pos, ir.OCAP, s),
   112  			num)),
   113  	}
   114  
   115  	l = append(l, nif)
   116  
   117  	ls = n.Args[1:]
   118  	for i, n := range ls {
   119  		// s[s.len-argc+i] = arg
   120  		ix := ir.NewIndexExpr(base.Pos, s, ir.NewBinaryExpr(base.Pos, ir.OSUB, newLen, ir.NewInt(base.Pos, int64(argc-i))))
   121  		ix.SetBounded(true)
   122  		l = append(l, ir.NewAssignStmt(base.Pos, ix, n))
   123  	}
   124  
   125  	typecheck.Stmts(l)
   126  	walkStmtList(l)
   127  	init.Append(l...)
   128  	return s
   129  }
   130  
   131  // growslice(ptr *T, newLen, oldCap, num int, <type>) (ret []T)
   132  func walkGrowslice(slice *ir.Name, init *ir.Nodes, oldPtr, newLen, oldCap, num ir.Node) *ir.CallExpr {
   133  	elemtype := slice.Type().Elem()
   134  	fn := typecheck.LookupRuntime("growslice", elemtype, elemtype)
   135  	elemtypeptr := reflectdata.TypePtrAt(base.Pos, elemtype)
   136  	return mkcall1(fn, slice.Type(), init, oldPtr, newLen, oldCap, num, elemtypeptr)
   137  }
   138  
   139  // walkClear walks an OCLEAR node.
   140  func walkClear(n *ir.UnaryExpr) ir.Node {
   141  	typ := n.X.Type()
   142  	switch {
   143  	case typ.IsSlice():
   144  		if n := arrayClear(n.X.Pos(), n.X, nil); n != nil {
   145  			return n
   146  		}
   147  		// If n == nil, we are clearing an array which takes zero memory, do nothing.
   148  		return ir.NewBlockStmt(n.Pos(), nil)
   149  	case typ.IsMap():
   150  		return mapClear(n.X, reflectdata.TypePtrAt(n.X.Pos(), n.X.Type()))
   151  	}
   152  	panic("unreachable")
   153  }
   154  
   155  // walkClose walks an OCLOSE node.
   156  func walkClose(n *ir.UnaryExpr, init *ir.Nodes) ir.Node {
   157  	return mkcall1(chanfn("closechan", 1, n.X.Type()), nil, init, n.X)
   158  }
   159  
   160  // Lower copy(a, b) to a memmove call or a runtime call.
   161  //
   162  //	init {
   163  //	  n := len(a)
   164  //	  if n > len(b) { n = len(b) }
   165  //	  if a.ptr != b.ptr { memmove(a.ptr, b.ptr, n*sizeof(elem(a))) }
   166  //	}
   167  //	n;
   168  //
   169  // Also works if b is a string.
   170  func walkCopy(n *ir.BinaryExpr, init *ir.Nodes, runtimecall bool) ir.Node {
   171  	if n.X.Type().Elem().HasPointers() {
   172  		ir.CurFunc.SetWBPos(n.Pos())
   173  		fn := writebarrierfn("typedslicecopy", n.X.Type().Elem(), n.Y.Type().Elem())
   174  		n.X = cheapExpr(n.X, init)
   175  		ptrL, lenL := backingArrayPtrLen(n.X)
   176  		n.Y = cheapExpr(n.Y, init)
   177  		ptrR, lenR := backingArrayPtrLen(n.Y)
   178  		return mkcall1(fn, n.Type(), init, reflectdata.CopyElemRType(base.Pos, n), ptrL, lenL, ptrR, lenR)
   179  	}
   180  
   181  	if runtimecall {
   182  		// rely on runtime to instrument:
   183  		//  copy(n.Left, n.Right)
   184  		// n.Right can be a slice or string.
   185  
   186  		n.X = cheapExpr(n.X, init)
   187  		ptrL, lenL := backingArrayPtrLen(n.X)
   188  		n.Y = cheapExpr(n.Y, init)
   189  		ptrR, lenR := backingArrayPtrLen(n.Y)
   190  
   191  		fn := typecheck.LookupRuntime("slicecopy", ptrL.Type().Elem(), ptrR.Type().Elem())
   192  
   193  		return mkcall1(fn, n.Type(), init, ptrL, lenL, ptrR, lenR, ir.NewInt(base.Pos, n.X.Type().Elem().Size()))
   194  	}
   195  
   196  	n.X = walkExpr(n.X, init)
   197  	n.Y = walkExpr(n.Y, init)
   198  	nl := typecheck.TempAt(base.Pos, ir.CurFunc, n.X.Type())
   199  	nr := typecheck.TempAt(base.Pos, ir.CurFunc, n.Y.Type())
   200  	var l []ir.Node
   201  	l = append(l, ir.NewAssignStmt(base.Pos, nl, n.X))
   202  	l = append(l, ir.NewAssignStmt(base.Pos, nr, n.Y))
   203  
   204  	nfrm := ir.NewUnaryExpr(base.Pos, ir.OSPTR, nr)
   205  	nto := ir.NewUnaryExpr(base.Pos, ir.OSPTR, nl)
   206  
   207  	nlen := typecheck.TempAt(base.Pos, ir.CurFunc, types.Types[types.TINT])
   208  
   209  	// n = len(to)
   210  	l = append(l, ir.NewAssignStmt(base.Pos, nlen, ir.NewUnaryExpr(base.Pos, ir.OLEN, nl)))
   211  
   212  	// if n > len(frm) { n = len(frm) }
   213  	nif := ir.NewIfStmt(base.Pos, nil, nil, nil)
   214  
   215  	nif.Cond = ir.NewBinaryExpr(base.Pos, ir.OGT, nlen, ir.NewUnaryExpr(base.Pos, ir.OLEN, nr))
   216  	nif.Body.Append(ir.NewAssignStmt(base.Pos, nlen, ir.NewUnaryExpr(base.Pos, ir.OLEN, nr)))
   217  	l = append(l, nif)
   218  
   219  	// if to.ptr != frm.ptr { memmove( ... ) }
   220  	ne := ir.NewIfStmt(base.Pos, ir.NewBinaryExpr(base.Pos, ir.ONE, nto, nfrm), nil, nil)
   221  	ne.Likely = true
   222  	l = append(l, ne)
   223  
   224  	fn := typecheck.LookupRuntime("memmove", nl.Type().Elem(), nl.Type().Elem())
   225  	nwid := ir.Node(typecheck.TempAt(base.Pos, ir.CurFunc, types.Types[types.TUINTPTR]))
   226  	setwid := ir.NewAssignStmt(base.Pos, nwid, typecheck.Conv(nlen, types.Types[types.TUINTPTR]))
   227  	ne.Body.Append(setwid)
   228  	nwid = ir.NewBinaryExpr(base.Pos, ir.OMUL, nwid, ir.NewInt(base.Pos, nl.Type().Elem().Size()))
   229  	call := mkcall1(fn, nil, init, nto, nfrm, nwid)
   230  	ne.Body.Append(call)
   231  
   232  	typecheck.Stmts(l)
   233  	walkStmtList(l)
   234  	init.Append(l...)
   235  	return nlen
   236  }
   237  
   238  // walkDelete walks an ODELETE node.
   239  func walkDelete(init *ir.Nodes, n *ir.CallExpr) ir.Node {
   240  	init.Append(ir.TakeInit(n)...)
   241  	map_ := n.Args[0]
   242  	key := n.Args[1]
   243  	map_ = walkExpr(map_, init)
   244  	key = walkExpr(key, init)
   245  
   246  	t := map_.Type()
   247  	fast := mapfast(t)
   248  	key = mapKeyArg(fast, n, key, false)
   249  	return mkcall1(mapfndel(mapdelete[fast], t), nil, init, reflectdata.DeleteMapRType(base.Pos, n), map_, key)
   250  }
   251  
   252  // walkLenCap walks an OLEN or OCAP node.
   253  func walkLenCap(n *ir.UnaryExpr, init *ir.Nodes) ir.Node {
   254  	if isRuneCount(n) {
   255  		// Replace len([]rune(string)) with runtime.countrunes(string).
   256  		return mkcall("countrunes", n.Type(), init, typecheck.Conv(n.X.(*ir.ConvExpr).X, types.Types[types.TSTRING]))
   257  	}
   258  	if isByteCount(n) {
   259  		conv := n.X.(*ir.ConvExpr)
   260  		walkStmtList(conv.Init())
   261  		init.Append(ir.TakeInit(conv)...)
   262  		_, len := backingArrayPtrLen(cheapExpr(conv.X, init))
   263  		return len
   264  	}
   265  	if isChanLenCap(n) {
   266  		name := "chanlen"
   267  		if n.Op() == ir.OCAP {
   268  			name = "chancap"
   269  		}
   270  		// cannot use chanfn - closechan takes any, not chan any,
   271  		// because it accepts both send-only and recv-only channels.
   272  		fn := typecheck.LookupRuntime(name, n.X.Type())
   273  		return mkcall1(fn, n.Type(), init, n.X)
   274  	}
   275  
   276  	n.X = walkExpr(n.X, init)
   277  
   278  	// replace len(*[10]int) with 10.
   279  	// delayed until now to preserve side effects.
   280  	t := n.X.Type()
   281  
   282  	if t.IsPtr() {
   283  		t = t.Elem()
   284  	}
   285  	if t.IsArray() {
   286  		safeExpr(n.X, init)
   287  		con := ir.NewConstExpr(constant.MakeInt64(t.NumElem()), n)
   288  		con.SetTypecheck(1)
   289  		return con
   290  	}
   291  	return n
   292  }
   293  
   294  // walkMakeChan walks an OMAKECHAN node.
   295  func walkMakeChan(n *ir.MakeExpr, init *ir.Nodes) ir.Node {
   296  	// When size fits into int, use makechan instead of
   297  	// makechan64, which is faster and shorter on 32 bit platforms.
   298  	size := n.Len
   299  	fnname := "makechan64"
   300  	argtype := types.Types[types.TINT64]
   301  
   302  	// Type checking guarantees that TIDEAL size is positive and fits in an int.
   303  	// The case of size overflow when converting TUINT or TUINTPTR to TINT
   304  	// will be handled by the negative range checks in makechan during runtime.
   305  	if size.Type().IsKind(types.TIDEAL) || size.Type().Size() <= types.Types[types.TUINT].Size() {
   306  		fnname = "makechan"
   307  		argtype = types.Types[types.TINT]
   308  	}
   309  
   310  	return mkcall1(chanfn(fnname, 1, n.Type()), n.Type(), init, reflectdata.MakeChanRType(base.Pos, n), typecheck.Conv(size, argtype))
   311  }
   312  
   313  // walkMakeMap walks an OMAKEMAP node.
   314  func walkMakeMap(n *ir.MakeExpr, init *ir.Nodes) ir.Node {
   315  	if buildcfg.Experiment.SwissMap {
   316  		return walkMakeSwissMap(n, init)
   317  	}
   318  	return walkMakeOldMap(n, init)
   319  }
   320  
   321  func walkMakeSwissMap(n *ir.MakeExpr, init *ir.Nodes) ir.Node {
   322  	t := n.Type()
   323  	mapType := reflectdata.SwissMapType()
   324  	hint := n.Len
   325  
   326  	// var m *Map
   327  	var m ir.Node
   328  	if n.Esc() == ir.EscNone {
   329  		// Allocate hmap on stack.
   330  
   331  		// var mv Map
   332  		// m = &mv
   333  		m = stackTempAddr(init, mapType)
   334  
   335  		// Allocate one group pointed to by m.dirPtr on stack if hint
   336  		// is not larger than SwissMapGroupSlots. In case hint is
   337  		// larger, runtime.makemap will allocate on the heap.
   338  		// Maximum key and elem size is 128 bytes, larger objects
   339  		// are stored with an indirection. So max bucket size is 2048+eps.
   340  		if !ir.IsConst(hint, constant.Int) ||
   341  			constant.Compare(hint.Val(), token.LEQ, constant.MakeInt64(abi.SwissMapGroupSlots)) {
   342  
   343  			// In case hint is larger than SwissMapGroupSlots
   344  			// runtime.makemap will allocate on the heap, see
   345  			// #20184
   346  			//
   347  			// if hint <= abi.SwissMapGroupSlots {
   348  			//     var gv group
   349  			//     g = &gv
   350  			//     g.ctrl = abi.SwissMapCtrlEmpty
   351  			//     m.dirPtr = g
   352  			// }
   353  
   354  			nif := ir.NewIfStmt(base.Pos, ir.NewBinaryExpr(base.Pos, ir.OLE, hint, ir.NewInt(base.Pos, abi.SwissMapGroupSlots)), nil, nil)
   355  			nif.Likely = true
   356  
   357  			groupType := reflectdata.SwissMapGroupType(t)
   358  
   359  			// var gv group
   360  			// g = &gv
   361  			g := stackTempAddr(&nif.Body, groupType)
   362  
   363  			// Can't use ir.NewInt because bit 63 is set, which
   364  			// makes conversion to uint64 upset.
   365  			empty := ir.NewBasicLit(base.Pos, types.UntypedInt, constant.MakeUint64(abi.SwissMapCtrlEmpty))
   366  
   367  			// g.ctrl = abi.SwissMapCtrlEmpty
   368  			csym := groupType.Field(0).Sym // g.ctrl see reflectdata/map_swiss.go
   369  			ca := ir.NewAssignStmt(base.Pos, ir.NewSelectorExpr(base.Pos, ir.ODOT, g, csym), empty)
   370  			nif.Body.Append(ca)
   371  
   372  			// m.dirPtr = g
   373  			dsym := mapType.Field(2).Sym // m.dirPtr see reflectdata/map_swiss.go
   374  			na := ir.NewAssignStmt(base.Pos, ir.NewSelectorExpr(base.Pos, ir.ODOT, m, dsym), typecheck.ConvNop(g, types.Types[types.TUNSAFEPTR]))
   375  			nif.Body.Append(na)
   376  			appendWalkStmt(init, nif)
   377  		}
   378  	}
   379  
   380  	if ir.IsConst(hint, constant.Int) && constant.Compare(hint.Val(), token.LEQ, constant.MakeInt64(abi.SwissMapGroupSlots)) {
   381  		// Handling make(map[any]any) and
   382  		// make(map[any]any, hint) where hint <= abi.SwissMapGroupSlots
   383  		// specially allows for faster map initialization and
   384  		// improves binary size by using calls with fewer arguments.
   385  		// For hint <= abi.SwissMapGroupSlots no groups will be
   386  		// allocated by makemap. Therefore, no groups need to be
   387  		// allocated in this code path.
   388  		if n.Esc() == ir.EscNone {
   389  			// Only need to initialize m.seed since
   390  			// m map has been allocated on the stack already.
   391  			// m.seed = uintptr(rand())
   392  			rand := mkcall("rand", types.Types[types.TUINT64], init)
   393  			seedSym := mapType.Field(1).Sym // m.seed see reflectdata/map_swiss.go
   394  			appendWalkStmt(init, ir.NewAssignStmt(base.Pos, ir.NewSelectorExpr(base.Pos, ir.ODOT, m, seedSym), typecheck.Conv(rand, types.Types[types.TUINTPTR])))
   395  			return typecheck.ConvNop(m, t)
   396  		}
   397  		// Call runtime.makemap_small to allocate a
   398  		// map on the heap and initialize the map's seed field.
   399  		fn := typecheck.LookupRuntime("makemap_small", t.Key(), t.Elem())
   400  		return mkcall1(fn, n.Type(), init)
   401  	}
   402  
   403  	if n.Esc() != ir.EscNone {
   404  		m = typecheck.NodNil()
   405  	}
   406  
   407  	// Map initialization with a variable or large hint is
   408  	// more complicated. We therefore generate a call to
   409  	// runtime.makemap to initialize hmap and allocate the
   410  	// map buckets.
   411  
   412  	// When hint fits into int, use makemap instead of
   413  	// makemap64, which is faster and shorter on 32 bit platforms.
   414  	fnname := "makemap64"
   415  	argtype := types.Types[types.TINT64]
   416  
   417  	// Type checking guarantees that TIDEAL hint is positive and fits in an int.
   418  	// See checkmake call in TMAP case of OMAKE case in OpSwitch in typecheck1 function.
   419  	// The case of hint overflow when converting TUINT or TUINTPTR to TINT
   420  	// will be handled by the negative range checks in makemap during runtime.
   421  	if hint.Type().IsKind(types.TIDEAL) || hint.Type().Size() <= types.Types[types.TUINT].Size() {
   422  		fnname = "makemap"
   423  		argtype = types.Types[types.TINT]
   424  	}
   425  
   426  	fn := typecheck.LookupRuntime(fnname, mapType, t.Key(), t.Elem())
   427  	return mkcall1(fn, n.Type(), init, reflectdata.MakeMapRType(base.Pos, n), typecheck.Conv(hint, argtype), m)
   428  }
   429  
   430  func walkMakeOldMap(n *ir.MakeExpr, init *ir.Nodes) ir.Node {
   431  	t := n.Type()
   432  	hmapType := reflectdata.OldMapType()
   433  	hint := n.Len
   434  
   435  	// var h *hmap
   436  	var h ir.Node
   437  	if n.Esc() == ir.EscNone {
   438  		// Allocate hmap on stack.
   439  
   440  		// var hv hmap
   441  		// h = &hv
   442  		h = stackTempAddr(init, hmapType)
   443  
   444  		// Allocate one bucket pointed to by hmap.buckets on stack if hint
   445  		// is not larger than BUCKETSIZE. In case hint is larger than
   446  		// BUCKETSIZE runtime.makemap will allocate the buckets on the heap.
   447  		// Maximum key and elem size is 128 bytes, larger objects
   448  		// are stored with an indirection. So max bucket size is 2048+eps.
   449  		if !ir.IsConst(hint, constant.Int) ||
   450  			constant.Compare(hint.Val(), token.LEQ, constant.MakeInt64(abi.OldMapBucketCount)) {
   451  
   452  			// In case hint is larger than BUCKETSIZE runtime.makemap
   453  			// will allocate the buckets on the heap, see #20184
   454  			//
   455  			// if hint <= BUCKETSIZE {
   456  			//     var bv bmap
   457  			//     b = &bv
   458  			//     h.buckets = b
   459  			// }
   460  
   461  			nif := ir.NewIfStmt(base.Pos, ir.NewBinaryExpr(base.Pos, ir.OLE, hint, ir.NewInt(base.Pos, abi.OldMapBucketCount)), nil, nil)
   462  			nif.Likely = true
   463  
   464  			// var bv bmap
   465  			// b = &bv
   466  			b := stackTempAddr(&nif.Body, reflectdata.OldMapBucketType(t))
   467  
   468  			// h.buckets = b
   469  			bsym := hmapType.Field(5).Sym // hmap.buckets see reflect.go:hmap
   470  			na := ir.NewAssignStmt(base.Pos, ir.NewSelectorExpr(base.Pos, ir.ODOT, h, bsym), typecheck.ConvNop(b, types.Types[types.TUNSAFEPTR]))
   471  			nif.Body.Append(na)
   472  			appendWalkStmt(init, nif)
   473  		}
   474  	}
   475  
   476  	if ir.IsConst(hint, constant.Int) && constant.Compare(hint.Val(), token.LEQ, constant.MakeInt64(abi.OldMapBucketCount)) {
   477  		// Handling make(map[any]any) and
   478  		// make(map[any]any, hint) where hint <= BUCKETSIZE
   479  		// special allows for faster map initialization and
   480  		// improves binary size by using calls with fewer arguments.
   481  		// For hint <= BUCKETSIZE overLoadFactor(hint, 0) is false
   482  		// and no buckets will be allocated by makemap. Therefore,
   483  		// no buckets need to be allocated in this code path.
   484  		if n.Esc() == ir.EscNone {
   485  			// Only need to initialize h.hash0 since
   486  			// hmap h has been allocated on the stack already.
   487  			// h.hash0 = rand32()
   488  			rand := mkcall("rand32", types.Types[types.TUINT32], init)
   489  			hashsym := hmapType.Field(4).Sym // hmap.hash0 see reflect.go:hmap
   490  			appendWalkStmt(init, ir.NewAssignStmt(base.Pos, ir.NewSelectorExpr(base.Pos, ir.ODOT, h, hashsym), rand))
   491  			return typecheck.ConvNop(h, t)
   492  		}
   493  		// Call runtime.makemap_small to allocate an
   494  		// hmap on the heap and initialize hmap's hash0 field.
   495  		fn := typecheck.LookupRuntime("makemap_small", t.Key(), t.Elem())
   496  		return mkcall1(fn, n.Type(), init)
   497  	}
   498  
   499  	if n.Esc() != ir.EscNone {
   500  		h = typecheck.NodNil()
   501  	}
   502  	// Map initialization with a variable or large hint is
   503  	// more complicated. We therefore generate a call to
   504  	// runtime.makemap to initialize hmap and allocate the
   505  	// map buckets.
   506  
   507  	// When hint fits into int, use makemap instead of
   508  	// makemap64, which is faster and shorter on 32 bit platforms.
   509  	fnname := "makemap64"
   510  	argtype := types.Types[types.TINT64]
   511  
   512  	// Type checking guarantees that TIDEAL hint is positive and fits in an int.
   513  	// See checkmake call in TMAP case of OMAKE case in OpSwitch in typecheck1 function.
   514  	// The case of hint overflow when converting TUINT or TUINTPTR to TINT
   515  	// will be handled by the negative range checks in makemap during runtime.
   516  	if hint.Type().IsKind(types.TIDEAL) || hint.Type().Size() <= types.Types[types.TUINT].Size() {
   517  		fnname = "makemap"
   518  		argtype = types.Types[types.TINT]
   519  	}
   520  
   521  	fn := typecheck.LookupRuntime(fnname, hmapType, t.Key(), t.Elem())
   522  	return mkcall1(fn, n.Type(), init, reflectdata.MakeMapRType(base.Pos, n), typecheck.Conv(hint, argtype), h)
   523  }
   524  
   525  // walkMakeSlice walks an OMAKESLICE node.
   526  func walkMakeSlice(n *ir.MakeExpr, init *ir.Nodes) ir.Node {
   527  	l := n.Len
   528  	r := n.Cap
   529  	if r == nil {
   530  		r = safeExpr(l, init)
   531  		l = r
   532  	}
   533  	t := n.Type()
   534  	if t.Elem().NotInHeap() {
   535  		base.Errorf("%v can't be allocated in Go; it is incomplete (or unallocatable)", t.Elem())
   536  	}
   537  	if n.Esc() == ir.EscNone {
   538  		if why := escape.HeapAllocReason(n); why != "" {
   539  			base.Fatalf("%v has EscNone, but %v", n, why)
   540  		}
   541  		// var arr [r]T
   542  		// n = arr[:l]
   543  		i := typecheck.IndexConst(r)
   544  
   545  		// cap is constrained to [0,2^31) or [0,2^63) depending on whether
   546  		// we're in 32-bit or 64-bit systems. So it's safe to do:
   547  		//
   548  		// if uint64(len) > cap {
   549  		//     if len < 0 { panicmakeslicelen() }
   550  		//     panicmakeslicecap()
   551  		// }
   552  		nif := ir.NewIfStmt(base.Pos, ir.NewBinaryExpr(base.Pos, ir.OGT, typecheck.Conv(l, types.Types[types.TUINT64]), ir.NewInt(base.Pos, i)), nil, nil)
   553  		niflen := ir.NewIfStmt(base.Pos, ir.NewBinaryExpr(base.Pos, ir.OLT, l, ir.NewInt(base.Pos, 0)), nil, nil)
   554  		niflen.Body = []ir.Node{mkcall("panicmakeslicelen", nil, init)}
   555  		nif.Body.Append(niflen, mkcall("panicmakeslicecap", nil, init))
   556  		init.Append(typecheck.Stmt(nif))
   557  
   558  		t = types.NewArray(t.Elem(), i) // [r]T
   559  		var_ := typecheck.TempAt(base.Pos, ir.CurFunc, t)
   560  		appendWalkStmt(init, ir.NewAssignStmt(base.Pos, var_, nil))  // zero temp
   561  		r := ir.NewSliceExpr(base.Pos, ir.OSLICE, var_, nil, l, nil) // arr[:l]
   562  		// The conv is necessary in case n.Type is named.
   563  		return walkExpr(typecheck.Expr(typecheck.Conv(r, n.Type())), init)
   564  	}
   565  
   566  	// n escapes; set up a call to makeslice.
   567  	// When len and cap can fit into int, use makeslice instead of
   568  	// makeslice64, which is faster and shorter on 32 bit platforms.
   569  
   570  	len, cap := l, r
   571  
   572  	fnname := "makeslice64"
   573  	argtype := types.Types[types.TINT64]
   574  
   575  	// Type checking guarantees that TIDEAL len/cap are positive and fit in an int.
   576  	// The case of len or cap overflow when converting TUINT or TUINTPTR to TINT
   577  	// will be handled by the negative range checks in makeslice during runtime.
   578  	if (len.Type().IsKind(types.TIDEAL) || len.Type().Size() <= types.Types[types.TUINT].Size()) &&
   579  		(cap.Type().IsKind(types.TIDEAL) || cap.Type().Size() <= types.Types[types.TUINT].Size()) {
   580  		fnname = "makeslice"
   581  		argtype = types.Types[types.TINT]
   582  	}
   583  	fn := typecheck.LookupRuntime(fnname)
   584  	ptr := mkcall1(fn, types.Types[types.TUNSAFEPTR], init, reflectdata.MakeSliceElemRType(base.Pos, n), typecheck.Conv(len, argtype), typecheck.Conv(cap, argtype))
   585  	ptr.MarkNonNil()
   586  	len = typecheck.Conv(len, types.Types[types.TINT])
   587  	cap = typecheck.Conv(cap, types.Types[types.TINT])
   588  	sh := ir.NewSliceHeaderExpr(base.Pos, t, ptr, len, cap)
   589  	return walkExpr(typecheck.Expr(sh), init)
   590  }
   591  
   592  // walkMakeSliceCopy walks an OMAKESLICECOPY node.
   593  func walkMakeSliceCopy(n *ir.MakeExpr, init *ir.Nodes) ir.Node {
   594  	if n.Esc() == ir.EscNone {
   595  		base.Fatalf("OMAKESLICECOPY with EscNone: %v", n)
   596  	}
   597  
   598  	t := n.Type()
   599  	if t.Elem().NotInHeap() {
   600  		base.Errorf("%v can't be allocated in Go; it is incomplete (or unallocatable)", t.Elem())
   601  	}
   602  
   603  	length := typecheck.Conv(n.Len, types.Types[types.TINT])
   604  	copylen := ir.NewUnaryExpr(base.Pos, ir.OLEN, n.Cap)
   605  	copyptr := ir.NewUnaryExpr(base.Pos, ir.OSPTR, n.Cap)
   606  
   607  	if !t.Elem().HasPointers() && n.Bounded() {
   608  		// When len(to)==len(from) and elements have no pointers:
   609  		// replace make+copy with runtime.mallocgc+runtime.memmove.
   610  
   611  		// We do not check for overflow of len(to)*elem.Width here
   612  		// since len(from) is an existing checked slice capacity
   613  		// with same elem.Width for the from slice.
   614  		size := ir.NewBinaryExpr(base.Pos, ir.OMUL, typecheck.Conv(length, types.Types[types.TUINTPTR]), typecheck.Conv(ir.NewInt(base.Pos, t.Elem().Size()), types.Types[types.TUINTPTR]))
   615  
   616  		// instantiate mallocgc(size uintptr, typ *byte, needszero bool) unsafe.Pointer
   617  		fn := typecheck.LookupRuntime("mallocgc")
   618  		ptr := mkcall1(fn, types.Types[types.TUNSAFEPTR], init, size, typecheck.NodNil(), ir.NewBool(base.Pos, false))
   619  		ptr.MarkNonNil()
   620  		sh := ir.NewSliceHeaderExpr(base.Pos, t, ptr, length, length)
   621  
   622  		s := typecheck.TempAt(base.Pos, ir.CurFunc, t)
   623  		r := typecheck.Stmt(ir.NewAssignStmt(base.Pos, s, sh))
   624  		r = walkExpr(r, init)
   625  		init.Append(r)
   626  
   627  		// instantiate memmove(to *any, frm *any, size uintptr)
   628  		fn = typecheck.LookupRuntime("memmove", t.Elem(), t.Elem())
   629  		ncopy := mkcall1(fn, nil, init, ir.NewUnaryExpr(base.Pos, ir.OSPTR, s), copyptr, size)
   630  		init.Append(walkExpr(typecheck.Stmt(ncopy), init))
   631  
   632  		return s
   633  	}
   634  	// Replace make+copy with runtime.makeslicecopy.
   635  	// instantiate makeslicecopy(typ *byte, tolen int, fromlen int, from unsafe.Pointer) unsafe.Pointer
   636  	fn := typecheck.LookupRuntime("makeslicecopy")
   637  	ptr := mkcall1(fn, types.Types[types.TUNSAFEPTR], init, reflectdata.MakeSliceElemRType(base.Pos, n), length, copylen, typecheck.Conv(copyptr, types.Types[types.TUNSAFEPTR]))
   638  	ptr.MarkNonNil()
   639  	sh := ir.NewSliceHeaderExpr(base.Pos, t, ptr, length, length)
   640  	return walkExpr(typecheck.Expr(sh), init)
   641  }
   642  
   643  // walkNew walks an ONEW node.
   644  func walkNew(n *ir.UnaryExpr, init *ir.Nodes) ir.Node {
   645  	t := n.Type().Elem()
   646  	if t.NotInHeap() {
   647  		base.Errorf("%v can't be allocated in Go; it is incomplete (or unallocatable)", n.Type().Elem())
   648  	}
   649  	if n.Esc() == ir.EscNone {
   650  		if t.Size() > ir.MaxImplicitStackVarSize {
   651  			base.Fatalf("large ONEW with EscNone: %v", n)
   652  		}
   653  		return stackTempAddr(init, t)
   654  	}
   655  	types.CalcSize(t)
   656  	n.MarkNonNil()
   657  	return n
   658  }
   659  
   660  func walkMinMax(n *ir.CallExpr, init *ir.Nodes) ir.Node {
   661  	init.Append(ir.TakeInit(n)...)
   662  	walkExprList(n.Args, init)
   663  	return n
   664  }
   665  
   666  // generate code for print.
   667  func walkPrint(nn *ir.CallExpr, init *ir.Nodes) ir.Node {
   668  	// Hoist all the argument evaluation up before the lock.
   669  	walkExprListCheap(nn.Args, init)
   670  
   671  	// For println, add " " between elements and "\n" at the end.
   672  	if nn.Op() == ir.OPRINTLN {
   673  		s := nn.Args
   674  		t := make([]ir.Node, 0, len(s)*2)
   675  		for i, n := range s {
   676  			if i != 0 {
   677  				t = append(t, ir.NewString(base.Pos, " "))
   678  			}
   679  			t = append(t, n)
   680  		}
   681  		t = append(t, ir.NewString(base.Pos, "\n"))
   682  		nn.Args = t
   683  	}
   684  
   685  	// Collapse runs of constant strings.
   686  	s := nn.Args
   687  	t := make([]ir.Node, 0, len(s))
   688  	for i := 0; i < len(s); {
   689  		var strs []string
   690  		for i < len(s) && ir.IsConst(s[i], constant.String) {
   691  			strs = append(strs, ir.StringVal(s[i]))
   692  			i++
   693  		}
   694  		if len(strs) > 0 {
   695  			t = append(t, ir.NewString(base.Pos, strings.Join(strs, "")))
   696  		}
   697  		if i < len(s) {
   698  			t = append(t, s[i])
   699  			i++
   700  		}
   701  	}
   702  	nn.Args = t
   703  
   704  	calls := []ir.Node{mkcall("printlock", nil, init)}
   705  	for i, n := range nn.Args {
   706  		if n.Op() == ir.OLITERAL {
   707  			if n.Type() == types.UntypedRune {
   708  				n = typecheck.DefaultLit(n, types.RuneType)
   709  			}
   710  
   711  			switch n.Val().Kind() {
   712  			case constant.Int:
   713  				n = typecheck.DefaultLit(n, types.Types[types.TINT64])
   714  
   715  			case constant.Float:
   716  				n = typecheck.DefaultLit(n, types.Types[types.TFLOAT64])
   717  			}
   718  		}
   719  
   720  		if n.Op() != ir.OLITERAL && n.Type() != nil && n.Type().Kind() == types.TIDEAL {
   721  			n = typecheck.DefaultLit(n, types.Types[types.TINT64])
   722  		}
   723  		n = typecheck.DefaultLit(n, nil)
   724  		nn.Args[i] = n
   725  		if n.Type() == nil || n.Type().Kind() == types.TFORW {
   726  			continue
   727  		}
   728  
   729  		var on *ir.Name
   730  		switch n.Type().Kind() {
   731  		case types.TINTER:
   732  			if n.Type().IsEmptyInterface() {
   733  				on = typecheck.LookupRuntime("printeface", n.Type())
   734  			} else {
   735  				on = typecheck.LookupRuntime("printiface", n.Type())
   736  			}
   737  		case types.TPTR:
   738  			if n.Type().Elem().NotInHeap() {
   739  				on = typecheck.LookupRuntime("printuintptr")
   740  				n = ir.NewConvExpr(base.Pos, ir.OCONV, nil, n)
   741  				n.SetType(types.Types[types.TUNSAFEPTR])
   742  				n = ir.NewConvExpr(base.Pos, ir.OCONV, nil, n)
   743  				n.SetType(types.Types[types.TUINTPTR])
   744  				break
   745  			}
   746  			fallthrough
   747  		case types.TCHAN, types.TMAP, types.TFUNC, types.TUNSAFEPTR:
   748  			on = typecheck.LookupRuntime("printpointer", n.Type())
   749  		case types.TSLICE:
   750  			on = typecheck.LookupRuntime("printslice", n.Type())
   751  		case types.TUINT, types.TUINT8, types.TUINT16, types.TUINT32, types.TUINT64, types.TUINTPTR:
   752  			if types.RuntimeSymName(n.Type().Sym()) == "hex" {
   753  				on = typecheck.LookupRuntime("printhex")
   754  			} else {
   755  				on = typecheck.LookupRuntime("printuint")
   756  			}
   757  		case types.TINT, types.TINT8, types.TINT16, types.TINT32, types.TINT64:
   758  			on = typecheck.LookupRuntime("printint")
   759  		case types.TFLOAT32, types.TFLOAT64:
   760  			on = typecheck.LookupRuntime("printfloat")
   761  		case types.TCOMPLEX64, types.TCOMPLEX128:
   762  			on = typecheck.LookupRuntime("printcomplex")
   763  		case types.TBOOL:
   764  			on = typecheck.LookupRuntime("printbool")
   765  		case types.TSTRING:
   766  			cs := ""
   767  			if ir.IsConst(n, constant.String) {
   768  				cs = ir.StringVal(n)
   769  			}
   770  			switch cs {
   771  			case " ":
   772  				on = typecheck.LookupRuntime("printsp")
   773  			case "\n":
   774  				on = typecheck.LookupRuntime("printnl")
   775  			default:
   776  				on = typecheck.LookupRuntime("printstring")
   777  			}
   778  		default:
   779  			badtype(ir.OPRINT, n.Type(), nil)
   780  			continue
   781  		}
   782  
   783  		r := ir.NewCallExpr(base.Pos, ir.OCALL, on, nil)
   784  		if params := on.Type().Params(); len(params) > 0 {
   785  			t := params[0].Type
   786  			n = typecheck.Conv(n, t)
   787  			r.Args.Append(n)
   788  		}
   789  		calls = append(calls, r)
   790  	}
   791  
   792  	calls = append(calls, mkcall("printunlock", nil, init))
   793  
   794  	typecheck.Stmts(calls)
   795  	walkExprList(calls, init)
   796  
   797  	r := ir.NewBlockStmt(base.Pos, nil)
   798  	r.List = calls
   799  	return walkStmt(typecheck.Stmt(r))
   800  }
   801  
   802  // walkRecoverFP walks an ORECOVERFP node.
   803  func walkRecoverFP(nn *ir.CallExpr, init *ir.Nodes) ir.Node {
   804  	return mkcall("gorecover", nn.Type(), init, walkExpr(nn.Args[0], init))
   805  }
   806  
   807  // walkUnsafeData walks an OUNSAFESLICEDATA or OUNSAFESTRINGDATA expression.
   808  func walkUnsafeData(n *ir.UnaryExpr, init *ir.Nodes) ir.Node {
   809  	slice := walkExpr(n.X, init)
   810  	res := typecheck.Expr(ir.NewUnaryExpr(n.Pos(), ir.OSPTR, slice))
   811  	res.SetType(n.Type())
   812  	return walkExpr(res, init)
   813  }
   814  
   815  func walkUnsafeSlice(n *ir.BinaryExpr, init *ir.Nodes) ir.Node {
   816  	ptr := safeExpr(n.X, init)
   817  	len := safeExpr(n.Y, init)
   818  	sliceType := n.Type()
   819  
   820  	lenType := types.Types[types.TINT64]
   821  	unsafePtr := typecheck.Conv(ptr, types.Types[types.TUNSAFEPTR])
   822  
   823  	// If checkptr enabled, call runtime.unsafeslicecheckptr to check ptr and len.
   824  	// for simplicity, unsafeslicecheckptr always uses int64.
   825  	// Type checking guarantees that TIDEAL len/cap are positive and fit in an int.
   826  	// The case of len or cap overflow when converting TUINT or TUINTPTR to TINT
   827  	// will be handled by the negative range checks in unsafeslice during runtime.
   828  	if ir.ShouldCheckPtr(ir.CurFunc, 1) {
   829  		fnname := "unsafeslicecheckptr"
   830  		fn := typecheck.LookupRuntime(fnname)
   831  		init.Append(mkcall1(fn, nil, init, reflectdata.UnsafeSliceElemRType(base.Pos, n), unsafePtr, typecheck.Conv(len, lenType)))
   832  	} else {
   833  		// Otherwise, open code unsafe.Slice to prevent runtime call overhead.
   834  		// Keep this code in sync with runtime.unsafeslice{,64}
   835  		if len.Type().IsKind(types.TIDEAL) || len.Type().Size() <= types.Types[types.TUINT].Size() {
   836  			lenType = types.Types[types.TINT]
   837  		} else {
   838  			// len64 := int64(len)
   839  			// if int64(int(len64)) != len64 {
   840  			//     panicunsafeslicelen()
   841  			// }
   842  			len64 := typecheck.Conv(len, lenType)
   843  			nif := ir.NewIfStmt(base.Pos, nil, nil, nil)
   844  			nif.Cond = ir.NewBinaryExpr(base.Pos, ir.ONE, typecheck.Conv(typecheck.Conv(len64, types.Types[types.TINT]), lenType), len64)
   845  			nif.Body.Append(mkcall("panicunsafeslicelen", nil, &nif.Body))
   846  			appendWalkStmt(init, nif)
   847  		}
   848  
   849  		// if len < 0 { panicunsafeslicelen() }
   850  		nif := ir.NewIfStmt(base.Pos, nil, nil, nil)
   851  		nif.Cond = ir.NewBinaryExpr(base.Pos, ir.OLT, typecheck.Conv(len, lenType), ir.NewInt(base.Pos, 0))
   852  		nif.Body.Append(mkcall("panicunsafeslicelen", nil, &nif.Body))
   853  		appendWalkStmt(init, nif)
   854  
   855  		if sliceType.Elem().Size() == 0 {
   856  			// if ptr == nil && len > 0  {
   857  			//      panicunsafesliceptrnil()
   858  			// }
   859  			nifPtr := ir.NewIfStmt(base.Pos, nil, nil, nil)
   860  			isNil := ir.NewBinaryExpr(base.Pos, ir.OEQ, unsafePtr, typecheck.NodNil())
   861  			gtZero := ir.NewBinaryExpr(base.Pos, ir.OGT, typecheck.Conv(len, lenType), ir.NewInt(base.Pos, 0))
   862  			nifPtr.Cond =
   863  				ir.NewLogicalExpr(base.Pos, ir.OANDAND, isNil, gtZero)
   864  			nifPtr.Body.Append(mkcall("panicunsafeslicenilptr", nil, &nifPtr.Body))
   865  			appendWalkStmt(init, nifPtr)
   866  
   867  			h := ir.NewSliceHeaderExpr(n.Pos(), sliceType,
   868  				typecheck.Conv(ptr, types.Types[types.TUNSAFEPTR]),
   869  				typecheck.Conv(len, types.Types[types.TINT]),
   870  				typecheck.Conv(len, types.Types[types.TINT]))
   871  			return walkExpr(typecheck.Expr(h), init)
   872  		}
   873  
   874  		// mem, overflow := math.mulUintptr(et.size, len)
   875  		mem := typecheck.TempAt(base.Pos, ir.CurFunc, types.Types[types.TUINTPTR])
   876  		overflow := typecheck.TempAt(base.Pos, ir.CurFunc, types.Types[types.TBOOL])
   877  
   878  		decl := types.NewSignature(nil,
   879  			[]*types.Field{
   880  				types.NewField(base.Pos, nil, types.Types[types.TUINTPTR]),
   881  				types.NewField(base.Pos, nil, types.Types[types.TUINTPTR]),
   882  			},
   883  			[]*types.Field{
   884  				types.NewField(base.Pos, nil, types.Types[types.TUINTPTR]),
   885  				types.NewField(base.Pos, nil, types.Types[types.TBOOL]),
   886  			})
   887  
   888  		fn := ir.NewFunc(n.Pos(), n.Pos(), math_MulUintptr, decl)
   889  
   890  		call := mkcall1(fn.Nname, fn.Type().ResultsTuple(), init, ir.NewInt(base.Pos, sliceType.Elem().Size()), typecheck.Conv(typecheck.Conv(len, lenType), types.Types[types.TUINTPTR]))
   891  		appendWalkStmt(init, ir.NewAssignListStmt(base.Pos, ir.OAS2, []ir.Node{mem, overflow}, []ir.Node{call}))
   892  
   893  		// if overflow || mem > -uintptr(ptr) {
   894  		//     if ptr == nil {
   895  		//         panicunsafesliceptrnil()
   896  		//     }
   897  		//     panicunsafeslicelen()
   898  		// }
   899  		nif = ir.NewIfStmt(base.Pos, nil, nil, nil)
   900  		memCond := ir.NewBinaryExpr(base.Pos, ir.OGT, mem, ir.NewUnaryExpr(base.Pos, ir.ONEG, typecheck.Conv(unsafePtr, types.Types[types.TUINTPTR])))
   901  		nif.Cond = ir.NewLogicalExpr(base.Pos, ir.OOROR, overflow, memCond)
   902  		nifPtr := ir.NewIfStmt(base.Pos, nil, nil, nil)
   903  		nifPtr.Cond = ir.NewBinaryExpr(base.Pos, ir.OEQ, unsafePtr, typecheck.NodNil())
   904  		nifPtr.Body.Append(mkcall("panicunsafeslicenilptr", nil, &nifPtr.Body))
   905  		nif.Body.Append(nifPtr, mkcall("panicunsafeslicelen", nil, &nif.Body))
   906  		appendWalkStmt(init, nif)
   907  	}
   908  
   909  	h := ir.NewSliceHeaderExpr(n.Pos(), sliceType,
   910  		typecheck.Conv(ptr, types.Types[types.TUNSAFEPTR]),
   911  		typecheck.Conv(len, types.Types[types.TINT]),
   912  		typecheck.Conv(len, types.Types[types.TINT]))
   913  	return walkExpr(typecheck.Expr(h), init)
   914  }
   915  
   916  var math_MulUintptr = &types.Sym{Pkg: types.NewPkg("internal/runtime/math", "math"), Name: "MulUintptr"}
   917  
   918  func walkUnsafeString(n *ir.BinaryExpr, init *ir.Nodes) ir.Node {
   919  	ptr := safeExpr(n.X, init)
   920  	len := safeExpr(n.Y, init)
   921  
   922  	lenType := types.Types[types.TINT64]
   923  	unsafePtr := typecheck.Conv(ptr, types.Types[types.TUNSAFEPTR])
   924  
   925  	// If checkptr enabled, call runtime.unsafestringcheckptr to check ptr and len.
   926  	// for simplicity, unsafestringcheckptr always uses int64.
   927  	// Type checking guarantees that TIDEAL len are positive and fit in an int.
   928  	if ir.ShouldCheckPtr(ir.CurFunc, 1) {
   929  		fnname := "unsafestringcheckptr"
   930  		fn := typecheck.LookupRuntime(fnname)
   931  		init.Append(mkcall1(fn, nil, init, unsafePtr, typecheck.Conv(len, lenType)))
   932  	} else {
   933  		// Otherwise, open code unsafe.String to prevent runtime call overhead.
   934  		// Keep this code in sync with runtime.unsafestring{,64}
   935  		if len.Type().IsKind(types.TIDEAL) || len.Type().Size() <= types.Types[types.TUINT].Size() {
   936  			lenType = types.Types[types.TINT]
   937  		} else {
   938  			// len64 := int64(len)
   939  			// if int64(int(len64)) != len64 {
   940  			//     panicunsafestringlen()
   941  			// }
   942  			len64 := typecheck.Conv(len, lenType)
   943  			nif := ir.NewIfStmt(base.Pos, nil, nil, nil)
   944  			nif.Cond = ir.NewBinaryExpr(base.Pos, ir.ONE, typecheck.Conv(typecheck.Conv(len64, types.Types[types.TINT]), lenType), len64)
   945  			nif.Body.Append(mkcall("panicunsafestringlen", nil, &nif.Body))
   946  			appendWalkStmt(init, nif)
   947  		}
   948  
   949  		// if len < 0 { panicunsafestringlen() }
   950  		nif := ir.NewIfStmt(base.Pos, nil, nil, nil)
   951  		nif.Cond = ir.NewBinaryExpr(base.Pos, ir.OLT, typecheck.Conv(len, lenType), ir.NewInt(base.Pos, 0))
   952  		nif.Body.Append(mkcall("panicunsafestringlen", nil, &nif.Body))
   953  		appendWalkStmt(init, nif)
   954  
   955  		// if uintpr(len) > -uintptr(ptr) {
   956  		//    if ptr == nil {
   957  		//       panicunsafestringnilptr()
   958  		//    }
   959  		//    panicunsafeslicelen()
   960  		// }
   961  		nifLen := ir.NewIfStmt(base.Pos, nil, nil, nil)
   962  		nifLen.Cond = ir.NewBinaryExpr(base.Pos, ir.OGT, typecheck.Conv(len, types.Types[types.TUINTPTR]), ir.NewUnaryExpr(base.Pos, ir.ONEG, typecheck.Conv(unsafePtr, types.Types[types.TUINTPTR])))
   963  		nifPtr := ir.NewIfStmt(base.Pos, nil, nil, nil)
   964  		nifPtr.Cond = ir.NewBinaryExpr(base.Pos, ir.OEQ, unsafePtr, typecheck.NodNil())
   965  		nifPtr.Body.Append(mkcall("panicunsafestringnilptr", nil, &nifPtr.Body))
   966  		nifLen.Body.Append(nifPtr, mkcall("panicunsafestringlen", nil, &nifLen.Body))
   967  		appendWalkStmt(init, nifLen)
   968  	}
   969  	h := ir.NewStringHeaderExpr(n.Pos(),
   970  		typecheck.Conv(ptr, types.Types[types.TUNSAFEPTR]),
   971  		typecheck.Conv(len, types.Types[types.TINT]),
   972  	)
   973  	return walkExpr(typecheck.Expr(h), init)
   974  }
   975  
   976  func badtype(op ir.Op, tl, tr *types.Type) {
   977  	var s string
   978  	if tl != nil {
   979  		s += fmt.Sprintf("\n\t%v", tl)
   980  	}
   981  	if tr != nil {
   982  		s += fmt.Sprintf("\n\t%v", tr)
   983  	}
   984  
   985  	// common mistake: *struct and *interface.
   986  	if tl != nil && tr != nil && tl.IsPtr() && tr.IsPtr() {
   987  		if tl.Elem().IsStruct() && tr.Elem().IsInterface() {
   988  			s += "\n\t(*struct vs *interface)"
   989  		} else if tl.Elem().IsInterface() && tr.Elem().IsStruct() {
   990  			s += "\n\t(*interface vs *struct)"
   991  		}
   992  	}
   993  
   994  	base.Errorf("illegal types for operand: %v%s", op, s)
   995  }
   996  
   997  func writebarrierfn(name string, l *types.Type, r *types.Type) ir.Node {
   998  	return typecheck.LookupRuntime(name, l, r)
   999  }
  1000  
  1001  // isRuneCount reports whether n is of the form len([]rune(string)).
  1002  // These are optimized into a call to runtime.countrunes.
  1003  func isRuneCount(n ir.Node) bool {
  1004  	return base.Flag.N == 0 && !base.Flag.Cfg.Instrumenting && n.Op() == ir.OLEN && n.(*ir.UnaryExpr).X.Op() == ir.OSTR2RUNES
  1005  }
  1006  
  1007  // isByteCount reports whether n is of the form len(string([]byte)).
  1008  func isByteCount(n ir.Node) bool {
  1009  	return base.Flag.N == 0 && !base.Flag.Cfg.Instrumenting && n.Op() == ir.OLEN &&
  1010  		(n.(*ir.UnaryExpr).X.Op() == ir.OBYTES2STR || n.(*ir.UnaryExpr).X.Op() == ir.OBYTES2STRTMP)
  1011  }
  1012  
  1013  // isChanLenCap reports whether n is of the form len(c) or cap(c) for a channel c.
  1014  // Note that this does not check for -n or instrumenting because this
  1015  // is a correctness rewrite, not an optimization.
  1016  func isChanLenCap(n ir.Node) bool {
  1017  	return (n.Op() == ir.OLEN || n.Op() == ir.OCAP) && n.(*ir.UnaryExpr).X.Type().IsChan()
  1018  }
  1019  

View as plain text