github.com/euank/go@v0.0.0-20160829210321-495514729181/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 // A Node is a single node in the syntax tree. 10 // Actually the syntax tree is a syntax DAG, because there is only one 11 // node with Op=ONAME for a given instance of a variable x. 12 // The same is true for Op=OTYPE and Op=OLITERAL. 13 type Node struct { 14 // Tree structure. 15 // Generic recursive walks should follow these fields. 16 Left *Node 17 Right *Node 18 Ninit Nodes 19 Nbody Nodes 20 List Nodes 21 Rlist Nodes 22 23 // most nodes 24 Type *Type 25 Orig *Node // original form, for printing, and tracking copies of ONAMEs 26 27 // func 28 Func *Func 29 30 // ONAME 31 Name *Name 32 33 Sym *Sym // various 34 E interface{} // Opt or Val, see methods below 35 36 // Various. Usually an offset into a struct. For example, ONAME nodes 37 // that refer to local variables use it to identify their stack frame 38 // position. ODOT, ODOTPTR, and OINDREG use it to indicate offset 39 // relative to their base address. ONAME nodes on the left side of an 40 // OKEY within an OSTRUCTLIT use it to store the named field's offset. 41 // OXCASE and OXFALL use it to validate the use of fallthrough. 42 // Possibly still more uses. If you find any, document them. 43 Xoffset int64 44 45 Lineno int32 46 47 // OREGISTER, OINDREG 48 Reg int16 49 50 Esc uint16 // EscXXX 51 52 Op Op 53 Ullman uint8 // sethi/ullman number 54 Addable bool // addressable 55 Etype EType // op for OASOP, etype for OTYPE, exclam for export, 6g saved reg, ChanDir for OTCHAN 56 Bounded bool // bounds check unnecessary 57 NonNil bool // guaranteed to be non-nil 58 Class Class // PPARAM, PAUTO, PEXTERN, etc 59 Embedded uint8 // ODCLFIELD embedded type 60 Colas bool // OAS resulting from := 61 Diag uint8 // already printed error about this 62 Noescape bool // func arguments do not escape; TODO(rsc): move Noescape to Func struct (see CL 7360) 63 Walkdef uint8 // tracks state during typecheckdef; 2 == loop detected 64 Typecheck uint8 // tracks state during typechecking; 2 == loop detected 65 Local bool 66 IsStatic bool // whether this Node will be converted to purely static data 67 Initorder uint8 68 Used bool // for variable/label declared and not used error 69 Isddd bool // is the argument variadic 70 Implicit bool 71 Addrtaken bool // address taken, even if not moved to heap 72 Assigned bool // is the variable ever assigned to 73 Likely int8 // likeliness of if statement 74 hasVal int8 // +1 for Val, -1 for Opt, 0 for not yet set 75 flags uint8 // TODO: store more bool fields in this flag field 76 } 77 78 const ( 79 hasBreak = 1 << iota 80 notLiveAtEnd 81 isClosureVar 82 isOutputParamHeapAddr 83 noInline // used internally by inliner to indicate that a function call should not be inlined; set for OCALLFUNC and OCALLMETH only 84 ) 85 86 func (n *Node) HasBreak() bool { 87 return n.flags&hasBreak != 0 88 } 89 func (n *Node) SetHasBreak(b bool) { 90 if b { 91 n.flags |= hasBreak 92 } else { 93 n.flags &^= hasBreak 94 } 95 } 96 func (n *Node) NotLiveAtEnd() bool { 97 return n.flags¬LiveAtEnd != 0 98 } 99 func (n *Node) SetNotLiveAtEnd(b bool) { 100 if b { 101 n.flags |= notLiveAtEnd 102 } else { 103 n.flags &^= notLiveAtEnd 104 } 105 } 106 func (n *Node) isClosureVar() bool { 107 return n.flags&isClosureVar != 0 108 } 109 func (n *Node) setIsClosureVar(b bool) { 110 if b { 111 n.flags |= isClosureVar 112 } else { 113 n.flags &^= isClosureVar 114 } 115 } 116 func (n *Node) noInline() bool { 117 return n.flags&noInline != 0 118 } 119 func (n *Node) setNoInline(b bool) { 120 if b { 121 n.flags |= noInline 122 } else { 123 n.flags &^= noInline 124 } 125 } 126 127 func (n *Node) IsOutputParamHeapAddr() bool { 128 return n.flags&isOutputParamHeapAddr != 0 129 } 130 func (n *Node) setIsOutputParamHeapAddr(b bool) { 131 if b { 132 n.flags |= isOutputParamHeapAddr 133 } else { 134 n.flags &^= isOutputParamHeapAddr 135 } 136 } 137 138 // Val returns the Val for the node. 139 func (n *Node) Val() Val { 140 if n.hasVal != +1 { 141 return Val{} 142 } 143 return Val{n.E} 144 } 145 146 // SetVal sets the Val for the node, which must not have been used with SetOpt. 147 func (n *Node) SetVal(v Val) { 148 if n.hasVal == -1 { 149 Debug['h'] = 1 150 Dump("have Opt", n) 151 Fatalf("have Opt") 152 } 153 n.hasVal = +1 154 n.E = v.U 155 } 156 157 // Opt returns the optimizer data for the node. 158 func (n *Node) Opt() interface{} { 159 if n.hasVal != -1 { 160 return nil 161 } 162 return n.E 163 } 164 165 // SetOpt sets the optimizer data for the node, which must not have been used with SetVal. 166 // SetOpt(nil) is ignored for Vals to simplify call sites that are clearing Opts. 167 func (n *Node) SetOpt(x interface{}) { 168 if x == nil && n.hasVal >= 0 { 169 return 170 } 171 if n.hasVal == +1 { 172 Debug['h'] = 1 173 Dump("have Val", n) 174 Fatalf("have Val") 175 } 176 n.hasVal = -1 177 n.E = x 178 } 179 180 // Name holds Node fields used only by named nodes (ONAME, OPACK, OLABEL, ODCLFIELD, some OLITERAL). 181 type Name struct { 182 Pack *Node // real package for import . names 183 Pkg *Pkg // pkg for OPACK nodes 184 Heapaddr *Node // temp holding heap address of param (could move to Param?) 185 Inlvar *Node // ONAME substitute while inlining (could move to Param?) 186 Defn *Node // initializing assignment 187 Curfn *Node // function for local variables 188 Param *Param // additional fields for ONAME, ODCLFIELD 189 Decldepth int32 // declaration loop depth, increased for every loop or label 190 Vargen int32 // unique name for ONAME within a function. Function outputs are numbered starting at one. 191 Iota int32 // value if this name is iota 192 Funcdepth int32 193 Method bool // OCALLMETH name 194 Readonly bool 195 Captured bool // is the variable captured by a closure 196 Byval bool // is the variable captured by value or by reference 197 Needzero bool // if it contains pointers, needs to be zeroed on function entry 198 Keepalive bool // mark value live across unknown assembly call 199 } 200 201 type Param struct { 202 Ntype *Node 203 204 // ONAME PAUTOHEAP 205 Stackcopy *Node // the PPARAM/PPARAMOUT on-stack slot (moved func params only) 206 207 // ONAME PPARAM 208 Field *Field // TFIELD in arg struct 209 210 // ONAME closure linkage 211 // Consider: 212 // 213 // func f() { 214 // x := 1 // x1 215 // func() { 216 // use(x) // x2 217 // func() { 218 // use(x) // x3 219 // --- parser is here --- 220 // }() 221 // }() 222 // } 223 // 224 // There is an original declaration of x and then a chain of mentions of x 225 // leading into the current function. Each time x is mentioned in a new closure, 226 // we create a variable representing x for use in that specific closure, 227 // since the way you get to x is different in each closure. 228 // 229 // Let's number the specific variables as shown in the code: 230 // x1 is the original x, x2 is when mentioned in the closure, 231 // and x3 is when mentioned in the closure in the closure. 232 // 233 // We keep these linked (assume N > 1): 234 // 235 // - x1.Defn = original declaration statement for x (like most variables) 236 // - x1.Innermost = current innermost closure x (in this case x3), or nil for none 237 // - x1.isClosureVar() = false 238 // 239 // - xN.Defn = x1, N > 1 240 // - xN.isClosureVar() = true, N > 1 241 // - x2.Outer = nil 242 // - xN.Outer = x(N-1), N > 2 243 // 244 // 245 // When we look up x in the symbol table, we always get x1. 246 // Then we can use x1.Innermost (if not nil) to get the x 247 // for the innermost known closure function, 248 // but the first reference in a closure will find either no x1.Innermost 249 // or an x1.Innermost with .Funcdepth < Funcdepth. 250 // In that case, a new xN must be created, linked in with: 251 // 252 // xN.Defn = x1 253 // xN.Outer = x1.Innermost 254 // x1.Innermost = xN 255 // 256 // When we finish the function, we'll process its closure variables 257 // and find xN and pop it off the list using: 258 // 259 // x1 := xN.Defn 260 // x1.Innermost = xN.Outer 261 // 262 // We leave xN.Innermost set so that we can still get to the original 263 // variable quickly. Not shown here, but once we're 264 // done parsing a function and no longer need xN.Outer for the 265 // lexical x reference links as described above, closurebody 266 // recomputes xN.Outer as the semantic x reference link tree, 267 // even filling in x in intermediate closures that might not 268 // have mentioned it along the way to inner closures that did. 269 // See closurebody for details. 270 // 271 // During the eventual compilation, then, for closure variables we have: 272 // 273 // xN.Defn = original variable 274 // xN.Outer = variable captured in next outward scope 275 // to make closure where xN appears 276 // 277 // Because of the sharding of pieces of the node, x.Defn means x.Name.Defn 278 // and x.Innermost/Outer means x.Name.Param.Innermost/Outer. 279 Innermost *Node 280 Outer *Node 281 } 282 283 // Func holds Node fields used only with function-like nodes. 284 type Func struct { 285 Shortname *Node 286 Enter Nodes // for example, allocate and initialize memory for escaping parameters 287 Exit Nodes 288 Cvars Nodes // closure params 289 Dcl []*Node // autodcl for this func/closure 290 Inldcl Nodes // copy of dcl for use in inlining 291 Closgen int 292 Outerfunc *Node // outer function (for closure) 293 FieldTrack map[*Sym]struct{} 294 Ntype *Node // signature 295 Top int // top context (Ecall, Eproc, etc) 296 Closure *Node // OCLOSURE <-> ODCLFUNC 297 FCurfn *Node 298 Nname *Node 299 300 Inl Nodes // copy of the body for use in inlining 301 InlCost int32 302 Depth int32 303 304 Label int32 // largest auto-generated label in this function 305 306 Endlineno int32 307 WBLineno int32 // line number of first write barrier 308 309 Pragma Pragma // go:xxx function annotations 310 Dupok bool // duplicate definitions ok 311 Wrapper bool // is method wrapper 312 Needctxt bool // function uses context register (has closure variables) 313 ReflectMethod bool // function calls reflect.Type.Method or MethodByName 314 } 315 316 type Op uint8 317 318 // Node ops. 319 const ( 320 OXXX = Op(iota) 321 322 // names 323 ONAME // var, const or func name 324 ONONAME // unnamed arg or return value: f(int, string) (int, error) { etc } 325 OTYPE // type name 326 OPACK // import 327 OLITERAL // literal 328 329 // expressions 330 OADD // Left + Right 331 OSUB // Left - Right 332 OOR // Left | Right 333 OXOR // Left ^ Right 334 OADDSTR // +{List} (string addition, list elements are strings) 335 OADDR // &Left 336 OANDAND // Left && Right 337 OAPPEND // append(List) 338 OARRAYBYTESTR // Type(Left) (Type is string, Left is a []byte) 339 OARRAYBYTESTRTMP // Type(Left) (Type is string, Left is a []byte, ephemeral) 340 OARRAYRUNESTR // Type(Left) (Type is string, Left is a []rune) 341 OSTRARRAYBYTE // Type(Left) (Type is []byte, Left is a string) 342 OSTRARRAYBYTETMP // Type(Left) (Type is []byte, Left is a string, ephemeral) 343 OSTRARRAYRUNE // Type(Left) (Type is []rune, Left is a string) 344 OAS // Left = Right or (if Colas=true) Left := Right 345 OAS2 // List = Rlist (x, y, z = a, b, c) 346 OAS2FUNC // List = Rlist (x, y = f()) 347 OAS2RECV // List = Rlist (x, ok = <-c) 348 OAS2MAPR // List = Rlist (x, ok = m["foo"]) 349 OAS2DOTTYPE // List = Rlist (x, ok = I.(int)) 350 OASOP // Left Etype= Right (x += y) 351 OASWB // Left = Right (with write barrier) 352 OCALL // Left(List) (function call, method call or type conversion) 353 OCALLFUNC // Left(List) (function call f(args)) 354 OCALLMETH // Left(List) (direct method call x.Method(args)) 355 OCALLINTER // Left(List) (interface method call x.Method(args)) 356 OCALLPART // Left.Right (method expression x.Method, not called) 357 OCAP // cap(Left) 358 OCLOSE // close(Left) 359 OCLOSURE // func Type { Body } (func literal) 360 OCMPIFACE // Left Etype Right (interface comparison, x == y or x != y) 361 OCMPSTR // Left Etype Right (string comparison, x == y, x < y, etc) 362 OCOMPLIT // Right{List} (composite literal, not yet lowered to specific form) 363 OMAPLIT // Type{List} (composite literal, Type is map) 364 OSTRUCTLIT // Type{List} (composite literal, Type is struct) 365 OARRAYLIT // Type{List} (composite literal, Type is array or slice) 366 OPTRLIT // &Left (left is composite literal) 367 OCONV // Type(Left) (type conversion) 368 OCONVIFACE // Type(Left) (type conversion, to interface) 369 OCONVNOP // Type(Left) (type conversion, no effect) 370 OCOPY // copy(Left, Right) 371 ODCL // var Left (declares Left of type Left.Type) 372 373 // Used during parsing but don't last. 374 ODCLFUNC // func f() or func (r) f() 375 ODCLFIELD // struct field, interface field, or func/method argument/return value. 376 ODCLCONST // const pi = 3.14 377 ODCLTYPE // type Int int 378 379 ODELETE // delete(Left, Right) 380 ODOT // Left.Sym (Left is of struct type) 381 ODOTPTR // Left.Sym (Left is of pointer to struct type) 382 ODOTMETH // Left.Sym (Left is non-interface, Right is method name) 383 ODOTINTER // Left.Sym (Left is interface, Right is method name) 384 OXDOT // Left.Sym (before rewrite to one of the preceding) 385 ODOTTYPE // Left.Right or Left.Type (.Right during parsing, .Type once resolved) 386 ODOTTYPE2 // Left.Right or Left.Type (.Right during parsing, .Type once resolved; on rhs of OAS2DOTTYPE) 387 OEQ // Left == Right 388 ONE // Left != Right 389 OLT // Left < Right 390 OLE // Left <= Right 391 OGE // Left >= Right 392 OGT // Left > Right 393 OIND // *Left 394 OINDEX // Left[Right] (index of array or slice) 395 OINDEXMAP // Left[Right] (index of map) 396 OKEY // Left:Right (key:value in struct/array/map literal, or slice index pair) 397 OIDATA // data word of an interface value in Left; TODO: move next to OITAB once it is easier to regenerate the binary blob in builtin.go (issues 15835, 15839) 398 OLEN // len(Left) 399 OMAKE // make(List) (before type checking converts to one of the following) 400 OMAKECHAN // make(Type, Left) (type is chan) 401 OMAKEMAP // make(Type, Left) (type is map) 402 OMAKESLICE // make(Type, Left, Right) (type is slice) 403 OMUL // Left * Right 404 ODIV // Left / Right 405 OMOD // Left % Right 406 OLSH // Left << Right 407 ORSH // Left >> Right 408 OAND // Left & Right 409 OANDNOT // Left &^ Right 410 ONEW // new(Left) 411 ONOT // !Left 412 OCOM // ^Left 413 OPLUS // +Left 414 OMINUS // -Left 415 OOROR // Left || Right 416 OPANIC // panic(Left) 417 OPRINT // print(List) 418 OPRINTN // println(List) 419 OPAREN // (Left) 420 OSEND // Left <- Right 421 OSLICE // Left[Right.Left : Right.Right] (Left is untypechecked or slice; Right.Op==OKEY) 422 OSLICEARR // Left[Right.Left : Right.Right] (Left is array) 423 OSLICESTR // Left[Right.Left : Right.Right] (Left is string) 424 OSLICE3 // Left[R.Left : R.R.Left : R.R.R] (R=Right; Left is untypedchecked or slice; R.Op and R.R.Op==OKEY) 425 OSLICE3ARR // Left[R.Left : R.R.Left : R.R.R] (R=Right; Left is array; R.Op and R.R.Op==OKEY) 426 ORECOVER // recover() 427 ORECV // <-Left 428 ORUNESTR // Type(Left) (Type is string, Left is rune) 429 OSELRECV // Left = <-Right.Left: (appears as .Left of OCASE; Right.Op == ORECV) 430 OSELRECV2 // List = <-Right.Left: (apperas as .Left of OCASE; count(List) == 2, Right.Op == ORECV) 431 OIOTA // iota 432 OREAL // real(Left) 433 OIMAG // imag(Left) 434 OCOMPLEX // complex(Left, Right) 435 436 // statements 437 OBLOCK // { List } (block of code) 438 OBREAK // break 439 OCASE // case Left: Nbody (select case after processing; Left==nil means default) 440 OXCASE // case List: Nbody (select case before processing; List==nil means default) 441 OCONTINUE // continue 442 ODEFER // defer Left (Left must be call) 443 OEMPTY // no-op (empty statement) 444 OFALL // fallthrough (after processing) 445 OXFALL // fallthrough (before processing) 446 OFOR // for Ninit; Left; Right { Nbody } 447 OGOTO // goto Left 448 OIF // if Ninit; Left { Nbody } else { Rlist } 449 OLABEL // Left: 450 OPROC // go Left (Left must be call) 451 ORANGE // for List = range Right { Nbody } 452 ORETURN // return List 453 OSELECT // select { List } (List is list of OXCASE or OCASE) 454 OSWITCH // switch Ninit; Left { List } (List is a list of OXCASE or OCASE) 455 OTYPESW // List = Left.(type) (appears as .Left of OSWITCH) 456 457 // types 458 OTCHAN // chan int 459 OTMAP // map[string]int 460 OTSTRUCT // struct{} 461 OTINTER // interface{} 462 OTFUNC // func() 463 OTARRAY // []int, [8]int, [N]int or [...]int 464 465 // misc 466 ODDD // func f(args ...int) or f(l...) or var a = [...]int{0, 1, 2}. 467 ODDDARG // func f(args ...int), introduced by escape analysis. 468 OINLCALL // intermediary representation of an inlined call. 469 OEFACE // itable and data words of an empty-interface value. 470 OITAB // itable word of an interface value. 471 OSPTR // base pointer of a slice or string. 472 OCLOSUREVAR // variable reference at beginning of closure function 473 OCFUNC // reference to c function pointer (not go func value) 474 OCHECKNIL // emit code to ensure pointer/interface not nil 475 OVARKILL // variable is dead 476 OVARLIVE // variable is alive 477 478 // thearch-specific registers 479 OREGISTER // a register, such as AX. 480 OINDREG // offset plus indirect of a register, such as 8(SP). 481 482 // arch-specific opcodes 483 OCMP // compare: ACMP. 484 ODEC // decrement: ADEC. 485 OINC // increment: AINC. 486 OEXTEND // extend: ACWD/ACDQ/ACQO. 487 OHMUL // high mul: AMUL/AIMUL for unsigned/signed (OMUL uses AIMUL for both). 488 OLROT // left rotate: AROL. 489 ORROTC // right rotate-carry: ARCR. 490 ORETJMP // return to other function 491 OPS // compare parity set (for x86 NaN check) 492 OPC // compare parity clear (for x86 NaN check) 493 OSQRT // sqrt(float64), on systems that have hw support 494 OGETG // runtime.getg() (read g pointer) 495 496 OEND 497 ) 498 499 // Nodes is a pointer to a slice of *Node. 500 // For fields that are not used in most nodes, this is used instead of 501 // a slice to save space. 502 type Nodes struct{ slice *[]*Node } 503 504 // Slice returns the entries in Nodes as a slice. 505 // Changes to the slice entries (as in s[i] = n) will be reflected in 506 // the Nodes. 507 func (n Nodes) Slice() []*Node { 508 if n.slice == nil { 509 return nil 510 } 511 return *n.slice 512 } 513 514 // Len returns the number of entries in Nodes. 515 func (n Nodes) Len() int { 516 if n.slice == nil { 517 return 0 518 } 519 return len(*n.slice) 520 } 521 522 // Index returns the i'th element of Nodes. 523 // It panics if n does not have at least i+1 elements. 524 func (n Nodes) Index(i int) *Node { 525 return (*n.slice)[i] 526 } 527 528 // First returns the first element of Nodes (same as n.Index(0)). 529 // It panics if n has no elements. 530 func (n Nodes) First() *Node { 531 return (*n.slice)[0] 532 } 533 534 // Second returns the second element of Nodes (same as n.Index(1)). 535 // It panics if n has fewer than two elements. 536 func (n Nodes) Second() *Node { 537 return (*n.slice)[1] 538 } 539 540 // Set sets n to a slice. 541 // This takes ownership of the slice. 542 func (n *Nodes) Set(s []*Node) { 543 if len(s) == 0 { 544 n.slice = nil 545 } else { 546 // Copy s and take address of t rather than s to avoid 547 // allocation in the case where len(s) == 0 (which is 548 // over 3x more common, dynamically, for make.bash). 549 t := s 550 n.slice = &t 551 } 552 } 553 554 // Set1 sets n to a slice containing a single node. 555 func (n *Nodes) Set1(node *Node) { 556 n.slice = &[]*Node{node} 557 } 558 559 // Set2 sets n to a slice containing two nodes. 560 func (n *Nodes) Set2(n1, n2 *Node) { 561 n.slice = &[]*Node{n1, n2} 562 } 563 564 // MoveNodes sets n to the contents of n2, then clears n2. 565 func (n *Nodes) MoveNodes(n2 *Nodes) { 566 n.slice = n2.slice 567 n2.slice = nil 568 } 569 570 // SetIndex sets the i'th element of Nodes to node. 571 // It panics if n does not have at least i+1 elements. 572 func (n Nodes) SetIndex(i int, node *Node) { 573 (*n.slice)[i] = node 574 } 575 576 // Addr returns the address of the i'th element of Nodes. 577 // It panics if n does not have at least i+1 elements. 578 func (n Nodes) Addr(i int) **Node { 579 return &(*n.slice)[i] 580 } 581 582 // Append appends entries to Nodes. 583 // If a slice is passed in, this will take ownership of it. 584 func (n *Nodes) Append(a ...*Node) { 585 if n.slice == nil { 586 if len(a) > 0 { 587 n.slice = &a 588 } 589 } else { 590 *n.slice = append(*n.slice, a...) 591 } 592 } 593 594 // AppendNodes appends the contents of *n2 to n, then clears n2. 595 func (n *Nodes) AppendNodes(n2 *Nodes) { 596 switch { 597 case n2.slice == nil: 598 case n.slice == nil: 599 n.slice = n2.slice 600 default: 601 *n.slice = append(*n.slice, *n2.slice...) 602 } 603 n2.slice = nil 604 }