/**
     * Write the Java code required for error checking and calling the emit method represented by a
     * singleton EmitterSet. A singleton EmiiterSet will typically be the result of a series of
     * splits of bigger sets, where the splits represent emitted queries of operand types and sizes.
     * (See emitSet) However, there may be cases when some operand has only one possible options, so
     * the splitting will not have generated any tests for it. In this case, we will emit assertions
     * that guarantee the operand is of the expected type. Note that the answers to queries
     * alrrready performed by splitting are known to be fine, so no additional error checking is
     * needed for cases they cover.
     *
     * @see #emitSet
     * @param opcode the IA32 opcode to generate
     * @param testsPerformed the set of queries already performed by splitting.
     * @param level level of indentation for prett printing
     */
    private void emitSingleton(String opcode, boolean[][] testsPerformed, int level) {
      EmitterDescriptor ed = (EmitterDescriptor) emitters.iterator().next();

      ArgumentType[] args = ed.getArgs();
      int count = ed.getCount();
      for (int i = 0; i < count; i++)
        if (!testsPerformed[i][args[i].ordinal()]) emitVerify(i, args[i], level);

      ArgumentType size = ed.getSize();
      if (size != null) {
        boolean needed = true;

        for (int i = 0; i < count; i++) if (testsPerformed[i][size.ordinal()]) needed = false;

        if (needed) emitVerify(0, size, level);

        if (size == ArgumentType.Byte)
          for (int i = 0; i < count; i++)
            if (args[i] == ArgumentType.GPRegister)
              if (currentOpcode.indexOf("MOVZX") == -1 && currentOpcode.indexOf("MOVSX") == -1) {
                emitTab(level);
                emit("if (VM.VerifyAssertions) opt_assert(");
                emitArgs(i, ArgumentType.GPRegister);
                emit(".isValidAs8bitRegister());\n");
              }
      }

      emitEmitCall(opcode, args, count, level, ed.getSize());
    }
Exemplo n.º 2
0
  /**
   * Returns a map of MBeans with ObjectName as the key and MBeanInfo value of a given domain. If
   * domain is <tt>null</tt>, all MBeans are returned. If no MBean found, an empty map is returned.
   */
  public Map<ObjectName, MBeanInfo> getMBeans(String domain) throws IOException {

    ObjectName name = null;
    if (domain != null) {
      try {
        name = new ObjectName(domain + ":*");
      } catch (MalformedObjectNameException e) {
        // should not reach here
        assert (false);
      }
    }
    Set<ObjectName> mbeans = server.queryNames(name, null);
    Map<ObjectName, MBeanInfo> result = new HashMap<ObjectName, MBeanInfo>(mbeans.size());
    Iterator<ObjectName> iterator = mbeans.iterator();
    while (iterator.hasNext()) {
      Object object = iterator.next();
      if (object instanceof ObjectName) {
        ObjectName o = (ObjectName) object;
        try {
          MBeanInfo info = server.getMBeanInfo(o);
          result.put(o, info);
        } catch (IntrospectionException e) {
          // TODO: should log the error
        } catch (InstanceNotFoundException e) {
          // TODO: should log the error
        } catch (ReflectionException e) {
          // TODO: should log the error
        }
      }
    }
    return result;
  }
Exemplo n.º 3
0
  public synchronized Collection<GarbageCollectorMXBean> getGarbageCollectorMXBeans()
      throws IOException {

    // TODO: How to deal with changes to the list??
    if (garbageCollectorMBeans == null) {
      ObjectName gcName = null;
      try {
        gcName = new ObjectName(GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE + ",*");
      } catch (MalformedObjectNameException e) {
        // should not reach here
        assert (false);
      }
      Set<ObjectName> mbeans = server.queryNames(gcName, null);
      if (mbeans != null) {
        garbageCollectorMBeans = new ArrayList<GarbageCollectorMXBean>();
        Iterator<ObjectName> iterator = mbeans.iterator();
        while (iterator.hasNext()) {
          ObjectName on = (ObjectName) iterator.next();
          String name = GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE + ",name=" + on.getKeyProperty("name");

          GarbageCollectorMXBean mBean =
              newPlatformMXBeanProxy(server, name, GarbageCollectorMXBean.class);
          garbageCollectorMBeans.add(mBean);
        }
      }
    }
    return garbageCollectorMBeans;
  }
    /**
     * Print this EmitterSet readably.
     *
     * @return a string describing this EmitterSet
     */
    public String toString() {
      StringBuffer s = new StringBuffer();
      s.append("Emitter Set of:\n");
      Iterator<EmitterDescriptor> i = emitters.iterator();
      while (i.hasNext()) s.append(i.next().toString() + "\n");

      s.append("-------------\n");
      return s.toString();
    }
