1#!/usr/bin/env ruby 2 3# Copyright (c) 2021-2024 Huawei Device Co., Ltd. 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 16require_relative 'output' 17 18class BasicBlock 19 attr_reader :index, :function, :preds, :instructions 20 attr_reader :true_succ, :false_succ 21 22 def initialize(index, function) 23 @instructions = [] 24 @index = index 25 @function = function 26 @true_succ = nil 27 @false_succ = nil 28 @preds = [] 29 @variables = {} 30 end 31 32 def last_instruction 33 @instructions[-1] 34 end 35 36 def empty? 37 @instructions.empty? 38 end 39 40 def terminator? 41 !empty? && @instructions[-1].terminator? 42 end 43 44 def append(inst) 45 raise "It is not allowed to add nil instruction" if inst.nil? 46 if inst.IsWhilePhi? 47 @instructions.prepend(inst) 48 else 49 @instructions << inst 50 end 51 end 52 53 def set_variable(var, inst) 54 @variables[var.to_sym] = inst 55 end 56 57 def set_successor(dir, bb) 58 if dir 59 @true_succ = bb 60 else 61 @false_succ = bb 62 end 63 bb.add_predecessor(self) 64 end 65 66 def set_true_succ(bb) 67 set_successor(true, bb) 68 end 69 70 def set_false_succ(bb) 71 set_successor(false, bb) 72 end 73 74 def add_predecessor(bb) 75 @preds << bb 76 end 77 78 def emit_ir 79 strue_str = @true_succ.nil? ? "-1" : @true_succ.index.to_s 80 sfalse_str = @false_succ.nil? ? "" : ", #{@false_succ.index}" 81 Output.printlni("BASIC_BLOCK(#{index}, #{strue_str}#{sfalse_str}) {") 82 @instructions.each(&:emit_ir) 83 Output.printlnd("}") 84 end 85 86 def generate_builder 87 @instructions.each(&:generate_builder) 88 end 89end 90