1 /*
   2  * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "compiler/compileLog.hpp"
  27 #include "opto/addnode.hpp"
  28 #include "opto/callGenerator.hpp"
  29 #include "opto/callnode.hpp"
  30 #include "opto/divnode.hpp"
  31 #include "opto/graphKit.hpp"
  32 #include "opto/idealKit.hpp"
  33 #include "opto/rootnode.hpp"
  34 #include "opto/runtime.hpp"
  35 #include "opto/stringopts.hpp"
  36 #include "opto/subnode.hpp"
  37 
  38 #define __ kit.
  39 
  40 class StringConcat : public ResourceObj {
  41  private:
  42   PhaseStringOpts*    _stringopts;
  43   Node*               _string_alloc;
  44   AllocateNode*       _begin;          // The allocation the begins the pattern
  45   CallStaticJavaNode* _end;            // The final call of the pattern.  Will either be
  46                                        // SB.toString or or String.<init>(SB.toString)
  47   bool                _multiple;       // indicates this is a fusion of two or more
  48                                        // separate StringBuilders
  49 
  50   Node*               _arguments;      // The list of arguments to be concatenated
  51   GrowableArray<int>  _mode;           // into a String along with a mode flag
  52                                        // indicating how to treat the value.
  53   Node_List           _constructors;   // List of constructors (many in case of stacked concat)
  54   Node_List           _control;        // List of control nodes that will be deleted
  55   Node_List           _uncommon_traps; // Uncommon traps that needs to be rewritten
  56                                        // to restart at the initial JVMState.
  57 
  58  public:
  59   // Mode for converting arguments to Strings
  60   enum {
  61     StringMode,
  62     IntMode,
  63     CharMode,
  64     StringNullCheckMode
  65   };
  66 
  67   StringConcat(PhaseStringOpts* stringopts, CallStaticJavaNode* end):
  68     _end(end),
  69     _begin(NULL),
  70     _multiple(false),
  71     _string_alloc(NULL),
  72     _stringopts(stringopts) {
  73     _arguments = new (_stringopts->C) Node(1);
  74     _arguments->del_req(0);
  75   }
  76 
  77   bool validate_mem_flow();
  78   bool validate_control_flow();
  79 
  80   void merge_add() {
  81 #if 0
  82     // XXX This is place holder code for reusing an existing String
  83     // allocation but the logic for checking the state safety is
  84     // probably inadequate at the moment.
  85     CallProjections endprojs;
  86     sc->end()->extract_projections(&endprojs, false);
  87     if (endprojs.resproj != NULL) {
  88       for (SimpleDUIterator i(endprojs.resproj); i.has_next(); i.next()) {
  89         CallStaticJavaNode *use = i.get()->isa_CallStaticJava();
  90         if (use != NULL && use->method() != NULL &&
  91             use->method()->intrinsic_id() == vmIntrinsics::_String_String &&
  92             use->in(TypeFunc::Parms + 1) == endprojs.resproj) {
  93           // Found useless new String(sb.toString()) so reuse the newly allocated String
  94           // when creating the result instead of allocating a new one.
  95           sc->set_string_alloc(use->in(TypeFunc::Parms));
  96           sc->set_end(use);
  97         }
  98       }
  99     }
 100 #endif
 101   }
 102 
 103   StringConcat* merge(StringConcat* other, Node* arg);
 104 
 105   void set_allocation(AllocateNode* alloc) {
 106     _begin = alloc;
 107   }
 108 
 109   void append(Node* value, int mode) {
 110     _arguments->add_req(value);
 111     _mode.append(mode);
 112   }
 113   void push(Node* value, int mode) {
 114     _arguments->ins_req(0, value);
 115     _mode.insert_before(0, mode);
 116   }
 117 
 118   void push_string(Node* value) {
 119     push(value, StringMode);
 120   }
 121   void push_string_null_check(Node* value) {
 122     push(value, StringNullCheckMode);
 123   }
 124   void push_int(Node* value) {
 125     push(value, IntMode);
 126   }
 127   void push_char(Node* value) {
 128     push(value, CharMode);
 129   }
 130 
 131   static bool is_SB_toString(Node* call) {
 132     if (call->is_CallStaticJava()) {
 133       CallStaticJavaNode* csj = call->as_CallStaticJava();
 134       ciMethod* m = csj->method();
 135       if (m != NULL &&
 136           (m->intrinsic_id() == vmIntrinsics::_StringBuilder_toString ||
 137            m->intrinsic_id() == vmIntrinsics::_StringBuffer_toString)) {
 138         return true;
 139       }
 140     }
 141     return false;
 142   }
 143 
 144   static Node* skip_string_null_check(Node* value) {
 145     // Look for a diamond shaped Null check of toString() result
 146     // (could be code from String.valueOf()):
 147     // (Proj == NULL) ? "null":"CastPP(Proj)#NotNULL
 148     if (value->is_Phi()) {
 149       int true_path = value->as_Phi()->is_diamond_phi();
 150       if (true_path != 0) {
 151         // phi->region->if_proj->ifnode->bool
 152         BoolNode* b = value->in(0)->in(1)->in(0)->in(1)->as_Bool();
 153         Node* cmp = b->in(1);
 154         Node* v1 = cmp->in(1);
 155         Node* v2 = cmp->in(2);
 156         // Null check of the return of toString which can simply be skipped.
 157         if (b->_test._test == BoolTest::ne &&
 158             v2->bottom_type() == TypePtr::NULL_PTR &&
 159             value->in(true_path)->Opcode() == Op_CastPP &&
 160             value->in(true_path)->in(1) == v1 &&
 161             v1->is_Proj() && is_SB_toString(v1->in(0))) {
 162           return v1;
 163         }
 164       }
 165     }
 166     return value;
 167   }
 168 
 169   Node* argument(int i) {
 170     return _arguments->in(i);
 171   }
 172   Node* argument_uncast(int i) {
 173     Node* arg = argument(i);
 174     int amode = mode(i);
 175     if (amode == StringConcat::StringMode ||
 176         amode == StringConcat::StringNullCheckMode) {
 177       arg = skip_string_null_check(arg);
 178     }
 179     return arg;
 180   }
 181   void set_argument(int i, Node* value) {
 182     _arguments->set_req(i, value);
 183   }
 184   int num_arguments() {
 185     return _mode.length();
 186   }
 187   int mode(int i) {
 188     return _mode.at(i);
 189   }
 190   void add_control(Node* ctrl) {
 191     assert(!_control.contains(ctrl), "only push once");
 192     _control.push(ctrl);
 193   }
 194   void add_constructor(Node* init) {
 195     assert(!_constructors.contains(init), "only push once");
 196     _constructors.push(init);
 197   }
 198   CallStaticJavaNode* end() { return _end; }
 199   AllocateNode* begin() { return _begin; }
 200   Node* string_alloc() { return _string_alloc; }
 201 
 202   void eliminate_unneeded_control();
 203   void eliminate_initialize(InitializeNode* init);
 204   void eliminate_call(CallNode* call);
 205 
 206   void maybe_log_transform() {
 207     CompileLog* log = _stringopts->C->log();
 208     if (log != NULL) {
 209       log->head("replace_string_concat arguments='%d' string_alloc='%d' multiple='%d'",
 210                 num_arguments(),
 211                 _string_alloc != NULL,
 212                 _multiple);
 213       JVMState* p = _begin->jvms();
 214       while (p != NULL) {
 215         log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
 216         p = p->caller();
 217       }
 218       log->tail("replace_string_concat");
 219     }
 220   }
 221 
 222   void convert_uncommon_traps(GraphKit& kit, const JVMState* jvms) {
 223     for (uint u = 0; u < _uncommon_traps.size(); u++) {
 224       Node* uct = _uncommon_traps.at(u);
 225 
 226       // Build a new call using the jvms state of the allocate
 227       address call_addr = SharedRuntime::uncommon_trap_blob()->entry_point();
 228       const TypeFunc* call_type = OptoRuntime::uncommon_trap_Type();
 229       const TypePtr* no_memory_effects = NULL;
 230       Compile* C = _stringopts->C;
 231       CallStaticJavaNode* call = new (C) CallStaticJavaNode(call_type, call_addr, "uncommon_trap",
 232                                                             jvms->bci(), no_memory_effects);
 233       for (int e = 0; e < TypeFunc::Parms; e++) {
 234         call->init_req(e, uct->in(e));
 235       }
 236       // Set the trap request to record intrinsic failure if this trap
 237       // is taken too many times.  Ideally we would handle then traps by
 238       // doing the original bookkeeping in the MDO so that if it caused
 239       // the code to be thrown out we could still recompile and use the
 240       // optimization.  Failing the uncommon traps doesn't really mean
 241       // that the optimization is a bad idea but there's no other way to
 242       // do the MDO updates currently.
 243       int trap_request = Deoptimization::make_trap_request(Deoptimization::Reason_intrinsic,
 244                                                            Deoptimization::Action_make_not_entrant);
 245       call->init_req(TypeFunc::Parms, __ intcon(trap_request));
 246       kit.add_safepoint_edges(call);
 247 
 248       _stringopts->gvn()->transform(call);
 249       C->gvn_replace_by(uct, call);
 250       uct->disconnect_inputs(NULL, C);
 251     }
 252   }
 253 
 254   void cleanup() {
 255     // disconnect the hook node
 256     _arguments->disconnect_inputs(NULL, _stringopts->C);
 257   }
 258 };
 259 
 260 
 261 void StringConcat::eliminate_unneeded_control() {
 262   for (uint i = 0; i < _control.size(); i++) {
 263     Node* n = _control.at(i);
 264     if (n->is_Allocate()) {
 265       eliminate_initialize(n->as_Allocate()->initialization());
 266     }
 267     if (n->is_Call()) {
 268       if (n != _end) {
 269         eliminate_call(n->as_Call());
 270       }
 271     } else if (n->is_IfTrue()) {
 272       Compile* C = _stringopts->C;
 273       C->gvn_replace_by(n, n->in(0)->in(0));
 274       // get rid of the other projection
 275       C->gvn_replace_by(n->in(0)->as_If()->proj_out(false), C->top());
 276     }
 277   }
 278 }
 279 
 280 
 281 StringConcat* StringConcat::merge(StringConcat* other, Node* arg) {
 282   StringConcat* result = new StringConcat(_stringopts, _end);
 283   for (uint x = 0; x < _control.size(); x++) {
 284     Node* n = _control.at(x);
 285     if (n->is_Call()) {
 286       result->_control.push(n);
 287     }
 288   }
 289   for (uint x = 0; x < other->_control.size(); x++) {
 290     Node* n = other->_control.at(x);
 291     if (n->is_Call()) {
 292       result->_control.push(n);
 293     }
 294   }
 295   assert(result->_control.contains(other->_end), "what?");
 296   assert(result->_control.contains(_begin), "what?");
 297   for (int x = 0; x < num_arguments(); x++) {
 298     Node* argx = argument_uncast(x);
 299     if (argx == arg) {
 300       // replace the toString result with the all the arguments that
 301       // made up the other StringConcat
 302       for (int y = 0; y < other->num_arguments(); y++) {
 303         result->append(other->argument(y), other->mode(y));
 304       }
 305     } else {
 306       result->append(argx, mode(x));
 307     }
 308   }
 309   result->set_allocation(other->_begin);
 310   for (uint i = 0; i < _constructors.size(); i++) {
 311     result->add_constructor(_constructors.at(i));
 312   }
 313   for (uint i = 0; i < other->_constructors.size(); i++) {
 314     result->add_constructor(other->_constructors.at(i));
 315   }
 316   result->_multiple = true;
 317   return result;
 318 }
 319 
 320 
 321 void StringConcat::eliminate_call(CallNode* call) {
 322   Compile* C = _stringopts->C;
 323   CallProjections projs;
 324   call->extract_projections(&projs, false);
 325   if (projs.fallthrough_catchproj != NULL) {
 326     C->gvn_replace_by(projs.fallthrough_catchproj, call->in(TypeFunc::Control));
 327   }
 328   if (projs.fallthrough_memproj != NULL) {
 329     C->gvn_replace_by(projs.fallthrough_memproj, call->in(TypeFunc::Memory));
 330   }
 331   if (projs.catchall_memproj != NULL) {
 332     C->gvn_replace_by(projs.catchall_memproj, C->top());
 333   }
 334   if (projs.fallthrough_ioproj != NULL) {
 335     C->gvn_replace_by(projs.fallthrough_ioproj, call->in(TypeFunc::I_O));
 336   }
 337   if (projs.catchall_ioproj != NULL) {
 338     C->gvn_replace_by(projs.catchall_ioproj, C->top());
 339   }
 340   if (projs.catchall_catchproj != NULL) {
 341     // EA can't cope with the partially collapsed graph this
 342     // creates so put it on the worklist to be collapsed later.
 343     for (SimpleDUIterator i(projs.catchall_catchproj); i.has_next(); i.next()) {
 344       Node *use = i.get();
 345       int opc = use->Opcode();
 346       if (opc == Op_CreateEx || opc == Op_Region) {
 347         _stringopts->record_dead_node(use);
 348       }
 349     }
 350     C->gvn_replace_by(projs.catchall_catchproj, C->top());
 351   }
 352   if (projs.resproj != NULL) {
 353     C->gvn_replace_by(projs.resproj, C->top());
 354   }
 355   C->gvn_replace_by(call, C->top());
 356 }
 357 
 358 void StringConcat::eliminate_initialize(InitializeNode* init) {
 359   Compile* C = _stringopts->C;
 360 
 361   // Eliminate Initialize node.
 362   assert(init->outcnt() <= 2, "only a control and memory projection expected");
 363   assert(init->req() <= InitializeNode::RawStores, "no pending inits");
 364   Node *ctrl_proj = init->proj_out(TypeFunc::Control);
 365   if (ctrl_proj != NULL) {
 366     C->gvn_replace_by(ctrl_proj, init->in(TypeFunc::Control));
 367   }
 368   Node *mem_proj = init->proj_out(TypeFunc::Memory);
 369   if (mem_proj != NULL) {
 370     Node *mem = init->in(TypeFunc::Memory);
 371     C->gvn_replace_by(mem_proj, mem);
 372   }
 373   C->gvn_replace_by(init, C->top());
 374   init->disconnect_inputs(NULL, C);
 375 }
 376 
 377 Node_List PhaseStringOpts::collect_toString_calls() {
 378   Node_List string_calls;
 379   Node_List worklist;
 380 
 381   _visited.Clear();
 382 
 383   // Prime the worklist
 384   for (uint i = 1; i < C->root()->len(); i++) {
 385     Node* n = C->root()->in(i);
 386     if (n != NULL && !_visited.test_set(n->_idx)) {
 387       worklist.push(n);
 388     }
 389   }
 390 
 391   while (worklist.size() > 0) {
 392     Node* ctrl = worklist.pop();
 393     if (StringConcat::is_SB_toString(ctrl)) {
 394       CallStaticJavaNode* csj = ctrl->as_CallStaticJava();
 395       string_calls.push(csj);
 396     }
 397     if (ctrl->in(0) != NULL && !_visited.test_set(ctrl->in(0)->_idx)) {
 398       worklist.push(ctrl->in(0));
 399     }
 400     if (ctrl->is_Region()) {
 401       for (uint i = 1; i < ctrl->len(); i++) {
 402         if (ctrl->in(i) != NULL && !_visited.test_set(ctrl->in(i)->_idx)) {
 403           worklist.push(ctrl->in(i));
 404         }
 405       }
 406     }
 407   }
 408   return string_calls;
 409 }
 410 
 411 
 412 StringConcat* PhaseStringOpts::build_candidate(CallStaticJavaNode* call) {
 413   ciMethod* m = call->method();
 414   ciSymbol* string_sig;
 415   ciSymbol* int_sig;
 416   ciSymbol* char_sig;
 417   if (m->holder() == C->env()->StringBuilder_klass()) {
 418     string_sig = ciSymbol::String_StringBuilder_signature();
 419     int_sig = ciSymbol::int_StringBuilder_signature();
 420     char_sig = ciSymbol::char_StringBuilder_signature();
 421   } else if (m->holder() == C->env()->StringBuffer_klass()) {
 422     string_sig = ciSymbol::String_StringBuffer_signature();
 423     int_sig = ciSymbol::int_StringBuffer_signature();
 424     char_sig = ciSymbol::char_StringBuffer_signature();
 425   } else {
 426     return NULL;
 427   }
 428 #ifndef PRODUCT
 429   if (PrintOptimizeStringConcat) {
 430     tty->print("considering toString call in ");
 431     call->jvms()->dump_spec(tty); tty->cr();
 432   }
 433 #endif
 434 
 435   StringConcat* sc = new StringConcat(this, call);
 436 
 437   AllocateNode* alloc = NULL;
 438   InitializeNode* init = NULL;
 439 
 440   // possible opportunity for StringBuilder fusion
 441   CallStaticJavaNode* cnode = call;
 442   while (cnode) {
 443     Node* recv = cnode->in(TypeFunc::Parms)->uncast();
 444     if (recv->is_Proj()) {
 445       recv = recv->in(0);
 446     }
 447     cnode = recv->isa_CallStaticJava();
 448     if (cnode == NULL) {
 449       alloc = recv->isa_Allocate();
 450       if (alloc == NULL) {
 451         break;
 452       }
 453       // Find the constructor call
 454       Node* result = alloc->result_cast();
 455       if (result == NULL || !result->is_CheckCastPP() || alloc->in(TypeFunc::Memory)->is_top()) {
 456         // strange looking allocation
 457 #ifndef PRODUCT
 458         if (PrintOptimizeStringConcat) {
 459           tty->print("giving up because allocation looks strange ");
 460           alloc->jvms()->dump_spec(tty); tty->cr();
 461         }
 462 #endif
 463         break;
 464       }
 465       Node* constructor = NULL;
 466       for (SimpleDUIterator i(result); i.has_next(); i.next()) {
 467         CallStaticJavaNode *use = i.get()->isa_CallStaticJava();
 468         if (use != NULL &&
 469             use->method() != NULL &&
 470             !use->method()->is_static() &&
 471             use->method()->name() == ciSymbol::object_initializer_name() &&
 472             use->method()->holder() == m->holder()) {
 473           // Matched the constructor.
 474           ciSymbol* sig = use->method()->signature()->as_symbol();
 475           if (sig == ciSymbol::void_method_signature() ||
 476               sig == ciSymbol::int_void_signature() ||
 477               sig == ciSymbol::string_void_signature()) {
 478             if (sig == ciSymbol::string_void_signature()) {
 479               // StringBuilder(String) so pick this up as the first argument
 480               assert(use->in(TypeFunc::Parms + 1) != NULL, "what?");
 481               const Type* type = _gvn->type(use->in(TypeFunc::Parms + 1));
 482               if (type == TypePtr::NULL_PTR) {
 483                 // StringBuilder(null) throws exception.
 484 #ifndef PRODUCT
 485                 if (PrintOptimizeStringConcat) {
 486                   tty->print("giving up because StringBuilder(null) throws exception");
 487                   alloc->jvms()->dump_spec(tty); tty->cr();
 488                 }
 489 #endif
 490                 return NULL;
 491               }
 492               // StringBuilder(str) argument needs null check.
 493               sc->push_string_null_check(use->in(TypeFunc::Parms + 1));
 494             }
 495             // The int variant takes an initial size for the backing
 496             // array so just treat it like the void version.
 497             constructor = use;
 498           } else {
 499 #ifndef PRODUCT
 500             if (PrintOptimizeStringConcat) {
 501               tty->print("unexpected constructor signature: %s", sig->as_utf8());
 502             }
 503 #endif
 504           }
 505           break;
 506         }
 507       }
 508       if (constructor == NULL) {
 509         // couldn't find constructor
 510 #ifndef PRODUCT
 511         if (PrintOptimizeStringConcat) {
 512           tty->print("giving up because couldn't find constructor ");
 513           alloc->jvms()->dump_spec(tty); tty->cr();
 514         }
 515 #endif
 516         break;
 517       }
 518 
 519       // Walked all the way back and found the constructor call so see
 520       // if this call converted into a direct string concatenation.
 521       sc->add_control(call);
 522       sc->add_control(constructor);
 523       sc->add_control(alloc);
 524       sc->set_allocation(alloc);
 525       sc->add_constructor(constructor);
 526       if (sc->validate_control_flow() && sc->validate_mem_flow()) {
 527         return sc;
 528       } else {
 529         return NULL;
 530       }
 531     } else if (cnode->method() == NULL) {
 532       break;
 533     } else if (!cnode->method()->is_static() &&
 534                cnode->method()->holder() == m->holder() &&
 535                cnode->method()->name() == ciSymbol::append_name() &&
 536                (cnode->method()->signature()->as_symbol() == string_sig ||
 537                 cnode->method()->signature()->as_symbol() == char_sig ||
 538                 cnode->method()->signature()->as_symbol() == int_sig)) {
 539       sc->add_control(cnode);
 540       Node* arg = cnode->in(TypeFunc::Parms + 1);
 541       if (cnode->method()->signature()->as_symbol() == int_sig) {
 542         sc->push_int(arg);
 543       } else if (cnode->method()->signature()->as_symbol() == char_sig) {
 544         sc->push_char(arg);
 545       } else {
 546         if (arg->is_Proj() && arg->in(0)->is_CallStaticJava()) {
 547           CallStaticJavaNode* csj = arg->in(0)->as_CallStaticJava();
 548           if (csj->method() != NULL &&
 549               csj->method()->intrinsic_id() == vmIntrinsics::_Integer_toString &&
 550               arg->outcnt() == 1) {
 551             // _control is the list of StringBuilder calls nodes which
 552             // will be replaced by new String code after this optimization.
 553             // Integer::toString() call is not part of StringBuilder calls
 554             // chain. It could be eliminated only if its result is used
 555             // only by this SB calls chain.
 556             // Another limitation: it should be used only once because
 557             // it is unknown that it is used only by this SB calls chain
 558             // until all related SB calls nodes are collected.
 559             assert(arg->unique_out() == cnode, "sanity");
 560             sc->add_control(csj);
 561             sc->push_int(csj->in(TypeFunc::Parms));
 562             continue;
 563           }
 564         }
 565         sc->push_string(arg);
 566       }
 567       continue;
 568     } else {
 569       // some unhandled signature
 570 #ifndef PRODUCT
 571       if (PrintOptimizeStringConcat) {
 572         tty->print("giving up because encountered unexpected signature ");
 573         cnode->tf()->dump(); tty->cr();
 574         cnode->in(TypeFunc::Parms + 1)->dump();
 575       }
 576 #endif
 577       break;
 578     }
 579   }
 580   return NULL;
 581 }
 582 
 583 
 584 PhaseStringOpts::PhaseStringOpts(PhaseGVN* gvn, Unique_Node_List*):
 585   Phase(StringOpts),
 586   _gvn(gvn),
 587   _visited(Thread::current()->resource_area()) {
 588 
 589   assert(OptimizeStringConcat, "shouldn't be here");
 590 
 591   size_table_field = C->env()->Integer_klass()->get_field_by_name(ciSymbol::make("sizeTable"),
 592                                                                   ciSymbol::make("[I"), true);
 593   if (size_table_field == NULL) {
 594     // Something wrong so give up.
 595     assert(false, "why can't we find Integer.sizeTable?");
 596     return;
 597   }
 598 
 599   // Collect the types needed to talk about the various slices of memory
 600   char_adr_idx = C->get_alias_index(TypeAryPtr::CHARS);
 601 
 602   // For each locally allocated StringBuffer see if the usages can be
 603   // collapsed into a single String construction.
 604 
 605   // Run through the list of allocation looking for SB.toString to see
 606   // if it's possible to fuse the usage of the SB into a single String
 607   // construction.
 608   GrowableArray<StringConcat*> concats;
 609   Node_List toStrings = collect_toString_calls();
 610   while (toStrings.size() > 0) {
 611     StringConcat* sc = build_candidate(toStrings.pop()->as_CallStaticJava());
 612     if (sc != NULL) {
 613       concats.push(sc);
 614     }
 615   }
 616 
 617   // try to coalesce separate concats
 618  restart:
 619   for (int c = 0; c < concats.length(); c++) {
 620     StringConcat* sc = concats.at(c);
 621     for (int i = 0; i < sc->num_arguments(); i++) {
 622       Node* arg = sc->argument_uncast(i);
 623       if (arg->is_Proj() && StringConcat::is_SB_toString(arg->in(0))) {
 624         CallStaticJavaNode* csj = arg->in(0)->as_CallStaticJava();
 625         for (int o = 0; o < concats.length(); o++) {
 626           if (c == o) continue;
 627           StringConcat* other = concats.at(o);
 628           if (other->end() == csj) {
 629 #ifndef PRODUCT
 630             if (PrintOptimizeStringConcat) {
 631               tty->print_cr("considering stacked concats");
 632             }
 633 #endif
 634 
 635             StringConcat* merged = sc->merge(other, arg);
 636             if (merged->validate_control_flow() && merged->validate_mem_flow()) {
 637 #ifndef PRODUCT
 638               if (PrintOptimizeStringConcat) {
 639                 tty->print_cr("stacking would succeed");
 640               }
 641 #endif
 642               if (c < o) {
 643                 concats.remove_at(o);
 644                 concats.at_put(c, merged);
 645               } else {
 646                 concats.remove_at(c);
 647                 concats.at_put(o, merged);
 648               }
 649               goto restart;
 650             } else {
 651 #ifndef PRODUCT
 652               if (PrintOptimizeStringConcat) {
 653                 tty->print_cr("stacking would fail");
 654               }
 655 #endif
 656             }
 657           }
 658         }
 659       }
 660     }
 661   }
 662 
 663 
 664   for (int c = 0; c < concats.length(); c++) {
 665     StringConcat* sc = concats.at(c);
 666     replace_string_concat(sc);
 667   }
 668 
 669   remove_dead_nodes();
 670 }
 671 
 672 void PhaseStringOpts::record_dead_node(Node* dead) {
 673   dead_worklist.push(dead);
 674 }
 675 
 676 void PhaseStringOpts::remove_dead_nodes() {
 677   // Delete any dead nodes to make things clean enough that escape
 678   // analysis doesn't get unhappy.
 679   while (dead_worklist.size() > 0) {
 680     Node* use = dead_worklist.pop();
 681     int opc = use->Opcode();
 682     switch (opc) {
 683       case Op_Region: {
 684         uint i = 1;
 685         for (i = 1; i < use->req(); i++) {
 686           if (use->in(i) != C->top()) {
 687             break;
 688           }
 689         }
 690         if (i >= use->req()) {
 691           for (SimpleDUIterator i(use); i.has_next(); i.next()) {
 692             Node* m = i.get();
 693             if (m->is_Phi()) {
 694               dead_worklist.push(m);
 695             }
 696           }
 697           C->gvn_replace_by(use, C->top());
 698         }
 699         break;
 700       }
 701       case Op_AddP:
 702       case Op_CreateEx: {
 703         // Recurisvely clean up references to CreateEx so EA doesn't
 704         // get unhappy about the partially collapsed graph.
 705         for (SimpleDUIterator i(use); i.has_next(); i.next()) {
 706           Node* m = i.get();
 707           if (m->is_AddP()) {
 708             dead_worklist.push(m);
 709           }
 710         }
 711         C->gvn_replace_by(use, C->top());
 712         break;
 713       }
 714       case Op_Phi:
 715         if (use->in(0) == C->top()) {
 716           C->gvn_replace_by(use, C->top());
 717         }
 718         break;
 719     }
 720   }
 721 }
 722 
 723 
 724 bool StringConcat::validate_mem_flow() {
 725   Compile* C = _stringopts->C;
 726 
 727   for (uint i = 0; i < _control.size(); i++) {
 728 #ifndef PRODUCT
 729     Node_List path;
 730 #endif
 731     Node* curr = _control.at(i);
 732     if (curr->is_Call() && curr != _begin) { // For all calls except the first allocation
 733       // Now here's the main invariant in our case:
 734       // For memory between the constructor, and appends, and toString we should only see bottom memory,
 735       // produced by the previous call we know about.
 736       if (!_constructors.contains(curr)) {
 737         NOT_PRODUCT(path.push(curr);)
 738         Node* mem = curr->in(TypeFunc::Memory);
 739         assert(mem != NULL, "calls should have memory edge");
 740         assert(!mem->is_Phi(), "should be handled by control flow validation");
 741         NOT_PRODUCT(path.push(mem);)
 742         if (mem->is_MergeMem()) {
 743           while (mem->is_MergeMem()) {
 744             for (uint i = 1; i < mem->req(); i++) {
 745               if (i != Compile::AliasIdxBot && mem->in(i) != C->top()) {
 746 #ifndef PRODUCT
 747                 tty->print("fusion has incorrect memory flow (side effects) for ");
 748                 _begin->jvms()->dump_spec(tty); tty->cr();
 749                 path.dump();
 750 #endif
 751                 return false;
 752               }
 753             }
 754             // skip through a potential MergeMem chain, linked through Bot
 755             mem = mem->in(Compile::AliasIdxBot);
 756             NOT_PRODUCT(path.push(mem);)
 757           }
 758           // now let it fall though, and see if the have a projection
 759         }
 760         if (mem->is_Proj()) {
 761           // Should point to a previous known call
 762           Node *prev = mem->in(0);
 763           NOT_PRODUCT(path.push(prev);)
 764           if (!prev->is_Call() || !_control.contains(prev)) {
 765 #ifndef PRODUCT
 766             tty->print("fusion has incorrect memory flow (unknown call) for ");
 767             _begin->jvms()->dump_spec(tty); tty->cr();
 768             path.dump();
 769 #endif
 770             return false;
 771           }
 772         } else {
 773           assert(mem->is_Store() || mem->is_LoadStore(), err_msg_res("Unexpected node type: %s", mem->Name()));
 774 #ifndef PRODUCT
 775           tty->print("fusion has incorrect memory flow (unexpected source) for ");
 776           _begin->jvms()->dump_spec(tty); tty->cr();
 777           path.dump();
 778 #endif
 779           return false;
 780         }
 781       } else {
 782         // For memory that feeds into constructors it's more complicated.
 783         // However the advantage is that any side effect that happens between the Allocate/Initialize and
 784         // the constructor will have to be control-dependent on Initialize.
 785         // So we actually don't have to do anything, since it's going to be caught by the control flow
 786         // analysis.
 787       }
 788     }
 789   }
 790 
 791 #ifndef PRODUCT
 792   if (PrintOptimizeStringConcat) {
 793     tty->print("fusion has correct memory flow for ");
 794     _begin->jvms()->dump_spec(tty); tty->cr();
 795     tty->cr();
 796   }
 797 #endif
 798   return true;
 799 }
 800 
 801 bool StringConcat::validate_control_flow() {
 802   // We found all the calls and arguments now lets see if it's
 803   // safe to transform the graph as we would expect.
 804 
 805   // Check to see if this resulted in too many uncommon traps previously
 806   if (Compile::current()->too_many_traps(_begin->jvms()->method(), _begin->jvms()->bci(),
 807                         Deoptimization::Reason_intrinsic)) {
 808     return false;
 809   }
 810 
 811   // Walk backwards over the control flow from toString to the
 812   // allocation and make sure all the control flow is ok.  This
 813   // means it's either going to be eliminated once the calls are
 814   // removed or it can safely be transformed into an uncommon
 815   // trap.
 816 
 817   int null_check_count = 0;
 818   Unique_Node_List ctrl_path;
 819 
 820   assert(_control.contains(_begin), "missing");
 821   assert(_control.contains(_end), "missing");
 822 
 823   // Collect the nodes that we know about and will eliminate into ctrl_path
 824   for (uint i = 0; i < _control.size(); i++) {
 825     // Push the call and it's control projection
 826     Node* n = _control.at(i);
 827     if (n->is_Allocate()) {
 828       AllocateNode* an = n->as_Allocate();
 829       InitializeNode* init = an->initialization();
 830       ctrl_path.push(init);
 831       ctrl_path.push(init->as_Multi()->proj_out(0));
 832     }
 833     if (n->is_Call()) {
 834       CallNode* cn = n->as_Call();
 835       ctrl_path.push(cn);
 836       ctrl_path.push(cn->proj_out(0));
 837       ctrl_path.push(cn->proj_out(0)->unique_out());
 838       if (cn->proj_out(0)->unique_out()->as_Catch()->proj_out(0) != NULL) {
 839         ctrl_path.push(cn->proj_out(0)->unique_out()->as_Catch()->proj_out(0));
 840       }
 841     } else {
 842       ShouldNotReachHere();
 843     }
 844   }
 845 
 846   // Skip backwards through the control checking for unexpected control flow
 847   Node* ptr = _end;
 848   bool fail = false;
 849   while (ptr != _begin) {
 850     if (ptr->is_Call() && ctrl_path.member(ptr)) {
 851       ptr = ptr->in(0);
 852     } else if (ptr->is_CatchProj() && ctrl_path.member(ptr)) {
 853       ptr = ptr->in(0)->in(0)->in(0);
 854       assert(ctrl_path.member(ptr), "should be a known piece of control");
 855     } else if (ptr->is_IfTrue()) {
 856       IfNode* iff = ptr->in(0)->as_If();
 857       BoolNode* b = iff->in(1)->isa_Bool();
 858 
 859       if (b == NULL) {
 860         fail = true;
 861         break;
 862       }
 863 
 864       Node* cmp = b->in(1);
 865       Node* v1 = cmp->in(1);
 866       Node* v2 = cmp->in(2);
 867       Node* otherproj = iff->proj_out(1 - ptr->as_Proj()->_con);
 868 
 869       // Null check of the return of append which can simply be eliminated
 870       if (b->_test._test == BoolTest::ne &&
 871           v2->bottom_type() == TypePtr::NULL_PTR &&
 872           v1->is_Proj() && ctrl_path.member(v1->in(0))) {
 873         // NULL check of the return value of the append
 874         null_check_count++;
 875         if (otherproj->outcnt() == 1) {
 876           CallStaticJavaNode* call = otherproj->unique_out()->isa_CallStaticJava();
 877           if (call != NULL && call->_name != NULL && strcmp(call->_name, "uncommon_trap") == 0) {
 878             ctrl_path.push(call);
 879           }
 880         }
 881         _control.push(ptr);
 882         ptr = ptr->in(0)->in(0);
 883         continue;
 884       }
 885 
 886       // A test which leads to an uncommon trap which should be safe.
 887       // Later this trap will be converted into a trap that restarts
 888       // at the beginning.
 889       if (otherproj->outcnt() == 1) {
 890         CallStaticJavaNode* call = otherproj->unique_out()->isa_CallStaticJava();
 891         if (call != NULL && call->_name != NULL && strcmp(call->_name, "uncommon_trap") == 0) {
 892           // control flow leads to uct so should be ok
 893           _uncommon_traps.push(call);
 894           ctrl_path.push(call);
 895           ptr = ptr->in(0)->in(0);
 896           continue;
 897         }
 898       }
 899 
 900 #ifndef PRODUCT
 901       // Some unexpected control flow we don't know how to handle.
 902       if (PrintOptimizeStringConcat) {
 903         tty->print_cr("failing with unknown test");
 904         b->dump();
 905         cmp->dump();
 906         v1->dump();
 907         v2->dump();
 908         tty->cr();
 909       }
 910 #endif
 911       fail = true;
 912       break;
 913     } else if (ptr->is_Proj() && ptr->in(0)->is_Initialize()) {
 914       ptr = ptr->in(0)->in(0);
 915     } else if (ptr->is_Region()) {
 916       Node* copy = ptr->as_Region()->is_copy();
 917       if (copy != NULL) {
 918         ptr = copy;
 919         continue;
 920       }
 921       if (ptr->req() == 3 &&
 922           ptr->in(1) != NULL && ptr->in(1)->is_Proj() &&
 923           ptr->in(2) != NULL && ptr->in(2)->is_Proj() &&
 924           ptr->in(1)->in(0) == ptr->in(2)->in(0) &&
 925           ptr->in(1)->in(0) != NULL && ptr->in(1)->in(0)->is_If()) {
 926         // Simple diamond.
 927         // XXX should check for possibly merging stores.  simple data merges are ok.
 928         // The IGVN will make this simple diamond go away when it
 929         // transforms the Region. Make sure it sees it.
 930         Compile::current()->record_for_igvn(ptr);
 931         ptr = ptr->in(1)->in(0)->in(0);
 932         continue;
 933       }
 934 #ifndef PRODUCT
 935       if (PrintOptimizeStringConcat) {
 936         tty->print_cr("fusion would fail for region");
 937         _begin->dump();
 938         ptr->dump(2);
 939       }
 940 #endif
 941       fail = true;
 942       break;
 943     } else {
 944       // other unknown control
 945       if (!fail) {
 946 #ifndef PRODUCT
 947         if (PrintOptimizeStringConcat) {
 948           tty->print_cr("fusion would fail for");
 949           _begin->dump();
 950         }
 951 #endif
 952         fail = true;
 953       }
 954 #ifndef PRODUCT
 955       if (PrintOptimizeStringConcat) {
 956         ptr->dump();
 957       }
 958 #endif
 959       ptr = ptr->in(0);
 960     }
 961   }
 962 #ifndef PRODUCT
 963   if (PrintOptimizeStringConcat && fail) {
 964     tty->cr();
 965   }
 966 #endif
 967   if (fail) return !fail;
 968 
 969   // Validate that all these results produced are contained within
 970   // this cluster of objects.  First collect all the results produced
 971   // by calls in the region.
 972   _stringopts->_visited.Clear();
 973   Node_List worklist;
 974   Node* final_result = _end->proj_out(TypeFunc::Parms);
 975   for (uint i = 0; i < _control.size(); i++) {
 976     CallNode* cnode = _control.at(i)->isa_Call();
 977     if (cnode != NULL) {
 978       _stringopts->_visited.test_set(cnode->_idx);
 979     }
 980     Node* result = cnode != NULL ? cnode->proj_out(TypeFunc::Parms) : NULL;
 981     if (result != NULL && result != final_result) {
 982       worklist.push(result);
 983     }
 984   }
 985 
 986   Node* last_result = NULL;
 987   while (worklist.size() > 0) {
 988     Node* result = worklist.pop();
 989     if (_stringopts->_visited.test_set(result->_idx))
 990       continue;
 991     for (SimpleDUIterator i(result); i.has_next(); i.next()) {
 992       Node *use = i.get();
 993       if (ctrl_path.member(use)) {
 994         // already checked this
 995         continue;
 996       }
 997       int opc = use->Opcode();
 998       if (opc == Op_CmpP || opc == Op_Node) {
 999         ctrl_path.push(use);
1000         continue;
1001       }
1002       if (opc == Op_CastPP || opc == Op_CheckCastPP) {
1003         for (SimpleDUIterator j(use); j.has_next(); j.next()) {
1004           worklist.push(j.get());
1005         }
1006         worklist.push(use->in(1));
1007         ctrl_path.push(use);
1008         continue;
1009       }
1010 #ifndef PRODUCT
1011       if (PrintOptimizeStringConcat) {
1012         if (result != last_result) {
1013           last_result = result;
1014           tty->print_cr("extra uses for result:");
1015           last_result->dump();
1016         }
1017         use->dump();
1018       }
1019 #endif
1020       fail = true;
1021       break;
1022     }
1023   }
1024 
1025 #ifndef PRODUCT
1026   if (PrintOptimizeStringConcat && !fail) {
1027     ttyLocker ttyl;
1028     tty->cr();
1029     tty->print("fusion has correct control flow (%d %d) for ", null_check_count, _uncommon_traps.size());
1030     _begin->jvms()->dump_spec(tty); tty->cr();
1031     for (int i = 0; i < num_arguments(); i++) {
1032       argument(i)->dump();
1033     }
1034     _control.dump();
1035     tty->cr();
1036   }
1037 #endif
1038 
1039   return !fail;
1040 }
1041 
1042 Node* PhaseStringOpts::fetch_static_field(GraphKit& kit, ciField* field) {
1043   const TypeInstPtr* mirror_type = TypeInstPtr::make(field->holder()->java_mirror());
1044   Node* klass_node = __ makecon(mirror_type);
1045   BasicType bt = field->layout_type();
1046   ciType* field_klass = field->type();
1047 
1048   const Type *type;
1049   if( bt == T_OBJECT ) {
1050     if (!field->type()->is_loaded()) {
1051       type = TypeInstPtr::BOTTOM;
1052     } else if (field->is_constant()) {
1053       // This can happen if the constant oop is non-perm.
1054       ciObject* con = field->constant_value().as_object();
1055       // Do not "join" in the previous type; it doesn't add value,
1056       // and may yield a vacuous result if the field is of interface type.
1057       type = TypeOopPtr::make_from_constant(con, true)->isa_oopptr();
1058       assert(type != NULL, "field singleton type must be consistent");
1059       return __ makecon(type);
1060     } else {
1061       type = TypeOopPtr::make_from_klass(field_klass->as_klass());
1062     }
1063   } else {
1064     type = Type::get_const_basic_type(bt);
1065   }
1066 
1067   return kit.make_load(NULL, kit.basic_plus_adr(klass_node, field->offset_in_bytes()),
1068                        type, T_OBJECT,
1069                        C->get_alias_index(mirror_type->add_offset(field->offset_in_bytes())));
1070 }
1071 
1072 Node* PhaseStringOpts::int_stringSize(GraphKit& kit, Node* arg) {
1073   RegionNode *final_merge = new (C) RegionNode(3);
1074   kit.gvn().set_type(final_merge, Type::CONTROL);
1075   Node* final_size = new (C) PhiNode(final_merge, TypeInt::INT);
1076   kit.gvn().set_type(final_size, TypeInt::INT);
1077 
1078   IfNode* iff = kit.create_and_map_if(kit.control(),
1079                                       __ Bool(__ CmpI(arg, __ intcon(0x80000000)), BoolTest::ne),
1080                                       PROB_FAIR, COUNT_UNKNOWN);
1081   Node* is_min = __ IfFalse(iff);
1082   final_merge->init_req(1, is_min);
1083   final_size->init_req(1, __ intcon(11));
1084 
1085   kit.set_control(__ IfTrue(iff));
1086   if (kit.stopped()) {
1087     final_merge->init_req(2, C->top());
1088     final_size->init_req(2, C->top());
1089   } else {
1090 
1091     // int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
1092     RegionNode *r = new (C) RegionNode(3);
1093     kit.gvn().set_type(r, Type::CONTROL);
1094     Node *phi = new (C) PhiNode(r, TypeInt::INT);
1095     kit.gvn().set_type(phi, TypeInt::INT);
1096     Node *size = new (C) PhiNode(r, TypeInt::INT);
1097     kit.gvn().set_type(size, TypeInt::INT);
1098     Node* chk = __ CmpI(arg, __ intcon(0));
1099     Node* p = __ Bool(chk, BoolTest::lt);
1100     IfNode* iff = kit.create_and_map_if(kit.control(), p, PROB_FAIR, COUNT_UNKNOWN);
1101     Node* lessthan = __ IfTrue(iff);
1102     Node* greaterequal = __ IfFalse(iff);
1103     r->init_req(1, lessthan);
1104     phi->init_req(1, __ SubI(__ intcon(0), arg));
1105     size->init_req(1, __ intcon(1));
1106     r->init_req(2, greaterequal);
1107     phi->init_req(2, arg);
1108     size->init_req(2, __ intcon(0));
1109     kit.set_control(r);
1110     C->record_for_igvn(r);
1111     C->record_for_igvn(phi);
1112     C->record_for_igvn(size);
1113 
1114     // for (int i=0; ; i++)
1115     //   if (x <= sizeTable[i])
1116     //     return i+1;
1117 
1118     // Add loop predicate first.
1119     kit.add_predicate();
1120 
1121     RegionNode *loop = new (C) RegionNode(3);
1122     loop->init_req(1, kit.control());
1123     kit.gvn().set_type(loop, Type::CONTROL);
1124 
1125     Node *index = new (C) PhiNode(loop, TypeInt::INT);
1126     index->init_req(1, __ intcon(0));
1127     kit.gvn().set_type(index, TypeInt::INT);
1128     kit.set_control(loop);
1129     Node* sizeTable = fetch_static_field(kit, size_table_field);
1130 
1131     Node* value = kit.load_array_element(NULL, sizeTable, index, TypeAryPtr::INTS);
1132     C->record_for_igvn(value);
1133     Node* limit = __ CmpI(phi, value);
1134     Node* limitb = __ Bool(limit, BoolTest::le);
1135     IfNode* iff2 = kit.create_and_map_if(kit.control(), limitb, PROB_MIN, COUNT_UNKNOWN);
1136     Node* lessEqual = __ IfTrue(iff2);
1137     Node* greater = __ IfFalse(iff2);
1138 
1139     loop->init_req(2, greater);
1140     index->init_req(2, __ AddI(index, __ intcon(1)));
1141 
1142     kit.set_control(lessEqual);
1143     C->record_for_igvn(loop);
1144     C->record_for_igvn(index);
1145 
1146     final_merge->init_req(2, kit.control());
1147     final_size->init_req(2, __ AddI(__ AddI(index, size), __ intcon(1)));
1148   }
1149 
1150   kit.set_control(final_merge);
1151   C->record_for_igvn(final_merge);
1152   C->record_for_igvn(final_size);
1153 
1154   return final_size;
1155 }
1156 
1157 void PhaseStringOpts::int_getChars(GraphKit& kit, Node* arg, Node* char_array, Node* start, Node* end) {
1158   RegionNode *final_merge = new (C) RegionNode(4);
1159   kit.gvn().set_type(final_merge, Type::CONTROL);
1160   Node *final_mem = PhiNode::make(final_merge, kit.memory(char_adr_idx), Type::MEMORY, TypeAryPtr::CHARS);
1161   kit.gvn().set_type(final_mem, Type::MEMORY);
1162 
1163   // need to handle Integer.MIN_VALUE specially because negating doesn't make it positive
1164   {
1165     // i == MIN_VALUE
1166     IfNode* iff = kit.create_and_map_if(kit.control(),
1167                                         __ Bool(__ CmpI(arg, __ intcon(0x80000000)), BoolTest::ne),
1168                                         PROB_FAIR, COUNT_UNKNOWN);
1169 
1170     Node* old_mem = kit.memory(char_adr_idx);
1171 
1172     kit.set_control(__ IfFalse(iff));
1173     if (kit.stopped()) {
1174       // Statically not equal to MIN_VALUE so this path is dead
1175       final_merge->init_req(3, kit.control());
1176     } else {
1177       copy_string(kit, __ makecon(TypeInstPtr::make(C->env()->the_min_jint_string())),
1178                   char_array, start);
1179       final_merge->init_req(3, kit.control());
1180       final_mem->init_req(3, kit.memory(char_adr_idx));
1181     }
1182 
1183     kit.set_control(__ IfTrue(iff));
1184     kit.set_memory(old_mem, char_adr_idx);
1185   }
1186 
1187 
1188   // Simplified version of Integer.getChars
1189 
1190   // int q, r;
1191   // int charPos = index;
1192   Node* charPos = end;
1193 
1194   // char sign = 0;
1195 
1196   Node* i = arg;
1197   Node* sign = __ intcon(0);
1198 
1199   // if (i < 0) {
1200   //     sign = '-';
1201   //     i = -i;
1202   // }
1203   {
1204     IfNode* iff = kit.create_and_map_if(kit.control(),
1205                                         __ Bool(__ CmpI(arg, __ intcon(0)), BoolTest::lt),
1206                                         PROB_FAIR, COUNT_UNKNOWN);
1207 
1208     RegionNode *merge = new (C) RegionNode(3);
1209     kit.gvn().set_type(merge, Type::CONTROL);
1210     i = new (C) PhiNode(merge, TypeInt::INT);
1211     kit.gvn().set_type(i, TypeInt::INT);
1212     sign = new (C) PhiNode(merge, TypeInt::INT);
1213     kit.gvn().set_type(sign, TypeInt::INT);
1214 
1215     merge->init_req(1, __ IfTrue(iff));
1216     i->init_req(1, __ SubI(__ intcon(0), arg));
1217     sign->init_req(1, __ intcon('-'));
1218     merge->init_req(2, __ IfFalse(iff));
1219     i->init_req(2, arg);
1220     sign->init_req(2, __ intcon(0));
1221 
1222     kit.set_control(merge);
1223 
1224     C->record_for_igvn(merge);
1225     C->record_for_igvn(i);
1226     C->record_for_igvn(sign);
1227   }
1228 
1229   // for (;;) {
1230   //     q = i / 10;
1231   //     r = i - ((q << 3) + (q << 1));  // r = i-(q*10) ...
1232   //     buf [--charPos] = digits [r];
1233   //     i = q;
1234   //     if (i == 0) break;
1235   // }
1236 
1237   {
1238     // Add loop predicate first.
1239     kit.add_predicate();
1240 
1241     RegionNode *head = new (C) RegionNode(3);
1242     head->init_req(1, kit.control());
1243     kit.gvn().set_type(head, Type::CONTROL);
1244     Node *i_phi = new (C) PhiNode(head, TypeInt::INT);
1245     i_phi->init_req(1, i);
1246     kit.gvn().set_type(i_phi, TypeInt::INT);
1247     charPos = PhiNode::make(head, charPos);
1248     kit.gvn().set_type(charPos, TypeInt::INT);
1249     Node *mem = PhiNode::make(head, kit.memory(char_adr_idx), Type::MEMORY, TypeAryPtr::CHARS);
1250     kit.gvn().set_type(mem, Type::MEMORY);
1251     kit.set_control(head);
1252     kit.set_memory(mem, char_adr_idx);
1253 
1254     Node* q = __ DivI(NULL, i_phi, __ intcon(10));
1255     Node* r = __ SubI(i_phi, __ AddI(__ LShiftI(q, __ intcon(3)),
1256                                      __ LShiftI(q, __ intcon(1))));
1257     Node* m1 = __ SubI(charPos, __ intcon(1));
1258     Node* ch = __ AddI(r, __ intcon('0'));
1259 
1260     Node* st = __ store_to_memory(kit.control(), kit.array_element_address(char_array, m1, T_CHAR),
1261                                   ch, T_CHAR, char_adr_idx);
1262 
1263 
1264     IfNode* iff = kit.create_and_map_if(head, __ Bool(__ CmpI(q, __ intcon(0)), BoolTest::ne),
1265                                         PROB_FAIR, COUNT_UNKNOWN);
1266     Node* ne = __ IfTrue(iff);
1267     Node* eq = __ IfFalse(iff);
1268 
1269     head->init_req(2, ne);
1270     mem->init_req(2, st);
1271     i_phi->init_req(2, q);
1272     charPos->init_req(2, m1);
1273 
1274     charPos = m1;
1275 
1276     kit.set_control(eq);
1277     kit.set_memory(st, char_adr_idx);
1278 
1279     C->record_for_igvn(head);
1280     C->record_for_igvn(mem);
1281     C->record_for_igvn(i_phi);
1282     C->record_for_igvn(charPos);
1283   }
1284 
1285   {
1286     // if (sign != 0) {
1287     //     buf [--charPos] = sign;
1288     // }
1289     IfNode* iff = kit.create_and_map_if(kit.control(),
1290                                         __ Bool(__ CmpI(sign, __ intcon(0)), BoolTest::ne),
1291                                         PROB_FAIR, COUNT_UNKNOWN);
1292 
1293     final_merge->init_req(2, __ IfFalse(iff));
1294     final_mem->init_req(2, kit.memory(char_adr_idx));
1295 
1296     kit.set_control(__ IfTrue(iff));
1297     if (kit.stopped()) {
1298       final_merge->init_req(1, C->top());
1299       final_mem->init_req(1, C->top());
1300     } else {
1301       Node* m1 = __ SubI(charPos, __ intcon(1));
1302       Node* st = __ store_to_memory(kit.control(), kit.array_element_address(char_array, m1, T_CHAR),
1303                                     sign, T_CHAR, char_adr_idx);
1304 
1305       final_merge->init_req(1, kit.control());
1306       final_mem->init_req(1, st);
1307     }
1308 
1309     kit.set_control(final_merge);
1310     kit.set_memory(final_mem, char_adr_idx);
1311 
1312     C->record_for_igvn(final_merge);
1313     C->record_for_igvn(final_mem);
1314   }
1315 }
1316 
1317 
1318 Node* PhaseStringOpts::copy_string(GraphKit& kit, Node* str, Node* char_array, Node* start) {
1319   Node* string = str;
1320   Node* offset = kit.load_String_offset(kit.control(), string);
1321   Node* count  = kit.load_String_length(kit.control(), string);
1322   Node* value  = kit.load_String_value (kit.control(), string);
1323 
1324   // copy the contents
1325   if (offset->is_Con() && count->is_Con() && value->is_Con() && count->get_int() < unroll_string_copy_length) {
1326     // For small constant strings just emit individual stores.
1327     // A length of 6 seems like a good space/speed tradeof.
1328     int c = count->get_int();
1329     int o = offset->get_int();
1330     const TypeOopPtr* t = kit.gvn().type(value)->isa_oopptr();
1331     ciTypeArray* value_array = t->const_oop()->as_type_array();
1332     for (int e = 0; e < c; e++) {
1333       __ store_to_memory(kit.control(), kit.array_element_address(char_array, start, T_CHAR),
1334                          __ intcon(value_array->char_at(o + e)), T_CHAR, char_adr_idx);
1335       start = __ AddI(start, __ intcon(1));
1336     }
1337   } else {
1338     Node* src_ptr = kit.array_element_address(value, offset, T_CHAR);
1339     Node* dst_ptr = kit.array_element_address(char_array, start, T_CHAR);
1340     Node* c = count;
1341     Node* extra = NULL;
1342 #ifdef _LP64
1343     c = __ ConvI2L(c);
1344     extra = C->top();
1345 #endif
1346     Node* call = kit.make_runtime_call(GraphKit::RC_LEAF|GraphKit::RC_NO_FP,
1347                                        OptoRuntime::fast_arraycopy_Type(),
1348                                        CAST_FROM_FN_PTR(address, StubRoutines::jshort_disjoint_arraycopy()),
1349                                        "jshort_disjoint_arraycopy", TypeAryPtr::CHARS,
1350                                        src_ptr, dst_ptr, c, extra);
1351     start = __ AddI(start, count);
1352   }
1353   return start;
1354 }
1355 
1356 
1357 void PhaseStringOpts::replace_string_concat(StringConcat* sc) {
1358   // Log a little info about the transformation
1359   sc->maybe_log_transform();
1360 
1361   // pull the JVMState of the allocation into a SafePointNode to serve as
1362   // as a shim for the insertion of the new code.
1363   JVMState* jvms     = sc->begin()->jvms()->clone_shallow(C);
1364   uint size = sc->begin()->req();
1365   SafePointNode* map = new (C) SafePointNode(size, jvms);
1366 
1367   // copy the control and memory state from the final call into our
1368   // new starting state.  This allows any preceeding tests to feed
1369   // into the new section of code.
1370   for (uint i1 = 0; i1 < TypeFunc::Parms; i1++) {
1371     map->init_req(i1, sc->end()->in(i1));
1372   }
1373   // blow away old allocation arguments
1374   for (uint i1 = TypeFunc::Parms; i1 < jvms->debug_start(); i1++) {
1375     map->init_req(i1, C->top());
1376   }
1377   // Copy the rest of the inputs for the JVMState
1378   for (uint i1 = jvms->debug_start(); i1 < sc->begin()->req(); i1++) {
1379     map->init_req(i1, sc->begin()->in(i1));
1380   }
1381   // Make sure the memory state is a MergeMem for parsing.
1382   if (!map->in(TypeFunc::Memory)->is_MergeMem()) {
1383     map->set_req(TypeFunc::Memory, MergeMemNode::make(C, map->in(TypeFunc::Memory)));
1384   }
1385 
1386   jvms->set_map(map);
1387   map->ensure_stack(jvms, jvms->method()->max_stack());
1388 
1389 
1390   // disconnect all the old StringBuilder calls from the graph
1391   sc->eliminate_unneeded_control();
1392 
1393   // At this point all the old work has been completely removed from
1394   // the graph and the saved JVMState exists at the point where the
1395   // final toString call used to be.
1396   GraphKit kit(jvms);
1397 
1398   // There may be uncommon traps which are still using the
1399   // intermediate states and these need to be rewritten to point at
1400   // the JVMState at the beginning of the transformation.
1401   sc->convert_uncommon_traps(kit, jvms);
1402 
1403   // Now insert the logic to compute the size of the string followed
1404   // by all the logic to construct array and resulting string.
1405 
1406   Node* null_string = __ makecon(TypeInstPtr::make(C->env()->the_null_string()));
1407 
1408   // Create a region for the overflow checks to merge into.
1409   int args = MAX2(sc->num_arguments(), 1);
1410   RegionNode* overflow = new (C) RegionNode(args);
1411   kit.gvn().set_type(overflow, Type::CONTROL);
1412 
1413   // Create a hook node to hold onto the individual sizes since they
1414   // are need for the copying phase.
1415   Node* string_sizes = new (C) Node(args);
1416 
1417   Node* length = __ intcon(0);
1418   for (int argi = 0; argi < sc->num_arguments(); argi++) {
1419     Node* arg = sc->argument(argi);
1420     switch (sc->mode(argi)) {
1421       case StringConcat::IntMode: {
1422         Node* string_size = int_stringSize(kit, arg);
1423 
1424         // accumulate total
1425         length = __ AddI(length, string_size);
1426 
1427         // Cache this value for the use by int_toString
1428         string_sizes->init_req(argi, string_size);
1429         break;
1430       }
1431       case StringConcat::StringNullCheckMode: {
1432         const Type* type = kit.gvn().type(arg);
1433         assert(type != TypePtr::NULL_PTR, "missing check");
1434         if (!type->higher_equal(TypeInstPtr::NOTNULL)) {
1435           // Null check with uncommont trap since
1436           // StringBuilder(null) throws exception.
1437           // Use special uncommon trap instead of
1438           // calling normal do_null_check().
1439           Node* p = __ Bool(__ CmpP(arg, kit.null()), BoolTest::ne);
1440           IfNode* iff = kit.create_and_map_if(kit.control(), p, PROB_MIN, COUNT_UNKNOWN);
1441           overflow->add_req(__ IfFalse(iff));
1442           Node* notnull = __ IfTrue(iff);
1443           kit.set_control(notnull); // set control for the cast_not_null
1444           arg = kit.cast_not_null(arg, false);
1445           sc->set_argument(argi, arg);
1446         }
1447         assert(kit.gvn().type(arg)->higher_equal(TypeInstPtr::NOTNULL), "sanity");
1448         // Fallthrough to add string length.
1449       }
1450       case StringConcat::StringMode: {
1451         const Type* type = kit.gvn().type(arg);
1452         if (type == TypePtr::NULL_PTR) {
1453           // replace the argument with the null checked version
1454           arg = null_string;
1455           sc->set_argument(argi, arg);
1456         } else if (!type->higher_equal(TypeInstPtr::NOTNULL)) {
1457           // s = s != null ? s : "null";
1458           // length = length + (s.count - s.offset);
1459           RegionNode *r = new (C) RegionNode(3);
1460           kit.gvn().set_type(r, Type::CONTROL);
1461           Node *phi = new (C) PhiNode(r, type);
1462           kit.gvn().set_type(phi, phi->bottom_type());
1463           Node* p = __ Bool(__ CmpP(arg, kit.null()), BoolTest::ne);
1464           IfNode* iff = kit.create_and_map_if(kit.control(), p, PROB_MIN, COUNT_UNKNOWN);
1465           Node* notnull = __ IfTrue(iff);
1466           Node* isnull =  __ IfFalse(iff);
1467           kit.set_control(notnull); // set control for the cast_not_null
1468           r->init_req(1, notnull);
1469           phi->init_req(1, kit.cast_not_null(arg, false));
1470           r->init_req(2, isnull);
1471           phi->init_req(2, null_string);
1472           kit.set_control(r);
1473           C->record_for_igvn(r);
1474           C->record_for_igvn(phi);
1475           // replace the argument with the null checked version
1476           arg = phi;
1477           sc->set_argument(argi, arg);
1478         }
1479 
1480         Node* count = kit.load_String_length(kit.control(), arg);
1481 
1482         length = __ AddI(length, count);
1483         string_sizes->init_req(argi, NULL);
1484         break;
1485       }
1486       case StringConcat::CharMode: {
1487         // one character only
1488         length = __ AddI(length, __ intcon(1));
1489         break;
1490       }
1491       default:
1492         ShouldNotReachHere();
1493     }
1494     if (argi > 0) {
1495       // Check that the sum hasn't overflowed
1496       IfNode* iff = kit.create_and_map_if(kit.control(),
1497                                           __ Bool(__ CmpI(length, __ intcon(0)), BoolTest::lt),
1498                                           PROB_MIN, COUNT_UNKNOWN);
1499       kit.set_control(__ IfFalse(iff));
1500       overflow->set_req(argi, __ IfTrue(iff));
1501     }
1502   }
1503 
1504   {
1505     // Hook
1506     PreserveJVMState pjvms(&kit);
1507     kit.set_control(overflow);
1508     C->record_for_igvn(overflow);
1509     kit.uncommon_trap(Deoptimization::Reason_intrinsic,
1510                       Deoptimization::Action_make_not_entrant);
1511   }
1512 
1513   Node* result;
1514   if (!kit.stopped()) {
1515 
1516     // length now contains the number of characters needed for the
1517     // char[] so create a new AllocateArray for the char[]
1518     Node* char_array = NULL;
1519     {
1520       PreserveReexecuteState preexecs(&kit);
1521       // The original jvms is for an allocation of either a String or
1522       // StringBuffer so no stack adjustment is necessary for proper
1523       // reexecution.  If we deoptimize in the slow path the bytecode
1524       // will be reexecuted and the char[] allocation will be thrown away.
1525       kit.jvms()->set_should_reexecute(true);
1526       char_array = kit.new_array(__ makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_CHAR))),
1527                                  length, 1);
1528     }
1529 
1530     // Mark the allocation so that zeroing is skipped since the code
1531     // below will overwrite the entire array
1532     AllocateArrayNode* char_alloc = AllocateArrayNode::Ideal_array_allocation(char_array, _gvn);
1533     char_alloc->maybe_set_complete(_gvn);
1534 
1535     // Now copy the string representations into the final char[]
1536     Node* start = __ intcon(0);
1537     for (int argi = 0; argi < sc->num_arguments(); argi++) {
1538       Node* arg = sc->argument(argi);
1539       switch (sc->mode(argi)) {
1540         case StringConcat::IntMode: {
1541           Node* end = __ AddI(start, string_sizes->in(argi));
1542           // getChars words backwards so pass the ending point as well as the start
1543           int_getChars(kit, arg, char_array, start, end);
1544           start = end;
1545           break;
1546         }
1547         case StringConcat::StringNullCheckMode:
1548         case StringConcat::StringMode: {
1549           start = copy_string(kit, arg, char_array, start);
1550           break;
1551         }
1552         case StringConcat::CharMode: {
1553           __ store_to_memory(kit.control(), kit.array_element_address(char_array, start, T_CHAR),
1554                              arg, T_CHAR, char_adr_idx);
1555           start = __ AddI(start, __ intcon(1));
1556           break;
1557         }
1558         default:
1559           ShouldNotReachHere();
1560       }
1561     }
1562 
1563     // If we're not reusing an existing String allocation then allocate one here.
1564     result = sc->string_alloc();
1565     if (result == NULL) {
1566       PreserveReexecuteState preexecs(&kit);
1567       // The original jvms is for an allocation of either a String or
1568       // StringBuffer so no stack adjustment is necessary for proper
1569       // reexecution.
1570       kit.jvms()->set_should_reexecute(true);
1571       result = kit.new_instance(__ makecon(TypeKlassPtr::make(C->env()->String_klass())));
1572     }
1573 
1574     // Intialize the string
1575     if (java_lang_String::has_offset_field()) {
1576       kit.store_String_offset(kit.control(), result, __ intcon(0));
1577       kit.store_String_length(kit.control(), result, length);
1578     }
1579     kit.store_String_value(kit.control(), result, char_array);
1580   } else {
1581     result = C->top();
1582   }
1583   // hook up the outgoing control and result
1584   kit.replace_call(sc->end(), result);
1585 
1586   // Unhook any hook nodes
1587   string_sizes->disconnect_inputs(NULL, C);
1588   sc->cleanup();
1589 }