Exemplo n.º 5
0
  boolean closeAndRemoveResourcesInSet(Set s, Method closeMethod) {
    boolean okay = true;

    Set temp;
    synchronized (s) {
      temp = new HashSet(s);
    }

    for (Iterator ii = temp.iterator(); ii.hasNext(); ) {
      Object rsrc = ii.next();
      try {
        closeMethod.invoke(rsrc, CLOSE_ARGS);
      } catch (Exception e) {
        Throwable t = e;
        if (t instanceof InvocationTargetException)
          t = ((InvocationTargetException) e).getTargetException();
        logger.log(MLevel.WARNING, "An exception occurred while cleaning up a resource.", t);
        // t.printStackTrace();
        okay = false;
      } finally {
        s.remove(rsrc);
      }
    }

    // We had to abandon the idea of simply iterating over s directly, because
    // our resource close methods sometimes try to remove the resource from
    // its parent Set. This is important (when the user closes the resources
    // directly), but leads to ConcurrenModificationExceptions while we are
    // iterating over the Set to close. So, now we iterate over a copy, but remove
    // from the original Set. Since removal is idempotent, it don't matter if
    // the close method already provoked a remove. Sucks that we have to copy
    // the set though.
    //
    // Original (direct iteration) version:
    //
    //  	synchronized (s)
    //  	    {
    //  		for (Iterator ii = s.iterator(); ii.hasNext(); )
    //  		    {
    //  			Object rsrc = ii.next();
    //  			try
    //  			    { closeMethod.invoke(rsrc, CLOSE_ARGS); }
    //  			catch (Exception e)
    //  			    {
    //  				Throwable t = e;
    //  				if (t instanceof InvocationTargetException)
    //  				    t = ((InvocationTargetException) e).getTargetException();
    //  				t.printStackTrace();
    //  				okay = false;
    //  			    }
    //  			finally
    //  			    { ii.remove(); }
    //  		    }
    //  	    }

    return okay;
  }
