Esempio n. 1
0
  /**
   * The confluence operator is essentially the union of all of the inItems. However, if two or more
   * of the initCount maps from the inItems each have a MinMaxInitCounts entry for the same
   * VarInstance, the conflict must be resolved, by using the minimum of all mins and the maximum of
   * all maxs.
   */
  public Item confluence(List inItems, Term node, FlowGraph graph) {
    // Resolve any conflicts pairwise.
    Iterator iter = inItems.iterator();
    Map m = null;
    while (iter.hasNext()) {
      Item itm = (Item) iter.next();
      if (itm == BOTTOM) continue;
      if (m == null) {
        m = new HashMap(((DataFlowItem) itm).initStatus);
      } else {
        Map n = ((DataFlowItem) itm).initStatus;
        for (Iterator iter2 = n.entrySet().iterator(); iter2.hasNext(); ) {
          Map.Entry entry = (Map.Entry) iter2.next();
          VarInstance v = (VarInstance) entry.getKey();
          MinMaxInitCount initCount1 = (MinMaxInitCount) m.get(v);
          MinMaxInitCount initCount2 = (MinMaxInitCount) entry.getValue();
          m.put(v, MinMaxInitCount.join(initCount1, initCount2));
        }
      }
    }

    if (m == null) return BOTTOM;

    return new DataFlowItem(m);
  }
Esempio n. 2
0
  /**
   * Check that the set of <code>LocalInstance</code>s <code>localsUsed</code>, which is the set of
   * locals used in the inner class declared by <code>cb</code> are initialized before the class
   * declaration.
   */
  protected void checkLocalsUsedByInnerClass(
      FlowGraph graph, ClassBody cb, Set localsUsed, DataFlowItem dfIn, DataFlowItem dfOut)
      throws SemanticException {
    for (Iterator iter = localsUsed.iterator(); iter.hasNext(); ) {
      LocalInstance li = (LocalInstance) iter.next();
      MinMaxInitCount initCount = (MinMaxInitCount) dfOut.initStatus.get(li);
      if (!currCBI.localDeclarations.contains(li)) {
        // the local wasn't defined in this scope.
        currCBI.outerLocalsUsed.add(li);
      } else if (initCount == null || InitCount.ZERO.equals(initCount.getMin())) {
        // initCount will in general not be null, as the local variable
        // li is declared in the current class; however, if the inner
        // class is declared in the initializer of the local variable
        // declaration, then initCount could in fact be null, as we
        // leave the inner class before we have performed flowLocalDecl
        // for the local variable declaration.

        throw new SemanticException(
            "Local variable \""
                + li.name()
                + "\" must be initialized before the class "
                + "declaration.",
            cb.position());
      }
    }
  }
Esempio n. 3
0
 /**
  * The ast nodes will use this callback to notify us that they throw an exception of type t. This
  * method will throw a SemanticException if the type t is not allowed to be thrown at this point;
  * the exception t will be added to the throwsSet of all exception checkers in the stack, up to
  * (and not including) the exception checker that catches the exception.
  *
  * @param t The type of exception that the node throws.
  * @throws SemanticException
  */
 public void throwsException(Type t, Position pos) throws SemanticException {
   if (!t.isUncheckedException()) {
     // go through the stack of catches and see if the exception
     // is caught.
     boolean exceptionCaught = false;
     ExceptionChecker ec = this;
     while (!exceptionCaught && ec != null) {
       if (ec.catchable != null) {
         for (Iterator<Type> iter = ec.catchable.iterator(); iter.hasNext(); ) {
           Type catchType = (Type) iter.next();
           if (ts.isSubtype(t, catchType, ts.emptyContext())) {
             exceptionCaught = true;
             break;
           }
         }
       }
       if (!exceptionCaught && ec.throwsSet != null) {
         // add t to ec's throwsSet.
         ec.throwsSet.add(t);
       }
       if (ec.catchAllThrowable) {
         // stop the propagation
         exceptionCaught = true;
       }
       ec = ec.pop();
     }
     if (!exceptionCaught) {
       reportUncaughtException(t, pos);
     }
   }
 }
