001/*
002 *  This file is part of the Jikes RVM project (http://jikesrvm.org).
003 *
004 *  This file is licensed to You under the Eclipse Public License (EPL);
005 *  You may not use this file except in compliance with the License. You
006 *  may obtain a copy of the License at
007 *
008 *      http://www.opensource.org/licenses/eclipse-1.0.php
009 *
010 *  See the COPYRIGHT.txt file distributed with this work for information
011 *  regarding copyright ownership.
012 */
013package org.jikesrvm.osr;
014
015/**
016 * Utility class used by BytecodeTraverser.
017 */
018class TypeStack {
019  private final byte[] stack;
020  private int top;
021  private final byte defv;
022
023  TypeStack(int depth, byte defv) {
024    byte[] stk = new byte[depth];
025    for (int i = 0; i < depth; i++) {
026      stk[i] = defv;
027    }
028
029    this.stack = stk;
030    this.top = 0;
031    this.defv = defv;
032  }
033
034  TypeStack(TypeStack other) {
035    int ssize = other.stack.length;
036    this.stack = new byte[ssize];
037    System.arraycopy(other.stack, 0, this.stack, 0, ssize);
038    this.top = other.top;
039    this.defv = other.defv;
040  }
041
042  void push(byte v) {
043    if (top == stack.length) {
044      throw new RuntimeException("TypeStack overflow!");
045    }
046    stack[top++] = v;
047  }
048
049  byte pop() {
050    if (top <= 0) {
051      throw new RuntimeException("TypeStack underflow!");
052    }
053    top--;
054    byte v = stack[top];
055    stack[top] = defv;
056
057    return v;
058  }
059
060  void pop(int n) {
061    int newtop = top - n;
062
063    if (newtop < 0) {
064      throw new RuntimeException("TypeStack underflow!");
065    }
066
067    for (int i = top - 1; i >= newtop; i--) {
068      stack[i] = defv;
069    }
070
071    top = newtop;
072  }
073
074  byte peek() {
075    if (top <= 0) {
076      throw new RuntimeException("Tried to peek on an empty TypeStack!");
077    }
078
079    return stack[top - 1];
080  }
081
082  byte[] snapshot() {
083    return stack;
084  }
085
086  void clear() {
087    top = 0;
088    for (int i = 0, n = stack.length; i < n; i++) {
089      stack[i] = defv;
090    }
091  }
092
093  int depth() {
094    return top;
095  }
096}