Exemplo n.º 6
0
  /**
   * Returns an array containing all installed providers that satisfy the specified* selection
   * criteria, or null if no such providers have been installed. The returned providers are ordered
   * according to their <a href= "#insertProviderAt(java.security.Provider, int)">preference
   * order</a>.
   *
   * <p>The selection criteria are represented by a map. Each map entry represents a selection
   * criterion. A provider is selected iff it satisfies all selection criteria. The key for any
   * entry in such a map must be in one of the following two formats:
   *
   * <ul>
   *   <li><i>&lt;crypto_service>.&lt;algorithm_or_type></i>
   *       <p>The cryptographic service name must not contain any dots.
   *       <p>The value associated with the key must be an empty string.
   *       <p>A provider satisfies this selection criterion iff the provider implements the
   *       specified algorithm or type for the specified cryptographic service.
   *   <li><i>&lt;crypto_service>.&lt;algorithm_or_type> &lt;attribute_name></i>
   *       <p>The cryptographic service name must not contain any dots. There must be one or more
   *       space charaters between the <i>&lt;algorithm_or_type></i> and the
   *       <i>&lt;attribute_name></i>.
   *       <p>The value associated with the key must be a non-empty string. A provider satisfies
   *       this selection criterion iff the provider implements the specified algorithm or type for
   *       the specified cryptographic service and its implementation meets the constraint expressed
   *       by the specified attribute name/value pair.
   * </ul>
   *
   * <p>See Appendix A in the <a href= "../../../guide/security/CryptoSpec.html#AppA"> Java
   * Cryptogaphy Architecture API Specification &amp; Reference </a> for information about standard
   * cryptographic service names, standard algorithm names and standard attribute names.
   *
   * @param filter the criteria for selecting providers. The filter is case-insensitive.
   * @return all the installed providers that satisfy the selection criteria, or null if no such
   *     providers have been installed.
   * @throws InvalidParameterException if the filter is not in the required format
   * @throws NullPointerException if filter is null
   * @see #getProviders(java.lang.String)
   */
  public static Provider[] getProviders(Map<String, String> filter) {
    // Get all installed providers first.
    // Then only return those providers who satisfy the selection criteria.
    Provider[] allProviders = Security.getProviders();
    Set keySet = filter.keySet();
    LinkedHashSet candidates = new LinkedHashSet(5);

    // Returns all installed providers
    // if the selection criteria is null.
    if ((keySet == null) || (allProviders == null)) {
      return allProviders;
    }

    boolean firstSearch = true;

    // For each selection criterion, remove providers
    // which don't satisfy the criterion from the candidate set.
    for (Iterator ite = keySet.iterator(); ite.hasNext(); ) {
      String key = (String) ite.next();
      String value = (String) filter.get(key);

      LinkedHashSet newCandidates = getAllQualifyingCandidates(key, value, allProviders);
      if (firstSearch) {
        candidates = newCandidates;
        firstSearch = false;
      }

      if ((newCandidates != null) && !newCandidates.isEmpty()) {
        // For each provider in the candidates set, if it
        // isn't in the newCandidate set, we should remove
        // it from the candidate set.
        for (Iterator cansIte = candidates.iterator(); cansIte.hasNext(); ) {
          Provider prov = (Provider) cansIte.next();
          if (!newCandidates.contains(prov)) {
            cansIte.remove();
          }
        }
      } else {
        candidates = null;
        break;
      }
    }

    if ((candidates == null) || (candidates.isEmpty())) return null;

    Object[] candidatesArray = candidates.toArray();
    Provider[] result = new Provider[candidatesArray.length];

    for (int i = 0; i < result.length; i++) {
      result[i] = (Provider) candidatesArray[i];
    }

    return result;
  }
Exemplo n.º 7
0
 private void nudge() {
   for (Iterator<RecorderEvent> iter = pendingEvents.iterator(); iter.hasNext(); ) {
     RecorderEvent ev = iter.next();
     long instant = getSynchronizer().getLocalTime(ev.getSsrc(), ev.getRtpTimestamp());
     if (instant != -1) {
       iter.remove();
       ev.setInstant(instant);
       handler.handleEvent(ev);
     }
   }
 }
    /**
     * This method uses a SplitRecord as the criertion to partition the given EmitterSet into two
     * subsets.
     *
     * @param split the plit record dicatating how to split
     */
    private EmitterSet[] makeSplit(SplitRecord split) {
      int arg = split.argument;
      ArgumentType test = split.test;
      EmitterSet yes = new EmitterSet();
      EmitterSet no = new EmitterSet();
      Iterator<EmitterDescriptor> i = emitters.iterator();
      while (i.hasNext()) {
        EmitterDescriptor ed = (EmitterDescriptor) i.next();
        if (ed.argMatchesEncoding(arg, test)) {
          yes.add(ed);
        } else {
          no.add(ed);
        }
      }

      return new EmitterSet[] {yes, no};
    }
Exemplo n.º 9
0
 boolean closeAndRemoveResultSets(Set rsSet) {
   boolean okay = true;
   synchronized (rsSet) {
     for (Iterator ii = rsSet.iterator(); ii.hasNext(); ) {
       ResultSet rs = (ResultSet) ii.next();
       try {
         rs.close();
       } catch (SQLException e) {
         if (Debug.DEBUG)
           logger.log(MLevel.WARNING, "An exception occurred while cleaning up a ResultSet.", e);
         // e.printStackTrace();
         okay = false;
       } finally {
         ii.remove();
       }
     }
   }
   return okay;
 }
