Ejemplo n.º 1
0
bool javaVFrame::structural_compare(javaVFrame* other) {
  // Check static part
  if (method() != other->method()) return false;
  if (bci()    != other->bci())    return false;

  // Check locals
  StackValueCollection *locs = locals();
  StackValueCollection *other_locs = other->locals();
  assert(locs->size() == other_locs->size(), "sanity check");
  int i;
  for(i = 0; i < locs->size(); i++) {
    // it might happen the compiler reports a conflict and
    // the interpreter reports a bogus int.
    if (       is_compiled_frame() &&       locs->at(i)->type() == T_CONFLICT) continue;
    if (other->is_compiled_frame() && other_locs->at(i)->type() == T_CONFLICT) continue;

    if (!locs->at(i)->equal(other_locs->at(i)))
      return false;
  }

  // Check expressions
  StackValueCollection* exprs = expressions();
  StackValueCollection* other_exprs = other->expressions();
  assert(exprs->size() == other_exprs->size(), "sanity check");
  for(i = 0; i < exprs->size(); i++) {
    if (!exprs->at(i)->equal(other_exprs->at(i)))
      return false;
  }

  return true;
}
Ejemplo n.º 2
0
ExpressionsPtr Parser::parseExpressionList()
{
    if (m_curToken.tokenType() != TokenType::Identifier &&
        m_curToken.tokenType() != TokenType::AddOp &&
        m_curToken.tokenType() != TokenType::Number &&
        m_curToken.tokenType() != TokenType::LParen &&
        m_curToken.tokenType() != TokenType::Not) {
        return ExpressionsPtr();
    }

    ExpressionsPtr expressions(new Expressions);

    ExpressionPtr curExpression = parseExpression();
    if (m_errorCode > ErrorCodes::NoError) {
        return ExpressionsPtr();
    }

    expressions->list.push_back(curExpression);

    ExpressionsPtr rest = parseExpressionList_r();
    if (rest) {
        expressions->list.insert(expressions->list.end(), rest->list.begin(), rest->list.end());
    }

    return expressions;
}
  std::shared_ptr<NeumannBCAbstract>
  ParsedFunctionNeumannBCFactoryHelper<FunctionType>::build_neumman_func_common( const GetPot& input,
                                                                                 MultiphysicsSystem& system,
                                                                                 const FEVariablesBase& fe_var,
                                                                                 const std::string& flux_input )
  {
    const std::vector<std::string>& var_names = fe_var.active_var_names();

    std::shared_ptr<NeumannBCAbstract> func;

    // Use "standard" parsed version if there's only one variable
    if( var_names.size() == 1 )
      {
        libmesh_assert_equal_to( fe_var.var_indices().size(), 1 );
        std::string expression = input(flux_input,std::string("DIE!"));
        func = this->build_parsed_neumann_func(system,expression,fe_var.var_indices()[0]);
      }
    // Otherwise, use the composite versions
    else
      {
        libmesh_assert_equal_to( fe_var.var_indices().size(), var_names.size() );

        // We already checked size consistency for flux input and var_names
        // so just use var_names for the size
        std::vector<std::string> expressions(var_names.size());

        for( unsigned int i = 0; i < var_names.size(); i++ )
          expressions[i] = input(flux_input,std::string("DIE!"),i);

        func = this->build_composite_parsed_neumann_func(system,expressions,fe_var.var_indices());
      }

    return func;
  }