Esempio n. 4
0
  protected void setupClassBody(ClassBody n) throws SemanticException {
    ClassBodyInfo newCDI = new ClassBodyInfo();
    newCDI.outer = currCBI;
    currCBI = newCDI;

    // set up currClassFinalFieldInitCounts to contain mappings
    // for all the final fields of the class.
    Iterator classMembers = n.members().iterator();
    while (classMembers.hasNext()) {
      ClassMember cm = (ClassMember) classMembers.next();
      if (cm instanceof FieldDecl) {
        FieldDecl fd = (FieldDecl) cm;
        if (fd.flags().isFinal()) {
          MinMaxInitCount initCount;
          if (fd.init() != null) {
            // the field has an initializer
            initCount = new MinMaxInitCount(InitCount.ONE, InitCount.ONE);

            // do dataflow over the initialization expression
            // to pick up any uses of outer local variables.
            if (currCBI.outer != null) dataflow(fd.init());
          } else {
            // the field does not have an initializer
            initCount = new MinMaxInitCount(InitCount.ZERO, InitCount.ZERO);
          }
          newCDI.currClassFinalFieldInitCounts.put(fd.fieldInstance(), initCount);
        }
      }
    }
  }
Esempio n. 5
0
  /** Write the statement to an output file. */
  public void prettyPrint(CodeWriter w, PrettyPrinter tr) {
    w.write("for (");
    w.begin(0);

    if (inits != null) {
      boolean first = true;
      for (Iterator i = inits.iterator(); i.hasNext(); ) {
        ForInit s = (ForInit) i.next();
        printForInit(s, w, tr, first);
        first = false;

        if (i.hasNext()) {
          w.write(",");
          w.allowBreak(2, " ");
        }
      }
    }

    w.write(";");
    w.allowBreak(0);

    if (cond != null) {
      printBlock(cond, w, tr);
    }

    w.write(";");
    w.allowBreak(0);

    if (iters != null) {
      for (Iterator i = iters.iterator(); i.hasNext(); ) {
        ForUpdate s = (ForUpdate) i.next();
        printForUpdate(s, w, tr);

        if (i.hasNext()) {
          w.write(",");
          w.allowBreak(2, " ");
        }
      }
    }

    w.end();
    w.write(")");

    printSubStmt(body, w, tr);
  }
Esempio n. 6
0
  /**
   * Check that each non static final field has been initialized exactly once, taking into account
   * the fact that constructors may call other constructors.
   *
   * @param cb The ClassBody of the class declaring the fields to check.
   * @throws SemanticException
   */
  protected void checkNonStaticFinalFieldsInit(ClassBody cb) throws SemanticException {
    // for each non-static final field instance, check that all
    // constructors intialize it exactly once, taking into account constructor calls.
    for (Iterator iter = currCBI.currClassFinalFieldInitCounts.keySet().iterator();
        iter.hasNext(); ) {
      FieldInstance fi = (FieldInstance) iter.next();
      if (fi.flags().isFinal() && !fi.flags().isStatic()) {
        // the field is final and not static
        // it must be initialized exactly once.
        // navigate up through all of the the constructors
        // that this constructor calls.

        boolean fieldInitializedBeforeConstructors = false;
        MinMaxInitCount ic = (MinMaxInitCount) currCBI.currClassFinalFieldInitCounts.get(fi);
        if (ic != null && !InitCount.ZERO.equals(ic.getMin())) {
          fieldInitializedBeforeConstructors = true;
        }

        for (Iterator iter2 = currCBI.allConstructors.iterator(); iter2.hasNext(); ) {
          ConstructorDecl cd = (ConstructorDecl) iter2.next();
          ConstructorInstance ciStart = cd.constructorInstance();
          ConstructorInstance ci = ciStart;

          boolean isInitialized = fieldInitializedBeforeConstructors;

          while (ci != null) {
            Set s = (Set) currCBI.fieldsConstructorInitializes.get(ci);
            if (s != null && s.contains(fi)) {
              if (isInitialized) {
                throw new SemanticException(
                    "field \"" + fi.name() + "\" might have already been initialized",
                    cd.position());
              }
              isInitialized = true;
            }
            ci = (ConstructorInstance) currCBI.constructorCalls.get(ci);
          }
          if (!isInitialized) {
            throw new SemanticException(
                "field \"" + fi.name() + "\" might not have been initialized", ciStart.position());
          }
        }
      }
    }
  }
