github.com/hlts2/go@v0.0.0-20170904000733-812b34efaed8/src/cmd/compile/internal/ssa/func.go (about) 1 // Copyright 2015 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 ssa 6 7 import ( 8 "cmd/compile/internal/types" 9 "cmd/internal/src" 10 "crypto/sha1" 11 "fmt" 12 "io" 13 "math" 14 "os" 15 "strings" 16 ) 17 18 type writeSyncer interface { 19 io.Writer 20 Sync() error 21 } 22 23 // A Func represents a Go func declaration (or function literal) and its body. 24 // This package compiles each Func independently. 25 // Funcs are single-use; a new Func must be created for every compiled function. 26 type Func struct { 27 Config *Config // architecture information 28 Cache *Cache // re-usable cache 29 fe Frontend // frontend state associated with this Func, callbacks into compiler frontend 30 pass *pass // current pass information (name, options, etc.) 31 Name string // e.g. bytes·Compare 32 Type *types.Type // type signature of the function. 33 Blocks []*Block // unordered set of all basic blocks (note: not indexable by ID) 34 Entry *Block // the entry basic block 35 bid idAlloc // block ID allocator 36 vid idAlloc // value ID allocator 37 38 // Given an environment variable used for debug hash match, 39 // what file (if any) receives the yes/no logging? 40 logfiles map[string]writeSyncer 41 HTMLWriter *HTMLWriter // html writer, for debugging 42 DebugTest bool // default true unless $GOSSAHASH != ""; as a debugging aid, make new code conditional on this and use GOSSAHASH to binary search for failing cases 43 44 scheduled bool // Values in Blocks are in final order 45 NoSplit bool // true if function is marked as nosplit. Used by schedule check pass. 46 47 WBPos src.XPos // line number of first write barrier 48 49 // when register allocation is done, maps value ids to locations 50 RegAlloc []Location 51 52 // map from LocalSlot to set of Values that we want to store in that slot. 53 NamedValues map[LocalSlot][]*Value 54 // Names is a copy of NamedValues.Keys. We keep a separate list 55 // of keys to make iteration order deterministic. 56 Names []LocalSlot 57 58 freeValues *Value // free Values linked by argstorage[0]. All other fields except ID are 0/nil. 59 freeBlocks *Block // free Blocks linked by succstorage[0].b. All other fields except ID are 0/nil. 60 61 cachedPostorder []*Block // cached postorder traversal 62 cachedIdom []*Block // cached immediate dominators 63 cachedSdom SparseTree // cached dominator tree 64 cachedLoopnest *loopnest // cached loop nest information 65 66 auxmap auxmap // map from aux values to opaque ids used by CSE 67 68 constants map[int64][]*Value // constants cache, keyed by constant value; users must check value's Op and Type 69 } 70 71 // NewFunc returns a new, empty function object. 72 // Caller must set f.Config and f.Cache before using f. 73 func NewFunc(fe Frontend) *Func { 74 return &Func{fe: fe, NamedValues: make(map[LocalSlot][]*Value)} 75 } 76 77 // NumBlocks returns an integer larger than the id of any Block in the Func. 78 func (f *Func) NumBlocks() int { 79 return f.bid.num() 80 } 81 82 // NumValues returns an integer larger than the id of any Value in the Func. 83 func (f *Func) NumValues() int { 84 return f.vid.num() 85 } 86 87 // newSparseSet returns a sparse set that can store at least up to n integers. 88 func (f *Func) newSparseSet(n int) *sparseSet { 89 for i, scr := range f.Cache.scrSparse { 90 if scr != nil && scr.cap() >= n { 91 f.Cache.scrSparse[i] = nil 92 scr.clear() 93 return scr 94 } 95 } 96 return newSparseSet(n) 97 } 98 99 // retSparseSet returns a sparse set to the config's cache of sparse sets to be reused by f.newSparseSet. 100 func (f *Func) retSparseSet(ss *sparseSet) { 101 for i, scr := range f.Cache.scrSparse { 102 if scr == nil { 103 f.Cache.scrSparse[i] = ss 104 return 105 } 106 } 107 f.Cache.scrSparse = append(f.Cache.scrSparse, ss) 108 } 109 110 // newValue allocates a new Value with the given fields and places it at the end of b.Values. 111 func (f *Func) newValue(op Op, t *types.Type, b *Block, pos src.XPos) *Value { 112 var v *Value 113 if f.freeValues != nil { 114 v = f.freeValues 115 f.freeValues = v.argstorage[0] 116 v.argstorage[0] = nil 117 } else { 118 ID := f.vid.get() 119 if int(ID) < len(f.Cache.values) { 120 v = &f.Cache.values[ID] 121 v.ID = ID 122 } else { 123 v = &Value{ID: ID} 124 } 125 } 126 v.Op = op 127 v.Type = t 128 v.Block = b 129 v.Pos = pos 130 b.Values = append(b.Values, v) 131 return v 132 } 133 134 // newValueNoBlock allocates a new Value with the given fields. 135 // The returned value is not placed in any block. Once the caller 136 // decides on a block b, it must set b.Block and append 137 // the returned value to b.Values. 138 func (f *Func) newValueNoBlock(op Op, t *types.Type, pos src.XPos) *Value { 139 var v *Value 140 if f.freeValues != nil { 141 v = f.freeValues 142 f.freeValues = v.argstorage[0] 143 v.argstorage[0] = nil 144 } else { 145 ID := f.vid.get() 146 if int(ID) < len(f.Cache.values) { 147 v = &f.Cache.values[ID] 148 v.ID = ID 149 } else { 150 v = &Value{ID: ID} 151 } 152 } 153 v.Op = op 154 v.Type = t 155 v.Block = nil // caller must fix this. 156 v.Pos = pos 157 return v 158 } 159 160 // logPassStat writes a string key and int value as a warning in a 161 // tab-separated format easily handled by spreadsheets or awk. 162 // file names, lines, and function names are included to provide enough (?) 163 // context to allow item-by-item comparisons across runs. 164 // For example: 165 // awk 'BEGIN {FS="\t"} $3~/TIME/{sum+=$4} END{print "t(ns)=",sum}' t.log 166 func (f *Func) LogStat(key string, args ...interface{}) { 167 value := "" 168 for _, a := range args { 169 value += fmt.Sprintf("\t%v", a) 170 } 171 n := "missing_pass" 172 if f.pass != nil { 173 n = strings.Replace(f.pass.name, " ", "_", -1) 174 } 175 f.Warnl(f.Entry.Pos, "\t%s\t%s%s\t%s", n, key, value, f.Name) 176 } 177 178 // freeValue frees a value. It must no longer be referenced or have any args. 179 func (f *Func) freeValue(v *Value) { 180 if v.Block == nil { 181 f.Fatalf("trying to free an already freed value") 182 } 183 if v.Uses != 0 { 184 f.Fatalf("value %s still has %d uses", v, v.Uses) 185 } 186 if len(v.Args) != 0 { 187 f.Fatalf("value %s still has %d args", v, len(v.Args)) 188 } 189 // Clear everything but ID (which we reuse). 190 id := v.ID 191 192 // Values with zero arguments and OpOffPtr values might be cached, so remove them there. 193 nArgs := opcodeTable[v.Op].argLen 194 if nArgs == 0 || v.Op == OpOffPtr { 195 vv := f.constants[v.AuxInt] 196 for i, cv := range vv { 197 if v == cv { 198 vv[i] = vv[len(vv)-1] 199 vv[len(vv)-1] = nil 200 f.constants[v.AuxInt] = vv[0 : len(vv)-1] 201 break 202 } 203 } 204 } 205 *v = Value{} 206 v.ID = id 207 v.argstorage[0] = f.freeValues 208 f.freeValues = v 209 } 210 211 // newBlock allocates a new Block of the given kind and places it at the end of f.Blocks. 212 func (f *Func) NewBlock(kind BlockKind) *Block { 213 var b *Block 214 if f.freeBlocks != nil { 215 b = f.freeBlocks 216 f.freeBlocks = b.succstorage[0].b 217 b.succstorage[0].b = nil 218 } else { 219 ID := f.bid.get() 220 if int(ID) < len(f.Cache.blocks) { 221 b = &f.Cache.blocks[ID] 222 b.ID = ID 223 } else { 224 b = &Block{ID: ID} 225 } 226 } 227 b.Kind = kind 228 b.Func = f 229 b.Preds = b.predstorage[:0] 230 b.Succs = b.succstorage[:0] 231 b.Values = b.valstorage[:0] 232 f.Blocks = append(f.Blocks, b) 233 f.invalidateCFG() 234 return b 235 } 236 237 func (f *Func) freeBlock(b *Block) { 238 if b.Func == nil { 239 f.Fatalf("trying to free an already freed block") 240 } 241 // Clear everything but ID (which we reuse). 242 id := b.ID 243 *b = Block{} 244 b.ID = id 245 b.succstorage[0].b = f.freeBlocks 246 f.freeBlocks = b 247 } 248 249 // NewValue0 returns a new value in the block with no arguments and zero aux values. 250 func (b *Block) NewValue0(pos src.XPos, op Op, t *types.Type) *Value { 251 v := b.Func.newValue(op, t, b, pos) 252 v.AuxInt = 0 253 v.Args = v.argstorage[:0] 254 return v 255 } 256 257 // NewValue returns a new value in the block with no arguments and an auxint value. 258 func (b *Block) NewValue0I(pos src.XPos, op Op, t *types.Type, auxint int64) *Value { 259 v := b.Func.newValue(op, t, b, pos) 260 v.AuxInt = auxint 261 v.Args = v.argstorage[:0] 262 return v 263 } 264 265 // NewValue returns a new value in the block with no arguments and an aux value. 266 func (b *Block) NewValue0A(pos src.XPos, op Op, t *types.Type, aux interface{}) *Value { 267 if _, ok := aux.(int64); ok { 268 // Disallow int64 aux values. They should be in the auxint field instead. 269 // Maybe we want to allow this at some point, but for now we disallow it 270 // to prevent errors like using NewValue1A instead of NewValue1I. 271 b.Fatalf("aux field has int64 type op=%s type=%s aux=%v", op, t, aux) 272 } 273 v := b.Func.newValue(op, t, b, pos) 274 v.AuxInt = 0 275 v.Aux = aux 276 v.Args = v.argstorage[:0] 277 return v 278 } 279 280 // NewValue returns a new value in the block with no arguments and both an auxint and aux values. 281 func (b *Block) NewValue0IA(pos src.XPos, op Op, t *types.Type, auxint int64, aux interface{}) *Value { 282 v := b.Func.newValue(op, t, b, pos) 283 v.AuxInt = auxint 284 v.Aux = aux 285 v.Args = v.argstorage[:0] 286 return v 287 } 288 289 // NewValue1 returns a new value in the block with one argument and zero aux values. 290 func (b *Block) NewValue1(pos src.XPos, op Op, t *types.Type, arg *Value) *Value { 291 v := b.Func.newValue(op, t, b, pos) 292 v.AuxInt = 0 293 v.Args = v.argstorage[:1] 294 v.argstorage[0] = arg 295 arg.Uses++ 296 return v 297 } 298 299 // NewValue1I returns a new value in the block with one argument and an auxint value. 300 func (b *Block) NewValue1I(pos src.XPos, op Op, t *types.Type, auxint int64, arg *Value) *Value { 301 v := b.Func.newValue(op, t, b, pos) 302 v.AuxInt = auxint 303 v.Args = v.argstorage[:1] 304 v.argstorage[0] = arg 305 arg.Uses++ 306 return v 307 } 308 309 // NewValue1A returns a new value in the block with one argument and an aux value. 310 func (b *Block) NewValue1A(pos src.XPos, op Op, t *types.Type, aux interface{}, arg *Value) *Value { 311 v := b.Func.newValue(op, t, b, pos) 312 v.AuxInt = 0 313 v.Aux = aux 314 v.Args = v.argstorage[:1] 315 v.argstorage[0] = arg 316 arg.Uses++ 317 return v 318 } 319 320 // NewValue1IA returns a new value in the block with one argument and both an auxint and aux values. 321 func (b *Block) NewValue1IA(pos src.XPos, op Op, t *types.Type, auxint int64, aux interface{}, arg *Value) *Value { 322 v := b.Func.newValue(op, t, b, pos) 323 v.AuxInt = auxint 324 v.Aux = aux 325 v.Args = v.argstorage[:1] 326 v.argstorage[0] = arg 327 arg.Uses++ 328 return v 329 } 330 331 // NewValue2 returns a new value in the block with two arguments and zero aux values. 332 func (b *Block) NewValue2(pos src.XPos, op Op, t *types.Type, arg0, arg1 *Value) *Value { 333 v := b.Func.newValue(op, t, b, pos) 334 v.AuxInt = 0 335 v.Args = v.argstorage[:2] 336 v.argstorage[0] = arg0 337 v.argstorage[1] = arg1 338 arg0.Uses++ 339 arg1.Uses++ 340 return v 341 } 342 343 // NewValue2I returns a new value in the block with two arguments and an auxint value. 344 func (b *Block) NewValue2I(pos src.XPos, op Op, t *types.Type, auxint int64, arg0, arg1 *Value) *Value { 345 v := b.Func.newValue(op, t, b, pos) 346 v.AuxInt = auxint 347 v.Args = v.argstorage[:2] 348 v.argstorage[0] = arg0 349 v.argstorage[1] = arg1 350 arg0.Uses++ 351 arg1.Uses++ 352 return v 353 } 354 355 // NewValue3 returns a new value in the block with three arguments and zero aux values. 356 func (b *Block) NewValue3(pos src.XPos, op Op, t *types.Type, arg0, arg1, arg2 *Value) *Value { 357 v := b.Func.newValue(op, t, b, pos) 358 v.AuxInt = 0 359 v.Args = v.argstorage[:3] 360 v.argstorage[0] = arg0 361 v.argstorage[1] = arg1 362 v.argstorage[2] = arg2 363 arg0.Uses++ 364 arg1.Uses++ 365 arg2.Uses++ 366 return v 367 } 368 369 // NewValue3I returns a new value in the block with three arguments and an auxint value. 370 func (b *Block) NewValue3I(pos src.XPos, op Op, t *types.Type, auxint int64, arg0, arg1, arg2 *Value) *Value { 371 v := b.Func.newValue(op, t, b, pos) 372 v.AuxInt = auxint 373 v.Args = v.argstorage[:3] 374 v.argstorage[0] = arg0 375 v.argstorage[1] = arg1 376 v.argstorage[2] = arg2 377 arg0.Uses++ 378 arg1.Uses++ 379 arg2.Uses++ 380 return v 381 } 382 383 // NewValue3A returns a new value in the block with three argument and an aux value. 384 func (b *Block) NewValue3A(pos src.XPos, op Op, t *types.Type, aux interface{}, arg0, arg1, arg2 *Value) *Value { 385 v := b.Func.newValue(op, t, b, pos) 386 v.AuxInt = 0 387 v.Aux = aux 388 v.Args = v.argstorage[:3] 389 v.argstorage[0] = arg0 390 v.argstorage[1] = arg1 391 v.argstorage[2] = arg2 392 arg0.Uses++ 393 arg1.Uses++ 394 arg2.Uses++ 395 return v 396 } 397 398 // NewValue4 returns a new value in the block with four arguments and zero aux values. 399 func (b *Block) NewValue4(pos src.XPos, op Op, t *types.Type, arg0, arg1, arg2, arg3 *Value) *Value { 400 v := b.Func.newValue(op, t, b, pos) 401 v.AuxInt = 0 402 v.Args = []*Value{arg0, arg1, arg2, arg3} 403 arg0.Uses++ 404 arg1.Uses++ 405 arg2.Uses++ 406 arg3.Uses++ 407 return v 408 } 409 410 // constVal returns a constant value for c. 411 func (f *Func) constVal(pos src.XPos, op Op, t *types.Type, c int64, setAuxInt bool) *Value { 412 if f.constants == nil { 413 f.constants = make(map[int64][]*Value) 414 } 415 vv := f.constants[c] 416 for _, v := range vv { 417 if v.Op == op && v.Type.Compare(t) == types.CMPeq { 418 if setAuxInt && v.AuxInt != c { 419 panic(fmt.Sprintf("cached const %s should have AuxInt of %d", v.LongString(), c)) 420 } 421 return v 422 } 423 } 424 var v *Value 425 if setAuxInt { 426 v = f.Entry.NewValue0I(pos, op, t, c) 427 } else { 428 v = f.Entry.NewValue0(pos, op, t) 429 } 430 f.constants[c] = append(vv, v) 431 return v 432 } 433 434 // These magic auxint values let us easily cache non-numeric constants 435 // using the same constants map while making collisions unlikely. 436 // These values are unlikely to occur in regular code and 437 // are easy to grep for in case of bugs. 438 const ( 439 constSliceMagic = 1122334455 440 constInterfaceMagic = 2233445566 441 constNilMagic = 3344556677 442 constEmptyStringMagic = 4455667788 443 ) 444 445 // ConstInt returns an int constant representing its argument. 446 func (f *Func) ConstBool(pos src.XPos, t *types.Type, c bool) *Value { 447 i := int64(0) 448 if c { 449 i = 1 450 } 451 return f.constVal(pos, OpConstBool, t, i, true) 452 } 453 func (f *Func) ConstInt8(pos src.XPos, t *types.Type, c int8) *Value { 454 return f.constVal(pos, OpConst8, t, int64(c), true) 455 } 456 func (f *Func) ConstInt16(pos src.XPos, t *types.Type, c int16) *Value { 457 return f.constVal(pos, OpConst16, t, int64(c), true) 458 } 459 func (f *Func) ConstInt32(pos src.XPos, t *types.Type, c int32) *Value { 460 return f.constVal(pos, OpConst32, t, int64(c), true) 461 } 462 func (f *Func) ConstInt64(pos src.XPos, t *types.Type, c int64) *Value { 463 return f.constVal(pos, OpConst64, t, c, true) 464 } 465 func (f *Func) ConstFloat32(pos src.XPos, t *types.Type, c float64) *Value { 466 return f.constVal(pos, OpConst32F, t, int64(math.Float64bits(float64(float32(c)))), true) 467 } 468 func (f *Func) ConstFloat64(pos src.XPos, t *types.Type, c float64) *Value { 469 return f.constVal(pos, OpConst64F, t, int64(math.Float64bits(c)), true) 470 } 471 472 func (f *Func) ConstSlice(pos src.XPos, t *types.Type) *Value { 473 return f.constVal(pos, OpConstSlice, t, constSliceMagic, false) 474 } 475 func (f *Func) ConstInterface(pos src.XPos, t *types.Type) *Value { 476 return f.constVal(pos, OpConstInterface, t, constInterfaceMagic, false) 477 } 478 func (f *Func) ConstNil(pos src.XPos, t *types.Type) *Value { 479 return f.constVal(pos, OpConstNil, t, constNilMagic, false) 480 } 481 func (f *Func) ConstEmptyString(pos src.XPos, t *types.Type) *Value { 482 v := f.constVal(pos, OpConstString, t, constEmptyStringMagic, false) 483 v.Aux = "" 484 return v 485 } 486 func (f *Func) ConstOffPtrSP(pos src.XPos, t *types.Type, c int64, sp *Value) *Value { 487 v := f.constVal(pos, OpOffPtr, t, c, true) 488 if len(v.Args) == 0 { 489 v.AddArg(sp) 490 } 491 return v 492 493 } 494 495 func (f *Func) Frontend() Frontend { return f.fe } 496 func (f *Func) Warnl(pos src.XPos, msg string, args ...interface{}) { f.fe.Warnl(pos, msg, args...) } 497 func (f *Func) Logf(msg string, args ...interface{}) { f.fe.Logf(msg, args...) } 498 func (f *Func) Log() bool { return f.fe.Log() } 499 func (f *Func) Fatalf(msg string, args ...interface{}) { f.fe.Fatalf(f.Entry.Pos, msg, args...) } 500 501 // postorder returns the reachable blocks in f in a postorder traversal. 502 func (f *Func) postorder() []*Block { 503 if f.cachedPostorder == nil { 504 f.cachedPostorder = postorder(f) 505 } 506 return f.cachedPostorder 507 } 508 509 func (f *Func) Postorder() []*Block { 510 return f.postorder() 511 } 512 513 // Idom returns a map from block ID to the immediate dominator of that block. 514 // f.Entry.ID maps to nil. Unreachable blocks map to nil as well. 515 func (f *Func) Idom() []*Block { 516 if f.cachedIdom == nil { 517 f.cachedIdom = dominators(f) 518 } 519 return f.cachedIdom 520 } 521 522 // sdom returns a sparse tree representing the dominator relationships 523 // among the blocks of f. 524 func (f *Func) sdom() SparseTree { 525 if f.cachedSdom == nil { 526 f.cachedSdom = newSparseTree(f, f.Idom()) 527 } 528 return f.cachedSdom 529 } 530 531 // loopnest returns the loop nest information for f. 532 func (f *Func) loopnest() *loopnest { 533 if f.cachedLoopnest == nil { 534 f.cachedLoopnest = loopnestfor(f) 535 } 536 return f.cachedLoopnest 537 } 538 539 // invalidateCFG tells f that its CFG has changed. 540 func (f *Func) invalidateCFG() { 541 f.cachedPostorder = nil 542 f.cachedIdom = nil 543 f.cachedSdom = nil 544 f.cachedLoopnest = nil 545 } 546 547 // DebugHashMatch returns true if environment variable evname 548 // 1) is empty (this is a special more-quickly implemented case of 3) 549 // 2) is "y" or "Y" 550 // 3) is a suffix of the sha1 hash of name 551 // 4) is a suffix of the environment variable 552 // fmt.Sprintf("%s%d", evname, n) 553 // provided that all such variables are nonempty for 0 <= i <= n 554 // Otherwise it returns false. 555 // When true is returned the message 556 // "%s triggered %s\n", evname, name 557 // is printed on the file named in environment variable 558 // GSHS_LOGFILE 559 // or standard out if that is empty or there is an error 560 // opening the file. 561 func (f *Func) DebugHashMatch(evname, name string) bool { 562 evhash := os.Getenv(evname) 563 switch evhash { 564 case "": 565 return true // default behavior with no EV is "on" 566 case "y", "Y": 567 f.logDebugHashMatch(evname, name) 568 return true 569 case "n", "N": 570 return false 571 } 572 // Check the hash of the name against a partial input hash. 573 // We use this feature to do a binary search to 574 // find a function that is incorrectly compiled. 575 hstr := "" 576 for _, b := range sha1.Sum([]byte(name)) { 577 hstr += fmt.Sprintf("%08b", b) 578 } 579 580 if strings.HasSuffix(hstr, evhash) { 581 f.logDebugHashMatch(evname, name) 582 return true 583 } 584 585 // Iteratively try additional hashes to allow tests for multi-point 586 // failure. 587 for i := 0; true; i++ { 588 ev := fmt.Sprintf("%s%d", evname, i) 589 evv := os.Getenv(ev) 590 if evv == "" { 591 break 592 } 593 if strings.HasSuffix(hstr, evv) { 594 f.logDebugHashMatch(ev, name) 595 return true 596 } 597 } 598 return false 599 } 600 601 func (f *Func) logDebugHashMatch(evname, name string) { 602 if f.logfiles == nil { 603 f.logfiles = make(map[string]writeSyncer) 604 } 605 file := f.logfiles[evname] 606 if file == nil { 607 file = os.Stdout 608 if tmpfile := os.Getenv("GSHS_LOGFILE"); tmpfile != "" { 609 var err error 610 file, err = os.Create(tmpfile) 611 if err != nil { 612 f.Fatalf("could not open hash-testing logfile %s", tmpfile) 613 } 614 } 615 f.logfiles[evname] = file 616 } 617 fmt.Fprintf(file, "%s triggered %s\n", evname, name) 618 file.Sync() 619 } 620 621 func DebugNameMatch(evname, name string) bool { 622 return os.Getenv(evname) == name 623 }