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

     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 walk
     6  
     7  import (
     8  	"fmt"
     9  	"go/constant"
    10  	"internal/abi"
    11  	"internal/buildcfg"
    12  	"strings"
    13  
    14  	"cmd/compile/internal/base"
    15  	"cmd/compile/internal/ir"
    16  	"cmd/compile/internal/objw"
    17  	"cmd/compile/internal/reflectdata"
    18  	"cmd/compile/internal/rttype"
    19  	"cmd/compile/internal/staticdata"
    20  	"cmd/compile/internal/typecheck"
    21  	"cmd/compile/internal/types"
    22  	"cmd/internal/obj"
    23  	"cmd/internal/objabi"
    24  )
    25  
    26  // The result of walkExpr MUST be assigned back to n, e.g.
    27  //
    28  //	n.Left = walkExpr(n.Left, init)
    29  func walkExpr(n ir.Node, init *ir.Nodes) ir.Node {
    30  	if n == nil {
    31  		return n
    32  	}
    33  
    34  	if n, ok := n.(ir.InitNode); ok && init == n.PtrInit() {
    35  		// not okay to use n->ninit when walking n,
    36  		// because we might replace n with some other node
    37  		// and would lose the init list.
    38  		base.Fatalf("walkExpr init == &n->ninit")
    39  	}
    40  
    41  	if len(n.Init()) != 0 {
    42  		walkStmtList(n.Init())
    43  		init.Append(ir.TakeInit(n)...)
    44  	}
    45  
    46  	lno := ir.SetPos(n)
    47  
    48  	if base.Flag.LowerW > 1 {
    49  		ir.Dump("before walk expr", n)
    50  	}
    51  
    52  	if n.Typecheck() != 1 {
    53  		base.Fatalf("missed typecheck: %+v", n)
    54  	}
    55  
    56  	if n.Type().IsUntyped() {
    57  		base.Fatalf("expression has untyped type: %+v", n)
    58  	}
    59  
    60  	n = walkExpr1(n, init)
    61  
    62  	// Eagerly compute sizes of all expressions for the back end.
    63  	if typ := n.Type(); typ != nil && typ.Kind() != types.TBLANK && !typ.IsFuncArgStruct() {
    64  		types.CheckSize(typ)
    65  	}
    66  	if n, ok := n.(*ir.Name); ok && n.Heapaddr != nil {
    67  		types.CheckSize(n.Heapaddr.Type())
    68  	}
    69  	if ir.IsConst(n, constant.String) {
    70  		// Emit string symbol now to avoid emitting
    71  		// any concurrently during the backend.
    72  		_ = staticdata.StringSym(n.Pos(), constant.StringVal(n.Val()))
    73  	}
    74  
    75  	if base.Flag.LowerW != 0 && n != nil {
    76  		ir.Dump("after walk expr", n)
    77  	}
    78  
    79  	base.Pos = lno
    80  	return n
    81  }
    82  
    83  func walkExpr1(n ir.Node, init *ir.Nodes) ir.Node {
    84  	switch n.Op() {
    85  	default:
    86  		ir.Dump("walk", n)
    87  		base.Fatalf("walkExpr: switch 1 unknown op %+v", n.Op())
    88  		panic("unreachable")
    89  
    90  	case ir.OGETG, ir.OGETCALLERSP:
    91  		return n
    92  
    93  	case ir.OTYPE, ir.ONAME, ir.OLITERAL, ir.ONIL, ir.OLINKSYMOFFSET:
    94  		// TODO(mdempsky): Just return n; see discussion on CL 38655.
    95  		// Perhaps refactor to use Node.mayBeShared for these instead.
    96  		// If these return early, make sure to still call
    97  		// StringSym for constant strings.
    98  		return n
    99  
   100  	case ir.OMETHEXPR:
   101  		// TODO(mdempsky): Do this right after type checking.
   102  		n := n.(*ir.SelectorExpr)
   103  		return n.FuncName()
   104  
   105  	case ir.OMIN, ir.OMAX:
   106  		n := n.(*ir.CallExpr)
   107  		return walkMinMax(n, init)
   108  
   109  	case ir.ONOT, ir.ONEG, ir.OPLUS, ir.OBITNOT, ir.OREAL, ir.OIMAG, ir.OSPTR, ir.OITAB, ir.OIDATA:
   110  		n := n.(*ir.UnaryExpr)
   111  		n.X = walkExpr(n.X, init)
   112  		return n
   113  
   114  	case ir.ODOTMETH, ir.ODOTINTER:
   115  		n := n.(*ir.SelectorExpr)
   116  		n.X = walkExpr(n.X, init)
   117  		return n
   118  
   119  	case ir.OADDR:
   120  		n := n.(*ir.AddrExpr)
   121  		n.X = walkExpr(n.X, init)
   122  		return n
   123  
   124  	case ir.ODEREF:
   125  		n := n.(*ir.StarExpr)
   126  		n.X = walkExpr(n.X, init)
   127  		return n
   128  
   129  	case ir.OMAKEFACE, ir.OAND, ir.OANDNOT, ir.OSUB, ir.OMUL, ir.OADD, ir.OOR, ir.OXOR, ir.OLSH, ir.ORSH,
   130  		ir.OUNSAFEADD:
   131  		n := n.(*ir.BinaryExpr)
   132  		n.X = walkExpr(n.X, init)
   133  		n.Y = walkExpr(n.Y, init)
   134  		if n.Op() == ir.OUNSAFEADD && ir.ShouldCheckPtr(ir.CurFunc, 1) {
   135  			// For unsafe.Add(p, n), just walk "unsafe.Pointer(uintptr(p)+uintptr(n))"
   136  			// for the side effects of validating unsafe.Pointer rules.
   137  			x := typecheck.ConvNop(n.X, types.Types[types.TUINTPTR])
   138  			y := typecheck.Conv(n.Y, types.Types[types.TUINTPTR])
   139  			conv := typecheck.ConvNop(ir.NewBinaryExpr(n.Pos(), ir.OADD, x, y), types.Types[types.TUNSAFEPTR])
   140  			walkExpr(conv, init)
   141  		}
   142  		return n
   143  
   144  	case ir.OUNSAFESLICE:
   145  		n := n.(*ir.BinaryExpr)
   146  		return walkUnsafeSlice(n, init)
   147  
   148  	case ir.OUNSAFESTRING:
   149  		n := n.(*ir.BinaryExpr)
   150  		return walkUnsafeString(n, init)
   151  
   152  	case ir.OUNSAFESTRINGDATA, ir.OUNSAFESLICEDATA:
   153  		n := n.(*ir.UnaryExpr)
   154  		return walkUnsafeData(n, init)
   155  
   156  	case ir.ODOT, ir.ODOTPTR:
   157  		n := n.(*ir.SelectorExpr)
   158  		return walkDot(n, init)
   159  
   160  	case ir.ODOTTYPE, ir.ODOTTYPE2:
   161  		n := n.(*ir.TypeAssertExpr)
   162  		return walkDotType(n, init)
   163  
   164  	case ir.ODYNAMICDOTTYPE, ir.ODYNAMICDOTTYPE2:
   165  		n := n.(*ir.DynamicTypeAssertExpr)
   166  		return walkDynamicDotType(n, init)
   167  
   168  	case ir.OLEN, ir.OCAP:
   169  		n := n.(*ir.UnaryExpr)
   170  		return walkLenCap(n, init)
   171  
   172  	case ir.OCOMPLEX:
   173  		n := n.(*ir.BinaryExpr)
   174  		n.X = walkExpr(n.X, init)
   175  		n.Y = walkExpr(n.Y, init)
   176  		return n
   177  
   178  	case ir.OEQ, ir.ONE, ir.OLT, ir.OLE, ir.OGT, ir.OGE:
   179  		n := n.(*ir.BinaryExpr)
   180  		return walkCompare(n, init)
   181  
   182  	case ir.OANDAND, ir.OOROR:
   183  		n := n.(*ir.LogicalExpr)
   184  		return walkLogical(n, init)
   185  
   186  	case ir.OPRINT, ir.OPRINTLN:
   187  		return walkPrint(n.(*ir.CallExpr), init)
   188  
   189  	case ir.OPANIC:
   190  		n := n.(*ir.UnaryExpr)
   191  		return mkcall("gopanic", nil, init, n.X)
   192  
   193  	case ir.ORECOVER:
   194  		return walkRecover(n.(*ir.CallExpr), init)
   195  
   196  	case ir.OCFUNC:
   197  		return n
   198  
   199  	case ir.OCALLINTER, ir.OCALLFUNC:
   200  		n := n.(*ir.CallExpr)
   201  		return walkCall(n, init)
   202  
   203  	case ir.OAS, ir.OASOP:
   204  		return walkAssign(init, n)
   205  
   206  	case ir.OAS2:
   207  		n := n.(*ir.AssignListStmt)
   208  		return walkAssignList(init, n)
   209  
   210  	// a,b,... = fn()
   211  	case ir.OAS2FUNC:
   212  		n := n.(*ir.AssignListStmt)
   213  		return walkAssignFunc(init, n)
   214  
   215  	// x, y = <-c
   216  	// order.stmt made sure x is addressable or blank.
   217  	case ir.OAS2RECV:
   218  		n := n.(*ir.AssignListStmt)
   219  		return walkAssignRecv(init, n)
   220  
   221  	// a,b = m[i]
   222  	case ir.OAS2MAPR:
   223  		n := n.(*ir.AssignListStmt)
   224  		return walkAssignMapRead(init, n)
   225  
   226  	case ir.ODELETE:
   227  		n := n.(*ir.CallExpr)
   228  		return walkDelete(init, n)
   229  
   230  	case ir.OAS2DOTTYPE:
   231  		n := n.(*ir.AssignListStmt)
   232  		return walkAssignDotType(n, init)
   233  
   234  	case ir.OCONVIFACE:
   235  		n := n.(*ir.ConvExpr)
   236  		return walkConvInterface(n, init)
   237  
   238  	case ir.OCONV, ir.OCONVNOP:
   239  		n := n.(*ir.ConvExpr)
   240  		return walkConv(n, init)
   241  
   242  	case ir.OSLICE2ARR:
   243  		n := n.(*ir.ConvExpr)
   244  		return walkSliceToArray(n, init)
   245  
   246  	case ir.OSLICE2ARRPTR:
   247  		n := n.(*ir.ConvExpr)
   248  		n.X = walkExpr(n.X, init)
   249  		return n
   250  
   251  	case ir.ODIV, ir.OMOD:
   252  		n := n.(*ir.BinaryExpr)
   253  		return walkDivMod(n, init)
   254  
   255  	case ir.OINDEX:
   256  		n := n.(*ir.IndexExpr)
   257  		return walkIndex(n, init)
   258  
   259  	case ir.OINDEXMAP:
   260  		n := n.(*ir.IndexExpr)
   261  		return walkIndexMap(n, init)
   262  
   263  	case ir.ORECV:
   264  		base.Fatalf("walkExpr ORECV") // should see inside OAS only
   265  		panic("unreachable")
   266  
   267  	case ir.OSLICEHEADER:
   268  		n := n.(*ir.SliceHeaderExpr)
   269  		return walkSliceHeader(n, init)
   270  
   271  	case ir.OSTRINGHEADER:
   272  		n := n.(*ir.StringHeaderExpr)
   273  		return walkStringHeader(n, init)
   274  
   275  	case ir.OSLICE, ir.OSLICEARR, ir.OSLICESTR, ir.OSLICE3, ir.OSLICE3ARR:
   276  		n := n.(*ir.SliceExpr)
   277  		return walkSlice(n, init)
   278  
   279  	case ir.ONEW:
   280  		n := n.(*ir.UnaryExpr)
   281  		return walkNew(n, init)
   282  
   283  	case ir.OADDSTR:
   284  		return walkAddString(n.(*ir.AddStringExpr), init, nil)
   285  
   286  	case ir.OAPPEND:
   287  		// order should make sure we only see OAS(node, OAPPEND), which we handle above.
   288  		base.Fatalf("append outside assignment")
   289  		panic("unreachable")
   290  
   291  	case ir.OCOPY:
   292  		return walkCopy(n.(*ir.BinaryExpr), init, base.Flag.Cfg.Instrumenting && !base.Flag.CompilingRuntime)
   293  
   294  	case ir.OCLEAR:
   295  		n := n.(*ir.UnaryExpr)
   296  		return walkClear(n)
   297  
   298  	case ir.OCLOSE:
   299  		n := n.(*ir.UnaryExpr)
   300  		return walkClose(n, init)
   301  
   302  	case ir.OMAKECHAN:
   303  		n := n.(*ir.MakeExpr)
   304  		return walkMakeChan(n, init)
   305  
   306  	case ir.OMAKEMAP:
   307  		n := n.(*ir.MakeExpr)
   308  		return walkMakeMap(n, init)
   309  
   310  	case ir.OMAKESLICE:
   311  		n := n.(*ir.MakeExpr)
   312  		return walkMakeSlice(n, init)
   313  
   314  	case ir.OMAKESLICECOPY:
   315  		n := n.(*ir.MakeExpr)
   316  		return walkMakeSliceCopy(n, init)
   317  
   318  	case ir.ORUNESTR:
   319  		n := n.(*ir.ConvExpr)
   320  		return walkRuneToString(n, init)
   321  
   322  	case ir.OBYTES2STR, ir.ORUNES2STR:
   323  		n := n.(*ir.ConvExpr)
   324  		return walkBytesRunesToString(n, init)
   325  
   326  	case ir.OBYTES2STRTMP:
   327  		n := n.(*ir.ConvExpr)
   328  		return walkBytesToStringTemp(n, init)
   329  
   330  	case ir.OSTR2BYTES:
   331  		n := n.(*ir.ConvExpr)
   332  		return walkStringToBytes(n, init)
   333  
   334  	case ir.OSTR2BYTESTMP:
   335  		n := n.(*ir.ConvExpr)
   336  		return walkStringToBytesTemp(n, init)
   337  
   338  	case ir.OSTR2RUNES:
   339  		n := n.(*ir.ConvExpr)
   340  		return walkStringToRunes(n, init)
   341  
   342  	case ir.OARRAYLIT, ir.OSLICELIT, ir.OMAPLIT, ir.OSTRUCTLIT, ir.OPTRLIT:
   343  		return walkCompLit(n, init)
   344  
   345  	case ir.OSEND:
   346  		n := n.(*ir.SendStmt)
   347  		return walkSend(n, init)
   348  
   349  	case ir.OCLOSURE:
   350  		return walkClosure(n.(*ir.ClosureExpr), init)
   351  
   352  	case ir.OMETHVALUE:
   353  		return walkMethodValue(n.(*ir.SelectorExpr), init)
   354  	}
   355  
   356  	// No return! Each case must return (or panic),
   357  	// to avoid confusion about what gets returned
   358  	// in the presence of type assertions.
   359  }
   360  
   361  // walk the whole tree of the body of an
   362  // expression or simple statement.
   363  // the types expressions are calculated.
   364  // compile-time constants are evaluated.
   365  // complex side effects like statements are appended to init.
   366  func walkExprList(s []ir.Node, init *ir.Nodes) {
   367  	for i := range s {
   368  		s[i] = walkExpr(s[i], init)
   369  	}
   370  }
   371  
   372  func walkExprListCheap(s []ir.Node, init *ir.Nodes) {
   373  	for i, n := range s {
   374  		s[i] = cheapExpr(n, init)
   375  		s[i] = walkExpr(s[i], init)
   376  	}
   377  }
   378  
   379  func walkExprListSafe(s []ir.Node, init *ir.Nodes) {
   380  	for i, n := range s {
   381  		s[i] = safeExpr(n, init)
   382  		s[i] = walkExpr(s[i], init)
   383  	}
   384  }
   385  
   386  // return side-effect free and cheap n, appending side effects to init.
   387  // result may not be assignable.
   388  func cheapExpr(n ir.Node, init *ir.Nodes) ir.Node {
   389  	switch n.Op() {
   390  	case ir.ONAME, ir.OLITERAL, ir.ONIL:
   391  		return n
   392  	}
   393  
   394  	return copyExpr(n, n.Type(), init)
   395  }
   396  
   397  // return side effect-free n, appending side effects to init.
   398  // result is assignable if n is.
   399  func safeExpr(n ir.Node, init *ir.Nodes) ir.Node {
   400  	if n == nil {
   401  		return nil
   402  	}
   403  
   404  	if len(n.Init()) != 0 {
   405  		walkStmtList(n.Init())
   406  		init.Append(ir.TakeInit(n)...)
   407  	}
   408  
   409  	switch n.Op() {
   410  	case ir.ONAME, ir.OLITERAL, ir.ONIL, ir.OLINKSYMOFFSET:
   411  		return n
   412  
   413  	case ir.OLEN, ir.OCAP:
   414  		n := n.(*ir.UnaryExpr)
   415  		l := safeExpr(n.X, init)
   416  		if l == n.X {
   417  			return n
   418  		}
   419  		a := ir.Copy(n).(*ir.UnaryExpr)
   420  		a.X = l
   421  		return walkExpr(typecheck.Expr(a), init)
   422  
   423  	case ir.ODOT, ir.ODOTPTR:
   424  		n := n.(*ir.SelectorExpr)
   425  		l := safeExpr(n.X, init)
   426  		if l == n.X {
   427  			return n
   428  		}
   429  		a := ir.Copy(n).(*ir.SelectorExpr)
   430  		a.X = l
   431  		return walkExpr(typecheck.Expr(a), init)
   432  
   433  	case ir.ODEREF:
   434  		n := n.(*ir.StarExpr)
   435  		l := safeExpr(n.X, init)
   436  		if l == n.X {
   437  			return n
   438  		}
   439  		a := ir.Copy(n).(*ir.StarExpr)
   440  		a.X = l
   441  		return walkExpr(typecheck.Expr(a), init)
   442  
   443  	case ir.OINDEX, ir.OINDEXMAP:
   444  		n := n.(*ir.IndexExpr)
   445  		l := safeExpr(n.X, init)
   446  		r := safeExpr(n.Index, init)
   447  		if l == n.X && r == n.Index {
   448  			return n
   449  		}
   450  		a := ir.Copy(n).(*ir.IndexExpr)
   451  		a.X = l
   452  		a.Index = r
   453  		return walkExpr(typecheck.Expr(a), init)
   454  
   455  	case ir.OSTRUCTLIT, ir.OARRAYLIT, ir.OSLICELIT:
   456  		n := n.(*ir.CompLitExpr)
   457  		if isStaticCompositeLiteral(n) {
   458  			return n
   459  		}
   460  	}
   461  
   462  	// make a copy; must not be used as an lvalue
   463  	if ir.IsAddressable(n) {
   464  		base.Fatalf("missing lvalue case in safeExpr: %v", n)
   465  	}
   466  	return cheapExpr(n, init)
   467  }
   468  
   469  func copyExpr(n ir.Node, t *types.Type, init *ir.Nodes) ir.Node {
   470  	l := typecheck.TempAt(base.Pos, ir.CurFunc, t)
   471  	appendWalkStmt(init, ir.NewAssignStmt(base.Pos, l, n))
   472  	return l
   473  }
   474  
   475  // walkAddString walks a string concatenation expression x.
   476  // If conv is non nil, x is the conv.X field.
   477  func walkAddString(x *ir.AddStringExpr, init *ir.Nodes, conv *ir.ConvExpr) ir.Node {
   478  	c := len(x.List)
   479  	if c < 2 {
   480  		base.Fatalf("walkAddString count %d too small", c)
   481  	}
   482  
   483  	typ := x.Type()
   484  	if conv != nil {
   485  		typ = conv.Type()
   486  	}
   487  
   488  	// list of string arguments
   489  	var args []ir.Node
   490  
   491  	var fn, fnsmall, fnbig string
   492  
   493  	buf := typecheck.NodNil()
   494  	switch {
   495  	default:
   496  		base.FatalfAt(x.Pos(), "unexpected type: %v", typ)
   497  	case typ.IsString():
   498  		if x.Esc() == ir.EscNone {
   499  			sz := int64(0)
   500  			for _, n1 := range x.List {
   501  				if n1.Op() == ir.OLITERAL {
   502  					sz += int64(len(ir.StringVal(n1)))
   503  				}
   504  			}
   505  
   506  			// Don't allocate the buffer if the result won't fit.
   507  			if sz < tmpstringbufsize {
   508  				// Create temporary buffer for result string on stack.
   509  				buf = stackBufAddr(tmpstringbufsize, types.Types[types.TUINT8])
   510  			}
   511  		}
   512  
   513  		args = []ir.Node{buf}
   514  		fnsmall, fnbig = "concatstring%d", "concatstrings"
   515  	case typ.IsSlice() && typ.Elem().IsKind(types.TUINT8): // Optimize []byte(str1+str2+...)
   516  		if conv != nil && conv.Esc() == ir.EscNone {
   517  			buf = stackBufAddr(tmpstringbufsize, types.Types[types.TUINT8])
   518  		}
   519  		args = []ir.Node{buf}
   520  		fnsmall, fnbig = "concatbyte%d", "concatbytes"
   521  	}
   522  
   523  	if c <= 5 {
   524  		// small numbers of strings use direct runtime helpers.
   525  		// note: order.expr knows this cutoff too.
   526  		fn = fmt.Sprintf(fnsmall, c)
   527  
   528  		for _, n2 := range x.List {
   529  			args = append(args, typecheck.Conv(n2, types.Types[types.TSTRING]))
   530  		}
   531  	} else {
   532  		// large numbers of strings are passed to the runtime as a slice.
   533  		fn = fnbig
   534  		t := types.NewSlice(types.Types[types.TSTRING])
   535  
   536  		slargs := make([]ir.Node, len(x.List))
   537  		for i, n2 := range x.List {
   538  			slargs[i] = typecheck.Conv(n2, types.Types[types.TSTRING])
   539  		}
   540  		slice := ir.NewCompLitExpr(base.Pos, ir.OCOMPLIT, t, slargs)
   541  		slice.Prealloc = x.Prealloc
   542  		args = append(args, slice)
   543  		slice.SetEsc(ir.EscNone)
   544  	}
   545  
   546  	cat := typecheck.LookupRuntime(fn)
   547  	r := ir.NewCallExpr(base.Pos, ir.OCALL, cat, nil)
   548  	r.Args = args
   549  	r1 := typecheck.Expr(r)
   550  	r1 = walkExpr(r1, init)
   551  	r1.SetType(typ)
   552  
   553  	return r1
   554  }
   555  
   556  type hookInfo struct {
   557  	paramType   types.Kind
   558  	argsNum     int
   559  	runtimeFunc string
   560  }
   561  
   562  var hooks = map[string]hookInfo{
   563  	"strings.EqualFold": {paramType: types.TSTRING, argsNum: 2, runtimeFunc: "libfuzzerHookEqualFold"},
   564  }
   565  
   566  // walkCall walks an OCALLFUNC or OCALLINTER node.
   567  func walkCall(n *ir.CallExpr, init *ir.Nodes) ir.Node {
   568  	if n.Op() == ir.OCALLMETH {
   569  		base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
   570  	}
   571  	if n.Op() == ir.OCALLINTER || n.Fun.Op() == ir.OMETHEXPR {
   572  		// We expect both interface call reflect.Type.Method and concrete
   573  		// call reflect.(*rtype).Method.
   574  		usemethod(n)
   575  	}
   576  	if n.Op() == ir.OCALLINTER {
   577  		reflectdata.MarkUsedIfaceMethod(n)
   578  	}
   579  
   580  	if n.Op() == ir.OCALLFUNC && n.Fun.Op() == ir.OCLOSURE {
   581  		directClosureCall(n)
   582  	}
   583  
   584  	if ir.IsFuncPCIntrinsic(n) {
   585  		// For internal/abi.FuncPCABIxxx(fn), if fn is a defined function, rewrite
   586  		// it to the address of the function of the ABI fn is defined.
   587  		name := n.Fun.(*ir.Name).Sym().Name
   588  		arg := n.Args[0]
   589  		var wantABI obj.ABI
   590  		switch name {
   591  		case "FuncPCABI0":
   592  			wantABI = obj.ABI0
   593  		case "FuncPCABIInternal":
   594  			wantABI = obj.ABIInternal
   595  		}
   596  		if n.Type() != types.Types[types.TUINTPTR] {
   597  			base.FatalfAt(n.Pos(), "FuncPC intrinsic should return uintptr, got %v", n.Type()) // as expected by typecheck.FuncPC.
   598  		}
   599  		n := ir.FuncPC(n.Pos(), arg, wantABI)
   600  		return walkExpr(n, init)
   601  	}
   602  
   603  	if n.Op() == ir.OCALLFUNC {
   604  		fn := ir.StaticCalleeName(n.Fun)
   605  		if fn != nil && fn.Sym().Pkg.Path == "internal/abi" && strings.HasPrefix(fn.Sym().Name, "EscapeNonString[") {
   606  			// internal/abi.EscapeNonString[T] is a compiler intrinsic
   607  			// for the escape analysis to escape its argument based on
   608  			// the type. The call itself is no-op. Just walk the
   609  			// argument.
   610  			ps := fn.Type().Params()
   611  			if len(ps) == 2 && ps[1].Type.IsShape() {
   612  				return walkExpr(n.Args[1], init)
   613  			}
   614  		}
   615  	}
   616  
   617  	if name, ok := n.Fun.(*ir.Name); ok {
   618  		sym := name.Sym()
   619  		if sym.Pkg.Path == "go.runtime" && sym.Name == "deferrangefunc" {
   620  			// Call to runtime.deferrangefunc is being shared with a range-over-func
   621  			// body that might add defers to this frame, so we cannot use open-coded defers
   622  			// and we need to call deferreturn even if we don't see any other explicit defers.
   623  			ir.CurFunc.SetHasDefer(true)
   624  			ir.CurFunc.SetOpenCodedDeferDisallowed(true)
   625  		}
   626  	}
   627  
   628  	walkCall1(n, init)
   629  	return n
   630  }
   631  
   632  func walkCall1(n *ir.CallExpr, init *ir.Nodes) {
   633  	if n.Walked() {
   634  		return // already walked
   635  	}
   636  	n.SetWalked(true)
   637  
   638  	if n.Op() == ir.OCALLMETH {
   639  		base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
   640  	}
   641  
   642  	args := n.Args
   643  	params := n.Fun.Type().Params()
   644  
   645  	n.Fun = walkExpr(n.Fun, init)
   646  	walkExprList(args, init)
   647  
   648  	for i, arg := range args {
   649  		// Validate argument and parameter types match.
   650  		param := params[i]
   651  		if !types.Identical(arg.Type(), param.Type) {
   652  			base.FatalfAt(n.Pos(), "assigning %L to parameter %v (type %v)", arg, param.Sym, param.Type)
   653  		}
   654  
   655  		// For any argument whose evaluation might require a function call,
   656  		// store that argument into a temporary variable,
   657  		// to prevent that calls from clobbering arguments already on the stack.
   658  		if mayCall(arg) {
   659  			// assignment of arg to Temp
   660  			tmp := typecheck.TempAt(base.Pos, ir.CurFunc, param.Type)
   661  			init.Append(convas(typecheck.Stmt(ir.NewAssignStmt(base.Pos, tmp, arg)).(*ir.AssignStmt), init))
   662  			// replace arg with temp
   663  			args[i] = tmp
   664  		}
   665  	}
   666  
   667  	funSym := n.Fun.Sym()
   668  	if base.Debug.Libfuzzer != 0 && funSym != nil {
   669  		if hook, found := hooks[funSym.Pkg.Path+"."+funSym.Name]; found {
   670  			if len(args) != hook.argsNum {
   671  				panic(fmt.Sprintf("%s.%s expects %d arguments, but received %d", funSym.Pkg.Path, funSym.Name, hook.argsNum, len(args)))
   672  			}
   673  			var hookArgs []ir.Node
   674  			for _, arg := range args {
   675  				hookArgs = append(hookArgs, tracecmpArg(arg, types.Types[hook.paramType], init))
   676  			}
   677  			hookArgs = append(hookArgs, fakePC(n))
   678  			init.Append(mkcall(hook.runtimeFunc, nil, init, hookArgs...))
   679  		}
   680  	}
   681  }
   682  
   683  // walkDivMod walks an ODIV or OMOD node.
   684  func walkDivMod(n *ir.BinaryExpr, init *ir.Nodes) ir.Node {
   685  	n.X = walkExpr(n.X, init)
   686  	n.Y = walkExpr(n.Y, init)
   687  
   688  	// rewrite complex div into function call.
   689  	et := n.X.Type().Kind()
   690  
   691  	if types.IsComplex[et] && n.Op() == ir.ODIV {
   692  		t := n.Type()
   693  		call := mkcall("complex128div", types.Types[types.TCOMPLEX128], init, typecheck.Conv(n.X, types.Types[types.TCOMPLEX128]), typecheck.Conv(n.Y, types.Types[types.TCOMPLEX128]))
   694  		return typecheck.Conv(call, t)
   695  	}
   696  
   697  	// Nothing to do for float divisions.
   698  	if types.IsFloat[et] {
   699  		return n
   700  	}
   701  
   702  	// rewrite 64-bit div and mod on 32-bit architectures.
   703  	// TODO: Remove this code once we can introduce
   704  	// runtime calls late in SSA processing.
   705  	if types.RegSize < 8 && (et == types.TINT64 || et == types.TUINT64) {
   706  		if n.Y.Op() == ir.OLITERAL {
   707  			// Leave div/mod by non-zero uint64 constants.
   708  			// The SSA backend will handle those.
   709  			// (Zero constants should have been rejected already, but we check just in case.)
   710  			switch et {
   711  			case types.TINT64:
   712  				if ir.Int64Val(n.Y) != 0 {
   713  					return n
   714  				}
   715  			case types.TUINT64:
   716  				if ir.Uint64Val(n.Y) != 0 {
   717  					return n
   718  				}
   719  			}
   720  		}
   721  		// Build call to uint64div, uint64mod, int64div, or int64mod.
   722  		var fn string
   723  		if et == types.TINT64 {
   724  			fn = "int64"
   725  		} else {
   726  			fn = "uint64"
   727  		}
   728  		if n.Op() == ir.ODIV {
   729  			fn += "div"
   730  		} else {
   731  			fn += "mod"
   732  		}
   733  		return mkcall(fn, n.Type(), init, typecheck.Conv(n.X, types.Types[et]), typecheck.Conv(n.Y, types.Types[et]))
   734  	}
   735  	return n
   736  }
   737  
   738  // walkDot walks an ODOT or ODOTPTR node.
   739  func walkDot(n *ir.SelectorExpr, init *ir.Nodes) ir.Node {
   740  	usefield(n)
   741  	n.X = walkExpr(n.X, init)
   742  	return n
   743  }
   744  
   745  // walkDotType walks an ODOTTYPE or ODOTTYPE2 node.
   746  func walkDotType(n *ir.TypeAssertExpr, init *ir.Nodes) ir.Node {
   747  	n.X = walkExpr(n.X, init)
   748  	// Set up interface type addresses for back end.
   749  	if !n.Type().IsInterface() && !n.X.Type().IsEmptyInterface() {
   750  		n.ITab = reflectdata.ITabAddrAt(base.Pos, n.Type(), n.X.Type())
   751  	}
   752  	if n.X.Type().IsInterface() && n.Type().IsInterface() && !n.Type().IsEmptyInterface() {
   753  		// This kind of conversion needs a runtime call. Allocate
   754  		// a descriptor for that call.
   755  		n.Descriptor = makeTypeAssertDescriptor(n.Type(), n.Op() == ir.ODOTTYPE2)
   756  	}
   757  	return n
   758  }
   759  
   760  func makeTypeAssertDescriptor(target *types.Type, canFail bool) *obj.LSym {
   761  	// When converting from an interface to a non-empty interface. Needs a runtime call.
   762  	// Allocate an internal/abi.TypeAssert descriptor for that call.
   763  	lsym := types.LocalPkg.Lookup(fmt.Sprintf(".typeAssert.%d", typeAssertGen)).LinksymABI(obj.ABI0)
   764  	typeAssertGen++
   765  	c := rttype.NewCursor(lsym, 0, rttype.TypeAssert)
   766  	c.Field("Cache").WritePtr(typecheck.LookupRuntimeVar("emptyTypeAssertCache"))
   767  	c.Field("Inter").WritePtr(reflectdata.TypeLinksym(target))
   768  	c.Field("CanFail").WriteBool(canFail)
   769  	objw.Global(lsym, int32(rttype.TypeAssert.Size()), obj.LOCAL)
   770  	lsym.Gotype = reflectdata.TypeLinksym(rttype.TypeAssert)
   771  	return lsym
   772  }
   773  
   774  var typeAssertGen int
   775  
   776  // walkDynamicDotType walks an ODYNAMICDOTTYPE or ODYNAMICDOTTYPE2 node.
   777  func walkDynamicDotType(n *ir.DynamicTypeAssertExpr, init *ir.Nodes) ir.Node {
   778  	n.X = walkExpr(n.X, init)
   779  	n.RType = walkExpr(n.RType, init)
   780  	n.ITab = walkExpr(n.ITab, init)
   781  	// Convert to non-dynamic if we can.
   782  	if n.RType != nil && n.RType.Op() == ir.OADDR {
   783  		addr := n.RType.(*ir.AddrExpr)
   784  		if addr.X.Op() == ir.OLINKSYMOFFSET {
   785  			r := ir.NewTypeAssertExpr(n.Pos(), n.X, n.Type())
   786  			if n.Op() == ir.ODYNAMICDOTTYPE2 {
   787  				r.SetOp(ir.ODOTTYPE2)
   788  			}
   789  			r.SetType(n.Type())
   790  			r.SetTypecheck(1)
   791  			return walkExpr(r, init)
   792  		}
   793  	}
   794  	return n
   795  }
   796  
   797  // walkIndex walks an OINDEX node.
   798  func walkIndex(n *ir.IndexExpr, init *ir.Nodes) ir.Node {
   799  	n.X = walkExpr(n.X, init)
   800  
   801  	// save the original node for bounds checking elision.
   802  	// If it was a ODIV/OMOD walk might rewrite it.
   803  	r := n.Index
   804  
   805  	n.Index = walkExpr(n.Index, init)
   806  
   807  	// if range of type cannot exceed static array bound,
   808  	// disable bounds check.
   809  	if n.Bounded() {
   810  		return n
   811  	}
   812  	t := n.X.Type()
   813  	if t != nil && t.IsPtr() {
   814  		t = t.Elem()
   815  	}
   816  	if t.IsArray() {
   817  		n.SetBounded(bounded(r, t.NumElem()))
   818  		if base.Flag.LowerM != 0 && n.Bounded() && !ir.IsConst(n.Index, constant.Int) {
   819  			base.Warn("index bounds check elided")
   820  		}
   821  	} else if ir.IsConst(n.X, constant.String) {
   822  		n.SetBounded(bounded(r, int64(len(ir.StringVal(n.X)))))
   823  		if base.Flag.LowerM != 0 && n.Bounded() && !ir.IsConst(n.Index, constant.Int) {
   824  			base.Warn("index bounds check elided")
   825  		}
   826  	}
   827  	return n
   828  }
   829  
   830  // mapKeyArg returns an expression for key that is suitable to be passed
   831  // as the key argument for runtime map* functions.
   832  // n is the map indexing or delete Node (to provide Pos).
   833  func mapKeyArg(fast int, n, key ir.Node, assigned bool) ir.Node {
   834  	if fast == mapslow {
   835  		// standard version takes key by reference.
   836  		// orderState.expr made sure key is addressable.
   837  		return typecheck.NodAddr(key)
   838  	}
   839  	if assigned {
   840  		// mapassign does distinguish pointer vs. integer key.
   841  		return key
   842  	}
   843  	// mapaccess and mapdelete don't distinguish pointer vs. integer key.
   844  	switch fast {
   845  	case mapfast32ptr:
   846  		return ir.NewConvExpr(n.Pos(), ir.OCONVNOP, types.Types[types.TUINT32], key)
   847  	case mapfast64ptr:
   848  		return ir.NewConvExpr(n.Pos(), ir.OCONVNOP, types.Types[types.TUINT64], key)
   849  	default:
   850  		// fast version takes key by value.
   851  		return key
   852  	}
   853  }
   854  
   855  // walkIndexMap walks an OINDEXMAP node.
   856  // It replaces m[k] with *map{access1,assign}(maptype, m, &k)
   857  func walkIndexMap(n *ir.IndexExpr, init *ir.Nodes) ir.Node {
   858  	n.X = walkExpr(n.X, init)
   859  	n.Index = walkExpr(n.Index, init)
   860  	map_ := n.X
   861  	t := map_.Type()
   862  	fast := mapfast(t)
   863  	key := mapKeyArg(fast, n, n.Index, n.Assigned)
   864  	args := []ir.Node{reflectdata.IndexMapRType(base.Pos, n), map_, key}
   865  
   866  	var mapFn ir.Node
   867  	switch {
   868  	case n.Assigned:
   869  		mapFn = mapfn(mapassign[fast], t, false)
   870  	case t.Elem().Size() > abi.ZeroValSize:
   871  		args = append(args, reflectdata.ZeroAddr(t.Elem().Size()))
   872  		mapFn = mapfn("mapaccess1_fat", t, true)
   873  	default:
   874  		mapFn = mapfn(mapaccess1[fast], t, false)
   875  	}
   876  	call := mkcall1(mapFn, nil, init, args...)
   877  	call.SetType(types.NewPtr(t.Elem()))
   878  	call.MarkNonNil() // mapaccess1* and mapassign always return non-nil pointers.
   879  	star := ir.NewStarExpr(base.Pos, call)
   880  	star.SetType(t.Elem())
   881  	star.SetTypecheck(1)
   882  	return star
   883  }
   884  
   885  // walkLogical walks an OANDAND or OOROR node.
   886  func walkLogical(n *ir.LogicalExpr, init *ir.Nodes) ir.Node {
   887  	n.X = walkExpr(n.X, init)
   888  
   889  	// cannot put side effects from n.Right on init,
   890  	// because they cannot run before n.Left is checked.
   891  	// save elsewhere and store on the eventual n.Right.
   892  	var ll ir.Nodes
   893  
   894  	n.Y = walkExpr(n.Y, &ll)
   895  	n.Y = ir.InitExpr(ll, n.Y)
   896  	return n
   897  }
   898  
   899  // walkSend walks an OSEND node.
   900  func walkSend(n *ir.SendStmt, init *ir.Nodes) ir.Node {
   901  	n1 := n.Value
   902  	n1 = typecheck.AssignConv(n1, n.Chan.Type().Elem(), "chan send")
   903  	n1 = walkExpr(n1, init)
   904  	n1 = typecheck.NodAddr(n1)
   905  	return mkcall1(chanfn("chansend1", 2, n.Chan.Type()), nil, init, n.Chan, n1)
   906  }
   907  
   908  // walkSlice walks an OSLICE, OSLICEARR, OSLICESTR, OSLICE3, or OSLICE3ARR node.
   909  func walkSlice(n *ir.SliceExpr, init *ir.Nodes) ir.Node {
   910  	n.X = walkExpr(n.X, init)
   911  	n.Low = walkExpr(n.Low, init)
   912  	if n.Low != nil && ir.IsZero(n.Low) {
   913  		// Reduce x[0:j] to x[:j] and x[0:j:k] to x[:j:k].
   914  		n.Low = nil
   915  	}
   916  	n.High = walkExpr(n.High, init)
   917  	n.Max = walkExpr(n.Max, init)
   918  
   919  	if (n.Op() == ir.OSLICE || n.Op() == ir.OSLICESTR) && n.Low == nil && n.High == nil {
   920  		// Reduce x[:] to x.
   921  		if base.Debug.Slice > 0 {
   922  			base.Warn("slice: omit slice operation")
   923  		}
   924  		return n.X
   925  	}
   926  	return n
   927  }
   928  
   929  // walkSliceHeader walks an OSLICEHEADER node.
   930  func walkSliceHeader(n *ir.SliceHeaderExpr, init *ir.Nodes) ir.Node {
   931  	n.Ptr = walkExpr(n.Ptr, init)
   932  	n.Len = walkExpr(n.Len, init)
   933  	n.Cap = walkExpr(n.Cap, init)
   934  	return n
   935  }
   936  
   937  // walkStringHeader walks an OSTRINGHEADER node.
   938  func walkStringHeader(n *ir.StringHeaderExpr, init *ir.Nodes) ir.Node {
   939  	n.Ptr = walkExpr(n.Ptr, init)
   940  	n.Len = walkExpr(n.Len, init)
   941  	return n
   942  }
   943  
   944  // return 1 if integer n must be in range [0, max), 0 otherwise.
   945  func bounded(n ir.Node, max int64) bool {
   946  	if n.Type() == nil || !n.Type().IsInteger() {
   947  		return false
   948  	}
   949  
   950  	sign := n.Type().IsSigned()
   951  	bits := int32(8 * n.Type().Size())
   952  
   953  	if ir.IsSmallIntConst(n) {
   954  		v := ir.Int64Val(n)
   955  		return 0 <= v && v < max
   956  	}
   957  
   958  	switch n.Op() {
   959  	case ir.OAND, ir.OANDNOT:
   960  		n := n.(*ir.BinaryExpr)
   961  		v := int64(-1)
   962  		switch {
   963  		case ir.IsSmallIntConst(n.X):
   964  			v = ir.Int64Val(n.X)
   965  		case ir.IsSmallIntConst(n.Y):
   966  			v = ir.Int64Val(n.Y)
   967  			if n.Op() == ir.OANDNOT {
   968  				v = ^v
   969  				if !sign {
   970  					v &= 1<<uint(bits) - 1
   971  				}
   972  			}
   973  		}
   974  		if 0 <= v && v < max {
   975  			return true
   976  		}
   977  
   978  	case ir.OMOD:
   979  		n := n.(*ir.BinaryExpr)
   980  		if !sign && ir.IsSmallIntConst(n.Y) {
   981  			v := ir.Int64Val(n.Y)
   982  			if 0 <= v && v <= max {
   983  				return true
   984  			}
   985  		}
   986  
   987  	case ir.ODIV:
   988  		n := n.(*ir.BinaryExpr)
   989  		if !sign && ir.IsSmallIntConst(n.Y) {
   990  			v := ir.Int64Val(n.Y)
   991  			for bits > 0 && v >= 2 {
   992  				bits--
   993  				v >>= 1
   994  			}
   995  		}
   996  
   997  	case ir.ORSH:
   998  		n := n.(*ir.BinaryExpr)
   999  		if !sign && ir.IsSmallIntConst(n.Y) {
  1000  			v := ir.Int64Val(n.Y)
  1001  			if v > int64(bits) {
  1002  				return true
  1003  			}
  1004  			bits -= int32(v)
  1005  		}
  1006  	}
  1007  
  1008  	if !sign && bits <= 62 && 1<<uint(bits) <= max {
  1009  		return true
  1010  	}
  1011  
  1012  	return false
  1013  }
  1014  
  1015  // usemethod checks calls for uses of Method and MethodByName of reflect.Value,
  1016  // reflect.Type, reflect.(*rtype), and reflect.(*interfaceType).
  1017  func usemethod(n *ir.CallExpr) {
  1018  	// Don't mark reflect.(*rtype).Method, etc. themselves in the reflect package.
  1019  	// Those functions may be alive via the itab, which should not cause all methods
  1020  	// alive. We only want to mark their callers.
  1021  	if base.Ctxt.Pkgpath == "reflect" {
  1022  		// TODO: is there a better way than hardcoding the names?
  1023  		switch fn := ir.CurFunc.Nname.Sym().Name; {
  1024  		case fn == "(*rtype).Method", fn == "(*rtype).MethodByName":
  1025  			return
  1026  		case fn == "(*interfaceType).Method", fn == "(*interfaceType).MethodByName":
  1027  			return
  1028  		case fn == "Value.Method", fn == "Value.MethodByName":
  1029  			return
  1030  		}
  1031  	}
  1032  
  1033  	dot, ok := n.Fun.(*ir.SelectorExpr)
  1034  	if !ok {
  1035  		return
  1036  	}
  1037  
  1038  	// looking for either direct method calls and interface method calls of:
  1039  	//	reflect.Type.Method        - func(int) reflect.Method
  1040  	//	reflect.Type.MethodByName  - func(string) (reflect.Method, bool)
  1041  	//
  1042  	//	reflect.Value.Method       - func(int) reflect.Value
  1043  	//	reflect.Value.MethodByName - func(string) reflect.Value
  1044  	methodName := dot.Sel.Name
  1045  	t := dot.Selection.Type
  1046  
  1047  	// Check the number of arguments and return values.
  1048  	if t.NumParams() != 1 || (t.NumResults() != 1 && t.NumResults() != 2) {
  1049  		return
  1050  	}
  1051  
  1052  	// Check the type of the argument.
  1053  	switch pKind := t.Param(0).Type.Kind(); {
  1054  	case methodName == "Method" && pKind == types.TINT,
  1055  		methodName == "MethodByName" && pKind == types.TSTRING:
  1056  
  1057  	default:
  1058  		// not a call to Method or MethodByName of reflect.{Type,Value}.
  1059  		return
  1060  	}
  1061  
  1062  	// Check that first result type is "reflect.Method" or "reflect.Value".
  1063  	// Note that we have to check sym name and sym package separately, as
  1064  	// we can't check for exact string "reflect.Method" reliably
  1065  	// (e.g., see #19028 and #38515).
  1066  	switch s := t.Result(0).Type.Sym(); {
  1067  	case s != nil && types.ReflectSymName(s) == "Method",
  1068  		s != nil && types.ReflectSymName(s) == "Value":
  1069  
  1070  	default:
  1071  		// not a call to Method or MethodByName of reflect.{Type,Value}.
  1072  		return
  1073  	}
  1074  
  1075  	var targetName ir.Node
  1076  	switch dot.Op() {
  1077  	case ir.ODOTINTER:
  1078  		if methodName == "MethodByName" {
  1079  			targetName = n.Args[0]
  1080  		}
  1081  	case ir.OMETHEXPR:
  1082  		if methodName == "MethodByName" {
  1083  			targetName = n.Args[1]
  1084  		}
  1085  	default:
  1086  		base.FatalfAt(dot.Pos(), "usemethod: unexpected dot.Op() %s", dot.Op())
  1087  	}
  1088  
  1089  	if ir.IsConst(targetName, constant.String) {
  1090  		name := constant.StringVal(targetName.Val())
  1091  		ir.CurFunc.LSym.AddRel(base.Ctxt, obj.Reloc{
  1092  			Type: objabi.R_USENAMEDMETHOD,
  1093  			Sym:  staticdata.StringSymNoCommon(name),
  1094  		})
  1095  	} else {
  1096  		ir.CurFunc.LSym.Set(obj.AttrReflectMethod, true)
  1097  	}
  1098  }
  1099  
  1100  func usefield(n *ir.SelectorExpr) {
  1101  	if !buildcfg.Experiment.FieldTrack {
  1102  		return
  1103  	}
  1104  
  1105  	switch n.Op() {
  1106  	default:
  1107  		base.Fatalf("usefield %v", n.Op())
  1108  
  1109  	case ir.ODOT, ir.ODOTPTR:
  1110  		break
  1111  	}
  1112  
  1113  	field := n.Selection
  1114  	if field == nil {
  1115  		base.Fatalf("usefield %v %v without paramfld", n.X.Type(), n.Sel)
  1116  	}
  1117  	if field.Sym != n.Sel {
  1118  		base.Fatalf("field inconsistency: %v != %v", field.Sym, n.Sel)
  1119  	}
  1120  	if !strings.Contains(field.Note, "go:\"track\"") {
  1121  		return
  1122  	}
  1123  
  1124  	outer := n.X.Type()
  1125  	if outer.IsPtr() {
  1126  		outer = outer.Elem()
  1127  	}
  1128  	if outer.Sym() == nil {
  1129  		base.Errorf("tracked field must be in named struct type")
  1130  	}
  1131  
  1132  	sym := reflectdata.TrackSym(outer, field)
  1133  	if ir.CurFunc.FieldTrack == nil {
  1134  		ir.CurFunc.FieldTrack = make(map[*obj.LSym]struct{})
  1135  	}
  1136  	ir.CurFunc.FieldTrack[sym] = struct{}{}
  1137  }
  1138  

View as plain text