global_pred.py 1.63 KB
Newer Older
Alan Marchiori's avatar
Alan Marchiori committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

class global_pht:
    def __init__(self, num_history_bits = 3):
        self.num_bits = num_history_bits
        
        self.num_index = 2**self.num_bits
        self.shift_register = self.num_index - 1         
        
        self.bin_fmt = "{{:0{}b}}".format(self.num_bits)
        self.counters = [ 'T' for i in range (self.num_index)]
        
    def predict(self, pc, target, outcome, verbose, learn = True):
                
        result = self.counters[self.shift_register]
                
        if verbose and learn:
            print ("predicting PC = 0x{:x}, branch history = ".format(pc) + \
                   self.bin_fmt.format(self.shift_register) + \
                   " outcome = {}".format(outcome))
            
            
            tag = {True: '<===',
                   False: ''}
            msg = {False: {True: "", False: ""},
                   True: {True: " (correct)",
                          False: " (MISSPREDICT)"}}
            for i in range (self.num_index):
                                
                print ("PHT[" + self.bin_fmt.format(i) + "] = {} {}{}".format(self.counters[i],
                                                                            tag[i == self.shift_register],
                                                                            msg[i == self.shift_register][result == outcome]))
                
            
        

        if learn:
            self.counters[self.shift_register] = outcome
        
        self.shift_register = ((self.shift_register << 1) & (self.num_index - 1))
        if outcome == 'T':
            self.shift_register |= 1
        
        return result