Esempio n. 7
0
 public boolean comprisedOfIntersectionType(IntersectionType iType) {
   for (Iterator it = typeArguments().iterator(); it.hasNext(); ) {
     Type next = (Type) it.next();
     if (next instanceof IntersectionType && ts.equals(next, iType)) return true;
     if (next instanceof ParameterizedType
         && ((ParameterizedType) next).comprisedOfIntersectionType(iType)) return true;
   }
   return false;
 }
Esempio n. 8
0
 public String toString() {
   StringBuffer sb = new StringBuffer(baseType.toString());
   sb.append("<");
   for (Iterator it = typeArguments().iterator(); it.hasNext(); ) {
     sb.append(((Type) it.next()));
     if (it.hasNext()) {
       sb.append(", ");
     }
   }
   sb.append(">");
   return sb.toString();
 }
  /**
   * Get the sub-list of passes for the job between passes <code>begin</code> and <code>end</code>,
   * inclusive.
   */
  public List passes(Job job, Pass.ID begin, Pass.ID end) {
    List l = passes(job);
    Pass p = null;

    Iterator i = l.iterator();

    while (i.hasNext()) {
      p = (Pass) i.next();
      if (begin == p.id()) break;
      if (!(p instanceof BarrierPass)) i.remove();
    }

    while (p.id() != end && i.hasNext()) {
      p = (Pass) i.next();
    }

    while (i.hasNext()) {
      p = (Pass) i.next();
      i.remove();
    }

    return l;
  }
Esempio n. 10
0
 public String signature() {
   StringBuffer signature = new StringBuffer();
   // no trailing ; for base type before the type args
   signature.append("L" + ((Named) baseType).fullName().replaceAll("\\.", "/") + "<");
   for (Iterator it = typeArguments.iterator(); it.hasNext(); ) {
     SignatureType next = (SignatureType) it.next();
     signature.append(next.signature());
     if (it.hasNext()) {
       signature.append(",");
     }
   }
   signature.append(">;");
   return signature.toString();
 }
Esempio n. 11
0
  /**
   * Insert the list of <code>newPasses</code> into <code>passes</code> immediately after the pass
   * named <code>id</code>.
   */
  public void afterPass(List passes, Pass.ID id, List newPasses) {
    for (ListIterator i = passes.listIterator(); i.hasNext(); ) {
      Pass p = (Pass) i.next();

      if (p.id() == id) {
        for (Iterator j = newPasses.iterator(); j.hasNext(); ) {
          i.add(j.next());
        }

        return;
      }
    }

    throw new InternalCompilerError("Pass " + id + " not found.");
  }
