1 /*
   2  * Copyright (c) 2009, 2018, 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 #include "runtime/sharedRuntime.hpp"
  38 #include "utilities/macros.hpp"
  39 #if INCLUDE_SHENANDOAHGC
  40 #include "gc/shenandoah/c2/shenandoahSupport.hpp"
  41 #endif
  42 
  43 #define __ kit.
  44 
  45 class StringConcat : public ResourceObj {
  46  private:
  47   PhaseStringOpts*    _stringopts;
  48   Node*               _string_alloc;
  49   AllocateNode*       _begin;          // The allocation the begins the pattern
  50   CallStaticJavaNode* _end;            // The final call of the pattern.  Will either be
  51                                        // SB.toString or or String.<init>(SB.toString)
  52   bool                _multiple;       // indicates this is a fusion of two or more
  53                                        // separate StringBuilders
  54 
  55   Node*               _arguments;      // The list of arguments to be concatenated
  56   GrowableArray<int>  _mode;           // into a String along with a mode flag
  57                                        // indicating how to treat the value.
  58   Node_List           _constructors;   // List of constructors (many in case of stacked concat)
  59   Node_List           _control;        // List of control nodes that will be deleted
  60   Node_List           _uncommon_traps; // Uncommon traps that needs to be rewritten
  61                                        // to restart at the initial JVMState.
  62 
  63  public:
  64   // Mode for converting arguments to Strings
  65   enum {
  66     StringMode,
  67     IntMode,
  68     CharMode,
  69     StringNullCheckMode
  70   };
  71 
  72   StringConcat(PhaseStringOpts* stringopts, CallStaticJavaNode* end):
  73     _stringopts(stringopts),
  74     _string_alloc(NULL),
  75     _begin(NULL),
  76     _end(end),
  77     _multiple(false) {
  78     _arguments = new Node(1);
  79     _arguments->del_req(0);
  80   }
  81 
  82   bool validate_mem_flow();
  83   bool validate_control_flow();
  84 
  85   void merge_add() {
  86 #if 0
  87     // XXX This is place holder code for reusing an existing String
  88     // allocation but the logic for checking the state safety is
  89     // probably inadequate at the moment.
  90     CallProjections endprojs;
  91     sc->end()->extract_projections(&endprojs, false);
  92     if (endprojs.resproj != NULL) {
  93       for (SimpleDUIterator i(endprojs.resproj); i.has_next(); i.next()) {
  94         CallStaticJavaNode *use = i.get()->isa_CallStaticJava();
  95         if (use != NULL && use->method() != NULL &&
  96             use->method()->intrinsic_id() == vmIntrinsics::_String_String &&
  97             use->in(TypeFunc::Parms + 1) == endprojs.resproj) {
  98           // Found useless new String(sb.toString()) so reuse the newly allocated String
  99           // when creating the result instead of allocating a new one.
 100           sc->set_string_alloc(use->in(TypeFunc::Parms));
 101           sc->set_end(use);
 102         }
 103       }
 104     }
 105 #endif
 106   }
 107 
 108   StringConcat* merge(StringConcat* other, Node* arg);
 109 
 110   void set_allocation(AllocateNode* alloc) {
 111     _begin = alloc;
 112   }
 113 
 114   void append(Node* value, int mode) {
 115     _arguments->add_req(value);
 116     _mode.append(mode);
 117   }
 118   void push(Node* value, int mode) {
 119     _arguments->ins_req(0, value);
 120     _mode.insert_before(0, mode);
 121   }
 122 
 123   void push_string(Node* value) {
 124     push(value, StringMode);
 125   }
 126   void push_string_null_check(Node* value) {
 127     push(value, StringNullCheckMode);
 128   }
 129   void push_int(Node* value) {
 130     push(value, IntMode);
 131   }
 132   void push_char(Node* value) {
 133     push(value, CharMode);
 134   }
 135 
 136   static bool is_SB_toString(Node* call) {
 137     if (call->is_CallStaticJava()) {
 138       CallStaticJavaNode* csj = call->as_CallStaticJava();
 139       ciMethod* m = csj->method();
 140       if (m != NULL &&
 141           (m->intrinsic_id() == vmIntrinsics::_StringBuilder_toString ||
 142            m->intrinsic_id() == vmIntrinsics::_StringBuffer_toString)) {
 143         return true;
 144       }
 145     }
 146     return false;
 147   }
 148 
 149   static Node* skip_string_null_check(Node* value) {
 150     // Look for a diamond shaped Null check of toString() result
 151     // (could be code from String.valueOf()):
 152     // (Proj == NULL) ? "null":"CastPP(Proj)#NotNULL
 153     if (value->is_Phi()) {
 154       int true_path = value->as_Phi()->is_diamond_phi();
 155       if (true_path != 0) {
 156         // phi->region->if_proj->ifnode->bool
 157         BoolNode* b = value->in(0)->in(1)->in(0)->in(1)->as_Bool();
 158         Node* cmp = b->in(1);
 159         Node* v1 = cmp->in(1);
 160         Node* v2 = cmp->in(2);
 161         // Null check of the return of toString which can simply be skipped.
 162         if (b->_test._test == BoolTest::ne &&
 163             v2->bottom_type() == TypePtr::NULL_PTR &&
 164             value->in(true_path)->Opcode() == Op_CastPP &&
 165             value->in(true_path)->in(1) == v1 &&
 166             v1->is_Proj() && is_SB_toString(v1->in(0))) {
 167           return v1;
 168         }
 169       }
 170     }
 171     return value;
 172   }
 173 
 174   Node* argument(int i) {
 175     return _arguments->in(i);
 176   }
 177   Node* argument_uncast(int i) {
 178     Node* arg = argument(i);
 179     int amode = mode(i);
 180     if (amode == StringConcat::StringMode ||
 181         amode == StringConcat::StringNullCheckMode) {
 182       arg = skip_string_null_check(arg);
 183     }
 184     return arg;
 185   }
 186   void set_argument(int i, Node* value) {
 187     _arguments->set_req(i, value);
 188   }
 189   int num_arguments() {
 190     return _mode.length();
 191   }
 192   int mode(int i) {
 193     return _mode.at(i);
 194   }
 195   void add_control(Node* ctrl) {
 196     assert(!_control.contains(ctrl), "only push once");
 197     _control.push(ctrl);
 198   }
 199   void add_constructor(Node* init) {
 200     assert(!_constructors.contains(init), "only push once");
 201     _constructors.push(init);
 202   }
 203   CallStaticJavaNode* end() { return _end; }
 204   AllocateNode* begin() { return _begin; }
 205   Node* string_alloc() { return _string_alloc; }
 206 
 207   void eliminate_unneeded_control();
 208   void eliminate_initialize(InitializeNode* init);
 209   void eliminate_call(CallNode* call);
 210 
 211   void maybe_log_transform() {
 212     CompileLog* log = _stringopts->C->log();
 213     if (log != NULL) {
 214       log->head("replace_string_concat arguments='%d' string_alloc='%d' multiple='%d'",
 215                 num_arguments(),
 216                 _string_alloc != NULL,
 217                 _multiple);
 218       JVMState* p = _begin->jvms();
 219       while (p != NULL) {
 220         log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
 221         p = p->caller();
 222       }
 223       log->tail("replace_string_concat");
 224     }
 225   }
 226 
 227   void convert_uncommon_traps(GraphKit& kit, const JVMState* jvms) {
 228     for (uint u = 0; u < _uncommon_traps.size(); u++) {
 229       Node* uct = _uncommon_traps.at(u);
 230 
 231       // Build a new call using the jvms state of the allocate
 232       address call_addr = SharedRuntime::uncommon_trap_blob()->entry_point();
 233       const TypeFunc* call_type = OptoRuntime::uncommon_trap_Type();
 234       const TypePtr* no_memory_effects = NULL;
 235       Compile* C = _stringopts->C;
 236       CallStaticJavaNode* call = new CallStaticJavaNode(call_type, call_addr, "uncommon_trap",
 237                                                         jvms->bci(), no_memory_effects);
 238       for (int e = 0; e < TypeFunc::Parms; e++) {
 239         call->init_req(e, uct->in(e));
 240       }
 241       // Set the trap request to record intrinsic failure if this trap
 242       // is taken too many times.  Ideally we would handle then traps by
 243       // doing the original bookkeeping in the MDO so that if it caused
 244       // the code to be thrown out we could still recompile and use the
 245       // optimization.  Failing the uncommon traps doesn't really mean
 246       // that the optimization is a bad idea but there's no other way to
 247       // do the MDO updates currently.
 248       int trap_request = Deoptimization::make_trap_request(Deoptimization::Reason_intrinsic,
 249                                                            Deoptimization::Action_make_not_entrant);
 250       call->init_req(TypeFunc::Parms, __ intcon(trap_request));
 251       kit.add_safepoint_edges(call);
 252 
 253       _stringopts->gvn()->transform(call);
 254       C->gvn_replace_by(uct, call);
 255       uct->disconnect_inputs(NULL, C);
 256     }
 257   }
 258 
 259   void cleanup() {
 260     // disconnect the hook node
 261     _arguments->disconnect_inputs(NULL, _stringopts->C);
 262   }
 263 };
 264 
 265 
 266 void StringConcat::eliminate_unneeded_control() {
 267   for (uint i = 0; i < _control.size(); i++) {
 268     Node* n = _control.at(i);
 269     if (n->is_Allocate()) {
 270       eliminate_initialize(n->as_Allocate()->initialization());
 271     }
 272     if (n->is_Call()) {
 273       if (n != _end) {
 274         eliminate_call(n->as_Call());
 275       }
 276     } else if (n->is_IfTrue()) {
 277       Compile* C = _stringopts->C;
 278       C->gvn_replace_by(n, n->in(0)->in(0));
 279       // get rid of the other projection
 280       C->gvn_replace_by(n->in(0)->as_If()->proj_out(false), C->top());
 281     }
 282   }
 283 }
 284 
 285 
 286 StringConcat* StringConcat::merge(StringConcat* other, Node* arg) {
 287   StringConcat* result = new StringConcat(_stringopts, _end);
 288   for (uint x = 0; x < _control.size(); x++) {
 289     Node* n = _control.at(x);
 290     if (n->is_Call()) {
 291       result->_control.push(n);
 292     }
 293   }
 294   for (uint x = 0; x < other->_control.size(); x++) {
 295     Node* n = other->_control.at(x);
 296     if (n->is_Call()) {
 297       result->_control.push(n);
 298     }
 299   }
 300   assert(result->_control.contains(other->_end), "what?");
 301   assert(result->_control.contains(_begin), "what?");
 302   for (int x = 0; x < num_arguments(); x++) {
 303     Node* argx = argument_uncast(x);
 304     if (argx == arg) {
 305       // replace the toString result with the all the arguments that
 306       // made up the other StringConcat
 307       for (int y = 0; y < other->num_arguments(); y++) {
 308         result->append(other->argument(y), other->mode(y));
 309       }
 310     } else {
 311       result->append(argx, mode(x));
 312     }
 313   }
 314   result->set_allocation(other->_begin);
 315   for (uint i = 0; i < _constructors.size(); i++) {
 316     result->add_constructor(_constructors.at(i));
 317   }
 318   for (uint i = 0; i < other->_constructors.size(); i++) {
 319     result->add_constructor(other->_constructors.at(i));
 320   }
 321   result->_multiple = true;
 322   return result;
 323 }
 324 
 325 
 326 void StringConcat::eliminate_call(CallNode* call) {
 327   Compile* C = _stringopts->C;
 328   CallProjections projs;
 329   call->extract_projections(&projs, false);
 330   if (projs.fallthrough_catchproj != NULL) {
 331     C->gvn_replace_by(projs.fallthrough_catchproj, call->in(TypeFunc::Control));
 332   }
 333   if (projs.fallthrough_memproj != NULL) {
 334     C->gvn_replace_by(projs.fallthrough_memproj, call->in(TypeFunc::Memory));
 335   }
 336   if (projs.catchall_memproj != NULL) {
 337     C->gvn_replace_by(projs.catchall_memproj, C->top());
 338   }
 339   if (projs.fallthrough_ioproj != NULL) {
 340     C->gvn_replace_by(projs.fallthrough_ioproj, call->in(TypeFunc::I_O));
 341   }
 342   if (projs.catchall_ioproj != NULL) {
 343     C->gvn_replace_by(projs.catchall_ioproj, C->top());
 344   }
 345   if (projs.catchall_catchproj != NULL) {
 346     // EA can't cope with the partially collapsed graph this
 347     // creates so put it on the worklist to be collapsed later.
 348     for (SimpleDUIterator i(projs.catchall_catchproj); i.has_next(); i.next()) {
 349       Node *use = i.get();
 350       int opc = use->Opcode();
 351       if (opc == Op_CreateEx || opc == Op_Region) {
 352         _stringopts->record_dead_node(use);
 353       }
 354     }
 355     C->gvn_replace_by(projs.catchall_catchproj, C->top());
 356   }
 357   if (projs.resproj != NULL) {
 358     C->gvn_replace_by(projs.resproj, C->top());
 359   }
 360   C->gvn_replace_by(call, C->top());
 361 }
 362 
 363 void StringConcat::eliminate_initialize(InitializeNode* init) {
 364   Compile* C = _stringopts->C;
 365 
 366   // Eliminate Initialize node.
 367   assert(init->outcnt() <= 2, "only a control and memory projection expected");
 368   assert(init->req() <= InitializeNode::RawStores, "no pending inits");
 369   Node *ctrl_proj = init->proj_out_or_null(TypeFunc::Control);
 370   if (ctrl_proj != NULL) {
 371     C->gvn_replace_by(ctrl_proj, init->in(TypeFunc::Control));
 372   }
 373   Node *mem_proj = init->proj_out_or_null(TypeFunc::Memory);
 374   if (mem_proj != NULL) {
 375     Node *mem = init->in(TypeFunc::Memory);
 376     C->gvn_replace_by(mem_proj, mem);
 377   }
 378   C->gvn_replace_by(init, C->top());
 379   init->disconnect_inputs(NULL, C);
 380 }
 381 
 382 Node_List PhaseStringOpts::collect_toString_calls() {
 383   Node_List string_calls;
 384   Node_List worklist;
 385 
 386   _visited.Clear();
 387 
 388   // Prime the worklist
 389   for (uint i = 1; i < C->root()->len(); i++) {
 390     Node* n = C->root()->in(i);
 391     if (n != NULL && !_visited.test_set(n->_idx)) {
 392       worklist.push(n);
 393     }
 394   }
 395 
 396   while (worklist.size() > 0) {
 397     Node* ctrl = worklist.pop();
 398     if (StringConcat::is_SB_toString(ctrl)) {
 399       CallStaticJavaNode* csj = ctrl->as_CallStaticJava();
 400       string_calls.push(csj);
 401     }
 402     if (ctrl->in(0) != NULL && !_visited.test_set(ctrl->in(0)->_idx)) {
 403       worklist.push(ctrl->in(0));
 404     }
 405     if (ctrl->is_Region()) {
 406       for (uint i = 1; i < ctrl->len(); i++) {
 407         if (ctrl->in(i) != NULL && !_visited.test_set(ctrl->in(i)->_idx)) {
 408           worklist.push(ctrl->in(i));
 409         }
 410       }
 411     }
 412   }
 413   return string_calls;
 414 }
 415 
 416 
 417 StringConcat* PhaseStringOpts::build_candidate(CallStaticJavaNode* call) {
 418   ciMethod* m = call->method();
 419   ciSymbol* string_sig;
 420   ciSymbol* int_sig;
 421   ciSymbol* char_sig;
 422   if (m->holder() == C->env()->StringBuilder_klass()) {
 423     string_sig = ciSymbol::String_StringBuilder_signature();
 424     int_sig = ciSymbol::int_StringBuilder_signature();
 425     char_sig = ciSymbol::char_StringBuilder_signature();
 426   } else if (m->holder() == C->env()->StringBuffer_klass()) {
 427     string_sig = ciSymbol::String_StringBuffer_signature();
 428     int_sig = ciSymbol::int_StringBuffer_signature();
 429     char_sig = ciSymbol::char_StringBuffer_signature();
 430   } else {
 431     return NULL;
 432   }
 433 #ifndef PRODUCT
 434   if (PrintOptimizeStringConcat) {
 435     tty->print("considering toString call in ");
 436     call->jvms()->dump_spec(tty); tty->cr();
 437   }
 438 #endif
 439 
 440   StringConcat* sc = new StringConcat(this, call);
 441 
 442   AllocateNode* alloc = NULL;
 443   InitializeNode* init = NULL;
 444 
 445   // possible opportunity for StringBuilder fusion
 446   CallStaticJavaNode* cnode = call;
 447   while (cnode) {
 448     Node* recv = cnode->in(TypeFunc::Parms)->uncast();
 449     if (recv->is_Proj()) {
 450       recv = recv->in(0);
 451     }
 452     cnode = recv->isa_CallStaticJava();
 453     if (cnode == NULL) {
 454       alloc = recv->isa_Allocate();
 455       if (alloc == NULL) {
 456         break;
 457       }
 458       // Find the constructor call
 459       Node* result = alloc->result_cast();
 460       if (result == NULL || !result->is_CheckCastPP() || alloc->in(TypeFunc::Memory)->is_top()) {
 461         // strange looking allocation
 462 #ifndef PRODUCT
 463         if (PrintOptimizeStringConcat) {
 464           tty->print("giving up because allocation looks strange ");
 465           alloc->jvms()->dump_spec(tty); tty->cr();
 466         }
 467 #endif
 468         break;
 469       }
 470       Node* constructor = NULL;
 471       for (SimpleDUIterator i(result); i.has_next(); i.next()) {
 472         CallStaticJavaNode *use = i.get()->isa_CallStaticJava();
 473         if (use != NULL &&
 474             use->method() != NULL &&
 475             !use->method()->is_static() &&
 476             use->method()->name() == ciSymbol::object_initializer_name() &&
 477             use->method()->holder() == m->holder()) {
 478           // Matched the constructor.
 479           ciSymbol* sig = use->method()->signature()->as_symbol();
 480           if (sig == ciSymbol::void_method_signature() ||
 481               sig == ciSymbol::int_void_signature() ||
 482               sig == ciSymbol::string_void_signature()) {
 483             if (sig == ciSymbol::string_void_signature()) {
 484               // StringBuilder(String) so pick this up as the first argument
 485               assert(use->in(TypeFunc::Parms + 1) != NULL, "what?");
 486               const Type* type = _gvn->type(use->in(TypeFunc::Parms + 1));
 487               if (type == TypePtr::NULL_PTR) {
 488                 // StringBuilder(null) throws exception.
 489 #ifndef PRODUCT
 490                 if (PrintOptimizeStringConcat) {
 491                   tty->print("giving up because StringBuilder(null) throws exception");
 492                   alloc->jvms()->dump_spec(tty); tty->cr();
 493                 }
 494 #endif
 495                 return NULL;
 496               }
 497               // StringBuilder(str) argument needs null check.
 498               sc->push_string_null_check(use->in(TypeFunc::Parms + 1));
 499             }
 500             // The int variant takes an initial size for the backing
 501             // array so just treat it like the void version.
 502             constructor = use;
 503           } else {
 504 #ifndef PRODUCT
 505             if (PrintOptimizeStringConcat) {
 506               tty->print("unexpected constructor signature: %s", sig->as_utf8());
 507             }
 508 #endif
 509           }
 510           break;
 511         }
 512       }
 513       if (constructor == NULL) {
 514         // couldn't find constructor
 515 #ifndef PRODUCT
 516         if (PrintOptimizeStringConcat) {
 517           tty->print("giving up because couldn't find constructor ");
 518           alloc->jvms()->dump_spec(tty); tty->cr();
 519         }
 520 #endif
 521         break;
 522       }
 523 
 524       // Walked all the way back and found the constructor call so see
 525       // if this call converted into a direct string concatenation.
 526       sc->add_control(call);
 527       sc->add_control(constructor);
 528       sc->add_control(alloc);
 529       sc->set_allocation(alloc);
 530       sc->add_constructor(constructor);
 531       if (sc->validate_control_flow() && sc->validate_mem_flow()) {
 532         return sc;
 533       } else {
 534         return NULL;
 535       }
 536     } else if (cnode->method() == NULL) {
 537       break;
 538     } else if (!cnode->method()->is_static() &&
 539                cnode->method()->holder() == m->holder() &&
 540                cnode->method()->name() == ciSymbol::append_name() &&
 541                (cnode->method()->signature()->as_symbol() == string_sig ||
 542                 cnode->method()->signature()->as_symbol() == char_sig ||
 543                 cnode->method()->signature()->as_symbol() == int_sig)) {
 544       sc->add_control(cnode);
 545       Node* arg = cnode->in(TypeFunc::Parms + 1);
 546       if (cnode->method()->signature()->as_symbol() == int_sig) {
 547         sc->push_int(arg);
 548       } else if (cnode->method()->signature()->as_symbol() == char_sig) {
 549         sc->push_char(arg);
 550       } else {
 551         if (arg->is_Proj() && arg->in(0)->is_CallStaticJava()) {
 552           CallStaticJavaNode* csj = arg->in(0)->as_CallStaticJava();
 553           if (csj->method() != NULL &&
 554               csj->method()->intrinsic_id() == vmIntrinsics::_Integer_toString &&
 555               arg->outcnt() == 1) {
 556             // _control is the list of StringBuilder calls nodes which
 557             // will be replaced by new String code after this optimization.
 558             // Integer::toString() call is not part of StringBuilder calls
 559             // chain. It could be eliminated only if its result is used
 560             // only by this SB calls chain.
 561             // Another limitation: it should be used only once because
 562             // it is unknown that it is used only by this SB calls chain
 563             // until all related SB calls nodes are collected.
 564             assert(arg->unique_out() == cnode, "sanity");
 565             sc->add_control(csj);
 566             sc->push_int(csj->in(TypeFunc::Parms));
 567             continue;
 568           }
 569         }
 570         sc->push_string(arg);
 571       }
 572       continue;
 573     } else {
 574       // some unhandled signature
 575 #ifndef PRODUCT
 576       if (PrintOptimizeStringConcat) {
 577         tty->print("giving up because encountered unexpected signature ");
 578         cnode->tf()->dump(); tty->cr();
 579         cnode->in(TypeFunc::Parms + 1)->dump();
 580       }
 581 #endif
 582       break;
 583     }
 584   }
 585   return NULL;
 586 }
 587 
 588 
 589 PhaseStringOpts::PhaseStringOpts(PhaseGVN* gvn, Unique_Node_List*):
 590   Phase(StringOpts),
 591   _gvn(gvn),
 592   _visited(Thread::current()->resource_area()) {
 593 
 594   assert(OptimizeStringConcat, "shouldn't be here");
 595 
 596   size_table_field = C->env()->Integer_klass()->get_field_by_name(ciSymbol::make("sizeTable"),
 597                                                                   ciSymbol::make("[I"), true);
 598   if (size_table_field == NULL) {
 599     // Something wrong so give up.
 600     assert(false, "why can't we find Integer.sizeTable?");
 601     return;
 602   }
 603 
 604   // Collect the types needed to talk about the various slices of memory
 605   byte_adr_idx = C->get_alias_index(TypeAryPtr::BYTES);
 606 
 607   // For each locally allocated StringBuffer see if the usages can be
 608   // collapsed into a single String construction.
 609 
 610   // Run through the list of allocation looking for SB.toString to see
 611   // if it's possible to fuse the usage of the SB into a single String
 612   // construction.
 613   GrowableArray<StringConcat*> concats;
 614   Node_List toStrings = collect_toString_calls();
 615   while (toStrings.size() > 0) {
 616     StringConcat* sc = build_candidate(toStrings.pop()->as_CallStaticJava());
 617     if (sc != NULL) {
 618       concats.push(sc);
 619     }
 620   }
 621 
 622   // try to coalesce separate concats
 623  restart:
 624   for (int c = 0; c < concats.length(); c++) {
 625     StringConcat* sc = concats.at(c);
 626     for (int i = 0; i < sc->num_arguments(); i++) {
 627       Node* arg = sc->argument_uncast(i);
 628       if (arg->is_Proj() && StringConcat::is_SB_toString(arg->in(0))) {
 629         CallStaticJavaNode* csj = arg->in(0)->as_CallStaticJava();
 630         for (int o = 0; o < concats.length(); o++) {
 631           if (c == o) continue;
 632           StringConcat* other = concats.at(o);
 633           if (other->end() == csj) {
 634 #ifndef PRODUCT
 635             if (PrintOptimizeStringConcat) {
 636               tty->print_cr("considering stacked concats");
 637             }
 638 #endif
 639 
 640             StringConcat* merged = sc->merge(other, arg);
 641             if (merged->validate_control_flow() && merged->validate_mem_flow()) {
 642 #ifndef PRODUCT
 643               if (PrintOptimizeStringConcat) {
 644                 tty->print_cr("stacking would succeed");
 645               }
 646 #endif
 647               if (c < o) {
 648                 concats.remove_at(o);
 649                 concats.at_put(c, merged);
 650               } else {
 651                 concats.remove_at(c);
 652                 concats.at_put(o, merged);
 653               }
 654               goto restart;
 655             } else {
 656 #ifndef PRODUCT
 657               if (PrintOptimizeStringConcat) {
 658                 tty->print_cr("stacking would fail");
 659               }
 660 #endif
 661             }
 662           }
 663         }
 664       }
 665     }
 666   }
 667 
 668 
 669   for (int c = 0; c < concats.length(); c++) {
 670     StringConcat* sc = concats.at(c);
 671     replace_string_concat(sc);
 672   }
 673 
 674   remove_dead_nodes();
 675 }
 676 
 677 void PhaseStringOpts::record_dead_node(Node* dead) {
 678   dead_worklist.push(dead);
 679 }
 680 
 681 void PhaseStringOpts::remove_dead_nodes() {
 682   // Delete any dead nodes to make things clean enough that escape
 683   // analysis doesn't get unhappy.
 684   while (dead_worklist.size() > 0) {
 685     Node* use = dead_worklist.pop();
 686     int opc = use->Opcode();
 687     switch (opc) {
 688       case Op_Region: {
 689         uint i = 1;
 690         for (i = 1; i < use->req(); i++) {
 691           if (use->in(i) != C->top()) {
 692             break;
 693           }
 694         }
 695         if (i >= use->req()) {
 696           for (SimpleDUIterator i(use); i.has_next(); i.next()) {
 697             Node* m = i.get();
 698             if (m->is_Phi()) {
 699               dead_worklist.push(m);
 700             }
 701           }
 702           C->gvn_replace_by(use, C->top());
 703         }
 704         break;
 705       }
 706       case Op_AddP:
 707       case Op_CreateEx: {
 708         // Recurisvely clean up references to CreateEx so EA doesn't
 709         // get unhappy about the partially collapsed graph.
 710         for (SimpleDUIterator i(use); i.has_next(); i.next()) {
 711           Node* m = i.get();
 712           if (m->is_AddP()) {
 713             dead_worklist.push(m);
 714           }
 715         }
 716         C->gvn_replace_by(use, C->top());
 717         break;
 718       }
 719       case Op_Phi:
 720         if (use->in(0) == C->top()) {
 721           C->gvn_replace_by(use, C->top());
 722         }
 723         break;
 724     }
 725   }
 726 }
 727 
 728 
 729 bool StringConcat::validate_mem_flow() {
 730   Compile* C = _stringopts->C;
 731 
 732   for (uint i = 0; i < _control.size(); i++) {
 733 #ifndef PRODUCT
 734     Node_List path;
 735 #endif
 736     Node* curr = _control.at(i);
 737     if (curr->is_Call() && curr != _begin) { // For all calls except the first allocation
 738       // Now here's the main invariant in our case:
 739       // For memory between the constructor, and appends, and toString we should only see bottom memory,
 740       // produced by the previous call we know about.
 741       if (!_constructors.contains(curr)) {
 742         NOT_PRODUCT(path.push(curr);)
 743         Node* mem = curr->in(TypeFunc::Memory);
 744         assert(mem != NULL, "calls should have memory edge");
 745         assert(!mem->is_Phi(), "should be handled by control flow validation");
 746         NOT_PRODUCT(path.push(mem);)
 747         while (mem->is_MergeMem()) {
 748           for (uint i = 1; i < mem->req(); i++) {
 749             if (i != Compile::AliasIdxBot && mem->in(i) != C->top()) {
 750 #ifndef PRODUCT
 751               if (PrintOptimizeStringConcat) {
 752                 tty->print("fusion has incorrect memory flow (side effects) for ");
 753                 _begin->jvms()->dump_spec(tty); tty->cr();
 754                 path.dump();
 755               }
 756 #endif
 757               return false;
 758             }
 759           }
 760           // skip through a potential MergeMem chain, linked through Bot
 761           mem = mem->in(Compile::AliasIdxBot);
 762           NOT_PRODUCT(path.push(mem);)
 763         }
 764         // now let it fall through, and see if we have a projection
 765         if (mem->is_Proj()) {
 766           // Should point to a previous known call
 767           Node *prev = mem->in(0);
 768           NOT_PRODUCT(path.push(prev);)
 769           if (!prev->is_Call() || !_control.contains(prev)) {
 770 #ifndef PRODUCT
 771             if (PrintOptimizeStringConcat) {
 772               tty->print("fusion has incorrect memory flow (unknown call) for ");
 773               _begin->jvms()->dump_spec(tty); tty->cr();
 774               path.dump();
 775             }
 776 #endif
 777             return false;
 778           }
 779         } else {
 780           assert(mem->is_Store() || mem->is_LoadStore(), "unexpected node type: %s", mem->Name());
 781 #ifndef PRODUCT
 782           if (PrintOptimizeStringConcat) {
 783             tty->print("fusion has incorrect memory flow (unexpected source) for ");
 784             _begin->jvms()->dump_spec(tty); tty->cr();
 785             path.dump();
 786           }
 787 #endif
 788           return false;
 789         }
 790       } else {
 791         // For memory that feeds into constructors it's more complicated.
 792         // However the advantage is that any side effect that happens between the Allocate/Initialize and
 793         // the constructor will have to be control-dependent on Initialize.
 794         // So we actually don't have to do anything, since it's going to be caught by the control flow
 795         // analysis.
 796 #ifdef ASSERT
 797         // Do a quick verification of the control pattern between the constructor and the initialize node
 798         assert(curr->is_Call(), "constructor should be a call");
 799         // Go up the control starting from the constructor call
 800         Node* ctrl = curr->in(0);
 801         IfNode* iff = NULL;
 802         RegionNode* copy = NULL;
 803 
 804         while (true) {
 805           // skip known check patterns
 806           if (ctrl->is_Region()) {
 807             if (ctrl->as_Region()->is_copy()) {
 808               copy = ctrl->as_Region();
 809               ctrl = copy->is_copy();
 810             } else { // a cast
 811               assert(ctrl->req() == 3 &&
 812                      ctrl->in(1) != NULL && ctrl->in(1)->is_Proj() &&
 813                      ctrl->in(2) != NULL && ctrl->in(2)->is_Proj() &&
 814                      ctrl->in(1)->in(0) == ctrl->in(2)->in(0) &&
 815                      ctrl->in(1)->in(0) != NULL && ctrl->in(1)->in(0)->is_If(),
 816                      "must be a simple diamond");
 817               Node* true_proj = ctrl->in(1)->is_IfTrue() ? ctrl->in(1) : ctrl->in(2);
 818               for (SimpleDUIterator i(true_proj); i.has_next(); i.next()) {
 819                 Node* use = i.get();
 820                 assert(use == ctrl || use->is_ConstraintCast(),
 821                        "unexpected user: %s", use->Name());
 822               }
 823 
 824               iff = ctrl->in(1)->in(0)->as_If();
 825               ctrl = iff->in(0);
 826             }
 827           } else if (ctrl->is_IfTrue()) { // null checks, class checks
 828             iff = ctrl->in(0)->as_If();
 829             // Verify that the other arm is an uncommon trap
 830             Node* otherproj = iff->proj_out(1 - ctrl->as_Proj()->_con);
 831             CallStaticJavaNode* call = otherproj->unique_out()->isa_CallStaticJava();
 832             assert(strcmp(call->_name, "uncommon_trap") == 0, "must be uncommon trap");
 833             ctrl = iff->in(0);
 834           } else {
 835             break;
 836           }
 837         }
 838 
 839         assert(ctrl->is_Proj(), "must be a projection");
 840         assert(ctrl->in(0)->is_Initialize(), "should be initialize");
 841         for (SimpleDUIterator i(ctrl); i.has_next(); i.next()) {
 842           Node* use = i.get();
 843           assert(use == copy || use == iff || use == curr || use->is_CheckCastPP() || use->is_Load(),
 844                  "unexpected user: %s", use->Name());
 845         }
 846 #endif // ASSERT
 847       }
 848     }
 849   }
 850 
 851 #ifndef PRODUCT
 852   if (PrintOptimizeStringConcat) {
 853     tty->print("fusion has correct memory flow for ");
 854     _begin->jvms()->dump_spec(tty); tty->cr();
 855     tty->cr();
 856   }
 857 #endif
 858   return true;
 859 }
 860 
 861 bool StringConcat::validate_control_flow() {
 862   // We found all the calls and arguments now lets see if it's
 863   // safe to transform the graph as we would expect.
 864 
 865   // Check to see if this resulted in too many uncommon traps previously
 866   if (Compile::current()->too_many_traps(_begin->jvms()->method(), _begin->jvms()->bci(),
 867                         Deoptimization::Reason_intrinsic)) {
 868     return false;
 869   }
 870 
 871   // Walk backwards over the control flow from toString to the
 872   // allocation and make sure all the control flow is ok.  This
 873   // means it's either going to be eliminated once the calls are
 874   // removed or it can safely be transformed into an uncommon
 875   // trap.
 876 
 877   int null_check_count = 0;
 878   Unique_Node_List ctrl_path;
 879 
 880   assert(_control.contains(_begin), "missing");
 881   assert(_control.contains(_end), "missing");
 882 
 883   // Collect the nodes that we know about and will eliminate into ctrl_path
 884   for (uint i = 0; i < _control.size(); i++) {
 885     // Push the call and it's control projection
 886     Node* n = _control.at(i);
 887     if (n->is_Allocate()) {
 888       AllocateNode* an = n->as_Allocate();
 889       InitializeNode* init = an->initialization();
 890       ctrl_path.push(init);
 891       ctrl_path.push(init->as_Multi()->proj_out(0));
 892     }
 893     if (n->is_Call()) {
 894       CallNode* cn = n->as_Call();
 895       ctrl_path.push(cn);
 896       ctrl_path.push(cn->proj_out(0));
 897       ctrl_path.push(cn->proj_out(0)->unique_out());
 898       Node* catchproj = cn->proj_out(0)->unique_out()->as_Catch()->proj_out_or_null(0);
 899       if (catchproj != NULL) {
 900         ctrl_path.push(catchproj);
 901       }
 902     } else {
 903       ShouldNotReachHere();
 904     }
 905   }
 906 
 907   // Skip backwards through the control checking for unexpected control flow
 908   Node* ptr = _end;
 909   bool fail = false;
 910   while (ptr != _begin) {
 911     if (ptr->is_Call() && ctrl_path.member(ptr)) {
 912       ptr = ptr->in(0);
 913     } else if (ptr->is_CatchProj() && ctrl_path.member(ptr)) {
 914       ptr = ptr->in(0)->in(0)->in(0);
 915       assert(ctrl_path.member(ptr), "should be a known piece of control");
 916     } else if (ptr->is_IfTrue()) {
 917       IfNode* iff = ptr->in(0)->as_If();
 918       BoolNode* b = iff->in(1)->isa_Bool();
 919 
 920       if (b == NULL) {
 921 #ifndef PRODUCT
 922         if (PrintOptimizeStringConcat) {
 923           tty->print_cr("unexpected input to IfNode");
 924           iff->in(1)->dump();
 925           tty->cr();
 926         }
 927 #endif
 928         fail = true;
 929         break;
 930       }
 931 
 932       Node* cmp = b->in(1);
 933       Node* v1 = cmp->in(1);
 934       Node* v2 = cmp->in(2);
 935       Node* otherproj = iff->proj_out(1 - ptr->as_Proj()->_con);
 936 
 937       // Null check of the return of append which can simply be eliminated
 938       if (b->_test._test == BoolTest::ne &&
 939           v2->bottom_type() == TypePtr::NULL_PTR &&
 940           v1->is_Proj() && ctrl_path.member(v1->in(0))) {
 941         // NULL check of the return value of the append
 942         null_check_count++;
 943         if (otherproj->outcnt() == 1) {
 944           CallStaticJavaNode* call = otherproj->unique_out()->isa_CallStaticJava();
 945           if (call != NULL && call->_name != NULL && strcmp(call->_name, "uncommon_trap") == 0) {
 946             ctrl_path.push(call);
 947           }
 948         }
 949         _control.push(ptr);
 950         ptr = ptr->in(0)->in(0);
 951         continue;
 952       }
 953 
 954       // A test which leads to an uncommon trap which should be safe.
 955       // Later this trap will be converted into a trap that restarts
 956       // at the beginning.
 957       if (otherproj->outcnt() == 1) {
 958         CallStaticJavaNode* call = otherproj->unique_out()->isa_CallStaticJava();
 959         if (call != NULL && call->_name != NULL && strcmp(call->_name, "uncommon_trap") == 0) {
 960           // control flow leads to uct so should be ok
 961           _uncommon_traps.push(call);
 962           ctrl_path.push(call);
 963           ptr = ptr->in(0)->in(0);
 964           continue;
 965         }
 966       }
 967 
 968 #ifndef PRODUCT
 969       // Some unexpected control flow we don't know how to handle.
 970       if (PrintOptimizeStringConcat) {
 971         tty->print_cr("failing with unknown test");
 972         b->dump();
 973         cmp->dump();
 974         v1->dump();
 975         v2->dump();
 976         tty->cr();
 977       }
 978 #endif
 979       fail = true;
 980       break;
 981     } else if (ptr->is_Proj() && ptr->in(0)->is_Initialize()) {
 982       ptr = ptr->in(0)->in(0);
 983     } else if (ptr->is_Region()) {
 984       Node* copy = ptr->as_Region()->is_copy();
 985       if (copy != NULL) {
 986         ptr = copy;
 987         continue;
 988       }
 989       if (ptr->req() == 3 &&
 990           ptr->in(1) != NULL && ptr->in(1)->is_Proj() &&
 991           ptr->in(2) != NULL && ptr->in(2)->is_Proj() &&
 992           ptr->in(1)->in(0) == ptr->in(2)->in(0) &&
 993           ptr->in(1)->in(0) != NULL && ptr->in(1)->in(0)->is_If()) {
 994         // Simple diamond.
 995         // XXX should check for possibly merging stores.  simple data merges are ok.
 996         // The IGVN will make this simple diamond go away when it
 997         // transforms the Region. Make sure it sees it.
 998         Compile::current()->record_for_igvn(ptr);
 999         ptr = ptr->in(1)->in(0)->in(0);
1000         continue;
1001       }
1002 #ifndef PRODUCT
1003       if (PrintOptimizeStringConcat) {
1004         tty->print_cr("fusion would fail for region");
1005         _begin->dump();
1006         ptr->dump(2);
1007       }
1008 #endif
1009       fail = true;
1010       break;
1011     } else {
1012       // other unknown control
1013       if (!fail) {
1014 #ifndef PRODUCT
1015         if (PrintOptimizeStringConcat) {
1016           tty->print_cr("fusion would fail for");
1017           _begin->dump();
1018         }
1019 #endif
1020         fail = true;
1021       }
1022 #ifndef PRODUCT
1023       if (PrintOptimizeStringConcat) {
1024         ptr->dump();
1025       }
1026 #endif
1027       ptr = ptr->in(0);
1028     }
1029   }
1030 #ifndef PRODUCT
1031   if (PrintOptimizeStringConcat && fail) {
1032     tty->cr();
1033   }
1034 #endif
1035   if (fail) return !fail;
1036 
1037   // Validate that all these results produced are contained within
1038   // this cluster of objects.  First collect all the results produced
1039   // by calls in the region.
1040   _stringopts->_visited.Clear();
1041   Node_List worklist;
1042   Node* final_result = _end->proj_out_or_null(TypeFunc::Parms);
1043   for (uint i = 0; i < _control.size(); i++) {
1044     CallNode* cnode = _control.at(i)->isa_Call();
1045     if (cnode != NULL) {
1046       _stringopts->_visited.test_set(cnode->_idx);
1047     }
1048     Node* result = cnode != NULL ? cnode->proj_out_or_null(TypeFunc::Parms) : NULL;
1049     if (result != NULL && result != final_result) {
1050       worklist.push(result);
1051     }
1052   }
1053 
1054   Node* last_result = NULL;
1055   while (worklist.size() > 0) {
1056     Node* result = worklist.pop();
1057     if (_stringopts->_visited.test_set(result->_idx))
1058       continue;
1059     for (SimpleDUIterator i(result); i.has_next(); i.next()) {
1060       Node *use = i.get();
1061       if (ctrl_path.member(use)) {
1062         // already checked this
1063         continue;
1064       }
1065       int opc = use->Opcode();
1066       if (opc == Op_CmpP || opc == Op_Node) {
1067         ctrl_path.push(use);
1068         continue;
1069       }
1070       if (opc == Op_CastPP || opc == Op_CheckCastPP) {
1071         for (SimpleDUIterator j(use); j.has_next(); j.next()) {
1072           worklist.push(j.get());
1073         }
1074         worklist.push(use->in(1));
1075         ctrl_path.push(use);
1076         continue;
1077       }
1078 #ifndef PRODUCT
1079       if (PrintOptimizeStringConcat) {
1080         if (result != last_result) {
1081           last_result = result;
1082           tty->print_cr("extra uses for result:");
1083           last_result->dump();
1084         }
1085         use->dump();
1086       }
1087 #endif
1088       fail = true;
1089       break;
1090     }
1091   }
1092 
1093 #ifndef PRODUCT
1094   if (PrintOptimizeStringConcat && !fail) {
1095     ttyLocker ttyl;
1096     tty->cr();
1097     tty->print("fusion has correct control flow (%d %d) for ", null_check_count, _uncommon_traps.size());
1098     _begin->jvms()->dump_spec(tty); tty->cr();
1099     for (int i = 0; i < num_arguments(); i++) {
1100       argument(i)->dump();
1101     }
1102     _control.dump();
1103     tty->cr();
1104   }
1105 #endif
1106 
1107   return !fail;
1108 }
1109 
1110 Node* PhaseStringOpts::fetch_static_field(GraphKit& kit, ciField* field) {
1111   const TypeInstPtr* mirror_type = TypeInstPtr::make(field->holder()->java_mirror());
1112   Node* klass_node = __ makecon(mirror_type);
1113   BasicType bt = field->layout_type();
1114   ciType* field_klass = field->type();
1115 
1116   const Type *type;
1117   if( bt == T_OBJECT ) {
1118     if (!field->type()->is_loaded()) {
1119       type = TypeInstPtr::BOTTOM;
1120     } else if (field->is_static_constant()) {
1121       // This can happen if the constant oop is non-perm.
1122       ciObject* con = field->constant_value().as_object();
1123       // Do not "join" in the previous type; it doesn't add value,
1124       // and may yield a vacuous result if the field is of interface type.
1125       type = TypeOopPtr::make_from_constant(con, true)->isa_oopptr();
1126       assert(type != NULL, "field singleton type must be consistent");
1127       return __ makecon(type);
1128     } else {
1129       type = TypeOopPtr::make_from_klass(field_klass->as_klass());
1130     }
1131   } else {
1132     type = Type::get_const_basic_type(bt);
1133   }
1134 
1135   return kit.make_load(NULL, kit.basic_plus_adr(klass_node, field->offset_in_bytes()),
1136                        type, T_OBJECT,
1137                        C->get_alias_index(mirror_type->add_offset(field->offset_in_bytes())),
1138                        MemNode::unordered);
1139 }
1140 
1141 Node* PhaseStringOpts::int_stringSize(GraphKit& kit, Node* arg) {
1142   if (arg->is_Con()) {
1143     // Constant integer. Compute constant length using Integer.sizeTable
1144     int arg_val = arg->get_int();
1145     int count = 1;
1146     if (arg_val < 0) {
1147       arg_val = -arg_val;
1148       count++;
1149     }
1150 
1151     ciArray* size_table = (ciArray*)size_table_field->constant_value().as_object();
1152     for (int i = 0; i < size_table->length(); i++) {
1153       if (arg_val <= size_table->element_value(i).as_int()) {
1154         count += i;
1155         break;
1156       }
1157     }
1158     return __ intcon(count);
1159   }
1160 
1161   RegionNode *final_merge = new RegionNode(3);
1162   kit.gvn().set_type(final_merge, Type::CONTROL);
1163   Node* final_size = new PhiNode(final_merge, TypeInt::INT);
1164   kit.gvn().set_type(final_size, TypeInt::INT);
1165 
1166   IfNode* iff = kit.create_and_map_if(kit.control(),
1167                                       __ Bool(__ CmpI(arg, __ intcon(0x80000000)), BoolTest::ne),
1168                                       PROB_FAIR, COUNT_UNKNOWN);
1169   Node* is_min = __ IfFalse(iff);
1170   final_merge->init_req(1, is_min);
1171   final_size->init_req(1, __ intcon(11));
1172 
1173   kit.set_control(__ IfTrue(iff));
1174   if (kit.stopped()) {
1175     final_merge->init_req(2, C->top());
1176     final_size->init_req(2, C->top());
1177   } else {
1178 
1179     // int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
1180     RegionNode *r = new RegionNode(3);
1181     kit.gvn().set_type(r, Type::CONTROL);
1182     Node *phi = new PhiNode(r, TypeInt::INT);
1183     kit.gvn().set_type(phi, TypeInt::INT);
1184     Node *size = new PhiNode(r, TypeInt::INT);
1185     kit.gvn().set_type(size, TypeInt::INT);
1186     Node* chk = __ CmpI(arg, __ intcon(0));
1187     Node* p = __ Bool(chk, BoolTest::lt);
1188     IfNode* iff = kit.create_and_map_if(kit.control(), p, PROB_FAIR, COUNT_UNKNOWN);
1189     Node* lessthan = __ IfTrue(iff);
1190     Node* greaterequal = __ IfFalse(iff);
1191     r->init_req(1, lessthan);
1192     phi->init_req(1, __ SubI(__ intcon(0), arg));
1193     size->init_req(1, __ intcon(1));
1194     r->init_req(2, greaterequal);
1195     phi->init_req(2, arg);
1196     size->init_req(2, __ intcon(0));
1197     kit.set_control(r);
1198     C->record_for_igvn(r);
1199     C->record_for_igvn(phi);
1200     C->record_for_igvn(size);
1201 
1202     // for (int i=0; ; i++)
1203     //   if (x <= sizeTable[i])
1204     //     return i+1;
1205 
1206     // Add loop predicate first.
1207     kit.add_predicate();
1208 
1209     RegionNode *loop = new RegionNode(3);
1210     loop->init_req(1, kit.control());
1211     kit.gvn().set_type(loop, Type::CONTROL);
1212 
1213     Node *index = new PhiNode(loop, TypeInt::INT);
1214     index->init_req(1, __ intcon(0));
1215     kit.gvn().set_type(index, TypeInt::INT);
1216     kit.set_control(loop);
1217     Node* sizeTable = fetch_static_field(kit, size_table_field);
1218 
1219     sizeTable = kit.access_resolve(sizeTable, ACCESS_READ);
1220     Node* value = kit.load_array_element(NULL, sizeTable, index, TypeAryPtr::INTS);
1221     C->record_for_igvn(value);
1222     Node* limit = __ CmpI(phi, value);
1223     Node* limitb = __ Bool(limit, BoolTest::le);
1224     IfNode* iff2 = kit.create_and_map_if(kit.control(), limitb, PROB_MIN, COUNT_UNKNOWN);
1225     Node* lessEqual = __ IfTrue(iff2);
1226     Node* greater = __ IfFalse(iff2);
1227 
1228     loop->init_req(2, greater);
1229     index->init_req(2, __ AddI(index, __ intcon(1)));
1230 
1231     kit.set_control(lessEqual);
1232     C->record_for_igvn(loop);
1233     C->record_for_igvn(index);
1234 
1235     final_merge->init_req(2, kit.control());
1236     final_size->init_req(2, __ AddI(__ AddI(index, size), __ intcon(1)));
1237   }
1238 
1239   kit.set_control(final_merge);
1240   C->record_for_igvn(final_merge);
1241   C->record_for_igvn(final_size);
1242 
1243   return final_size;
1244 }
1245 
1246 // Simplified version of Integer.getChars
1247 void PhaseStringOpts::getChars(GraphKit& kit, Node* arg, Node* dst_array, BasicType bt, Node* end, Node* final_merge, Node* final_mem, int merge_index) {
1248   // if (i < 0) {
1249   //     sign = '-';
1250   //     i = -i;
1251   // }
1252   IfNode* iff = kit.create_and_map_if(kit.control(), __ Bool(__ CmpI(arg, __ intcon(0)), BoolTest::lt),
1253                                       PROB_FAIR, COUNT_UNKNOWN);
1254 
1255   RegionNode* merge = new RegionNode(3);
1256   kit.gvn().set_type(merge, Type::CONTROL);
1257   Node* i = new PhiNode(merge, TypeInt::INT);
1258   kit.gvn().set_type(i, TypeInt::INT);
1259   Node* sign = new PhiNode(merge, TypeInt::INT);
1260   kit.gvn().set_type(sign, TypeInt::INT);
1261 
1262   merge->init_req(1, __ IfTrue(iff));
1263   i->init_req(1, __ SubI(__ intcon(0), arg));
1264   sign->init_req(1, __ intcon('-'));
1265   merge->init_req(2, __ IfFalse(iff));
1266   i->init_req(2, arg);
1267   sign->init_req(2, __ intcon(0));
1268 
1269   kit.set_control(merge);
1270 
1271   C->record_for_igvn(merge);
1272   C->record_for_igvn(i);
1273   C->record_for_igvn(sign);
1274 
1275   // for (;;) {
1276   //     q = i / 10;
1277   //     r = i - ((q << 3) + (q << 1));  // r = i-(q*10) ...
1278   //     buf [--charPos] = digits [r];
1279   //     i = q;
1280   //     if (i == 0) break;
1281   // }
1282 
1283   // Add loop predicate first.
1284   kit.add_predicate();
1285 
1286   RegionNode* head = new RegionNode(3);
1287   head->init_req(1, kit.control());
1288 
1289   kit.gvn().set_type(head, Type::CONTROL);
1290   Node* i_phi = new PhiNode(head, TypeInt::INT);
1291   i_phi->init_req(1, i);
1292   kit.gvn().set_type(i_phi, TypeInt::INT);
1293   Node* charPos = new PhiNode(head, TypeInt::INT);
1294   charPos->init_req(1, end);
1295   kit.gvn().set_type(charPos, TypeInt::INT);
1296   Node* mem = PhiNode::make(head, kit.memory(byte_adr_idx), Type::MEMORY, TypeAryPtr::BYTES);
1297   kit.gvn().set_type(mem, Type::MEMORY);
1298 
1299   kit.set_control(head);
1300   kit.set_memory(mem, byte_adr_idx);
1301 
1302   Node* q = __ DivI(kit.null(), i_phi, __ intcon(10));
1303   Node* r = __ SubI(i_phi, __ AddI(__ LShiftI(q, __ intcon(3)),
1304                                    __ LShiftI(q, __ intcon(1))));
1305   Node* index = __ SubI(charPos, __ intcon((bt == T_BYTE) ? 1 : 2));
1306   Node* ch = __ AddI(r, __ intcon('0'));
1307   Node* st = __ store_to_memory(kit.control(), kit.array_element_address(dst_array, index, T_BYTE),
1308                                 ch, bt, byte_adr_idx, MemNode::unordered, (bt != T_BYTE) /* mismatched */);
1309 
1310   iff = kit.create_and_map_if(head, __ Bool(__ CmpI(q, __ intcon(0)), BoolTest::ne),
1311                               PROB_FAIR, COUNT_UNKNOWN);
1312   Node* ne = __ IfTrue(iff);
1313   Node* eq = __ IfFalse(iff);
1314 
1315   head->init_req(2, ne);
1316   mem->init_req(2, st);
1317 
1318   i_phi->init_req(2, q);
1319   charPos->init_req(2, index);
1320   charPos = index;
1321 
1322   kit.set_control(eq);
1323   kit.set_memory(st, byte_adr_idx);
1324 
1325   C->record_for_igvn(head);
1326   C->record_for_igvn(mem);
1327   C->record_for_igvn(i_phi);
1328   C->record_for_igvn(charPos);
1329 
1330   // if (sign != 0) {
1331   //     buf [--charPos] = sign;
1332   // }
1333   iff = kit.create_and_map_if(kit.control(), __ Bool(__ CmpI(sign, __ intcon(0)), BoolTest::ne),
1334                               PROB_FAIR, COUNT_UNKNOWN);
1335 
1336   final_merge->init_req(merge_index + 2, __ IfFalse(iff));
1337   final_mem->init_req(merge_index + 2, kit.memory(byte_adr_idx));
1338 
1339   kit.set_control(__ IfTrue(iff));
1340   if (kit.stopped()) {
1341     final_merge->init_req(merge_index + 1, C->top());
1342     final_mem->init_req(merge_index + 1, C->top());
1343   } else {
1344     Node* index = __ SubI(charPos, __ intcon((bt == T_BYTE) ? 1 : 2));
1345     st = __ store_to_memory(kit.control(), kit.array_element_address(dst_array, index, T_BYTE),
1346                             sign, bt, byte_adr_idx, MemNode::unordered, (bt != T_BYTE) /* mismatched */);
1347 
1348     final_merge->init_req(merge_index + 1, kit.control());
1349     final_mem->init_req(merge_index + 1, st);
1350   }
1351 }
1352 
1353 // Copy the characters representing arg into dst_array starting at start
1354 Node* PhaseStringOpts::int_getChars(GraphKit& kit, Node* arg, Node* dst_array, Node* dst_coder, Node* start, Node* size) {
1355   bool dcon = dst_coder->is_Con();
1356   bool dbyte = dcon ? (dst_coder->get_int() == java_lang_String::CODER_LATIN1) : false;
1357   Node* end = __ AddI(start, __ LShiftI(size, dst_coder));
1358 
1359   // The final_merge node has 4 entries in case the encoding is known:
1360   // (0) Control, (1) result w/ sign, (2) result w/o sign, (3) result for Integer.min_value
1361   // or 6 entries in case the encoding is not known:
1362   // (0) Control, (1) Latin1 w/ sign, (2) Latin1 w/o sign, (3) min_value, (4) UTF16 w/ sign, (5) UTF16 w/o sign
1363   RegionNode* final_merge = new RegionNode(dcon ? 4 : 6);
1364   kit.gvn().set_type(final_merge, Type::CONTROL);
1365 
1366   Node* final_mem = PhiNode::make(final_merge, kit.memory(byte_adr_idx), Type::MEMORY, TypeAryPtr::BYTES);
1367   kit.gvn().set_type(final_mem, Type::MEMORY);
1368 
1369   // need to handle arg == Integer.MIN_VALUE specially because negating doesn't make it positive
1370   IfNode* iff = kit.create_and_map_if(kit.control(), __ Bool(__ CmpI(arg, __ intcon(0x80000000)), BoolTest::ne),
1371                                       PROB_FAIR, COUNT_UNKNOWN);
1372 
1373   Node* old_mem = kit.memory(byte_adr_idx);
1374 
1375   kit.set_control(__ IfFalse(iff));
1376   if (kit.stopped()) {
1377     // Statically not equal to MIN_VALUE so this path is dead
1378     final_merge->init_req(3, kit.control());
1379   } else {
1380     copy_string(kit, __ makecon(TypeInstPtr::make(C->env()->the_min_jint_string())),
1381                 dst_array, dst_coder, start);
1382     final_merge->init_req(3, kit.control());
1383     final_mem->init_req(3, kit.memory(byte_adr_idx));
1384   }
1385 
1386   kit.set_control(__ IfTrue(iff));
1387   kit.set_memory(old_mem, byte_adr_idx);
1388 
1389   if (!dcon) {
1390     // Check encoding of destination
1391     iff = kit.create_and_map_if(kit.control(), __ Bool(__ CmpI(dst_coder, __ intcon(0)), BoolTest::eq),
1392                                 PROB_FAIR, COUNT_UNKNOWN);
1393     old_mem = kit.memory(byte_adr_idx);
1394   }
1395   if (!dcon || dbyte) {
1396     // Destination is Latin1,
1397     if (!dcon) {
1398       kit.set_control(__ IfTrue(iff));
1399     }
1400     getChars(kit, arg, dst_array, T_BYTE, end, final_merge, final_mem);
1401   }
1402   if (!dcon || !dbyte) {
1403     // Destination is UTF16
1404     int merge_index = 0;
1405     if (!dcon) {
1406       kit.set_control(__ IfFalse(iff));
1407       kit.set_memory(old_mem, byte_adr_idx);
1408       merge_index = 3; // Account for Latin1 case
1409     }
1410     getChars(kit, arg, dst_array, T_CHAR, end, final_merge, final_mem, merge_index);
1411   }
1412 
1413   // Final merge point for Latin1 and UTF16 case
1414   kit.set_control(final_merge);
1415   kit.set_memory(final_mem, byte_adr_idx);
1416 
1417   C->record_for_igvn(final_merge);
1418   C->record_for_igvn(final_mem);
1419   return end;
1420 }
1421 
1422 // Copy 'count' bytes/chars from src_array to dst_array starting at index start
1423 void PhaseStringOpts::arraycopy(GraphKit& kit, IdealKit& ideal, Node* src_array, Node* dst_array, BasicType elembt, Node* start, Node* count) {
1424   assert(elembt == T_BYTE || elembt == T_CHAR, "Invalid type for arraycopy");
1425 
1426   if (elembt == T_CHAR) {
1427     // Get number of chars
1428     count = __ RShiftI(count, __ intcon(1));
1429   }
1430 
1431   Node* extra = NULL;
1432 #ifdef _LP64
1433   count = __ ConvI2L(count);
1434   extra = C->top();
1435 #endif
1436 
1437   Node* src_ptr = __ array_element_address(src_array, __ intcon(0), T_BYTE);
1438   Node* dst_ptr = __ array_element_address(dst_array, start, T_BYTE);
1439   // Check if destination address is aligned to HeapWordSize
1440   const TypeInt* tdst = __ gvn().type(start)->is_int();
1441   bool aligned = tdst->is_con() && ((tdst->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0);
1442   // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1443   const char* copyfunc_name = "arraycopy";
1444   address     copyfunc_addr = StubRoutines::select_arraycopy_function(elembt, aligned, true, copyfunc_name, true);
1445   ideal.make_leaf_call_no_fp(OptoRuntime::fast_arraycopy_Type(), copyfunc_addr, copyfunc_name,
1446                              TypeAryPtr::BYTES, src_ptr, dst_ptr, count, extra);
1447 }
1448 
1449 #undef __
1450 #define __ ideal.
1451 
1452 // Copy contents of a Latin1 encoded string from src_array to dst_array
1453 void PhaseStringOpts::copy_latin1_string(GraphKit& kit, IdealKit& ideal, Node* src_array, IdealVariable& count,
1454                                          Node* dst_array, Node* dst_coder, Node* start) {
1455   bool dcon = dst_coder->is_Con();
1456   bool dbyte = dcon ? (dst_coder->get_int() == java_lang_String::CODER_LATIN1) : false;
1457 
1458   if (!dcon) {
1459     __ if_then(dst_coder, BoolTest::eq, __ ConI(java_lang_String::CODER_LATIN1));
1460   }
1461   if (!dcon || dbyte) {
1462     // Destination is Latin1. Simply emit a byte arraycopy.
1463     arraycopy(kit, ideal, src_array, dst_array, T_BYTE, start, __ value(count));
1464   }
1465   if (!dcon) {
1466     __ else_();
1467   }
1468   if (!dcon || !dbyte) {
1469     // Destination is UTF16. Inflate src_array into dst_array.
1470     kit.sync_kit(ideal);
1471     if (Matcher::match_rule_supported(Op_StrInflatedCopy)) {
1472       // Use fast intrinsic
1473       Node* src = kit.array_element_address(src_array, kit.intcon(0), T_BYTE);
1474       Node* dst = kit.array_element_address(dst_array, start, T_BYTE);
1475       kit.inflate_string(src, dst, TypeAryPtr::BYTES, __ value(count));
1476     } else {
1477       // No intrinsic available, use slow method
1478       kit.inflate_string_slow(src_array, dst_array, start, __ value(count));
1479     }
1480     ideal.sync_kit(&kit);
1481     // Multiply count by two since we now need two bytes per char
1482     __ set(count, __ LShiftI(__ value(count), __ ConI(1)));
1483   }
1484   if (!dcon) {
1485     __ end_if();
1486   }
1487 }
1488 
1489 // Read two bytes from index and index+1 and convert them to a char
1490 static jchar readChar(ciTypeArray* array, int index) {
1491   int shift_high, shift_low;
1492 #ifdef VM_LITTLE_ENDIAN
1493     shift_high = 0;
1494     shift_low = 8;
1495 #else
1496     shift_high = 8;
1497     shift_low = 0;
1498 #endif
1499 
1500   jchar b1 = ((jchar) array->byte_at(index)) & 0xff;
1501   jchar b2 = ((jchar) array->byte_at(index+1)) & 0xff;
1502   return (b1 << shift_high) | (b2 << shift_low);
1503 }
1504 
1505 // Copy contents of constant src_array to dst_array by emitting individual stores
1506 void PhaseStringOpts::copy_constant_string(GraphKit& kit, IdealKit& ideal, ciTypeArray* src_array, IdealVariable& count,
1507                                            bool src_is_byte, Node* dst_array, Node* dst_coder, Node* start) {
1508   bool dcon = dst_coder->is_Con();
1509   bool dbyte = dcon ? (dst_coder->get_int() == java_lang_String::CODER_LATIN1) : false;
1510   int length = src_array->length();
1511 
1512   if (!dcon) {
1513     __ if_then(dst_coder, BoolTest::eq, __ ConI(java_lang_String::CODER_LATIN1));
1514   }
1515   if (!dcon || dbyte) {
1516     // Destination is Latin1. Copy each byte of src_array into dst_array.
1517     Node* index = start;
1518     for (int i = 0; i < length; i++) {
1519       Node* adr = kit.array_element_address(dst_array, index, T_BYTE);
1520       Node* val = __ ConI(src_array->byte_at(i));
1521       __ store(__ ctrl(), adr, val, T_BYTE, byte_adr_idx, MemNode::unordered);
1522       index = __ AddI(index, __ ConI(1));
1523     }
1524   }
1525   if (!dcon) {
1526     __ else_();
1527   }
1528   if (!dcon || !dbyte) {
1529     // Destination is UTF16. Copy each char of src_array into dst_array.
1530     Node* index = start;
1531     for (int i = 0; i < length; i++) {
1532       Node* adr = kit.array_element_address(dst_array, index, T_BYTE);
1533       jchar val;
1534       if (src_is_byte) {
1535         val = src_array->byte_at(i) & 0xff;
1536       } else {
1537         val = readChar(src_array, i++);
1538       }
1539       __ store(__ ctrl(), adr, __ ConI(val), T_CHAR, byte_adr_idx, MemNode::unordered, true /* mismatched */);
1540       index = __ AddI(index, __ ConI(2));
1541     }
1542     if (src_is_byte) {
1543       // Multiply count by two since we now need two bytes per char
1544       __ set(count, __ ConI(2 * length));
1545     }
1546   }
1547   if (!dcon) {
1548     __ end_if();
1549   }
1550 }
1551 
1552 // Compress copy contents of the byte/char String str into dst_array starting at index start.
1553 Node* PhaseStringOpts::copy_string(GraphKit& kit, Node* str, Node* dst_array, Node* dst_coder, Node* start) {
1554   Node* src_array = kit.load_String_value(str, true);
1555   src_array = kit.access_resolve(src_array, ACCESS_READ);
1556 
1557   IdealKit ideal(&kit, true, true);
1558   IdealVariable count(ideal); __ declarations_done();
1559 
1560   if (str->is_Con()) {
1561     // Constant source string
1562     ciTypeArray* src_array_type = get_constant_value(kit, str);
1563 
1564     // Check encoding of constant string
1565     bool src_is_byte = (get_constant_coder(kit, str) == java_lang_String::CODER_LATIN1);
1566 
1567     // For small constant strings just emit individual stores.
1568     // A length of 6 seems like a good space/speed tradeof.
1569     __ set(count, __ ConI(src_array_type->length()));
1570     int src_len = src_array_type->length() / (src_is_byte ? 1 : 2);
1571     if (src_len < unroll_string_copy_length) {
1572       // Small constant string
1573       copy_constant_string(kit, ideal, src_array_type, count, src_is_byte, dst_array, dst_coder, start);
1574     } else if (src_is_byte) {
1575       // Source is Latin1
1576       copy_latin1_string(kit, ideal, src_array, count, dst_array, dst_coder, start);
1577     } else {
1578       // Source is UTF16 (destination too). Simply emit a char arraycopy.
1579       arraycopy(kit, ideal, src_array, dst_array, T_CHAR, start, __ value(count));
1580     }
1581   } else {
1582     Node* size = kit.load_array_length(src_array);
1583     __ set(count, size);
1584     // Non-constant source string
1585     if (CompactStrings) {
1586       // Emit runtime check for coder
1587       Node* coder = kit.load_String_coder(str, true);
1588       __ if_then(coder, BoolTest::eq, __ ConI(java_lang_String::CODER_LATIN1)); {
1589         // Source is Latin1
1590         copy_latin1_string(kit, ideal, src_array, count, dst_array, dst_coder, start);
1591       } __ else_();
1592     }
1593     // Source is UTF16 (destination too). Simply emit a char arraycopy.
1594     arraycopy(kit, ideal, src_array, dst_array, T_CHAR, start, __ value(count));
1595 
1596     if (CompactStrings) {
1597       __ end_if();
1598     }
1599   }
1600 
1601   // Finally sync IdealKit and GraphKit.
1602   kit.sync_kit(ideal);
1603   return __ AddI(start, __ value(count));
1604 }
1605 
1606 // Compress copy the char into dst_array at index start.
1607 Node* PhaseStringOpts::copy_char(GraphKit& kit, Node* val, Node* dst_array, Node* dst_coder, Node* start) {
1608   bool dcon = (dst_coder != NULL) && dst_coder->is_Con();
1609   bool dbyte = dcon ? (dst_coder->get_int() == java_lang_String::CODER_LATIN1) : false;
1610 
1611   IdealKit ideal(&kit, true, true);
1612   IdealVariable end(ideal); __ declarations_done();
1613   Node* adr = kit.array_element_address(dst_array, start, T_BYTE);
1614   if (!dcon){
1615     __ if_then(dst_coder, BoolTest::eq, __ ConI(java_lang_String::CODER_LATIN1));
1616   }
1617   if (!dcon || dbyte) {
1618     // Destination is Latin1. Store a byte.
1619     __ store(__ ctrl(), adr, val, T_BYTE, byte_adr_idx, MemNode::unordered);
1620     __ set(end, __ AddI(start, __ ConI(1)));
1621   }
1622   if (!dcon) {
1623     __ else_();
1624   }
1625   if (!dcon || !dbyte) {
1626     // Destination is UTF16. Store a char.
1627     __ store(__ ctrl(), adr, val, T_CHAR, byte_adr_idx, MemNode::unordered, true /* mismatched */);
1628     __ set(end, __ AddI(start, __ ConI(2)));
1629   }
1630   if (!dcon) {
1631     __ end_if();
1632   }
1633   // Finally sync IdealKit and GraphKit.
1634   kit.sync_kit(ideal);
1635   return __ value(end);
1636 }
1637 
1638 #undef __
1639 #define __ kit.
1640 
1641 // Allocate a byte array of specified length.
1642 Node* PhaseStringOpts::allocate_byte_array(GraphKit& kit, IdealKit* ideal, Node* length) {
1643   if (ideal != NULL) {
1644     // Sync IdealKit and graphKit.
1645     kit.sync_kit(*ideal);
1646   }
1647   Node* byte_array = NULL;
1648   {
1649     PreserveReexecuteState preexecs(&kit);
1650     // The original jvms is for an allocation of either a String or
1651     // StringBuffer so no stack adjustment is necessary for proper
1652     // reexecution.  If we deoptimize in the slow path the bytecode
1653     // will be reexecuted and the char[] allocation will be thrown away.
1654     kit.jvms()->set_should_reexecute(true);
1655     byte_array = kit.new_array(__ makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE))),
1656                                length, 1);
1657   }
1658 
1659   // Mark the allocation so that zeroing is skipped since the code
1660   // below will overwrite the entire array
1661   AllocateArrayNode* byte_alloc = AllocateArrayNode::Ideal_array_allocation(byte_array, _gvn);
1662   byte_alloc->maybe_set_complete(_gvn);
1663 
1664   if (ideal != NULL) {
1665     // Sync IdealKit and graphKit.
1666     ideal->sync_kit(&kit);
1667   }
1668   return byte_array;
1669 }
1670 
1671 jbyte PhaseStringOpts::get_constant_coder(GraphKit& kit, Node* str) {
1672   assert(str->is_Con(), "String must be constant");
1673   const TypeOopPtr* str_type = kit.gvn().type(str)->isa_oopptr();
1674   ciInstance* str_instance = str_type->const_oop()->as_instance();
1675   jbyte coder = str_instance->field_value_by_offset(java_lang_String::coder_offset_in_bytes()).as_byte();
1676   assert(CompactStrings || (coder == java_lang_String::CODER_UTF16), "Strings must be UTF16 encoded");
1677   return coder;
1678 }
1679 
1680 int PhaseStringOpts::get_constant_length(GraphKit& kit, Node* str) {
1681   assert(str->is_Con(), "String must be constant");
1682   return get_constant_value(kit, str)->length();
1683 }
1684 
1685 ciTypeArray* PhaseStringOpts::get_constant_value(GraphKit& kit, Node* str) {
1686   assert(str->is_Con(), "String must be constant");
1687   const TypeOopPtr* str_type = kit.gvn().type(str)->isa_oopptr();
1688   ciInstance* str_instance = str_type->const_oop()->as_instance();
1689   ciObject* src_array = str_instance->field_value_by_offset(java_lang_String::value_offset_in_bytes()).as_object();
1690   return src_array->as_type_array();
1691 }
1692 
1693 void PhaseStringOpts::replace_string_concat(StringConcat* sc) {
1694   // Log a little info about the transformation
1695   sc->maybe_log_transform();
1696 
1697   // pull the JVMState of the allocation into a SafePointNode to serve as
1698   // as a shim for the insertion of the new code.
1699   JVMState* jvms     = sc->begin()->jvms()->clone_shallow(C);
1700   uint size = sc->begin()->req();
1701   SafePointNode* map = new SafePointNode(size, jvms);
1702 
1703   // copy the control and memory state from the final call into our
1704   // new starting state.  This allows any preceeding tests to feed
1705   // into the new section of code.
1706   for (uint i1 = 0; i1 < TypeFunc::Parms; i1++) {
1707     map->init_req(i1, sc->end()->in(i1));
1708   }
1709   // blow away old allocation arguments
1710   for (uint i1 = TypeFunc::Parms; i1 < jvms->debug_start(); i1++) {
1711     map->init_req(i1, C->top());
1712   }
1713   // Copy the rest of the inputs for the JVMState
1714   for (uint i1 = jvms->debug_start(); i1 < sc->begin()->req(); i1++) {
1715     map->init_req(i1, sc->begin()->in(i1));
1716   }
1717   // Make sure the memory state is a MergeMem for parsing.
1718   if (!map->in(TypeFunc::Memory)->is_MergeMem()) {
1719     map->set_req(TypeFunc::Memory, MergeMemNode::make(map->in(TypeFunc::Memory)));
1720   }
1721 
1722   jvms->set_map(map);
1723   map->ensure_stack(jvms, jvms->method()->max_stack());
1724 
1725   // disconnect all the old StringBuilder calls from the graph
1726   sc->eliminate_unneeded_control();
1727 
1728   // At this point all the old work has been completely removed from
1729   // the graph and the saved JVMState exists at the point where the
1730   // final toString call used to be.
1731   GraphKit kit(jvms);
1732 
1733   // There may be uncommon traps which are still using the
1734   // intermediate states and these need to be rewritten to point at
1735   // the JVMState at the beginning of the transformation.
1736   sc->convert_uncommon_traps(kit, jvms);
1737 
1738   // Now insert the logic to compute the size of the string followed
1739   // by all the logic to construct array and resulting string.
1740 
1741   Node* null_string = __ makecon(TypeInstPtr::make(C->env()->the_null_string()));
1742 
1743   // Create a region for the overflow checks to merge into.
1744   int args = MAX2(sc->num_arguments(), 1);
1745   RegionNode* overflow = new RegionNode(args);
1746   kit.gvn().set_type(overflow, Type::CONTROL);
1747 
1748   // Create a hook node to hold onto the individual sizes since they
1749   // are need for the copying phase.
1750   Node* string_sizes = new Node(args);
1751 
1752   Node* coder = __ intcon(0);
1753   Node* length = __ intcon(0);
1754   // If at least one argument is UTF16 encoded, we can fix the encoding.
1755   bool coder_fixed = false;
1756 
1757   if (!CompactStrings) {
1758     // Fix encoding of result string to UTF16
1759     coder_fixed = true;
1760     coder = __ intcon(java_lang_String::CODER_UTF16);
1761   }
1762 
1763   for (int argi = 0; argi < sc->num_arguments(); argi++) {
1764     Node* arg = sc->argument(argi);
1765     switch (sc->mode(argi)) {
1766       case StringConcat::IntMode: {
1767         Node* string_size = int_stringSize(kit, arg);
1768 
1769         // accumulate total
1770         length = __ AddI(length, string_size);
1771 
1772         // Cache this value for the use by int_toString
1773         string_sizes->init_req(argi, string_size);
1774         break;
1775       }
1776       case StringConcat::StringNullCheckMode: {
1777         const Type* type = kit.gvn().type(arg);
1778         assert(type != TypePtr::NULL_PTR, "missing check");
1779         if (!type->higher_equal(TypeInstPtr::NOTNULL)) {
1780           // Null check with uncommon trap since
1781           // StringBuilder(null) throws exception.
1782           // Use special uncommon trap instead of
1783           // calling normal do_null_check().
1784           Node* p = __ Bool(__ CmpP(arg, kit.null()), BoolTest::ne);
1785           IfNode* iff = kit.create_and_map_if(kit.control(), p, PROB_MIN, COUNT_UNKNOWN);
1786           overflow->add_req(__ IfFalse(iff));
1787           Node* notnull = __ IfTrue(iff);
1788           kit.set_control(notnull); // set control for the cast_not_null
1789           arg = kit.cast_not_null(arg, false);
1790           sc->set_argument(argi, arg);
1791         }
1792         assert(kit.gvn().type(arg)->higher_equal(TypeInstPtr::NOTNULL), "sanity");
1793         // Fallthrough to add string length.
1794       }
1795       case StringConcat::StringMode: {
1796         const Type* type = kit.gvn().type(arg);
1797         Node* count = NULL;
1798         Node* arg_coder = NULL;
1799         if (type == TypePtr::NULL_PTR) {
1800           // replace the argument with the null checked version
1801           arg = null_string;
1802           sc->set_argument(argi, arg);
1803           count = kit.load_String_length(arg, true);
1804           arg_coder = kit.load_String_coder(arg, true);
1805         } else if (!type->higher_equal(TypeInstPtr::NOTNULL)) {
1806           // s = s != null ? s : "null";
1807           // length = length + (s.count - s.offset);
1808           RegionNode *r = new RegionNode(3);
1809           kit.gvn().set_type(r, Type::CONTROL);
1810           Node *phi = new PhiNode(r, type);
1811           kit.gvn().set_type(phi, phi->bottom_type());
1812           Node* p = __ Bool(__ CmpP(arg, kit.null()), BoolTest::ne);
1813           IfNode* iff = kit.create_and_map_if(kit.control(), p, PROB_MIN, COUNT_UNKNOWN);
1814           Node* notnull = __ IfTrue(iff);
1815           Node* isnull =  __ IfFalse(iff);
1816           kit.set_control(notnull); // set control for the cast_not_null
1817           r->init_req(1, notnull);
1818           phi->init_req(1, kit.cast_not_null(arg, false));
1819           r->init_req(2, isnull);
1820           phi->init_req(2, null_string);
1821           kit.set_control(r);
1822           C->record_for_igvn(r);
1823           C->record_for_igvn(phi);
1824           // replace the argument with the null checked version
1825           arg = phi;
1826           sc->set_argument(argi, arg);
1827           count = kit.load_String_length(arg, true);
1828           arg_coder = kit.load_String_coder(arg, true);
1829         } else {
1830           // A corresponding nullcheck will be connected during IGVN MemNode::Ideal_common_DU_postCCP
1831           // kit.control might be a different test, that can be hoisted above the actual nullcheck
1832           // in case, that the control input is not null, Ideal_common_DU_postCCP will not look for a nullcheck.
1833           count = kit.load_String_length(arg, false);
1834           arg_coder = kit.load_String_coder(arg, false);
1835         }
1836 
1837         if (arg->is_Con()) {
1838           // Constant string. Get constant coder and length.
1839           jbyte const_coder = get_constant_coder(kit, arg);
1840           int const_length = get_constant_length(kit, arg);
1841           if (const_coder == java_lang_String::CODER_LATIN1) {
1842             // Can be latin1 encoded
1843             arg_coder = __ intcon(const_coder);
1844             count = __ intcon(const_length);
1845           } else {
1846             // Found UTF16 encoded string. Fix result array encoding to UTF16.
1847             coder_fixed = true;
1848             coder = __ intcon(const_coder);
1849             count = __ intcon(const_length / 2);
1850           }
1851         }
1852 
1853         if (!coder_fixed) {
1854           coder = __ OrI(coder, arg_coder);
1855         }
1856         length = __ AddI(length, count);
1857         string_sizes->init_req(argi, NULL);
1858         break;
1859       }
1860       case StringConcat::CharMode: {
1861         // one character only
1862         const TypeInt* t = kit.gvn().type(arg)->is_int();
1863         if (!coder_fixed && t->is_con()) {
1864           // Constant char
1865           if (t->get_con() <= 255) {
1866             // Can be latin1 encoded
1867             coder = __ OrI(coder, __ intcon(java_lang_String::CODER_LATIN1));
1868           } else {
1869             // Must be UTF16 encoded. Fix result array encoding to UTF16.
1870             coder_fixed = true;
1871             coder = __ intcon(java_lang_String::CODER_UTF16);
1872           }
1873         } else if (!coder_fixed) {
1874           // Not constant
1875 #undef __
1876 #define __ ideal.
1877           IdealKit ideal(&kit, true, true);
1878           IdealVariable char_coder(ideal); __ declarations_done();
1879           // Check if character can be latin1 encoded
1880           __ if_then(arg, BoolTest::le, __ ConI(0xFF));
1881             __ set(char_coder, __ ConI(java_lang_String::CODER_LATIN1));
1882           __ else_();
1883             __ set(char_coder, __ ConI(java_lang_String::CODER_UTF16));
1884           __ end_if();
1885           kit.sync_kit(ideal);
1886           coder = __ OrI(coder, __ value(char_coder));
1887 #undef __
1888 #define __ kit.
1889         }
1890         length = __ AddI(length, __ intcon(1));
1891         break;
1892       }
1893       default:
1894         ShouldNotReachHere();
1895     }
1896     if (argi > 0) {
1897       // Check that the sum hasn't overflowed
1898       IfNode* iff = kit.create_and_map_if(kit.control(),
1899                                           __ Bool(__ CmpI(length, __ intcon(0)), BoolTest::lt),
1900                                           PROB_MIN, COUNT_UNKNOWN);
1901       kit.set_control(__ IfFalse(iff));
1902       overflow->set_req(argi, __ IfTrue(iff));
1903     }
1904   }
1905 
1906   {
1907     // Hook
1908     PreserveJVMState pjvms(&kit);
1909     kit.set_control(overflow);
1910     C->record_for_igvn(overflow);
1911     kit.uncommon_trap(Deoptimization::Reason_intrinsic,
1912                       Deoptimization::Action_make_not_entrant);
1913   }
1914 
1915   Node* result;
1916   if (!kit.stopped()) {
1917     assert(CompactStrings || (coder->is_Con() && coder->get_int() == java_lang_String::CODER_UTF16),
1918            "Result string must be UTF16 encoded if CompactStrings is disabled");
1919 
1920     Node* dst_array = NULL;
1921     if (sc->num_arguments() == 1 &&
1922         (sc->mode(0) == StringConcat::StringMode ||
1923          sc->mode(0) == StringConcat::StringNullCheckMode)) {
1924       // Handle the case when there is only a single String argument.
1925       // In this case, we can just pull the value from the String itself.
1926       dst_array = kit.load_String_value(sc->argument(0), true);
1927     } else {
1928       // Allocate destination byte array according to coder
1929       dst_array = allocate_byte_array(kit, NULL, __ LShiftI(length, coder));
1930 
1931       // Now copy the string representations into the final byte[]
1932       Node* start = __ intcon(0);
1933       for (int argi = 0; argi < sc->num_arguments(); argi++) {
1934         Node* arg = sc->argument(argi);
1935         switch (sc->mode(argi)) {
1936           case StringConcat::IntMode: {
1937             start = int_getChars(kit, arg, dst_array, coder, start, string_sizes->in(argi));
1938             break;
1939           }
1940           case StringConcat::StringNullCheckMode:
1941           case StringConcat::StringMode: {
1942             start = copy_string(kit, arg, dst_array, coder, start);
1943             break;
1944           }
1945           case StringConcat::CharMode: {
1946             start = copy_char(kit, arg, dst_array, coder, start);
1947           break;
1948           }
1949           default:
1950             ShouldNotReachHere();
1951         }
1952       }
1953     }
1954 
1955     // If we're not reusing an existing String allocation then allocate one here.
1956     result = sc->string_alloc();
1957     if (result == NULL) {
1958       PreserveReexecuteState preexecs(&kit);
1959       // The original jvms is for an allocation of either a String or
1960       // StringBuffer so no stack adjustment is necessary for proper
1961       // reexecution.
1962       kit.jvms()->set_should_reexecute(true);
1963       result = kit.new_instance(__ makecon(TypeKlassPtr::make(C->env()->String_klass())));
1964     }
1965 
1966     // Initialize the string
1967     kit.store_String_value(result, dst_array);
1968     kit.store_String_coder(result, coder);
1969 
1970     // The value field is final. Emit a barrier here to ensure that the effect
1971     // of the initialization is committed to memory before any code publishes
1972     // a reference to the newly constructed object (see Parse::do_exits()).
1973     assert(AllocateNode::Ideal_allocation(result, _gvn) != NULL, "should be newly allocated");
1974     kit.insert_mem_bar(Op_MemBarRelease, result);
1975   } else {
1976     result = C->top();
1977   }
1978   // hook up the outgoing control and result
1979   kit.replace_call(sc->end(), result);
1980 
1981   // Unhook any hook nodes
1982   string_sizes->disconnect_inputs(NULL, C);
1983   sc->cleanup();
1984 }