Source file src/cmd/compile/internal/ssa/nilcheck.go

     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/ir"
     9  	"cmd/internal/src"
    10  	"internal/buildcfg"
    11  )
    12  
    13  // nilcheckelim eliminates unnecessary nil checks.
    14  // runs on machine-independent code.
    15  func nilcheckelim(f *Func) {
    16  	// A nil check is redundant if the same nil check was successful in a
    17  	// dominating block. The efficacy of this pass depends heavily on the
    18  	// efficacy of the cse pass.
    19  	sdom := f.Sdom()
    20  
    21  	// TODO: Eliminate more nil checks.
    22  	// We can recursively remove any chain of fixed offset calculations,
    23  	// i.e. struct fields and array elements, even with non-constant
    24  	// indices: x is non-nil iff x.a.b[i].c is.
    25  
    26  	type walkState int
    27  	const (
    28  		Work     walkState = iota // process nil checks and traverse to dominees
    29  		ClearPtr                  // forget the fact that ptr is nil
    30  	)
    31  
    32  	type bp struct {
    33  		block *Block // block, or nil in ClearPtr state
    34  		ptr   *Value // if non-nil, ptr that is to be cleared in ClearPtr state
    35  		op    walkState
    36  	}
    37  
    38  	work := make([]bp, 0, 256)
    39  	work = append(work, bp{block: f.Entry})
    40  
    41  	// map from value ID to bool indicating if value is known to be non-nil
    42  	// in the current dominator path being walked. This slice is updated by
    43  	// walkStates to maintain the known non-nil values.
    44  	nonNilValues := make([]bool, f.NumValues())
    45  
    46  	// make an initial pass identifying any non-nil values
    47  	for _, b := range f.Blocks {
    48  		for _, v := range b.Values {
    49  			// a value resulting from taking the address of a
    50  			// value, or a value constructed from an offset of a
    51  			// non-nil ptr (OpAddPtr) implies it is non-nil
    52  			// We also assume unsafe pointer arithmetic generates non-nil pointers. See #27180.
    53  			// We assume that SlicePtr is non-nil because we do a bounds check
    54  			// before the slice access (and all cap>0 slices have a non-nil ptr). See #30366.
    55  			if v.Op == OpAddr || v.Op == OpLocalAddr || v.Op == OpAddPtr || v.Op == OpOffPtr || v.Op == OpAdd32 || v.Op == OpAdd64 || v.Op == OpSub32 || v.Op == OpSub64 || v.Op == OpSlicePtr {
    56  				nonNilValues[v.ID] = true
    57  			}
    58  		}
    59  	}
    60  
    61  	for changed := true; changed; {
    62  		changed = false
    63  		for _, b := range f.Blocks {
    64  			for _, v := range b.Values {
    65  				// phis whose arguments are all non-nil
    66  				// are non-nil
    67  				if v.Op == OpPhi {
    68  					argsNonNil := true
    69  					for _, a := range v.Args {
    70  						if !nonNilValues[a.ID] {
    71  							argsNonNil = false
    72  							break
    73  						}
    74  					}
    75  					if argsNonNil {
    76  						if !nonNilValues[v.ID] {
    77  							changed = true
    78  						}
    79  						nonNilValues[v.ID] = true
    80  					}
    81  				}
    82  			}
    83  		}
    84  	}
    85  
    86  	// allocate auxiliary date structures for computing store order
    87  	sset := f.newSparseSet(f.NumValues())
    88  	defer f.retSparseSet(sset)
    89  	storeNumber := make([]int32, f.NumValues())
    90  
    91  	// perform a depth first walk of the dominee tree
    92  	for len(work) > 0 {
    93  		node := work[len(work)-1]
    94  		work = work[:len(work)-1]
    95  
    96  		switch node.op {
    97  		case Work:
    98  			b := node.block
    99  
   100  			// First, see if we're dominated by an explicit nil check.
   101  			if len(b.Preds) == 1 {
   102  				p := b.Preds[0].b
   103  				if p.Kind == BlockIf && p.Controls[0].Op == OpIsNonNil && p.Succs[0].b == b {
   104  					if ptr := p.Controls[0].Args[0]; !nonNilValues[ptr.ID] {
   105  						nonNilValues[ptr.ID] = true
   106  						work = append(work, bp{op: ClearPtr, ptr: ptr})
   107  					}
   108  				}
   109  			}
   110  
   111  			// Next, order values in the current block w.r.t. stores.
   112  			b.Values = storeOrder(b.Values, sset, storeNumber)
   113  
   114  			pendingLines := f.cachedLineStarts // Holds statement boundaries that need to be moved to a new value/block
   115  			pendingLines.clear()
   116  
   117  			// Next, process values in the block.
   118  			i := 0
   119  			for _, v := range b.Values {
   120  				b.Values[i] = v
   121  				i++
   122  				switch v.Op {
   123  				case OpIsNonNil:
   124  					ptr := v.Args[0]
   125  					if nonNilValues[ptr.ID] {
   126  						if v.Pos.IsStmt() == src.PosIsStmt { // Boolean true is a terrible statement boundary.
   127  							pendingLines.add(v.Pos)
   128  							v.Pos = v.Pos.WithNotStmt()
   129  						}
   130  						// This is a redundant explicit nil check.
   131  						v.reset(OpConstBool)
   132  						v.AuxInt = 1 // true
   133  					}
   134  				case OpNilCheck:
   135  					ptr := v.Args[0]
   136  					if nonNilValues[ptr.ID] {
   137  						// This is a redundant implicit nil check.
   138  						// Logging in the style of the former compiler -- and omit line 1,
   139  						// which is usually in generated code.
   140  						if f.fe.Debug_checknil() && v.Pos.Line() > 1 {
   141  							f.Warnl(v.Pos, "removed nil check")
   142  						}
   143  						if v.Pos.IsStmt() == src.PosIsStmt { // About to lose a statement boundary
   144  							pendingLines.add(v.Pos)
   145  						}
   146  						v.reset(OpUnknown)
   147  						f.freeValue(v)
   148  						i--
   149  						continue
   150  					}
   151  					// Record the fact that we know ptr is non nil, and remember to
   152  					// undo that information when this dominator subtree is done.
   153  					nonNilValues[ptr.ID] = true
   154  					work = append(work, bp{op: ClearPtr, ptr: ptr})
   155  					fallthrough // a non-eliminated nil check might be a good place for a statement boundary.
   156  				default:
   157  					if v.Pos.IsStmt() != src.PosNotStmt && !isPoorStatementOp(v.Op) && pendingLines.contains(v.Pos) {
   158  						v.Pos = v.Pos.WithIsStmt()
   159  						pendingLines.remove(v.Pos)
   160  					}
   161  				}
   162  			}
   163  			// This reduces the lost statement count in "go" by 5 (out of 500 total).
   164  			for j := 0; j < i; j++ { // is this an ordering problem?
   165  				v := b.Values[j]
   166  				if v.Pos.IsStmt() != src.PosNotStmt && !isPoorStatementOp(v.Op) && pendingLines.contains(v.Pos) {
   167  					v.Pos = v.Pos.WithIsStmt()
   168  					pendingLines.remove(v.Pos)
   169  				}
   170  			}
   171  			if pendingLines.contains(b.Pos) {
   172  				b.Pos = b.Pos.WithIsStmt()
   173  				pendingLines.remove(b.Pos)
   174  			}
   175  			b.truncateValues(i)
   176  
   177  			// Add all dominated blocks to the work list.
   178  			for w := sdom[node.block.ID].child; w != nil; w = sdom[w.ID].sibling {
   179  				work = append(work, bp{op: Work, block: w})
   180  			}
   181  
   182  		case ClearPtr:
   183  			nonNilValues[node.ptr.ID] = false
   184  			continue
   185  		}
   186  	}
   187  }
   188  
   189  // All platforms are guaranteed to fault if we load/store to anything smaller than this address.
   190  //
   191  // This should agree with minLegalPointer in the runtime.
   192  const minZeroPage = 4096
   193  
   194  // faultOnLoad is true if a load to an address below minZeroPage will trigger a SIGSEGV.
   195  var faultOnLoad = buildcfg.GOOS != "aix"
   196  
   197  // nilcheckelim2 eliminates unnecessary nil checks.
   198  // Runs after lowering and scheduling.
   199  func nilcheckelim2(f *Func) {
   200  	unnecessary := f.newSparseMap(f.NumValues()) // map from pointer that will be dereferenced to index of dereferencing value in b.Values[]
   201  	defer f.retSparseMap(unnecessary)
   202  
   203  	pendingLines := f.cachedLineStarts // Holds statement boundaries that need to be moved to a new value/block
   204  
   205  	for _, b := range f.Blocks {
   206  		// Walk the block backwards. Find instructions that will fault if their
   207  		// input pointer is nil. Remove nil checks on those pointers, as the
   208  		// faulting instruction effectively does the nil check for free.
   209  		unnecessary.clear()
   210  		pendingLines.clear()
   211  		// Optimization: keep track of removed nilcheck with smallest index
   212  		firstToRemove := len(b.Values)
   213  		for i := len(b.Values) - 1; i >= 0; i-- {
   214  			v := b.Values[i]
   215  			if opcodeTable[v.Op].nilCheck && unnecessary.contains(v.Args[0].ID) {
   216  				if f.fe.Debug_checknil() && v.Pos.Line() > 1 {
   217  					f.Warnl(v.Pos, "removed nil check")
   218  				}
   219  				// For bug 33724, policy is that we might choose to bump an existing position
   220  				// off the faulting load/store in favor of the one from the nil check.
   221  
   222  				// Iteration order means that first nilcheck in the chain wins, others
   223  				// are bumped into the ordinary statement preservation algorithm.
   224  				u := b.Values[unnecessary.get(v.Args[0].ID)]
   225  				if !u.Pos.SameFileAndLine(v.Pos) {
   226  					if u.Pos.IsStmt() == src.PosIsStmt {
   227  						pendingLines.add(u.Pos)
   228  					}
   229  					u.Pos = v.Pos
   230  				} else if v.Pos.IsStmt() == src.PosIsStmt {
   231  					pendingLines.add(v.Pos)
   232  				}
   233  
   234  				v.reset(OpUnknown)
   235  				firstToRemove = i
   236  				continue
   237  			}
   238  			if v.Type.IsMemory() || v.Type.IsTuple() && v.Type.FieldType(1).IsMemory() {
   239  				if v.Op == OpVarKill || v.Op == OpVarLive || (v.Op == OpVarDef && !v.Aux.(*ir.Name).Type().HasPointers()) {
   240  					// These ops don't really change memory.
   241  					continue
   242  					// Note: OpVarDef requires that the defined variable not have pointers.
   243  					// We need to make sure that there's no possible faulting
   244  					// instruction between a VarDef and that variable being
   245  					// fully initialized. If there was, then anything scanning
   246  					// the stack during the handling of that fault will see
   247  					// a live but uninitialized pointer variable on the stack.
   248  					//
   249  					// If we have:
   250  					//
   251  					//   NilCheck p
   252  					//   VarDef x
   253  					//   x = *p
   254  					//
   255  					// We can't rewrite that to
   256  					//
   257  					//   VarDef x
   258  					//   NilCheck p
   259  					//   x = *p
   260  					//
   261  					// Particularly, even though *p faults on p==nil, we still
   262  					// have to do the explicit nil check before the VarDef.
   263  					// See issue #32288.
   264  				}
   265  				// This op changes memory.  Any faulting instruction after v that
   266  				// we've recorded in the unnecessary map is now obsolete.
   267  				unnecessary.clear()
   268  			}
   269  
   270  			// Find any pointers that this op is guaranteed to fault on if nil.
   271  			var ptrstore [2]*Value
   272  			ptrs := ptrstore[:0]
   273  			if opcodeTable[v.Op].faultOnNilArg0 && (faultOnLoad || v.Type.IsMemory()) {
   274  				// On AIX, only writing will fault.
   275  				ptrs = append(ptrs, v.Args[0])
   276  			}
   277  			if opcodeTable[v.Op].faultOnNilArg1 && (faultOnLoad || (v.Type.IsMemory() && v.Op != OpPPC64LoweredMove)) {
   278  				// On AIX, only writing will fault.
   279  				// LoweredMove is a special case because it's considered as a "mem" as it stores on arg0 but arg1 is accessed as a load and should be checked.
   280  				ptrs = append(ptrs, v.Args[1])
   281  			}
   282  
   283  			for _, ptr := range ptrs {
   284  				// Check to make sure the offset is small.
   285  				switch opcodeTable[v.Op].auxType {
   286  				case auxSym:
   287  					if v.Aux != nil {
   288  						continue
   289  					}
   290  				case auxSymOff:
   291  					if v.Aux != nil || v.AuxInt < 0 || v.AuxInt >= minZeroPage {
   292  						continue
   293  					}
   294  				case auxSymValAndOff:
   295  					off := ValAndOff(v.AuxInt).Off()
   296  					if v.Aux != nil || off < 0 || off >= minZeroPage {
   297  						continue
   298  					}
   299  				case auxInt32:
   300  					// Mips uses this auxType for atomic add constant. It does not affect the effective address.
   301  				case auxInt64:
   302  					// ARM uses this auxType for duffcopy/duffzero/alignment info.
   303  					// It does not affect the effective address.
   304  				case auxNone:
   305  					// offset is zero.
   306  				default:
   307  					v.Fatalf("can't handle aux %s (type %d) yet\n", v.auxString(), int(opcodeTable[v.Op].auxType))
   308  				}
   309  				// This instruction is guaranteed to fault if ptr is nil.
   310  				// Any previous nil check op is unnecessary.
   311  				unnecessary.set(ptr.ID, int32(i), src.NoXPos)
   312  			}
   313  		}
   314  		// Remove values we've clobbered with OpUnknown.
   315  		i := firstToRemove
   316  		for j := i; j < len(b.Values); j++ {
   317  			v := b.Values[j]
   318  			if v.Op != OpUnknown {
   319  				if !notStmtBoundary(v.Op) && pendingLines.contains(v.Pos) { // Late in compilation, so any remaining NotStmt values are probably okay now.
   320  					v.Pos = v.Pos.WithIsStmt()
   321  					pendingLines.remove(v.Pos)
   322  				}
   323  				b.Values[i] = v
   324  				i++
   325  			}
   326  		}
   327  
   328  		if pendingLines.contains(b.Pos) {
   329  			b.Pos = b.Pos.WithIsStmt()
   330  		}
   331  
   332  		b.truncateValues(i)
   333  
   334  		// TODO: if b.Kind == BlockPlain, start the analysis in the subsequent block to find
   335  		// more unnecessary nil checks.  Would fix test/nilptr3.go:159.
   336  	}
   337  }
   338  

View as plain text