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