github.com/corona10/go@v0.0.0-20180224231303-7a218942be57/src/cmd/compile/internal/gc/syntax.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  // “Abstract” syntax representation.
     6  
     7  package gc
     8  
     9  import (
    10  	"cmd/compile/internal/ssa"
    11  	"cmd/compile/internal/syntax"
    12  	"cmd/compile/internal/types"
    13  	"cmd/internal/obj"
    14  	"cmd/internal/src"
    15  )
    16  
    17  // A Node is a single node in the syntax tree.
    18  // Actually the syntax tree is a syntax DAG, because there is only one
    19  // node with Op=ONAME for a given instance of a variable x.
    20  // The same is true for Op=OTYPE and Op=OLITERAL. See Node.mayBeShared.
    21  type Node struct {
    22  	// Tree structure.
    23  	// Generic recursive walks should follow these fields.
    24  	Left  *Node
    25  	Right *Node
    26  	Ninit Nodes
    27  	Nbody Nodes
    28  	List  Nodes
    29  	Rlist Nodes
    30  
    31  	// most nodes
    32  	Type *types.Type
    33  	Orig *Node // original form, for printing, and tracking copies of ONAMEs
    34  
    35  	// func
    36  	Func *Func
    37  
    38  	// ONAME, OTYPE, OPACK, OLABEL, some OLITERAL
    39  	Name *Name
    40  
    41  	Sym *types.Sym  // various
    42  	E   interface{} // Opt or Val, see methods below
    43  
    44  	// Various. Usually an offset into a struct. For example:
    45  	// - ONAME nodes that refer to local variables use it to identify their stack frame position.
    46  	// - ODOT, ODOTPTR, and OINDREGSP use it to indicate offset relative to their base address.
    47  	// - OSTRUCTKEY uses it to store the named field's offset.
    48  	// - Named OLITERALs use it to to store their ambient iota value.
    49  	// Possibly still more uses. If you find any, document them.
    50  	Xoffset int64
    51  
    52  	Pos src.XPos
    53  
    54  	flags bitset32
    55  
    56  	Esc uint16 // EscXXX
    57  
    58  	Op    Op
    59  	Etype types.EType // op for OASOP, etype for OTYPE, exclam for export, 6g saved reg, ChanDir for OTCHAN, for OINDEXMAP 1=LHS,0=RHS
    60  }
    61  
    62  func (n *Node) IsSynthetic() bool {
    63  	name := n.Sym.Name
    64  	return name[0] == '.' || name[0] == '~'
    65  }
    66  
    67  // IsAutoTmp indicates if n was created by the compiler as a temporary,
    68  // based on the setting of the .AutoTemp flag in n's Name.
    69  func (n *Node) IsAutoTmp() bool {
    70  	if n == nil || n.Op != ONAME {
    71  		return false
    72  	}
    73  	return n.Name.AutoTemp()
    74  }
    75  
    76  const (
    77  	nodeClass, _     = iota, 1 << iota // PPARAM, PAUTO, PEXTERN, etc; three bits; first in the list because frequently accessed
    78  	_, _                               // second nodeClass bit
    79  	_, _                               // third nodeClass bit
    80  	nodeWalkdef, _                     // tracks state during typecheckdef; 2 == loop detected; two bits
    81  	_, _                               // second nodeWalkdef bit
    82  	nodeTypecheck, _                   // tracks state during typechecking; 2 == loop detected; two bits
    83  	_, _                               // second nodeTypecheck bit
    84  	nodeInitorder, _                   // tracks state during init1; two bits
    85  	_, _                               // second nodeInitorder bit
    86  	_, nodeHasBreak
    87  	_, nodeIsClosureVar
    88  	_, nodeIsOutputParamHeapAddr
    89  	_, nodeNoInline  // used internally by inliner to indicate that a function call should not be inlined; set for OCALLFUNC and OCALLMETH only
    90  	_, nodeAssigned  // is the variable ever assigned to
    91  	_, nodeAddrtaken // address taken, even if not moved to heap
    92  	_, nodeImplicit
    93  	_, nodeIsddd     // is the argument variadic
    94  	_, nodeDiag      // already printed error about this
    95  	_, nodeColas     // OAS resulting from :=
    96  	_, nodeNonNil    // guaranteed to be non-nil
    97  	_, nodeNoescape  // func arguments do not escape; TODO(rsc): move Noescape to Func struct (see CL 7360)
    98  	_, nodeBounded   // bounds check unnecessary
    99  	_, nodeAddable   // addressable
   100  	_, nodeHasCall   // expression contains a function call
   101  	_, nodeLikely    // if statement condition likely
   102  	_, nodeHasVal    // node.E contains a Val
   103  	_, nodeHasOpt    // node.E contains an Opt
   104  	_, nodeEmbedded  // ODCLFIELD embedded type
   105  	_, nodeInlFormal // OPAUTO created by inliner, derived from callee formal
   106  	_, nodeInlLocal  // OPAUTO created by inliner, derived from callee local
   107  )
   108  
   109  func (n *Node) Class() Class     { return Class(n.flags.get3(nodeClass)) }
   110  func (n *Node) Walkdef() uint8   { return n.flags.get2(nodeWalkdef) }
   111  func (n *Node) Typecheck() uint8 { return n.flags.get2(nodeTypecheck) }
   112  func (n *Node) Initorder() uint8 { return n.flags.get2(nodeInitorder) }
   113  
   114  func (n *Node) HasBreak() bool              { return n.flags&nodeHasBreak != 0 }
   115  func (n *Node) IsClosureVar() bool          { return n.flags&nodeIsClosureVar != 0 }
   116  func (n *Node) NoInline() bool              { return n.flags&nodeNoInline != 0 }
   117  func (n *Node) IsOutputParamHeapAddr() bool { return n.flags&nodeIsOutputParamHeapAddr != 0 }
   118  func (n *Node) Assigned() bool              { return n.flags&nodeAssigned != 0 }
   119  func (n *Node) Addrtaken() bool             { return n.flags&nodeAddrtaken != 0 }
   120  func (n *Node) Implicit() bool              { return n.flags&nodeImplicit != 0 }
   121  func (n *Node) Isddd() bool                 { return n.flags&nodeIsddd != 0 }
   122  func (n *Node) Diag() bool                  { return n.flags&nodeDiag != 0 }
   123  func (n *Node) Colas() bool                 { return n.flags&nodeColas != 0 }
   124  func (n *Node) NonNil() bool                { return n.flags&nodeNonNil != 0 }
   125  func (n *Node) Noescape() bool              { return n.flags&nodeNoescape != 0 }
   126  func (n *Node) Bounded() bool               { return n.flags&nodeBounded != 0 }
   127  func (n *Node) Addable() bool               { return n.flags&nodeAddable != 0 }
   128  func (n *Node) HasCall() bool               { return n.flags&nodeHasCall != 0 }
   129  func (n *Node) Likely() bool                { return n.flags&nodeLikely != 0 }
   130  func (n *Node) HasVal() bool                { return n.flags&nodeHasVal != 0 }
   131  func (n *Node) HasOpt() bool                { return n.flags&nodeHasOpt != 0 }
   132  func (n *Node) Embedded() bool              { return n.flags&nodeEmbedded != 0 }
   133  func (n *Node) InlFormal() bool             { return n.flags&nodeInlFormal != 0 }
   134  func (n *Node) InlLocal() bool              { return n.flags&nodeInlLocal != 0 }
   135  
   136  func (n *Node) SetClass(b Class)     { n.flags.set3(nodeClass, uint8(b)) }
   137  func (n *Node) SetWalkdef(b uint8)   { n.flags.set2(nodeWalkdef, b) }
   138  func (n *Node) SetTypecheck(b uint8) { n.flags.set2(nodeTypecheck, b) }
   139  func (n *Node) SetInitorder(b uint8) { n.flags.set2(nodeInitorder, b) }
   140  
   141  func (n *Node) SetHasBreak(b bool)              { n.flags.set(nodeHasBreak, b) }
   142  func (n *Node) SetIsClosureVar(b bool)          { n.flags.set(nodeIsClosureVar, b) }
   143  func (n *Node) SetNoInline(b bool)              { n.flags.set(nodeNoInline, b) }
   144  func (n *Node) SetIsOutputParamHeapAddr(b bool) { n.flags.set(nodeIsOutputParamHeapAddr, b) }
   145  func (n *Node) SetAssigned(b bool)              { n.flags.set(nodeAssigned, b) }
   146  func (n *Node) SetAddrtaken(b bool)             { n.flags.set(nodeAddrtaken, b) }
   147  func (n *Node) SetImplicit(b bool)              { n.flags.set(nodeImplicit, b) }
   148  func (n *Node) SetIsddd(b bool)                 { n.flags.set(nodeIsddd, b) }
   149  func (n *Node) SetDiag(b bool)                  { n.flags.set(nodeDiag, b) }
   150  func (n *Node) SetColas(b bool)                 { n.flags.set(nodeColas, b) }
   151  func (n *Node) SetNonNil(b bool)                { n.flags.set(nodeNonNil, b) }
   152  func (n *Node) SetNoescape(b bool)              { n.flags.set(nodeNoescape, b) }
   153  func (n *Node) SetBounded(b bool)               { n.flags.set(nodeBounded, b) }
   154  func (n *Node) SetAddable(b bool)               { n.flags.set(nodeAddable, b) }
   155  func (n *Node) SetHasCall(b bool)               { n.flags.set(nodeHasCall, b) }
   156  func (n *Node) SetLikely(b bool)                { n.flags.set(nodeLikely, b) }
   157  func (n *Node) SetHasVal(b bool)                { n.flags.set(nodeHasVal, b) }
   158  func (n *Node) SetHasOpt(b bool)                { n.flags.set(nodeHasOpt, b) }
   159  func (n *Node) SetEmbedded(b bool)              { n.flags.set(nodeEmbedded, b) }
   160  func (n *Node) SetInlFormal(b bool)             { n.flags.set(nodeInlFormal, b) }
   161  func (n *Node) SetInlLocal(b bool)              { n.flags.set(nodeInlLocal, b) }
   162  
   163  // Val returns the Val for the node.
   164  func (n *Node) Val() Val {
   165  	if !n.HasVal() {
   166  		return Val{}
   167  	}
   168  	return Val{n.E}
   169  }
   170  
   171  // SetVal sets the Val for the node, which must not have been used with SetOpt.
   172  func (n *Node) SetVal(v Val) {
   173  	if n.HasOpt() {
   174  		Debug['h'] = 1
   175  		Dump("have Opt", n)
   176  		Fatalf("have Opt")
   177  	}
   178  	n.SetHasVal(true)
   179  	n.E = v.U
   180  }
   181  
   182  // Opt returns the optimizer data for the node.
   183  func (n *Node) Opt() interface{} {
   184  	if !n.HasOpt() {
   185  		return nil
   186  	}
   187  	return n.E
   188  }
   189  
   190  // SetOpt sets the optimizer data for the node, which must not have been used with SetVal.
   191  // SetOpt(nil) is ignored for Vals to simplify call sites that are clearing Opts.
   192  func (n *Node) SetOpt(x interface{}) {
   193  	if x == nil && n.HasVal() {
   194  		return
   195  	}
   196  	if n.HasVal() {
   197  		Debug['h'] = 1
   198  		Dump("have Val", n)
   199  		Fatalf("have Val")
   200  	}
   201  	n.SetHasOpt(true)
   202  	n.E = x
   203  }
   204  
   205  func (n *Node) Iota() int64 {
   206  	return n.Xoffset
   207  }
   208  
   209  func (n *Node) SetIota(x int64) {
   210  	n.Xoffset = x
   211  }
   212  
   213  // mayBeShared reports whether n may occur in multiple places in the AST.
   214  // Extra care must be taken when mutating such a node.
   215  func (n *Node) mayBeShared() bool {
   216  	switch n.Op {
   217  	case ONAME, OLITERAL, OTYPE:
   218  		return true
   219  	}
   220  	return false
   221  }
   222  
   223  // isMethodExpression reports whether n represents a method expression T.M.
   224  func (n *Node) isMethodExpression() bool {
   225  	return n.Op == ONAME && n.Left != nil && n.Left.Op == OTYPE && n.Right != nil && n.Right.Op == ONAME
   226  }
   227  
   228  // funcname returns the name of the function n.
   229  func (n *Node) funcname() string {
   230  	if n == nil || n.Func == nil || n.Func.Nname == nil {
   231  		return "<nil>"
   232  	}
   233  	return n.Func.Nname.Sym.Name
   234  }
   235  
   236  // Name holds Node fields used only by named nodes (ONAME, OTYPE, OPACK, OLABEL, some OLITERAL).
   237  type Name struct {
   238  	Pack      *Node      // real package for import . names
   239  	Pkg       *types.Pkg // pkg for OPACK nodes
   240  	Defn      *Node      // initializing assignment
   241  	Curfn     *Node      // function for local variables
   242  	Param     *Param     // additional fields for ONAME, OTYPE
   243  	Decldepth int32      // declaration loop depth, increased for every loop or label
   244  	Vargen    int32      // unique name for ONAME within a function.  Function outputs are numbered starting at one.
   245  	Funcdepth int32
   246  
   247  	used  bool // for variable declared and not used error
   248  	flags bitset8
   249  }
   250  
   251  const (
   252  	nameCaptured = 1 << iota // is the variable captured by a closure
   253  	nameReadonly
   254  	nameByval     // is the variable captured by value or by reference
   255  	nameNeedzero  // if it contains pointers, needs to be zeroed on function entry
   256  	nameKeepalive // mark value live across unknown assembly call
   257  	nameAutoTemp  // is the variable a temporary (implies no dwarf info. reset if escapes to heap)
   258  )
   259  
   260  func (n *Name) Captured() bool  { return n.flags&nameCaptured != 0 }
   261  func (n *Name) Readonly() bool  { return n.flags&nameReadonly != 0 }
   262  func (n *Name) Byval() bool     { return n.flags&nameByval != 0 }
   263  func (n *Name) Needzero() bool  { return n.flags&nameNeedzero != 0 }
   264  func (n *Name) Keepalive() bool { return n.flags&nameKeepalive != 0 }
   265  func (n *Name) AutoTemp() bool  { return n.flags&nameAutoTemp != 0 }
   266  func (n *Name) Used() bool      { return n.used }
   267  
   268  func (n *Name) SetCaptured(b bool)  { n.flags.set(nameCaptured, b) }
   269  func (n *Name) SetReadonly(b bool)  { n.flags.set(nameReadonly, b) }
   270  func (n *Name) SetByval(b bool)     { n.flags.set(nameByval, b) }
   271  func (n *Name) SetNeedzero(b bool)  { n.flags.set(nameNeedzero, b) }
   272  func (n *Name) SetKeepalive(b bool) { n.flags.set(nameKeepalive, b) }
   273  func (n *Name) SetAutoTemp(b bool)  { n.flags.set(nameAutoTemp, b) }
   274  func (n *Name) SetUsed(b bool)      { n.used = b }
   275  
   276  type Param struct {
   277  	Ntype    *Node
   278  	Heapaddr *Node // temp holding heap address of param
   279  
   280  	// ONAME PAUTOHEAP
   281  	Stackcopy *Node // the PPARAM/PPARAMOUT on-stack slot (moved func params only)
   282  
   283  	// ONAME PPARAM
   284  	Field *types.Field // TFIELD in arg struct
   285  
   286  	// ONAME closure linkage
   287  	// Consider:
   288  	//
   289  	//	func f() {
   290  	//		x := 1 // x1
   291  	//		func() {
   292  	//			use(x) // x2
   293  	//			func() {
   294  	//				use(x) // x3
   295  	//				--- parser is here ---
   296  	//			}()
   297  	//		}()
   298  	//	}
   299  	//
   300  	// There is an original declaration of x and then a chain of mentions of x
   301  	// leading into the current function. Each time x is mentioned in a new closure,
   302  	// we create a variable representing x for use in that specific closure,
   303  	// since the way you get to x is different in each closure.
   304  	//
   305  	// Let's number the specific variables as shown in the code:
   306  	// x1 is the original x, x2 is when mentioned in the closure,
   307  	// and x3 is when mentioned in the closure in the closure.
   308  	//
   309  	// We keep these linked (assume N > 1):
   310  	//
   311  	//   - x1.Defn = original declaration statement for x (like most variables)
   312  	//   - x1.Innermost = current innermost closure x (in this case x3), or nil for none
   313  	//   - x1.IsClosureVar() = false
   314  	//
   315  	//   - xN.Defn = x1, N > 1
   316  	//   - xN.IsClosureVar() = true, N > 1
   317  	//   - x2.Outer = nil
   318  	//   - xN.Outer = x(N-1), N > 2
   319  	//
   320  	//
   321  	// When we look up x in the symbol table, we always get x1.
   322  	// Then we can use x1.Innermost (if not nil) to get the x
   323  	// for the innermost known closure function,
   324  	// but the first reference in a closure will find either no x1.Innermost
   325  	// or an x1.Innermost with .Funcdepth < Funcdepth.
   326  	// In that case, a new xN must be created, linked in with:
   327  	//
   328  	//     xN.Defn = x1
   329  	//     xN.Outer = x1.Innermost
   330  	//     x1.Innermost = xN
   331  	//
   332  	// When we finish the function, we'll process its closure variables
   333  	// and find xN and pop it off the list using:
   334  	//
   335  	//     x1 := xN.Defn
   336  	//     x1.Innermost = xN.Outer
   337  	//
   338  	// We leave xN.Innermost set so that we can still get to the original
   339  	// variable quickly. Not shown here, but once we're
   340  	// done parsing a function and no longer need xN.Outer for the
   341  	// lexical x reference links as described above, closurebody
   342  	// recomputes xN.Outer as the semantic x reference link tree,
   343  	// even filling in x in intermediate closures that might not
   344  	// have mentioned it along the way to inner closures that did.
   345  	// See closurebody for details.
   346  	//
   347  	// During the eventual compilation, then, for closure variables we have:
   348  	//
   349  	//     xN.Defn = original variable
   350  	//     xN.Outer = variable captured in next outward scope
   351  	//                to make closure where xN appears
   352  	//
   353  	// Because of the sharding of pieces of the node, x.Defn means x.Name.Defn
   354  	// and x.Innermost/Outer means x.Name.Param.Innermost/Outer.
   355  	Innermost *Node
   356  	Outer     *Node
   357  
   358  	// OTYPE
   359  	//
   360  	// TODO: Should Func pragmas also be stored on the Name?
   361  	Pragma syntax.Pragma
   362  	Alias  bool // node is alias for Ntype (only used when type-checking ODCLTYPE)
   363  }
   364  
   365  // Functions
   366  //
   367  // A simple function declaration is represented as an ODCLFUNC node f
   368  // and an ONAME node n. They're linked to one another through
   369  // f.Func.Nname == n and n.Name.Defn == f. When functions are
   370  // referenced by name in an expression, the function's ONAME node is
   371  // used directly.
   372  //
   373  // Function names have n.Class() == PFUNC. This distinguishes them
   374  // from variables of function type.
   375  //
   376  // Confusingly, n.Func and f.Func both exist, but commonly point to
   377  // different Funcs. (Exception: an OCALLPART's Func does point to its
   378  // ODCLFUNC's Func.)
   379  //
   380  // A method declaration is represented like functions, except n.Sym
   381  // will be the qualified method name (e.g., "T.m") and
   382  // f.Func.Shortname is the bare method name (e.g., "m").
   383  //
   384  // Method expressions are represented as ONAME/PFUNC nodes like
   385  // function names, but their Left and Right fields still point to the
   386  // type and method, respectively. They can be distinguished from
   387  // normal functions with isMethodExpression. Also, unlike function
   388  // name nodes, method expression nodes exist for each method
   389  // expression. The declaration ONAME can be accessed with
   390  // x.Type.Nname(), where x is the method expression ONAME node.
   391  //
   392  // Method values are represented by ODOTMETH/ODOTINTER when called
   393  // immediately, and OCALLPART otherwise. They are like method
   394  // expressions, except that for ODOTMETH/ODOTINTER the method name is
   395  // stored in Sym instead of Right.
   396  //
   397  // Closures are represented by OCLOSURE node c. They link back and
   398  // forth with the ODCLFUNC via Func.Closure; that is, c.Func.Closure
   399  // == f and f.Func.Closure == c.
   400  //
   401  // Function bodies are stored in f.Nbody, and inline function bodies
   402  // are stored in n.Func.Inl. Pragmas are stored in f.Func.Pragma.
   403  //
   404  // Imported functions skip the ODCLFUNC, so n.Name.Defn is nil. They
   405  // also use Dcl instead of Inldcl.
   406  
   407  // Func holds Node fields used only with function-like nodes.
   408  type Func struct {
   409  	Shortname *types.Sym
   410  	Enter     Nodes // for example, allocate and initialize memory for escaping parameters
   411  	Exit      Nodes
   412  	Cvars     Nodes   // closure params
   413  	Dcl       []*Node // autodcl for this func/closure
   414  	Inldcl    Nodes   // copy of dcl for use in inlining
   415  
   416  	// Parents records the parent scope of each scope within a
   417  	// function. The root scope (0) has no parent, so the i'th
   418  	// scope's parent is stored at Parents[i-1].
   419  	Parents []ScopeID
   420  
   421  	// Marks records scope boundary changes.
   422  	Marks []Mark
   423  
   424  	Closgen    int
   425  	Outerfunc  *Node // outer function (for closure)
   426  	FieldTrack map[*types.Sym]struct{}
   427  	DebugInfo  *ssa.FuncDebug
   428  	Ntype      *Node // signature
   429  	Top        int   // top context (Ecall, Eproc, etc)
   430  	Closure    *Node // OCLOSURE <-> ODCLFUNC
   431  	Nname      *Node
   432  	lsym       *obj.LSym
   433  
   434  	Inl     Nodes // copy of the body for use in inlining
   435  	InlCost int32
   436  	Depth   int32
   437  
   438  	Label int32 // largest auto-generated label in this function
   439  
   440  	Endlineno src.XPos
   441  	WBPos     src.XPos // position of first write barrier; see SetWBPos
   442  
   443  	Pragma syntax.Pragma // go:xxx function annotations
   444  
   445  	flags bitset16
   446  
   447  	// nwbrCalls records the LSyms of functions called by this
   448  	// function for go:nowritebarrierrec analysis. Only filled in
   449  	// if nowritebarrierrecCheck != nil.
   450  	nwbrCalls *[]nowritebarrierrecCallSym
   451  }
   452  
   453  // A Mark represents a scope boundary.
   454  type Mark struct {
   455  	// Pos is the position of the token that marks the scope
   456  	// change.
   457  	Pos src.XPos
   458  
   459  	// Scope identifies the innermost scope to the right of Pos.
   460  	Scope ScopeID
   461  }
   462  
   463  // A ScopeID represents a lexical scope within a function.
   464  type ScopeID int32
   465  
   466  const (
   467  	funcDupok         = 1 << iota // duplicate definitions ok
   468  	funcWrapper                   // is method wrapper
   469  	funcNeedctxt                  // function uses context register (has closure variables)
   470  	funcReflectMethod             // function calls reflect.Type.Method or MethodByName
   471  	funcIsHiddenClosure
   472  	funcHasDefer            // contains a defer statement
   473  	funcNilCheckDisabled    // disable nil checks when compiling this function
   474  	funcInlinabilityChecked // inliner has already determined whether the function is inlinable
   475  	funcExportInline        // include inline body in export data
   476  )
   477  
   478  func (f *Func) Dupok() bool               { return f.flags&funcDupok != 0 }
   479  func (f *Func) Wrapper() bool             { return f.flags&funcWrapper != 0 }
   480  func (f *Func) Needctxt() bool            { return f.flags&funcNeedctxt != 0 }
   481  func (f *Func) ReflectMethod() bool       { return f.flags&funcReflectMethod != 0 }
   482  func (f *Func) IsHiddenClosure() bool     { return f.flags&funcIsHiddenClosure != 0 }
   483  func (f *Func) HasDefer() bool            { return f.flags&funcHasDefer != 0 }
   484  func (f *Func) NilCheckDisabled() bool    { return f.flags&funcNilCheckDisabled != 0 }
   485  func (f *Func) InlinabilityChecked() bool { return f.flags&funcInlinabilityChecked != 0 }
   486  func (f *Func) ExportInline() bool        { return f.flags&funcExportInline != 0 }
   487  
   488  func (f *Func) SetDupok(b bool)               { f.flags.set(funcDupok, b) }
   489  func (f *Func) SetWrapper(b bool)             { f.flags.set(funcWrapper, b) }
   490  func (f *Func) SetNeedctxt(b bool)            { f.flags.set(funcNeedctxt, b) }
   491  func (f *Func) SetReflectMethod(b bool)       { f.flags.set(funcReflectMethod, b) }
   492  func (f *Func) SetIsHiddenClosure(b bool)     { f.flags.set(funcIsHiddenClosure, b) }
   493  func (f *Func) SetHasDefer(b bool)            { f.flags.set(funcHasDefer, b) }
   494  func (f *Func) SetNilCheckDisabled(b bool)    { f.flags.set(funcNilCheckDisabled, b) }
   495  func (f *Func) SetInlinabilityChecked(b bool) { f.flags.set(funcInlinabilityChecked, b) }
   496  func (f *Func) SetExportInline(b bool)        { f.flags.set(funcExportInline, b) }
   497  
   498  func (f *Func) setWBPos(pos src.XPos) {
   499  	if Debug_wb != 0 {
   500  		Warnl(pos, "write barrier")
   501  	}
   502  	if !f.WBPos.IsKnown() {
   503  		f.WBPos = pos
   504  	}
   505  }
   506  
   507  //go:generate stringer -type=Op -trimprefix=O
   508  
   509  type Op uint8
   510  
   511  // Node ops.
   512  const (
   513  	OXXX Op = iota
   514  
   515  	// names
   516  	ONAME    // var, const or func name
   517  	ONONAME  // unnamed arg or return value: f(int, string) (int, error) { etc }
   518  	OTYPE    // type name
   519  	OPACK    // import
   520  	OLITERAL // literal
   521  
   522  	// expressions
   523  	OADD             // Left + Right
   524  	OSUB             // Left - Right
   525  	OOR              // Left | Right
   526  	OXOR             // Left ^ Right
   527  	OADDSTR          // +{List} (string addition, list elements are strings)
   528  	OADDR            // &Left
   529  	OANDAND          // Left && Right
   530  	OAPPEND          // append(List); after walk, Left may contain elem type descriptor
   531  	OARRAYBYTESTR    // Type(Left) (Type is string, Left is a []byte)
   532  	OARRAYBYTESTRTMP // Type(Left) (Type is string, Left is a []byte, ephemeral)
   533  	OARRAYRUNESTR    // Type(Left) (Type is string, Left is a []rune)
   534  	OSTRARRAYBYTE    // Type(Left) (Type is []byte, Left is a string)
   535  	OSTRARRAYBYTETMP // Type(Left) (Type is []byte, Left is a string, ephemeral)
   536  	OSTRARRAYRUNE    // Type(Left) (Type is []rune, Left is a string)
   537  	OAS              // Left = Right or (if Colas=true) Left := Right
   538  	OAS2             // List = Rlist (x, y, z = a, b, c)
   539  	OAS2FUNC         // List = Rlist (x, y = f())
   540  	OAS2RECV         // List = Rlist (x, ok = <-c)
   541  	OAS2MAPR         // List = Rlist (x, ok = m["foo"])
   542  	OAS2DOTTYPE      // List = Rlist (x, ok = I.(int))
   543  	OASOP            // Left Etype= Right (x += y)
   544  	OCALL            // Left(List) (function call, method call or type conversion)
   545  	OCALLFUNC        // Left(List) (function call f(args))
   546  	OCALLMETH        // Left(List) (direct method call x.Method(args))
   547  	OCALLINTER       // Left(List) (interface method call x.Method(args))
   548  	OCALLPART        // Left.Right (method expression x.Method, not called)
   549  	OCAP             // cap(Left)
   550  	OCLOSE           // close(Left)
   551  	OCLOSURE         // func Type { Body } (func literal)
   552  	OCMPIFACE        // Left Etype Right (interface comparison, x == y or x != y)
   553  	OCMPSTR          // Left Etype Right (string comparison, x == y, x < y, etc)
   554  	OCOMPLIT         // Right{List} (composite literal, not yet lowered to specific form)
   555  	OMAPLIT          // Type{List} (composite literal, Type is map)
   556  	OSTRUCTLIT       // Type{List} (composite literal, Type is struct)
   557  	OARRAYLIT        // Type{List} (composite literal, Type is array)
   558  	OSLICELIT        // Type{List} (composite literal, Type is slice)
   559  	OPTRLIT          // &Left (left is composite literal)
   560  	OCONV            // Type(Left) (type conversion)
   561  	OCONVIFACE       // Type(Left) (type conversion, to interface)
   562  	OCONVNOP         // Type(Left) (type conversion, no effect)
   563  	OCOPY            // copy(Left, Right)
   564  	ODCL             // var Left (declares Left of type Left.Type)
   565  
   566  	// Used during parsing but don't last.
   567  	ODCLFUNC  // func f() or func (r) f()
   568  	ODCLFIELD // struct field, interface field, or func/method argument/return value.
   569  	ODCLCONST // const pi = 3.14
   570  	ODCLTYPE  // type Int int or type Int = int
   571  
   572  	ODELETE    // delete(Left, Right)
   573  	ODOT       // Left.Sym (Left is of struct type)
   574  	ODOTPTR    // Left.Sym (Left is of pointer to struct type)
   575  	ODOTMETH   // Left.Sym (Left is non-interface, Right is method name)
   576  	ODOTINTER  // Left.Sym (Left is interface, Right is method name)
   577  	OXDOT      // Left.Sym (before rewrite to one of the preceding)
   578  	ODOTTYPE   // Left.Right or Left.Type (.Right during parsing, .Type once resolved); after walk, .Right contains address of interface type descriptor and .Right.Right contains address of concrete type descriptor
   579  	ODOTTYPE2  // Left.Right or Left.Type (.Right during parsing, .Type once resolved; on rhs of OAS2DOTTYPE); after walk, .Right contains address of interface type descriptor
   580  	OEQ        // Left == Right
   581  	ONE        // Left != Right
   582  	OLT        // Left < Right
   583  	OLE        // Left <= Right
   584  	OGE        // Left >= Right
   585  	OGT        // Left > Right
   586  	OIND       // *Left
   587  	OINDEX     // Left[Right] (index of array or slice)
   588  	OINDEXMAP  // Left[Right] (index of map)
   589  	OKEY       // Left:Right (key:value in struct/array/map literal)
   590  	OSTRUCTKEY // Sym:Left (key:value in struct literal, after type checking)
   591  	OLEN       // len(Left)
   592  	OMAKE      // make(List) (before type checking converts to one of the following)
   593  	OMAKECHAN  // make(Type, Left) (type is chan)
   594  	OMAKEMAP   // make(Type, Left) (type is map)
   595  	OMAKESLICE // make(Type, Left, Right) (type is slice)
   596  	OMUL       // Left * Right
   597  	ODIV       // Left / Right
   598  	OMOD       // Left % Right
   599  	OLSH       // Left << Right
   600  	ORSH       // Left >> Right
   601  	OAND       // Left & Right
   602  	OANDNOT    // Left &^ Right
   603  	ONEW       // new(Left)
   604  	ONOT       // !Left
   605  	OCOM       // ^Left
   606  	OPLUS      // +Left
   607  	OMINUS     // -Left
   608  	OOROR      // Left || Right
   609  	OPANIC     // panic(Left)
   610  	OPRINT     // print(List)
   611  	OPRINTN    // println(List)
   612  	OPAREN     // (Left)
   613  	OSEND      // Left <- Right
   614  	OSLICE     // Left[List[0] : List[1]] (Left is untypechecked or slice)
   615  	OSLICEARR  // Left[List[0] : List[1]] (Left is array)
   616  	OSLICESTR  // Left[List[0] : List[1]] (Left is string)
   617  	OSLICE3    // Left[List[0] : List[1] : List[2]] (Left is untypedchecked or slice)
   618  	OSLICE3ARR // Left[List[0] : List[1] : List[2]] (Left is array)
   619  	ORECOVER   // recover()
   620  	ORECV      // <-Left
   621  	ORUNESTR   // Type(Left) (Type is string, Left is rune)
   622  	OSELRECV   // Left = <-Right.Left: (appears as .Left of OCASE; Right.Op == ORECV)
   623  	OSELRECV2  // List = <-Right.Left: (apperas as .Left of OCASE; count(List) == 2, Right.Op == ORECV)
   624  	OIOTA      // iota
   625  	OREAL      // real(Left)
   626  	OIMAG      // imag(Left)
   627  	OCOMPLEX   // complex(Left, Right)
   628  	OALIGNOF   // unsafe.Alignof(Left)
   629  	OOFFSETOF  // unsafe.Offsetof(Left)
   630  	OSIZEOF    // unsafe.Sizeof(Left)
   631  
   632  	// statements
   633  	OBLOCK    // { List } (block of code)
   634  	OBREAK    // break
   635  	OCASE     // case Left or List[0]..List[1]: Nbody (select case after processing; Left==nil and List==nil means default)
   636  	OXCASE    // case List: Nbody (select case before processing; List==nil means default)
   637  	OCONTINUE // continue
   638  	ODEFER    // defer Left (Left must be call)
   639  	OEMPTY    // no-op (empty statement)
   640  	OFALL     // fallthrough
   641  	OFOR      // for Ninit; Left; Right { Nbody }
   642  	OFORUNTIL // for Ninit; Left; Right { Nbody } ; test applied after executing body, not before
   643  	OGOTO     // goto Left
   644  	OIF       // if Ninit; Left { Nbody } else { Rlist }
   645  	OLABEL    // Left:
   646  	OPROC     // go Left (Left must be call)
   647  	ORANGE    // for List = range Right { Nbody }
   648  	ORETURN   // return List
   649  	OSELECT   // select { List } (List is list of OXCASE or OCASE)
   650  	OSWITCH   // switch Ninit; Left { List } (List is a list of OXCASE or OCASE)
   651  	OTYPESW   // Left = Right.(type) (appears as .Left of OSWITCH)
   652  
   653  	// types
   654  	OTCHAN   // chan int
   655  	OTMAP    // map[string]int
   656  	OTSTRUCT // struct{}
   657  	OTINTER  // interface{}
   658  	OTFUNC   // func()
   659  	OTARRAY  // []int, [8]int, [N]int or [...]int
   660  
   661  	// misc
   662  	ODDD        // func f(args ...int) or f(l...) or var a = [...]int{0, 1, 2}.
   663  	ODDDARG     // func f(args ...int), introduced by escape analysis.
   664  	OINLCALL    // intermediary representation of an inlined call.
   665  	OEFACE      // itable and data words of an empty-interface value.
   666  	OITAB       // itable word of an interface value.
   667  	OIDATA      // data word of an interface value in Left
   668  	OSPTR       // base pointer of a slice or string.
   669  	OCLOSUREVAR // variable reference at beginning of closure function
   670  	OCFUNC      // reference to c function pointer (not go func value)
   671  	OCHECKNIL   // emit code to ensure pointer/interface not nil
   672  	OVARKILL    // variable is dead
   673  	OVARLIVE    // variable is alive
   674  	OINDREGSP   // offset plus indirect of REGSP, such as 8(SP).
   675  
   676  	// arch-specific opcodes
   677  	ORETJMP // return to other function
   678  	OGETG   // runtime.getg() (read g pointer)
   679  
   680  	OEND
   681  )
   682  
   683  // Nodes is a pointer to a slice of *Node.
   684  // For fields that are not used in most nodes, this is used instead of
   685  // a slice to save space.
   686  type Nodes struct{ slice *[]*Node }
   687  
   688  // Slice returns the entries in Nodes as a slice.
   689  // Changes to the slice entries (as in s[i] = n) will be reflected in
   690  // the Nodes.
   691  func (n Nodes) Slice() []*Node {
   692  	if n.slice == nil {
   693  		return nil
   694  	}
   695  	return *n.slice
   696  }
   697  
   698  // Len returns the number of entries in Nodes.
   699  func (n Nodes) Len() int {
   700  	if n.slice == nil {
   701  		return 0
   702  	}
   703  	return len(*n.slice)
   704  }
   705  
   706  // Index returns the i'th element of Nodes.
   707  // It panics if n does not have at least i+1 elements.
   708  func (n Nodes) Index(i int) *Node {
   709  	return (*n.slice)[i]
   710  }
   711  
   712  // First returns the first element of Nodes (same as n.Index(0)).
   713  // It panics if n has no elements.
   714  func (n Nodes) First() *Node {
   715  	return (*n.slice)[0]
   716  }
   717  
   718  // Second returns the second element of Nodes (same as n.Index(1)).
   719  // It panics if n has fewer than two elements.
   720  func (n Nodes) Second() *Node {
   721  	return (*n.slice)[1]
   722  }
   723  
   724  // Set sets n to a slice.
   725  // This takes ownership of the slice.
   726  func (n *Nodes) Set(s []*Node) {
   727  	if len(s) == 0 {
   728  		n.slice = nil
   729  	} else {
   730  		// Copy s and take address of t rather than s to avoid
   731  		// allocation in the case where len(s) == 0 (which is
   732  		// over 3x more common, dynamically, for make.bash).
   733  		t := s
   734  		n.slice = &t
   735  	}
   736  }
   737  
   738  // Set1 sets n to a slice containing a single node.
   739  func (n *Nodes) Set1(n1 *Node) {
   740  	n.slice = &[]*Node{n1}
   741  }
   742  
   743  // Set2 sets n to a slice containing two nodes.
   744  func (n *Nodes) Set2(n1, n2 *Node) {
   745  	n.slice = &[]*Node{n1, n2}
   746  }
   747  
   748  // Set3 sets n to a slice containing three nodes.
   749  func (n *Nodes) Set3(n1, n2, n3 *Node) {
   750  	n.slice = &[]*Node{n1, n2, n3}
   751  }
   752  
   753  // MoveNodes sets n to the contents of n2, then clears n2.
   754  func (n *Nodes) MoveNodes(n2 *Nodes) {
   755  	n.slice = n2.slice
   756  	n2.slice = nil
   757  }
   758  
   759  // SetIndex sets the i'th element of Nodes to node.
   760  // It panics if n does not have at least i+1 elements.
   761  func (n Nodes) SetIndex(i int, node *Node) {
   762  	(*n.slice)[i] = node
   763  }
   764  
   765  // SetFirst sets the first element of Nodes to node.
   766  // It panics if n does not have at least one elements.
   767  func (n Nodes) SetFirst(node *Node) {
   768  	(*n.slice)[0] = node
   769  }
   770  
   771  // SetSecond sets the second element of Nodes to node.
   772  // It panics if n does not have at least two elements.
   773  func (n Nodes) SetSecond(node *Node) {
   774  	(*n.slice)[1] = node
   775  }
   776  
   777  // Addr returns the address of the i'th element of Nodes.
   778  // It panics if n does not have at least i+1 elements.
   779  func (n Nodes) Addr(i int) **Node {
   780  	return &(*n.slice)[i]
   781  }
   782  
   783  // Append appends entries to Nodes.
   784  func (n *Nodes) Append(a ...*Node) {
   785  	if len(a) == 0 {
   786  		return
   787  	}
   788  	if n.slice == nil {
   789  		s := make([]*Node, len(a))
   790  		copy(s, a)
   791  		n.slice = &s
   792  		return
   793  	}
   794  	*n.slice = append(*n.slice, a...)
   795  }
   796  
   797  // Prepend prepends entries to Nodes.
   798  // If a slice is passed in, this will take ownership of it.
   799  func (n *Nodes) Prepend(a ...*Node) {
   800  	if len(a) == 0 {
   801  		return
   802  	}
   803  	if n.slice == nil {
   804  		n.slice = &a
   805  	} else {
   806  		*n.slice = append(a, *n.slice...)
   807  	}
   808  }
   809  
   810  // AppendNodes appends the contents of *n2 to n, then clears n2.
   811  func (n *Nodes) AppendNodes(n2 *Nodes) {
   812  	switch {
   813  	case n2.slice == nil:
   814  	case n.slice == nil:
   815  		n.slice = n2.slice
   816  	default:
   817  		*n.slice = append(*n.slice, *n2.slice...)
   818  	}
   819  	n2.slice = nil
   820  }
   821  
   822  // inspect invokes f on each node in an AST in depth-first order.
   823  // If f(n) returns false, inspect skips visiting n's children.
   824  func inspect(n *Node, f func(*Node) bool) {
   825  	if n == nil || !f(n) {
   826  		return
   827  	}
   828  	inspectList(n.Ninit, f)
   829  	inspect(n.Left, f)
   830  	inspect(n.Right, f)
   831  	inspectList(n.List, f)
   832  	inspectList(n.Nbody, f)
   833  	inspectList(n.Rlist, f)
   834  }
   835  
   836  func inspectList(l Nodes, f func(*Node) bool) {
   837  	for _, n := range l.Slice() {
   838  		inspect(n, f)
   839  	}
   840  }
   841  
   842  // nodeQueue is a FIFO queue of *Node. The zero value of nodeQueue is
   843  // a ready-to-use empty queue.
   844  type nodeQueue struct {
   845  	ring       []*Node
   846  	head, tail int
   847  }
   848  
   849  // empty returns true if q contains no Nodes.
   850  func (q *nodeQueue) empty() bool {
   851  	return q.head == q.tail
   852  }
   853  
   854  // pushRight appends n to the right of the queue.
   855  func (q *nodeQueue) pushRight(n *Node) {
   856  	if len(q.ring) == 0 {
   857  		q.ring = make([]*Node, 16)
   858  	} else if q.head+len(q.ring) == q.tail {
   859  		// Grow the ring.
   860  		nring := make([]*Node, len(q.ring)*2)
   861  		// Copy the old elements.
   862  		part := q.ring[q.head%len(q.ring):]
   863  		if q.tail-q.head <= len(part) {
   864  			part = part[:q.tail-q.head]
   865  			copy(nring, part)
   866  		} else {
   867  			pos := copy(nring, part)
   868  			copy(nring[pos:], q.ring[:q.tail%len(q.ring)])
   869  		}
   870  		q.ring, q.head, q.tail = nring, 0, q.tail-q.head
   871  	}
   872  
   873  	q.ring[q.tail%len(q.ring)] = n
   874  	q.tail++
   875  }
   876  
   877  // popLeft pops a node from the left of the queue. It panics if q is
   878  // empty.
   879  func (q *nodeQueue) popLeft() *Node {
   880  	if q.empty() {
   881  		panic("dequeue empty")
   882  	}
   883  	n := q.ring[q.head%len(q.ring)]
   884  	q.head++
   885  	return n
   886  }