Esempio n. 12
0
 /**
  * Check that each static final field is initialized exactly once.
  *
  * @param cb The ClassBody of the class declaring the fields to check.
  * @throws SemanticException
  */
 protected void checkStaticFinalFieldsInit(ClassBody cb) throws SemanticException {
   // check that all static fields have been initialized exactly once.
   for (Iterator iter = currCBI.currClassFinalFieldInitCounts.entrySet().iterator();
       iter.hasNext(); ) {
     Map.Entry e = (Map.Entry) iter.next();
     if (e.getKey() instanceof FieldInstance) {
       FieldInstance fi = (FieldInstance) e.getKey();
       if (fi.flags().isStatic() && fi.flags().isFinal()) {
         MinMaxInitCount initCount = (MinMaxInitCount) e.getValue();
         if (InitCount.ZERO.equals(initCount.getMin())) {
           throw new SemanticException(
               "field \"" + fi.name() + "\" might not have been initialized", cb.position());
         }
       }
     }
   }
 }
Esempio n. 13
0
  /**
   * Insert the list of <code>newPasses</code> into <code>passes</code> immediately before the pass
   * named <code>id</code>.
   */
  public void beforePass(List passes, Pass.ID id, List newPasses) {
    for (ListIterator i = passes.listIterator(); i.hasNext(); ) {
      Pass p = (Pass) i.next();

      if (p.id() == id) {
        // Backup one position.
        i.previous();

        for (Iterator j = newPasses.iterator(); j.hasNext(); ) {
          i.add(j.next());
        }

        return;
      }
    }

    throw new InternalCompilerError("Pass " + id + " not found.");
  }
Esempio n. 14
0
  /** Perform necessary actions upon seeing the ConstructorDecl <code>cd</code>. */
  protected void finishConstructorDecl(
      FlowGraph graph, ConstructorDecl cd, DataFlowItem dfIn, DataFlowItem dfOut) {
    ConstructorInstance ci = cd.constructorInstance();

    // we need to set currCBI.fieldsConstructorInitializes correctly.
    // It is meant to contain the non-static final fields that the
    // constructor ci initializes.
    //
    // Note that dfOut.initStatus contains only the MinMaxInitCounts
    // for _normal_ termination of the constructor (see the
    // method confluence). This means that if dfOut says the min
    // count of the initialization for a final non-static field
    // is one, and that is different from what is recoreded in
    // currCBI.currClassFinalFieldInitCounts (which is the counts
    // of the initializations performed by initializers), then
    // the constructor does indeed initialize the field.

    Set s = new HashSet();

    // go through every final non-static field in dfOut.initStatus
    Iterator iter = dfOut.initStatus.entrySet().iterator();
    while (iter.hasNext()) {
      Entry e = (Entry) iter.next();
      if (e.getKey() instanceof FieldInstance
          && ((FieldInstance) e.getKey()).flags().isFinal()
          && !((FieldInstance) e.getKey()).flags().isStatic()) {
        // we have a final non-static field
        FieldInstance fi = (FieldInstance) e.getKey();
        MinMaxInitCount initCount = (MinMaxInitCount) e.getValue();
        MinMaxInitCount origInitCount =
            (MinMaxInitCount) currCBI.currClassFinalFieldInitCounts.get(fi);
        if (initCount.getMin() == InitCount.ONE
            && (origInitCount == null || origInitCount.getMin() == InitCount.ZERO)) {
          // the constructor initialized this field
          s.add(fi);
        }
      }
    }
    if (!s.isEmpty()) {
      currCBI.fieldsConstructorInitializes.put(ci, s);
    }
  }
Esempio n. 15
0
 public Type convertToInferred(List typeVars, List inferredTypes) {
   List newBounds = new ArrayList();
   for (Iterator it = typeArguments().iterator(); it.hasNext(); ) {
     Type next = (Type) it.next();
     if (next instanceof IntersectionType) {
       newBounds.add(inferredTypes.get(typeVars.indexOf(next)));
     } else if (next instanceof ParameterizedType) {
       newBounds.add(((ParameterizedType) next).convertToInferred(typeVars, inferredTypes));
     }
     /*else if (next instanceof AnySubType){
         newBounds.add(((AnySubType)next).convertToInferred(typeVars, inferredTypes));
     }*/
     else {
       newBounds.add(next);
     }
   }
   ParameterizedType converted = ((JL5TypeSystem) typeSystem()).parameterizedType(this.baseType());
   converted.typeArguments(newBounds);
   return converted;
 }