Ejemplo n.º 4
0
void javaVFrame::print() {
  ResourceMark rm;
  vframe::print();
  tty->print("\t");
  method()->print_value();
  tty->cr();
  tty->print_cr("\tbci:    %d", bci());

  print_stack_values("locals",      locals());
  print_stack_values("expressions", expressions());

  GrowableArray<MonitorInfo*>* list = monitors();
  if (list->is_empty()) return;
  tty->print_cr("\tmonitor list:");
  for (int index = (list->length()-1); index >= 0; index--) {
    MonitorInfo* monitor = list->at(index);
    tty->print("\t  obj\t");
    if (monitor->owner_is_scalar_replaced()) {
      Klass* k = java_lang_Class::as_Klass(monitor->owner_klass());
      tty->print("( is scalar replaced %s)", k->external_name());
    } else if (monitor->owner() == NULL) {
      tty->print("( null )");
    } else {
      monitor->owner()->print_value();
      tty->print("(" INTPTR_FORMAT ")", (address)monitor->owner());
    }
    if (monitor->eliminated() && is_compiled_frame())
      tty->print(" ( lock is eliminated )");
    tty->cr();
    tty->print("\t  ");
    monitor->lock()->print_on(tty);
    tty->cr();
  }
}
nsresult nsAbQueryStringToExpression::ParseExpressions (
    const char** index,
    nsIAbBooleanExpression* expression)
{
    nsresult rv;
    nsCOMPtr<nsIMutableArray> expressions(do_CreateInstance(NS_ARRAY_CONTRACTID,
                                                            &rv));
    if (NS_FAILED(rv))
        return NS_ERROR_OUT_OF_MEMORY;

    // Case: ")(*)(*)....(*))"
    // printf ("Case: )(*)(*)....(*)): %s\n", *index);
    while (**index == '(')
    {
        nsCOMPtr<nsISupports> childExpression;
        rv = ParseExpression(index, getter_AddRefs (childExpression));
        NS_ENSURE_SUCCESS(rv, rv);

        expressions->AppendElement(childExpression, false);
    }

    if (**index == 0)
        return NS_ERROR_FAILURE;

    // Case: "))"
    // printf ("Case: )): %s\n", *index);

    if (**index != ')')
        return NS_ERROR_FAILURE;

    expression->SetExpressions (expressions);

    return NS_OK;
}
Ejemplo n.º 6
0
int GMSH_CutParametricPlugin::fillXYZ()
{
  std::vector<std::string> expressions(3), variables(2);
  for(int i = 0; i < 3; i++)
    expressions[i] = CutParametricOptions_String[i].def;
  variables[0] = "u";
  variables[1] = "v";
  mathEvaluator f(expressions, variables);
  if(expressions.empty()) return 0;

  int nbU = (int)CutParametricOptions_Number[2].def;
  int nbV = (int)CutParametricOptions_Number[5].def;
  x.resize(nbU * nbV);
  y.resize(nbU * nbV);
  z.resize(nbU * nbV);
  std::vector<double> val(2), res(3);
  for(int i = 0; i < nbU; ++i){
    val[0] = getU(i);
    for(int j = 0; j < nbV; ++j){
      val[1] = getV(j);
      if(f.eval(val, res)){
        x[i * nbV + j] = res[0];
        y[i * nbV + j] = res[1];
        z[i * nbV + j] = res[2];
      }
    }
  }
  return 1;
}
Ejemplo n.º 7
0
void ScopeDesc::verify() {
  ResourceMark rm;
  guarantee(method()->is_method(), "type check");

  // check if we have any illegal elements on the expression stack
  { GrowableArray<ScopeValue*>* l = expressions();
    if (l != NULL) {
      for (int index = 0; index < l->length(); index++) {
       //guarantee(!l->at(index)->is_illegal(), "expression element cannot be illegal");
      }
    }
  }
}
Ejemplo n.º 8
0
gmshParametricSurface::gmshParametricSurface(char *valX, char *valY, char *valZ)
{
  std::vector<std::string> expressions(3), variables(2);
  expressions[0] = valX;
  expressions[1] = valY;
  expressions[2] = valZ;
  variables[0] = "u";
  variables[1] = "v";
  _f = new mathEvaluator(expressions, variables);
  if(expressions.empty()){
    delete _f;
    _f = 0;
  }
}
Ejemplo n.º 9
0
int vframeArrayElement::on_stack_size(int callee_parameters,
                                      int callee_locals,
                                      bool is_top_frame,
                                      int popframe_extra_stack_expression_els) const {
  assert(method()->max_locals() == locals()->size(), "just checking");
  int locks = monitors() == NULL ? 0 : monitors()->number_of_monitors();
  int temps = expressions()->size();
  return Interpreter::size_activation(method()->max_stack(),
                                      temps + callee_parameters,
                                      popframe_extra_stack_expression_els,
                                      locks,
                                      callee_parameters,
                                      callee_locals,
                                      is_top_frame);
}
Ejemplo n.º 10
0
void PViewOptions::createGeneralRaise()
{
  const char *names[] =
    { "x", "y", "z", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8",
      "s", "t"};
  unsigned int numVariables = sizeof(names) / sizeof(names[0]);
  std::vector<std::string> expressions(3), variables(numVariables);
  expressions[0] = genRaiseX;
  expressions[1] = genRaiseY;
  expressions[2] = genRaiseZ;
  for(unsigned int i = 0; i < numVariables; i++) variables[i] = names[i];

  if(genRaiseEvaluator) delete genRaiseEvaluator;
  genRaiseEvaluator = new mathEvaluator(expressions, variables);
  if(expressions.empty()){
    delete genRaiseEvaluator;
    genRaiseEvaluator = 0;
  }
}
Ejemplo n.º 11
0
void javaVFrame::print() {
  ResourceMark rm;
  vframe::print();
  tty->print("\t"); 
  method()->print_value();
  tty->cr();
  tty->print_cr("\tbci:    %d", bci());

  print_stack_values("locals",      locals());
  print_stack_values("expressions", expressions());

  GrowableArray<MonitorInfo*>* list = monitors();
  if (list->is_empty()) return;
  tty->print_cr("\tmonitor list:");
  for (int index = (list->length()-1); index >= 0; index--) {
    MonitorInfo* monitor = list->at(index);
    tty->print("\t  obj\t"); monitor->owner()->print_value(); 
    tty->print("(" INTPTR_FORMAT ")", monitor->owner());
    tty->cr();
    tty->print("\t  ");
    monitor->lock()->print_on(tty);
    tty->cr(); 
  }
}
Ejemplo n.º 12
0
/* ARGSUSED1 */
static void Key ( unsigned char key, int x, int y )
{
  char title[512];
  
    switch ( key ) {
      case 27 :
      case 'q' :
      case 'Q' :
	exit (0) ;

      case 'r' :
      case 'R' :
	printf ("Rereading expression file\n");
        read_expressions();
	e = 0; /* reset the expression count variable */
	glutPostRedisplay();
	break;

      case 'a' :
	printf ("increment muscle: %s\n", face->muscle[m]->name ) ;

	/* set the muscle activation */
	face->muscle[m]->mstat += 0.1 ;
	
	activate_muscle ( face, 
			 face->muscle[m]->head, 
			 face->muscle[m]->tail, 
			 face->muscle[m]->fs,
			 face->muscle[m]->fe,
			 face->muscle[m]->zone,
			 0.1 ) ;
	glutPostRedisplay();
	break;

      case 'A' :
	printf ("decrement muscle: %s\n", face->muscle[m]->name ) ;
	face->muscle[m]->mstat -= 0.1 ;

	activate_muscle ( face, 
			 face->muscle[m]->head, 
			 face->muscle[m]->tail, 
			 face->muscle[m]->fs,
			 face->muscle[m]->fe,
			 face->muscle[m]->zone,
			 -0.1 ) ;
	glutPostRedisplay();
	break;

      case 'b' :
	DRAW_MODE++ ;

	if ( DRAW_MODE >= 3 ) DRAW_MODE = 0 ;
	printf ("draw mode: %d\n", DRAW_MODE ) ;
	glutPostRedisplay();
	break;

      case 'c' :
	face_reset ( face ) ;
	glutPostRedisplay();
	break;
	
      case 'n' :
	m++ ;
	if ( m >= face->nmuscles ) m = 0 ;
        sprintf(title, "geoface (%s)", face->muscle[m]->name);
        glutSetWindowTitle(title);
	break;

      case 'e' :
	if (face->expression) {
	face_reset  ( face ) ;
	expressions ( face, e ) ;

	e++ ;
	if ( e >= face->nexpressions ) e = 0 ;
	glutPostRedisplay();
	}
	break;

      case 'h' :
	
	print_mesg();
	
    }
}
Ejemplo n.º 13
0
PView *GMSH_ModifyComponentPlugin::execute(PView *view)
{
  int component = (int)ModifyComponentOptions_Number[0].def;
  int timeStep = (int)ModifyComponentOptions_Number[1].def;
  int iView = (int)ModifyComponentOptions_Number[2].def;
  int otherTimeStep = (int)ModifyComponentOptions_Number[3].def;
  int otherView = (int)ModifyComponentOptions_Number[4].def;
  int forceInterpolation = (int)ModifyComponentOptions_Number[5].def;

  PView *v1 = getView(iView, view);
  if(!v1) return view;

  PViewData *data1 = v1->getData();

  if(timeStep > data1->getNumTimeSteps() - 1){
    Msg::Error("Invalid time step (%d) in View[%d]: using step 0 instead",
               timeStep, v1->getIndex());
    timeStep = 0;
  }

  PView *v2 = v1;

  if(otherView >= 0){
    if(otherView < (int)PView::list.size())
      v2 = PView::list[otherView];
    else
      Msg::Error("View[%d] does not exist: using self", otherView);
  }

  PViewData *data2 = getPossiblyAdaptiveData(v2);

  if(otherTimeStep < 0 && data2->getNumTimeSteps() != data1->getNumTimeSteps()){
    Msg::Error("Number of time steps don't match: using step 0");
    otherTimeStep = 0;
  }
  else if(otherTimeStep > data2->getNumTimeSteps() - 1){
    Msg::Error("Invalid time step (%d) in View[%d]: using step 0 instead",
               otherTimeStep, v2->getIndex());
    otherTimeStep = 0;
  }

  const char *names[] =
    {"x", "y", "z", "Time", "TimeStep",
     "v", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8",
     "w", "w0", "w1", "w2", "w3", "w4", "w5", "w6", "w7", "w8"};
  unsigned int numVariables = sizeof(names) / sizeof(names[0]);
  std::vector<std::string> expressions(1), variables(numVariables);
  expressions[0] = ModifyComponentOptions_String[0].def;
  for(unsigned int i = 0; i < numVariables; i++) variables[i] = names[i];
  mathEvaluator f(expressions, variables);
  if(expressions.empty()) return view;
  std::vector<double> values(numVariables), res(1);

  OctreePost *octree = 0;
  if(forceInterpolation ||
     (data1->getNumEntities() != data2->getNumEntities()) ||
     (data1->getNumElements() != data2->getNumElements())){
    Msg::Info("Other view based on different grid: interpolating...");
    octree = new OctreePost(v2);
  }

  for(int step = 0; step < data1->getNumTimeSteps(); step++){
    if(timeStep >= 0 && timeStep != step) continue;

    double time = data1->getTime(step);
    int step2 = (otherTimeStep < 0) ? step : otherTimeStep;

    // tag all the nodes with "0" (the default tag)
    for(int ent = 0; ent < data1->getNumEntities(step); ent++){
      for(int ele = 0; ele < data1->getNumElements(step, ent); ele++){
        if(data1->skipElement(step, ent, ele)) continue;
        for(int nod = 0; nod < data1->getNumNodes(step, ent, ele); nod++)
          data1->tagNode(step, ent, ele, nod, 0);
      }
    }

    for(int ent = 0; ent < data1->getNumEntities(step); ent++){
      for(int ele = 0; ele < data1->getNumElements(step, ent); ele++){
        if(data1->skipElement(step, ent, ele)) continue;
        int numComp = data1->getNumComponents(step, ent, ele);
        int numComp2 = octree ? 9 : data2->getNumComponents(step2, ent, ele);
        int numNodes = data1->getNumNodes(step, ent, ele);
        std::vector<int> tag(numNodes);
        std::vector<double> x(numNodes), y(numNodes), z(numNodes);
        for(int nod = 0; nod < numNodes; nod++)
          tag[nod] = data1->getNode(step, ent, ele, nod, x[nod], y[nod], z[nod]);
        for(int nod = 0; nod < numNodes; nod++){
          if(tag[nod]) continue; // node has already been modified
          std::vector<double> v(std::max(9, numComp), 0.);
          for(int comp = 0; comp < numComp; comp++)
            data1->getValue(step, ent, ele, nod, comp, v[comp]);
          std::vector<double> w(std::max(9, numComp2), 0.);
          if(octree){
            int qn = forceInterpolation ? numNodes : 0;
            if(!octree->searchScalar(x[nod], y[nod], z[nod], &w[0], step2,
                                     0, qn, &x[0], &y[0], &z[0]))
              if(!octree->searchVector(x[nod], y[nod], z[nod], &w[0], step2,
                                       0, qn, &x[0], &y[0], &z[0]))
                octree->searchTensor(x[nod], y[nod], z[nod], &w[0], step2,
                                     0, qn, &x[0], &y[0], &z[0]);
          }
          else
            for(int comp = 0; comp < numComp2; comp++)
              data2->getValue(step2, ent, ele, nod, comp, w[comp]);
          for(int comp = 0; comp < numComp; comp++){
            if(component >= 0 && component != comp) continue;
            values[0] = x[nod]; values[1] = y[nod]; values[2] = z[nod];
            values[3] = time; values[4] = step;
            values[5] = v[comp];
            for(int i = 0; i < 9; i++) values[6 + i] = v[i];
            values[15] = w[comp];
            for(int i = 0; i < 9; i++) values[16 + i] = w[i];
            if(f.eval(values, res))
              data1->setValue(step, ent, ele, nod, comp, res[0]);
            data1->tagNode(step, ent, ele, nod, 1);
          }
        }
      }
    }
  }

  if(octree) delete octree;

  data1->finalize();
  v1->setChanged(true);

  return v1;
}
void vframeArrayElement::unpack_on_stack(int caller_actual_parameters,
                                         int callee_parameters,
                                         int callee_locals,
                                         frame* caller,
                                         bool is_top_frame,
                                         bool is_bottom_frame,
                                         int exec_mode) {
  JavaThread* thread = (JavaThread*) Thread::current();

  // Look at bci and decide on bcp and continuation pc
  address bcp;
  // C++ interpreter doesn't need a pc since it will figure out what to do when it
  // begins execution
  address pc;
  bool use_next_mdp = false; // true if we should use the mdp associated with the next bci
                             // rather than the one associated with bcp
  if (raw_bci() == SynchronizationEntryBCI) {
    // We are deoptimizing while hanging in prologue code for synchronized method
    bcp = method()->bcp_from(0); // first byte code
    pc  = Interpreter::deopt_entry(vtos, 0); // step = 0 since we don't skip current bytecode
  } else if (should_reexecute()) { //reexecute this bytecode
    assert(is_top_frame, "reexecute allowed only for the top frame");
    bcp = method()->bcp_from(bci());
    pc  = Interpreter::deopt_reexecute_entry(method(), bcp);
  } else {
    bcp = method()->bcp_from(bci());
    pc  = Interpreter::deopt_continue_after_entry(method(), bcp, callee_parameters, is_top_frame);
    use_next_mdp = true;
  }
  assert(Bytecodes::is_defined(*bcp), "must be a valid bytecode");

  // Monitorenter and pending exceptions:
  //
  // For Compiler2, there should be no pending exception when deoptimizing at monitorenter
  // because there is no safepoint at the null pointer check (it is either handled explicitly
  // or prior to the monitorenter) and asynchronous exceptions are not made "pending" by the
  // runtime interface for the slow case (see JRT_ENTRY_FOR_MONITORENTER).  If an asynchronous
  // exception was processed, the bytecode pointer would have to be extended one bytecode beyond
  // the monitorenter to place it in the proper exception range.
  //
  // For Compiler1, deoptimization can occur while throwing a NullPointerException at monitorenter,
  // in which case bcp should point to the monitorenter since it is within the exception's range.

  assert(*bcp != Bytecodes::_monitorenter || is_top_frame, "a _monitorenter must be a top frame");
  assert(thread->deopt_nmethod() != NULL, "nmethod should be known");
  guarantee(!(thread->deopt_nmethod()->is_compiled_by_c2() &&
              *bcp == Bytecodes::_monitorenter             &&
              exec_mode == Deoptimization::Unpack_exception),
            "shouldn't get exception during monitorenter");

  int popframe_preserved_args_size_in_bytes = 0;
  int popframe_preserved_args_size_in_words = 0;
  if (is_top_frame) {
    JvmtiThreadState *state = thread->jvmti_thread_state();
    if (JvmtiExport::can_pop_frame() &&
        (thread->has_pending_popframe() || thread->popframe_forcing_deopt_reexecution())) {
      if (thread->has_pending_popframe()) {
        // Pop top frame after deoptimization
#ifndef CC_INTERP
        pc = Interpreter::remove_activation_preserving_args_entry();
#else
        // Do an uncommon trap type entry. c++ interpreter will know
        // to pop frame and preserve the args
        pc = Interpreter::deopt_entry(vtos, 0);
        use_next_mdp = false;
#endif
      } else {
        // Reexecute invoke in top frame
        pc = Interpreter::deopt_entry(vtos, 0);
        use_next_mdp = false;
        popframe_preserved_args_size_in_bytes = in_bytes(thread->popframe_preserved_args_size());
        // Note: the PopFrame-related extension of the expression stack size is done in
        // Deoptimization::fetch_unroll_info_helper
        popframe_preserved_args_size_in_words = in_words(thread->popframe_preserved_args_size_in_words());
      }
    } else if (JvmtiExport::can_force_early_return() && state != NULL && state->is_earlyret_pending()) {
      // Force early return from top frame after deoptimization
#ifndef CC_INTERP
      pc = Interpreter::remove_activation_early_entry(state->earlyret_tos());
#else
     // TBD: Need to implement ForceEarlyReturn for CC_INTERP (ia64)
#endif
    } else {
      // Possibly override the previous pc computation of the top (youngest) frame
      switch (exec_mode) {
      case Deoptimization::Unpack_deopt:
        // use what we've got
        break;
      case Deoptimization::Unpack_exception:
        // exception is pending
        pc = SharedRuntime::raw_exception_handler_for_return_address(thread, pc);
        // [phh] We're going to end up in some handler or other, so it doesn't
        // matter what mdp we point to.  See exception_handler_for_exception()
        // in interpreterRuntime.cpp.
        break;
      case Deoptimization::Unpack_uncommon_trap:
      case Deoptimization::Unpack_reexecute:
        // redo last byte code
        pc  = Interpreter::deopt_entry(vtos, 0);
        use_next_mdp = false;
        break;
      default:
        ShouldNotReachHere();
      }
    }
  }

  // Setup the interpreter frame

  assert(method() != NULL, "method must exist");
  int temps = expressions()->size();

  int locks = monitors() == NULL ? 0 : monitors()->number_of_monitors();

  Interpreter::layout_activation(method(),
                                 temps + callee_parameters,
                                 popframe_preserved_args_size_in_words,
                                 locks,
                                 caller_actual_parameters,
                                 callee_parameters,
                                 callee_locals,
                                 caller,
                                 iframe(),
                                 is_top_frame,
                                 is_bottom_frame);

  // Update the pc in the frame object and overwrite the temporary pc
  // we placed in the skeletal frame now that we finally know the
  // exact interpreter address we should use.

  _frame.patch_pc(thread, pc);

  assert (!method()->is_synchronized() || locks > 0, "synchronized methods must have monitors");

  BasicObjectLock* top = iframe()->interpreter_frame_monitor_begin();
  for (int index = 0; index < locks; index++) {
    top = iframe()->previous_monitor_in_interpreter_frame(top);
    BasicObjectLock* src = _monitors->at(index);
    top->set_obj(src->obj());
    src->lock()->move_to(src->obj(), top->lock());
  }
  if (ProfileInterpreter) {
    iframe()->interpreter_frame_set_mdx(0); // clear out the mdp.
  }
  iframe()->interpreter_frame_set_bcx((intptr_t)bcp); // cannot use bcp because frame is not initialized yet
  if (ProfileInterpreter) {
    methodDataOop mdo = method()->method_data();
    if (mdo != NULL) {
      int bci = iframe()->interpreter_frame_bci();
      if (use_next_mdp) ++bci;
      address mdp = mdo->bci_to_dp(bci);
      iframe()->interpreter_frame_set_mdp(mdp);
    }
  }

  // Unpack expression stack
  // If this is an intermediate frame (i.e. not top frame) then this
  // only unpacks the part of the expression stack not used by callee
  // as parameters. The callee parameters are unpacked as part of the
  // callee locals.
  int i;
  for(i = 0; i < expressions()->size(); i++) {
    StackValue *value = expressions()->at(i);
    intptr_t*   addr  = iframe()->interpreter_frame_expression_stack_at(i);
    switch(value->type()) {
      case T_INT:
        *addr = value->get_int();
        break;
      case T_OBJECT:
        *addr = value->get_int(T_OBJECT);
        break;
      case T_CONFLICT:
        // A dead stack slot.  Initialize to null in case it is an oop.
        *addr = NULL_WORD;
        break;
      default:
        ShouldNotReachHere();
    }
  }


  // Unpack the locals
  for(i = 0; i < locals()->size(); i++) {
    StackValue *value = locals()->at(i);
    intptr_t* addr  = iframe()->interpreter_frame_local_at(i);
    switch(value->type()) {
      case T_INT:
        *addr = value->get_int();
        break;
      case T_OBJECT:
        *addr = value->get_int(T_OBJECT);
        break;
      case T_CONFLICT:
        // A dead location. If it is an oop then we need a NULL to prevent GC from following it
        *addr = NULL_WORD;
        break;
      default:
        ShouldNotReachHere();
    }
  }

  if (is_top_frame && JvmtiExport::can_pop_frame() && thread->popframe_forcing_deopt_reexecution()) {
    // An interpreted frame was popped but it returns to a deoptimized
    // frame. The incoming arguments to the interpreted activation
    // were preserved in thread-local storage by the
    // remove_activation_preserving_args_entry in the interpreter; now
    // we put them back into the just-unpacked interpreter frame.
    // Note that this assumes that the locals arena grows toward lower
    // addresses.
    if (popframe_preserved_args_size_in_words != 0) {
      void* saved_args = thread->popframe_preserved_args();
      assert(saved_args != NULL, "must have been saved by interpreter");
#ifdef ASSERT
      assert(popframe_preserved_args_size_in_words <=
             iframe()->interpreter_frame_expression_stack_size()*Interpreter::stackElementWords,
             "expression stack size should have been extended");
#endif // ASSERT
      int top_element = iframe()->interpreter_frame_expression_stack_size()-1;
      intptr_t* base;
      if (frame::interpreter_frame_expression_stack_direction() < 0) {
        base = iframe()->interpreter_frame_expression_stack_at(top_element);
      } else {
        base = iframe()->interpreter_frame_expression_stack();
      }
      Copy::conjoint_jbytes(saved_args,
                            base,
                            popframe_preserved_args_size_in_bytes);
      thread->popframe_free_preserved_args();
    }
  }

#ifndef PRODUCT
  if (TraceDeoptimization && Verbose) {
    ttyLocker ttyl;
    tty->print_cr("[%d Interpreted Frame]", ++unpack_counter);
    iframe()->print_on(tty);
    RegisterMap map(thread);
    vframe* f = vframe::new_vframe(iframe(), &map, thread);
    f->print();

    tty->print_cr("locals size     %d", locals()->size());
    tty->print_cr("expression size %d", expressions()->size());

    method()->print_value();
    tty->cr();
    // method()->print_codes();
  } else if (TraceDeoptimization) {
    tty->print("     ");
    method()->print_value();
    Bytecodes::Code code = Bytecodes::java_code_at(method(), bcp);
    int bci = method()->bci_from(bcp);
    tty->print(" - %s", Bytecodes::name(code));
    tty->print(" @ bci %d ", bci);
    tty->print_cr("sp = " PTR_FORMAT, iframe()->sp());
  }
#endif // PRODUCT

  // The expression stack and locals are in the resource area don't leave
  // a dangling pointer in the vframeArray we leave around for debug
  // purposes

  _locals = _expressions = NULL;

}
Ejemplo n.º 15
0
int main (int argc, char **argv) {

  IloEnv env;

  try {
    IloCplex cplex(env);
    IloTimer timer(env);

    const IloNum startTime = cplex.getCplexTime();

    parseCommandLine(argc, argv);
    printCommandLine(argc, argv);

    // set all default constraint weights as zero
    consWts["NonOperatorsAtMostOnce"]           = 0;
    consWts["StackDepthUpperBound"]             = 0;
    consWts["ExactlyOneUnknown"]                = 0;
    consWts["NoTwoConsecutiveMultiplications"]  = 0;  // note: this may be disabled if word "dozen" appears
    consWts["NoTwoConsecutiveDivisions"]        = 0;
    consWts["NoConsecutiveMultAndDiv"]          = 0;
    consWts["NoNegatives"]                      = 0;
    consWts["TypeConsistency"]                  = 0;
    consWts["EqualityFirstOrLast"]              = 0;
    consWts["IntConstantsImplyIntUnknown"]      = 0;
    consWts["PreserveOrderingInText"]           = 0;
    consWts["UnknownFirstOrLast"]               = 0;
    consWts["EqualityNextToUnknown"]            = 0;
    consWts["HasAddition"]                      = 0;
    consWts["HasSubtraction"]                   = 0;
    consWts["HasMultiplication"]                = 0;
    consWts["HasDivision"]                      = 0;

    // parse config file defining constraint weights
    parseConfigFile(param_wts_config_file);

    cout << "Starting IloTimer" << endl;
    timer.start();

    // parse arithmetic model parameters; note: this may override previously
    // set constraint weights
    if (strlen(arith_filename) > 0)
      parseInputFile(arith_filename);

    // set cplex paramters
    setCplexParameters(cplex);

    // import or build the model
    IloModel       model(env);
    IloObjective   obj(env);
    IloNumVarArray corevars(env);
    IloRangeArray  rngs(env);

    if (strlen(mip_filename) > 0) {
      cout << "------- Importing the model -------" << endl;
      cplex.importModel(model, mip_filename, obj, corevars, rngs);
      cout << "Model imported at " << (cplex.getCplexTime() - startTime) << " sec" << endl;
    }
    else {
      cout << "------- Building the model -------" << endl;
      buildArithmeticModel(model, obj, corevars, rngs);
    }

    int nvars = corevars.getSize();
    cout << "Number of Core Variables: " << nvars << endl;

    cplex.extract(model);
    cout << "Model extracted at " << (cplex.getCplexTime() - startTime) << " sec" << endl;

    // save the MIP model to a file, if desired
    if (!param_savemodel.empty()) {
      cout << endl << "Saving generated MIP model to " << param_savemodel << endl << endl;
      cplex.exportModel(param_savemodel.c_str());
    }

    // find out whether it is a minimization problem or a maximization one
    bool isMinimization = true;
    if (cplex.getObjective().getSense() == IloObjective::Maximize)
      isMinimization = false;

    // ask cplex to use MIPInfoCallback
    cplex.use(MIPInfoCallback(env, isMinimization, cplex, startTime));

    cout << "------- Solving the extracted model -------" << endl;
    //const bool solutionFound = cplex.solve();
    const bool solutionFound = (param_nsolutions > 1 ? cplex.populate() : cplex.solve());
    const int nSolutionsFound = cplex.getSolnPoolNsolns();

    cout << "Stopping IloTimer" << endl;
    timer.stop();
    const IloNum endTime = cplex.getCplexTime();

    cout << "-------------------------------------------" << endl;
    printCommandLine(argc, argv);
    cout << "-------------------------------------------" << endl;
    cout << "Number of cplex nodes        = " << cplex.getNnodes() << endl;
    cout << "Number of cplex iterations   = " << cplex.getNiterations() << endl;
    cout << "Aggregated CPU time          = " << timer.getTime() << " seconds" << endl;
    cout << "Elapsed wall clock time      = " << endTime - startTime << " seconds" << endl;
    cout << "Number of threads used       = " << param_threads << endl;
    cout << "Solution status              = " << cplex.getStatus() << endl;

    if (solutionFound) {
      cout << "Solution value               = " << cplex.getObjValue() << endl;
      cout << "Optimality Gap (in %)        = " << fabs((cplex.getBestObjValue() - cplex.getObjValue()) / (1.0 * cplex.getObjValue())) * 100 << endl;
      //cout << "Maximum bound violation      = " << cplex.getQuality(IloCplex::MaxPrimalInfeas) << endl;
    }
    cout << endl << "parameters: n=" << n << " l=" << l << " k=" << k << " p=" << p << " q=" << q << " m=" << m << endl;
    if (solutionFound) {
      cout << "TOTAL " << nSolutionsFound << " solutions found" << endl;
      int nAllowedSolutionsFound = 0;
      if (param_printexpr || param_printanswer || param_printsoln) {
        IloNumArray objValues(env, nSolutionsFound);
        vector<pair<IloNum,unsigned> > sortedIndex(nSolutionsFound);  // to sort solutions by objective value
        vector<FormattedExpr> expressions(nSolutionsFound);
        // extract all solutions as formatted expressions
        for (int s=0; s<nSolutionsFound; s++) {
          IloNumArray vals(env);
          cplex.getValues(vals, corevars, s);
          // convert solution values to integers; note: simple int cast may lead to errors!
          IloIntArray intvals(env, vals.getSize());
          for (int i=0; i<vals.getSize(); i++)
            intvals[i] = IloRound(vals[i]);  // use IloRound rather than std::round
          if (param_printsoln)
            prettyPrintSoln(intvals);
          objValues[s] = cplex.getObjValue(s);
          expressions[s] = getFormattedExpr(intvals);
          sortedIndex[s] = pair<IloNum,unsigned> (objValues[s],s);
        }
        // sort solutions by increasing objective value
        std::stable_sort(sortedIndex.begin(), sortedIndex.end());
        // identify which expressions are unique (ignoring type differences);
        // prefer to keep those that appear earlier in the above sorted order
        set<int>    uniqueExprIndices;
        set<string> seenExpressions;
        if (!param_allowdupes) {
          for (int s=0; s<nSolutionsFound; s++) {
            const int sId = sortedIndex[s].second;
            const string & exprPf = expressions[sId].postfix;
            if (seenExpressions.find(exprPf) == seenExpressions.end()) {
              uniqueExprIndices.insert(sId);
              seenExpressions.insert(exprPf);
            }
          }
        }
        // evaluate all expressions with a single call to Python's SymPy package
        if (param_printanswer)
          solveExpressionsWithSymPy(expressions);
        // print expressions if desired, in sorted order
        if (param_printexpr) {
          cout << "SOLN: CORRECT | POS/NEG | INT/FRA | OBJ-SCORE | TRUE-ANS | ANS | INFIX | POSTFIX | TYPED-POSTFIX" << endl;
          for (int s=0; s<nSolutionsFound; s++) {
            const int sId = sortedIndex[s].second;
            if (!param_allowdupes && uniqueExprIndices.find(sId) == uniqueExprIndices.end())
              continue;
            const FormattedExpr & expr = expressions[sId];
            const double answerValue = atof(expr.answer.c_str());
            const bool isCorrect = (fabs(answerValue - trueAnswer) < epsilon);
            const bool isAnswerNegative = answerValue < 0;
            const bool isAnswerInteger = isInt(answerValue);
            if (!isAnswerNegative && (!allIntConstants || consWts["IntConstantsImplyIntUnknown"] == 0 || isAnswerInteger)) {
              ++nAllowedSolutionsFound;
              cout << "EXPR: " << isCorrect
                   << " | " << (isAnswerNegative ? "NEG" : "POS")
                   << " | " << (isAnswerInteger ? "INT" : "FRA")
                   << " | " << objValues[sId]
                   << " | " << trueAnswer
                   << " | " << expr.answer
                   << " | " << expr.infix
                   << " | " << expr.postfix
                   << " | " << expr.typedPostfix
                   << endl;
            }
          }
        }
      }
      const string solnProperty = (param_allowdupes ? "" : " unique,")
        + string(" non-negative")
        + (allIntConstants && consWts["IntConstantsImplyIntUnknown"] != 0 ? ", integer-valued " : " ");
      cout << "NET " << nAllowedSolutionsFound << solnProperty << "solutions found out of "
           << nSolutionsFound << " total solutions" << endl;
    }

    cout << "-------------------------------------------" << endl;
    cout << "RESULT:"
         << " NODES " << cplex.getNnodes()
         << " | ITERATIONS " << cplex.getNiterations()
         << " | CPUTIME " << timer.getTime()
         << " | WALLTIME " << endTime - startTime
         << " | THREADS " << param_threads
         << " | STATUS " << cplex.getStatus();
    if (solutionFound)
      cout << " | SOLUTION " << cplex.getObjValue()
           << " | OPTGAP " << fabs((cplex.getBestObjValue() - cplex.getObjValue()) / (1.0 * cplex.getObjValue())) * 100;
    else
      cout << " | SOLUTION - | OPTGAP -";
    cout << endl;

    //try {     // basis may not exist
    //  IloCplex::BasisStatusArray cstat(env);
    //  cplex.getBasisStatuses(cstat, vars);
    //  cout << "Basis statuses               = " << cstat << endl;
    //}
    //catch (...) {
    //}


  }
  catch (IloException& e) {
    cerr << "Concert exception caught: " << e << endl;
  }
  catch (...) {
    cerr << "Unknown exception caught" << endl;
  }

  env.end();
  return 0;
}  // END main