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