github.com/cloudwego/frugal@v0.1.15/internal/atm/ssa/pass_rematerialize.go (about)

     1  /*
     2   * Copyright 2022 ByteDance Inc.
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package ssa
    18  
    19  // Rematerialize recalculates simple values to reduce register pressure.
    20  type Rematerialize struct{}
    21  
    22  func (Rematerialize) Apply(cfg *CFG) {
    23      consts := make(map[Reg]_ConstData)
    24      consts[Rz] = constint(0)
    25      consts[Pn] = constptr(nil, Const)
    26  
    27      /* Phase 1: Scan all the constants */
    28      for _, bb := range cfg.PostOrder().Reversed() {
    29          for _, v := range bb.Ins {
    30              if r, x, ok := IrArchTryIntoConstInt(v); ok {
    31                  consts[r] = constint(x)
    32              } else if r, p, ok := IrArchTryIntoConstPtr(v); ok {
    33                  consts[r] = constptr(p, Volatile)
    34              }
    35          }
    36      }
    37  
    38      /* Phase 2: Replace register copies with consts if possible */
    39      cfg.PostOrder().ForEach(func(bb *BasicBlock) {
    40          for i, v := range bb.Ins {
    41              if d, s, ok := IrArchTryIntoCopy(v); ok {
    42                  if cc, ok := consts[s]; ok {
    43                      if cc.i {
    44                          bb.Ins[i] = IrArchConstInt(d, cc.v)
    45                      } else {
    46                          bb.Ins[i] = IrArchConstPtr(d, cc.p)
    47                      }
    48                  }
    49              }
    50          }
    51      })
    52  }