Esempio n. 16
0
 /** Perform necessary actions upon seeing the Initializer <code>initializer</code>. */
 protected void finishInitializer(
     FlowGraph graph, Initializer initializer, DataFlowItem dfIn, DataFlowItem dfOut) {
   // We are finishing the checking of an intializer.
   // We need to copy back the init counts of any fields back into
   // currClassFinalFieldInitCounts, so that the counts are
   // correct for the next initializer or constructor.
   Iterator iter = dfOut.initStatus.entrySet().iterator();
   while (iter.hasNext()) {
     Map.Entry e = (Map.Entry) iter.next();
     if (e.getKey() instanceof FieldInstance) {
       FieldInstance fi = (FieldInstance) e.getKey();
       if (fi.flags().isFinal()) {
         // we don't need to join the init counts, as all
         // dataflows will go through all of the
         // initializers
         currCBI.currClassFinalFieldInitCounts.put(fi, e.getValue());
       }
     }
   }
 }
Esempio n. 17
0
  /**
   * Replace the pass named <code>id</code> in <code>passes</code> with the list of <code>newPasses
   * </code>.
   */
  public void replacePass(List passes, Pass.ID id, List newPasses) {
    for (ListIterator i = passes.listIterator(); i.hasNext(); ) {
      Pass p = (Pass) i.next();

      if (p.id() == id) {
        if (p instanceof BarrierPass) {
          throw new InternalCompilerError("Cannot replace a barrier pass.");
        }

        i.remove();

        for (Iterator j = newPasses.iterator(); j.hasNext(); ) {
          i.add(j.next());
        }

        return;
      }
    }

    throw new InternalCompilerError("Pass " + id + " not found.");
  }
Esempio n. 18
0
  /**
   * Postpone the checking of constructors until the end of the class declaration is encountered, to
   * ensure that all initializers are processed first.
   *
   * <p>Also, at the end of the class declaration, check that all static final fields have been
   * initialized at least once, and that for each constructor all non-static final fields must have
   * been initialized at least once, taking into account the constructor calls.
   */
  public Node leaveCall(Node n) throws SemanticException {
    if (n instanceof ConstructorDecl) {
      // postpone the checking of the constructors until all the
      // initializer blocks have been processed.
      currCBI.allConstructors.add(n);
      return n;
    }

    if (n instanceof ClassBody) {
      // Now that we are at the end of the class declaration, and can
      // be sure that all of the initializer blocks have been processed,
      // we can now process the constructors.

      for (Iterator iter = currCBI.allConstructors.iterator(); iter.hasNext(); ) {
        ConstructorDecl cd = (ConstructorDecl) iter.next();

        // rely on the fact that our dataflow does not change the AST,
        // so we can discard the result of this call.
        dataflow(cd);
      }

      // check that all static fields have been initialized exactly once
      checkStaticFinalFieldsInit((ClassBody) n);

      // check that at the end of each constructor all non-static final
      // fields are initialzed.
      checkNonStaticFinalFieldsInit((ClassBody) n);

      // copy the locals used to the outer scope
      if (currCBI.outer != null) {
        currCBI.outer.localsUsedInClassBodies.put(n, currCBI.outerLocalsUsed);
      }

      // pop the stack
      currCBI = currCBI.outer;
    }

    return super.leaveCall(n);
  }