Exemplo n.º 10
0
  public Collection<MemoryPoolProxy> getMemoryPoolProxies() throws IOException {

    // TODO: How to deal with changes to the list??
    if (memoryPoolProxies == null) {
      ObjectName poolName = null;
      try {
        poolName = new ObjectName(MEMORY_POOL_MXBEAN_DOMAIN_TYPE + ",*");
      } catch (MalformedObjectNameException e) {
        // should not reach here
        assert (false);
      }
      Set<ObjectName> mbeans = server.queryNames(poolName, null);
      if (mbeans != null) {
        memoryPoolProxies = new ArrayList<MemoryPoolProxy>();
        Iterator<ObjectName> iterator = mbeans.iterator();
        while (iterator.hasNext()) {
          ObjectName objName = (ObjectName) iterator.next();
          MemoryPoolProxy p = new MemoryPoolProxy(this, objName);
          memoryPoolProxies.add(p);
        }
      }
    }
    return memoryPoolProxies;
  }
Exemplo n.º 11
0
  /* PROTECTED METHODS */
  protected void getBeanElements(
      Element parentElement, String objectName, String objectType, Object bean)
      throws IntrospectionException, IllegalAccessException {
    if (objectName == null) {
      // Get just the class name by lopping off the package name
      StringBuffer sb = new StringBuffer(bean.getClass().getName());
      sb.delete(0, sb.lastIndexOf(".") + 1);
      objectName = sb.toString();
    }

    // Check if the bean is a standard Java object type or a byte[] (encoded as a base 64 array)
    Element element = getStandardObjectElement(document, bean, objectName);
    // If the body element object is null then the bean is not a standard Java object type
    if (element != null) {
      if (includeNullValues
          || !element
              .getAttribute(
                  NamespaceConstants.NSPREFIX_SCHEMA_XSI
                      + ":"
                      + org.apache.axis.Constants.ATTR_TYPE)
              .equals("anyType")) {
        if (!includeTypeInfo) {
          element.removeAttribute(
              NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + org.apache.axis.Constants.ATTR_TYPE);
          element.removeAttribute(NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null");
        }
        parentElement.appendChild(element);
      }
    } else {
      // Analyze the bean
      Class classOfBean = null;
      if (bean != null) classOfBean = bean.getClass();
      // If the object is an array, then serialize each of the beans in the array.
      if ((classOfBean != null) && (classOfBean.isArray())) {
        String[] arrayInfo = getXsdSoapArrayInfo(classOfBean.getCanonicalName(), nsPrefix);
        int arrayLen = Array.getLength(bean);
        StringBuffer arrayType = new StringBuffer(arrayInfo[1]);
        arrayType.insert(arrayType.indexOf("[]") + 1, arrayLen);
        if (objectName.charAt(objectName.length() - 1) == ';')
          objectName =
              new StringBuffer(objectName).deleteCharAt(objectName.length() - 1).toString();
        element = document.createElement(objectName);
        parentElement.appendChild(element);
        // Get the bean objects from the array and serialize each
        for (int i = 0; i < arrayLen; i++) {
          Object b = Array.get(bean, i);
          if (b != null) {
            String name = null;
            if (objectName.charAt(objectName.length() - 1) == 's') {
              name = formatName(objectName.substring(0, objectName.length() - 1));
            }
            getBeanElements(element, name, b.getClass().getName(), b);
          } else {
            // Array element is null, so don't include it and decrement the # elements in the array
            int index = arrayType.indexOf("[");
            arrayType.replace(index + 1, index + 2, String.valueOf(--arrayLen));
          }
          if (includeTypeInfo) {
            element.setAttributeNS(
                NamespaceConstants.NSURI_SCHEMA_XSI,
                NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + Constants.ATTR_TYPE,
                NamespaceConstants.NSPREFIX_SOAP_ENCODING + ":Array");
            element.setAttributeNS(
                NamespaceConstants.NSURI_SOAP_ENCODING,
                NamespaceConstants.NSPREFIX_SOAP_ENCODING + ":" + Constants.ATTR_ARRAY_TYPE,
                arrayInfo[0] + ":" + arrayType.toString());
          }
        }
      } else {
        int beanType = 0;
        String beanName = null;
        if (classOfBean != null) {
          if (classOfBean == Vector.class) {
            beanType = 1;
            beanName = "Vector";
          } else if (classOfBean == ArrayList.class) {
            beanType = 2;
            beanName = "ArrayList";
          } else if (classOfBean == LinkedList.class) {
            beanType = 3;
            beanName = "LinkedList";
          } else if (classOfBean == Hashtable.class) {
            beanType = 4;
            beanName = "Hashtable";
          } else if (classOfBean == Properties.class) {
            beanType = 5;
            beanName = "Properties";
          } else if ((classOfBean == HashMap.class) || (classOfBean == SortedMap.class)) {
            beanType = 6;
            beanName = "Map";
          }
        }
        if (beanType > 0) {
          String prefix = null;
          if ((beanType == 1) || (beanType == 5))
            prefix = NamespaceConstants.NSPREFIX_SOAP_ENCODING;
          if (beanType == 6) prefix = Constants.NS_PREFIX_XMLSOAP;
          else prefix = DEFAULT_NS_PREFIX;
          element = document.createElement(objectName);
          if (includeTypeInfo) {
            element.setAttributeNS(
                NamespaceConstants.NSURI_SCHEMA_XSI,
                NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + Constants.ATTR_TYPE,
                prefix + ":" + beanName);
            if (bean == null)
              element.setAttributeNS(
                  NamespaceConstants.NSURI_SCHEMA_XSI,
                  NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null",
                  "true");
          }
          parentElement.appendChild(element);
          if ((beanType >= 1) && (beanType <= 3)) {
            AbstractCollection collection = (AbstractCollection) bean;
            // Get the bean objects from the vector and serialize each
            Iterator it = collection.iterator();
            while (it.hasNext()) {
              Object b = it.next();
              String name = null;
              if (b != null) {
                if (objectName.charAt(objectName.length() - 1) == 's') {
                  name = formatName(objectName.substring(0, objectName.length() - 1));
                } else name = "item";
              }
              getBeanElements(element, name, b.getClass().getName(), b);
            }
          } else if ((beanType == 4) || (beanType == 5)) {
            Hashtable hashtable = (Hashtable) bean;
            // Get the bean objects from the hashtable or properties and serialize each
            Enumeration en = hashtable.keys();
            while (en.hasMoreElements()) {
              Object key = en.nextElement();
              String keyClassName = key.getClass().getName();
              Object value = hashtable.get(key);
              String beanClassName = null;
              if (value != null) beanClassName = value.getClass().getName();
              Element itemElement = document.createElement("item");
              element.appendChild(itemElement);
              getBeanElements(itemElement, "key", keyClassName, key);
              getBeanElements(itemElement, "value", beanClassName, value);
            }
          } else if (beanType == 6) {
            Map map = null;
            if (classOfBean == HashMap.class) map = (HashMap) bean;
            else if (classOfBean == SortedMap.class) map = (SortedMap) bean;
            // Get the bean objects from the hashmap and serialize each
            Set set = map.keySet();
            Iterator it = set.iterator();
            while (it.hasNext()) {
              Object key = it.next();
              String keyClassName = key.getClass().getName();
              Object value = map.get(key);
              String beanClassName = null;
              if (value != null) beanClassName = value.getClass().getName();
              Element itemElement = document.createElement("item");
              element.appendChild(itemElement);
              getBeanElements(itemElement, "key", keyClassName, key);
              getBeanElements(itemElement, "value", beanClassName, value);
            }
          }
        } else {
          // Create a parent element for this bean's properties
          if (objectName.charAt(objectName.length() - 1) == ';')
            objectName =
                new StringBuffer(objectName).deleteCharAt(objectName.length() - 1).toString();
          objectName = formatName(objectName);
          element = document.createElement(objectName);
          parentElement.appendChild(element);
          if (includeTypeInfo) {
            StringBuffer className = new StringBuffer(objectType);
            element.setAttributeNS(
                NamespaceConstants.NSURI_SCHEMA_XSI,
                NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + Constants.ATTR_TYPE,
                nsPrefix + ":" + className.delete(0, className.lastIndexOf(".") + 1).toString());
          }
          if (classOfBean != null) {
            // Get an array of property descriptors
            BeanInfo bi = Introspector.getBeanInfo(classOfBean);
            PropertyDescriptor[] pds = bi.getPropertyDescriptors();
            // For each property of the bean, get a SOAPBodyElement that
            // represents the individual property. Append that SOAPBodyElement
            // to the class name element of the SOAP body.
            for (int i = 0; i < pds.length; i++) {
              PropertyDescriptor pd = pds[i];
              getBeanElementProperties(element, bean, pd);
            }
          } else {
            if (includeTypeInfo)
              element.setAttributeNS(
                  NamespaceConstants.NSURI_SCHEMA_XSI,
                  NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null",
                  "true");
          }
        }
      }
    }
  }
Exemplo n.º 12
0
 /**
  * Count how many of the emit represented by this set match a given operand type and size
  * encoding. This method is used (via getEncodingSplit) while recursively partitioning a given
  * EmitterSet to determine how evenly (or even whether) a given operand type and size splits
  * this set.
  *
  * @see #getEncodingSplit
  * @param n the operand being examined
  * @param code the operand type or size code being considered
  * @return the number of emit methods of which the specified operand type matches the specified
  *     one.
  */
 private int countEncoding(int n, ArgumentType code) {
   Iterator<EmitterDescriptor> i = emitters.iterator();
   int count = 0;
   while (i.hasNext()) if (((EmitterDescriptor) i.next()).argMatchesEncoding(n, code)) count++;
   return count;
 }
Exemplo n.º 13
0
  /** Generate an assembler for the opt compiler */
  public static void main(String[] args) {
    try {
      out = new FileWriter(System.getProperty("generateToDir") + "/AssemblerOpt.java");
    } catch (IOException e) {
      throw new Error(e);
    }

    emit("package org.jikesrvm.compilers.opt.mir2mc.ia32;\n\n");
    emit("import org.jikesrvm.*;\n\n");
    emit("import org.jikesrvm.compilers.opt.*;\n\n");
    emit("import org.jikesrvm.compilers.opt.ir.*;\n\n");
    emit("import org.jikesrvm.compilers.opt.ir.ia32.*;\n\n");
    emit("import static org.jikesrvm.compilers.opt.ir.ia32.ArchOperators.*;\n\n");
    emit("import static org.jikesrvm.compilers.opt.OptimizingCompilerException.opt_assert;\n\n");
    emit("\n\n");

    emit("/**\n");
    emit(" *  This class is the automatically-generated assembler for\n");
    emit(" * the optimizing compiler.  It consists of methods that\n");
    emit(" * understand the possible operand combinations of each\n");
    emit(" * instruction type, and how to translate those operands to\n");
    emit(" * calls to the Assember low-level emit method\n");
    emit(" *\n");
    emit(" * It is generated by GenerateAssembler.java\n");
    emit(" *\n");
    emit(" */\n");
    emit("public class AssemblerOpt extends AssemblerBase {\n\n");

    emitTab(1);
    emit("/**\n");
    emitTab(1);
    emit(" * @see org.jikesrvm.ArchitectureSpecific.Assembler\n");
    emitTab(1);
    emit(" */\n");
    emitTab(1);
    emit("public AssemblerOpt(int bcSize, boolean print, IR ir) {\n");
    emitTab(2);
    emit("super(bcSize, print, ir);\n");
    emitTab(1);
    emit("}");
    emit("\n\n");

    Method[] emitters = lowLevelAsm.getDeclaredMethods();
    Set<String> opcodes = getOpcodes(emitters);

    Iterator<String> i = opcodes.iterator();
    while (i.hasNext()) {
      String opcode = (String) i.next();
      setCurrentOpcode(opcode);
      emitTab(1);
      emit("/**\n");
      emitTab(1);
      emit(" *  Emit the given instruction, assuming that\n");
      emitTab(1);
      emit(" * it is a " + currentFormat + " instruction\n");
      emitTab(1);
      emit(" * and has a " + currentOpcode + " operator\n");
      emitTab(1);
      emit(" *\n");
      emitTab(1);
      emit(" * @param inst the instruction to assemble\n");
      emitTab(1);
      emit(" */\n");
      emitTab(1);
      emit("private void do" + opcode + "(Instruction inst) {\n");
      EmitterSet emitter = buildSetForOpcode(emitters, opcode);
      boolean[][] tp = new boolean[4][ArgumentType.values().length];
      emitter.emitSet(opcode, tp, 2);
      emitTab(1);
      emit("}\n\n");
    }

    emitTab(1);
    emit("/**\n");
    emitTab(1);
    emit(" *  The number of instructions emitted so far\n");
    emitTab(1);
    emit(" */\n");
    emitTab(1);
    emit("private int instructionCount = 0;\n\n");

    emitTab(1);
    emit("/**\n");
    emitTab(1);
    emit(" *  Assemble the given instruction\n");
    emitTab(1);
    emit(" *\n");
    emitTab(1);
    emit(" * @param inst the instruction to assemble\n");
    emitTab(1);
    emit(" */\n");
    emitTab(1);
    emit("public void doInst(Instruction inst) {\n");
    emitTab(2);
    emit("instructionCount++;\n");
    emitTab(2);
    emit("resolveForwardReferences(instructionCount);\n");
    emitTab(2);
    emit("switch (inst.getOpcode()) {\n");

    Set<String> emittedOpcodes = new HashSet<String>();

    i = opcodes.iterator();
    while (i.hasNext()) {
      String opcode = i.next();
      Iterator<String> operators = getMatchingOperators(opcode).iterator();
      while (operators.hasNext()) {
        String operator = operators.next();
        emitTab(3);
        emittedOpcodes.add(operator);
        emit("case IA32_" + operator + "_opcode:\n");
      }
      emitTab(4);
      emit("do" + opcode + "(inst);\n");
      emitTab(4);
      emit("break;\n");
    }

    // Special case because doJCC is handwritten to add
    // logic for short-forward branches
    emittedOpcodes.add("JCC");
    emitTab(3);
    emit("case IA32_JCC_opcode:\n");
    emitTab(4);
    emit("doJCC(inst);\n");
    emitTab(4);
    emit("break;\n");

    // Special case because doJMP is handwritten to add
    // logic for short-forward branches
    emittedOpcodes.add("JMP");
    emitTab(3);
    emit("case IA32_JMP_opcode:\n");
    emitTab(4);
    emit("doJMP(inst);\n");
    emitTab(4);
    emit("break;\n");

    // Kludge for IA32_LOCK which needs to call emitLockNextInstruction
    emittedOpcodes.add("LOCK");
    emitTab(3);
    emit("case IA32_LOCK_opcode:\n");
    emitTab(4);
    emit("emitLockNextInstruction();\n");
    emitTab(4);
    emit("break;\n");

    // Kludge for PATCH_POINT
    emitTab(3);
    emit("case IG_PATCH_POINT_opcode:\n");
    emitTab(4);
    emit("emitPatchPoint();\n");
    emitTab(4);
    emit("break;\n");

    // Kludge for LOWTABLESWITCH
    emitTab(3);
    emit("case MIR_LOWTABLESWITCH_opcode:\n");
    emitTab(4);
    emit("doLOWTABLESWITCH(inst);\n");
    emitTab(4);
    emit("// kludge table switches that are unusually long instructions\n");
    emitTab(4);
    emit("instructionCount += MIR_LowTableSwitch.getNumberOfTargets(inst);\n");
    emitTab(4);
    emit("break;\n");

    Set<String> errorOpcodes = getErrorOpcodes(emittedOpcodes);
    if (!errorOpcodes.isEmpty()) {
      i = errorOpcodes.iterator();
      while (i.hasNext()) {
        emitTab(3);
        emit("case IA32_" + i.next() + "_opcode:\n");
      }
      emitTab(4);
      emit(
          "throw new OptimizingCompilerException(inst + \" has unimplemented IA32 opcode (check excludedOpcodes)\");\n");
    }

    emitTab(2);
    emit("}\n");
    emitTab(2);
    emit("inst.setmcOffset( mi );\n");
    emitTab(1);
    emit("}\n\n");

    emit("\n}\n");

    try {
      out.close();
    } catch (IOException e) {
      throw new Error(e);
    }
  }
  public void buildTypeGraph() {
    Map<String, JarFile> openJarFiles = new HashMap<String, JarFile>();
    Map<String, File> openClassFiles = new HashMap<String, File>();
    // use global cache to load resource in/out of the same jar as the classes
    Set<String> resourceCacheSet = new HashSet<>();
    try {
      for (String path : pathsToScan) {
        File f = null;
        try {
          f = new File(path);
          if (!f.exists()
              || f.isDirectory()
              || (!f.getName().endsWith("jar") && !f.getName().endsWith("class"))) {
            continue;
          }
          if (GENERATED_CLASSES_JAR.equals(f.getName())) {
            continue;
          }
          if (f.getName().endsWith("class")) {
            typeGraph.addNode(f);
            openClassFiles.put(path, f);
          } else {
            JarFile jar = new JarFile(path);
            openJarFiles.put(path, jar);
            java.util.Enumeration<JarEntry> entriesEnum = jar.entries();
            while (entriesEnum.hasMoreElements()) {
              final java.util.jar.JarEntry jarEntry = entriesEnum.nextElement();
              String entryName = jarEntry.getName();
              if (jarEntry.isDirectory()) {
                continue;
              }
              if (entryName.endsWith("-javadoc.xml")) {
                try {
                  processJavadocXml(jar.getInputStream(jarEntry));
                  // break;
                } catch (Exception ex) {
                  LOG.warn("Cannot process javadoc {} : ", entryName, ex);
                }
              } else if (entryName.endsWith(".class")) {
                TypeGraph.TypeGraphVertex newNode = typeGraph.addNode(jarEntry, jar);
                // check if any visited resources belong to this type
                for (Iterator<String> iter = resourceCacheSet.iterator(); iter.hasNext(); ) {
                  String entry = iter.next();
                  if (entry.startsWith(entryName.substring(0, entryName.length() - 6))) {
                    newNode.setHasResource(true);
                    iter.remove();
                  }
                }
              } else {
                String className = entryName;
                boolean foundClass = false;
                // check if this resource belongs to any visited type
                while (className.contains("/")) {
                  className = className.substring(0, className.lastIndexOf('/'));
                  TypeGraph.TypeGraphVertex tgv = typeGraph.getNode(className.replace('/', '.'));
                  if (tgv != null) {
                    tgv.setHasResource(true);
                    foundClass = true;
                    break;
                  }
                }
                if (!foundClass) {
                  resourceCacheSet.add(entryName);
                }
              }
            }
          }
        } catch (IOException ex) {
          LOG.warn("Cannot process file {}", f, ex);
        }
      }

      typeGraph.trim();

      typeGraph.updatePortTypeInfoInTypeGraph(openJarFiles, openClassFiles);
    } finally {
      for (Entry<String, JarFile> entry : openJarFiles.entrySet()) {
        try {
          entry.getValue().close();
        } catch (IOException e) {
          DTThrowable.wrapIfChecked(e);
        }
      }
    }
  }