Esempio n. 19
0
  /** Type check the statement. */
  public Node typeCheck(TypeChecker tc) throws SemanticException {
    TypeSystem ts = tc.typeSystem();

    // Check that all initializers have the same type.
    // This should be enforced by the parser, but check again here,
    // just to be sure.
    Type t = null;

    for (Iterator i = inits.iterator(); i.hasNext(); ) {
      ForInit s = (ForInit) i.next();

      if (s instanceof LocalDecl) {
        LocalDecl d = (LocalDecl) s;
        Type dt = d.type().type();
        if (t == null) {
          t = dt;
        } else if (!t.equals(dt)) {
          throw new InternalCompilerError(
              "Local variable "
                  + "declarations in a for loop initializer must all "
                  + "be the same type, in this case "
                  + t
                  + ", not "
                  + dt
                  + ".",
              d.position());
        }
      }
    }

    if (cond != null && !ts.isImplicitCastValid(cond.type(), ts.Boolean())) {
      throw new SemanticException(
          "The condition of a for statement must have boolean type.", cond.position());
    }

    return this;
  }
Esempio n. 20
0
  /**
   * Before running <code>Pass pass</code> on <code>SourceJob job</code> make sure that all
   * appropriate scheduling invariants are satisfied, to ensure that all passes of other jobs that
   * <code>job</code> depends on will have already been done.
   */
  protected void enforceInvariants(Job job, Pass pass) throws CyclicDependencyException {
    SourceJob srcJob = job.sourceJob();
    if (srcJob == null) {
      return;
    }

    BarrierPass lastBarrier = srcJob.lastBarrier();
    if (lastBarrier != null) {
      // make sure that _all_ dependent jobs have completed at least up to
      // the last barrier (not just children).
      //
      // Ideally the invariant should be that only the source jobs that
      // job _depends on_ should be brought up to the last barrier.
      // This is work to be done in the future...
      List allDependentSrcs = new ArrayList(srcJob.dependencies());
      Iterator i = allDependentSrcs.iterator();
      while (i.hasNext()) {
        Source s = (Source) i.next();
        Object o = jobs.get(s);
        if (o == COMPLETED_JOB) continue;
        if (o == null) {
          throw new InternalCompilerError("Unknown source " + s);
        }
        SourceJob sj = (SourceJob) o;
        if (sj.pending(lastBarrier.id())) {
          // Make the job run up to the last barrier.
          // We ignore the return result, since even if the job
          // fails, we will keep on going and see
          // how far we get...
          if (Report.should_report(Report.frontend, 3)) {
            Report.report(3, "Running " + sj + " to " + lastBarrier.id() + " for " + srcJob);
          }
          runToPass(sj, lastBarrier.id());
        }
      }
    }

    if (pass instanceof GlobalBarrierPass) {
      // need to make sure that _all_ jobs have completed just up to
      // this global barrier.

      // If we hit a cyclic dependency, ignore it and run the other
      // jobs up to that pass.  Then try again to run the cyclic
      // pass.  If we hit the cycle again for the same job, stop.
      LinkedList barrierWorklist = new LinkedList(jobs.values());

      while (!barrierWorklist.isEmpty()) {
        Object o = barrierWorklist.removeFirst();
        if (o == COMPLETED_JOB) continue;
        SourceJob sj = (SourceJob) o;
        if (sj.completed(pass.id()) || sj.nextPass() == sj.passByID(pass.id())) {
          // the source job has either done this global pass
          // (which is possible if the job was loaded late in the
          // game), or is right up to the global barrier.
          continue;
        }

        // Make the job run up to just before the global barrier.
        // We ignore the return result, since even if the job
        // fails, we will keep on going and see
        // how far we get...
        Pass beforeGlobal = sj.getPreviousTo(pass.id());
        if (Report.should_report(Report.frontend, 3)) {
          Report.report(3, "Running " + sj + " to " + beforeGlobal.id() + " for " + srcJob);
        }

        // Don't use runToPass, since that catches the
        // CyclicDependencyException that we should report
        // back to the caller.
        while (!sj.pendingPasses().isEmpty()) {
          Pass p = (Pass) sj.pendingPasses().get(0);

          runPass(sj, p);

          if (p == beforeGlobal) {
            break;
          }
        }
      }
    }
  }