1 /*
   2  * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.tools.javac.jvm;
  27 
  28 import com.sun.tools.javac.code.*;
  29 import com.sun.tools.javac.comp.ConstFold;
  30 import com.sun.tools.javac.comp.Resolve;
  31 import com.sun.tools.javac.tree.JCTree;
  32 import com.sun.tools.javac.tree.TreeInfo;
  33 import com.sun.tools.javac.tree.TreeMaker;
  34 import com.sun.tools.javac.util.*;
  35 
  36 import static com.sun.tools.javac.code.Kinds.Kind.MTH;
  37 import static com.sun.tools.javac.code.TypeTag.*;
  38 import static com.sun.tools.javac.jvm.ByteCodes.*;
  39 import static com.sun.tools.javac.tree.JCTree.Tag.PLUS;
  40 import com.sun.tools.javac.jvm.Items.*;
  41 
  42 import java.util.HashMap;
  43 import java.util.Map;
  44 
  45 /** This lowers the String concatenation to something that JVM can understand.
  46  *
  47  *  <p><b>This is NOT part of any supported API.
  48  *  If you write code that depends on this, you do so at your own risk.
  49  *  This code and its internal interfaces are subject to change or
  50  *  deletion without notice.</b>
  51  */
  52 public abstract class StringConcat {
  53 
  54     /**
  55      * Maximum number of slots for String Concat call.
  56      * JDK's StringConcatFactory does not support more than that.
  57      */
  58     private static final int MAX_INDY_CONCAT_ARG_SLOTS = 200;
  59     private static final char TAG_ARG   = '\u0001';
  60     private static final char TAG_CONST = '\u0002';
  61 
  62     protected final Gen gen;
  63     protected final Symtab syms;
  64     protected final Names names;
  65     protected final TreeMaker make;
  66     protected final Types types;
  67     protected final Map<Type, Symbol> sbAppends;
  68     protected final Resolve rs;
  69 
  70     protected static final Context.Key<StringConcat> concatKey = new Context.Key<>();
  71 
  72     public static StringConcat instance(Context context) {
  73         StringConcat instance = context.get(concatKey);
  74         if (instance == null) {
  75             instance = makeConcat(context);
  76         }
  77         return instance;
  78     }
  79 
  80     private static StringConcat makeConcat(Context context) {
  81         Target target = Target.instance(context);
  82         String opt = Options.instance(context).get("stringConcat");
  83         if (target.hasStringConcatFactory()) {
  84             if (opt == null) {
  85                 opt = "indyWithConstants";
  86             }
  87         } else {
  88             if (opt != null && !"inline".equals(opt)) {
  89                 Assert.error("StringConcatFactory-based string concat is requested on a platform that does not support it.");
  90             }
  91             opt = "inline";
  92         }
  93 
  94         switch (opt) {
  95             case "inline":
  96                 return new Inline(context);
  97             case "indy":
  98                 return new IndyPlain(context);
  99             case "indyWithConstants":
 100                 return new IndyConstants(context);
 101             default:
 102                 Assert.error("Unknown stringConcat: " + opt);
 103                 throw new IllegalStateException("Unknown stringConcat: " + opt);
 104         }
 105     }
 106 
 107     protected StringConcat(Context context) {
 108         context.put(concatKey, this);
 109         gen = Gen.instance(context);
 110         syms = Symtab.instance(context);
 111         types = Types.instance(context);
 112         names = Names.instance(context);
 113         make = TreeMaker.instance(context);
 114         rs = Resolve.instance(context);
 115         sbAppends = new HashMap<>();
 116     }
 117 
 118     public abstract Item makeConcat(JCTree.JCAssignOp tree);
 119     public abstract Item makeConcat(JCTree.JCBinary tree);
 120 
 121     protected List<JCTree> collectAll(JCTree tree) {
 122         return collect(tree, List.nil());
 123     }
 124 
 125     protected List<JCTree> collectAll(JCTree.JCExpression lhs, JCTree.JCExpression rhs) {
 126         return List.<JCTree>nil()
 127                 .appendList(collectAll(lhs))
 128                 .appendList(collectAll(rhs));
 129     }
 130 
 131     private List<JCTree> collect(JCTree tree, List<JCTree> res) {
 132         tree = TreeInfo.skipParens(tree);
 133         if (tree.hasTag(PLUS) && tree.type.constValue() == null) {
 134             JCTree.JCBinary op = (JCTree.JCBinary) tree;
 135             if (op.operator.kind == MTH && op.operator.opcode == string_add) {
 136                 return res
 137                         .appendList(collect(op.lhs, res))
 138                         .appendList(collect(op.rhs, res));
 139             }
 140         }
 141         return res.append(tree);
 142     }
 143 
 144     /**
 145      * If the type is not accessible from current context, try to figure out the
 146      * sharpest accessible supertype.
 147      *
 148      * @param originalType type to sharpen
 149      * @return sharped type
 150      */
 151     Type sharpestAccessible(Type originalType) {
 152         if (originalType.hasTag(ARRAY)) {
 153             return types.makeArrayType(sharpestAccessible(types.elemtype(originalType)));
 154         }
 155 
 156         Type type = originalType;
 157         while (!rs.isAccessible(gen.getAttrEnv(), type.asElement())) {
 158             type = types.supertype(type);
 159         }
 160         return type;
 161     }
 162 
 163     /**
 164      * "Legacy" bytecode flavor: emit the StringBuilder.append chains for string
 165      * concatenation.
 166      */
 167     private static class Inline extends StringConcat {
 168         public Inline(Context context) {
 169             super(context);
 170         }
 171 
 172         @Override
 173         public Item makeConcat(JCTree.JCAssignOp tree) {
 174             // Generate code to make a string builder
 175             JCDiagnostic.DiagnosticPosition pos = tree.pos();
 176 
 177             // Create a string builder.
 178             newStringBuilder(tree);
 179 
 180             // Generate code for first string, possibly save one
 181             // copy under builder
 182             Item l = gen.genExpr(tree.lhs, tree.lhs.type);
 183             if (l.width() > 0) {
 184                 gen.getCode().emitop0(dup_x1 + 3 * (l.width() - 1));
 185             }
 186 
 187             // Load first string and append to builder.
 188             l.load();
 189             appendString(tree.lhs);
 190 
 191             // Append all other strings to builder.
 192             List<JCTree> args = collectAll(tree.rhs);
 193             for (JCTree t : args) {
 194                 gen.genExpr(t, t.type).load();
 195                 appendString(t);
 196             }
 197 
 198             // Convert builder to string.
 199             builderToString(pos);
 200 
 201             return l;
 202         }
 203 
 204         @Override
 205         public Item makeConcat(JCTree.JCBinary tree) {
 206             JCDiagnostic.DiagnosticPosition pos = tree.pos();
 207 
 208             // Create a string builder.
 209             newStringBuilder(tree);
 210 
 211             // Append all strings to builder.
 212             List<JCTree> args = collectAll(tree);
 213             for (JCTree t : args) {
 214                 gen.genExpr(t, t.type).load();
 215                 appendString(t);
 216             }
 217 
 218             // Convert builder to string.
 219             builderToString(pos);
 220 
 221             return gen.getItems().makeStackItem(syms.stringType);
 222         }
 223 
 224         private JCDiagnostic.DiagnosticPosition newStringBuilder(JCTree tree) {
 225             JCDiagnostic.DiagnosticPosition pos = tree.pos();
 226             gen.getCode().emitop2(new_, gen.makeRef(pos, syms.stringBuilderType));
 227             gen.getCode().emitop0(dup);
 228             gen.callMethod(pos, syms.stringBuilderType, names.init, List.nil(), false);
 229             return pos;
 230         }
 231 
 232         private void appendString(JCTree tree) {
 233             Type t = tree.type.baseType();
 234             if (!t.isPrimitive() && t.tsym != syms.stringType.tsym) {
 235                 t = syms.objectType;
 236             }
 237 
 238             Assert.checkNull(t.constValue());
 239             Symbol method = sbAppends.get(t);
 240             if (method == null) {
 241                 method = rs.resolveInternalMethod(tree.pos(), gen.getAttrEnv(), syms.stringBuilderType, names.append, List.of(t), null);
 242                 sbAppends.put(t, method);
 243             }
 244 
 245             gen.getItems().makeMemberItem(method, false).invoke();
 246         }
 247 
 248         private void builderToString(JCDiagnostic.DiagnosticPosition pos) {
 249             gen.callMethod(pos, syms.stringBuilderType, names.toString, List.nil(), false);
 250         }
 251     }
 252 
 253     /**
 254      * Base class for indified concatenation bytecode flavors.
 255      */
 256     private static abstract class Indy extends StringConcat {
 257         public Indy(Context context) {
 258             super(context);
 259         }
 260 
 261         @Override
 262         public Item makeConcat(JCTree.JCAssignOp tree) {
 263             List<JCTree> args = collectAll(tree.lhs, tree.rhs);
 264             Item l = gen.genExpr(tree.lhs, tree.lhs.type);
 265             l.duplicate();
 266             l.load();
 267             emit(tree.pos(), args, false, tree.type);
 268             return l;
 269         }
 270 
 271         @Override
 272         public Item makeConcat(JCTree.JCBinary tree) {
 273             List<JCTree> args = collectAll(tree.lhs, tree.rhs);
 274             emit(tree.pos(), args, true, tree.type);
 275             return gen.getItems().makeStackItem(syms.stringType);
 276         }
 277 
 278         protected abstract void emit(JCDiagnostic.DiagnosticPosition pos, List<JCTree> args, boolean generateFirstArg, Type type);
 279 
 280         /** Peel the argument list into smaller chunks. */
 281         protected List<List<JCTree>> split(List<JCTree> args) {
 282             ListBuffer<List<JCTree>> splits = new ListBuffer<>();
 283 
 284             int slots = 0;
 285 
 286             // Need to peel, so that neither call has more than acceptable number
 287             // of slots for the arguments.
 288             ListBuffer<JCTree> cArgs = new ListBuffer<>();
 289             for (JCTree t : args) {
 290                 int needSlots = (t.type.getTag() == LONG || t.type.getTag() == DOUBLE) ? 2 : 1;
 291                 if (slots + needSlots >= MAX_INDY_CONCAT_ARG_SLOTS) {
 292                     splits.add(cArgs.toList());
 293                     cArgs.clear();
 294                     slots = 0;
 295                 }
 296                 cArgs.add(t);
 297                 slots += needSlots;
 298             }
 299 
 300             // Flush the tail slice
 301             if (!cArgs.isEmpty()) {
 302                 splits.add(cArgs.toList());
 303             }
 304 
 305             return splits.toList();
 306         }
 307     }
 308 
 309     /**
 310      * Emits the invokedynamic call to JDK java.lang.invoke.StringConcatFactory,
 311      * without handling constants specially.
 312      *
 313      * We bypass empty strings, because they have no meaning at this level. This
 314      * captures the Java language trick to force String concat with e.g. ("" + int)-like
 315      * expression. Down here, we already know we are in String concat business, and do
 316      * not require these markers.
 317      */
 318     private static class IndyPlain extends Indy {
 319         public IndyPlain(Context context) {
 320             super(context);
 321         }
 322 
 323         /** Emit the indy concat for all these arguments, possibly peeling along the way */
 324         protected void emit(JCDiagnostic.DiagnosticPosition pos, List<JCTree> args, boolean generateFirstArg, Type type) {
 325             List<List<JCTree>> split = split(args);
 326 
 327             boolean first = true;
 328             for (List<JCTree> t : split) {
 329                 Assert.check(!t.isEmpty(), "Arguments list is empty");
 330 
 331                 ListBuffer<Type> dynamicArgs = new ListBuffer<>();
 332                 for (JCTree arg : t) {
 333                     Object constVal = arg.type.constValue();
 334                     if ("".equals(constVal)) continue;
 335                     if (arg.type == syms.botType) {
 336                         dynamicArgs.add(types.boxedClass(syms.voidType).type);
 337                     } else {
 338                         dynamicArgs.add(sharpestAccessible(arg.type));
 339                     }
 340                     if (!first || generateFirstArg) {
 341                         gen.genExpr(arg, arg.type).load();
 342                     }
 343                     first = false;
 344                 }
 345                 doCall(type, pos, dynamicArgs.toList());
 346             }
 347 
 348             // More that one peel slice produced: concatenate the results
 349             if (split.size() > 1) {
 350                 ListBuffer<Type> argTypes = new ListBuffer<>();
 351                 for (int c = 0; c < split.size(); c++) {
 352                     argTypes.append(syms.stringType);
 353                 }
 354                 doCall(type, pos, argTypes.toList());
 355             }
 356         }
 357 
 358         /** Produce the actual invokedynamic call to StringConcatFactory */
 359         private void doCall(Type type, JCDiagnostic.DiagnosticPosition pos, List<Type> dynamicArgTypes) {
 360             Type.MethodType indyType = new Type.MethodType(dynamicArgTypes,
 361                     type,
 362                     List.nil(),
 363                     syms.methodClass);
 364 
 365             int prevPos = make.pos;
 366             try {
 367                 make.at(pos);
 368 
 369                 List<Type> bsm_staticArgs = List.of(syms.methodHandlesLookupType,
 370                         syms.stringType,
 371                         syms.methodTypeType);
 372 
 373                 Symbol bsm = rs.resolveInternalMethod(pos,
 374                         gen.getAttrEnv(),
 375                         syms.stringConcatFactory,
 376                         names.makeConcat,
 377                         bsm_staticArgs,
 378                         null);
 379 
 380                 Symbol.DynamicMethodSymbol dynSym = new Symbol.DynamicMethodSymbol(names.makeConcat,
 381                         syms.noSymbol,
 382                         ClassFile.REF_invokeStatic,
 383                         (Symbol.MethodSymbol)bsm,
 384                         indyType,
 385                         List.nil().toArray());
 386 
 387                 Items.Item item = gen.getItems().makeDynamicItem(dynSym);
 388                 item.invoke();
 389             } finally {
 390                 make.at(prevPos);
 391             }
 392         }
 393     }
 394 
 395     /**
 396      * Emits the invokedynamic call to JDK java.lang.invoke.StringConcatFactory.
 397      * This code concatenates all known constants into the recipe, possibly escaping
 398      * some constants separately.
 399      *
 400      * We also bypass empty strings, because they have no meaning at this level. This
 401      * captures the Java language trick to force String concat with e.g. ("" + int)-like
 402      * expression. Down here, we already know we are in String concat business, and do
 403      * not require these markers.
 404      */
 405     private static final class IndyConstants extends Indy {
 406         public IndyConstants(Context context) {
 407             super(context);
 408         }
 409 
 410         @Override
 411         protected void emit(JCDiagnostic.DiagnosticPosition pos, List<JCTree> args, boolean generateFirstArg, Type type) {
 412             List<List<JCTree>> split = split(args);
 413 
 414             boolean first = true;
 415             for (List<JCTree> t : split) {
 416                 Assert.check(!t.isEmpty(), "Arguments list is empty");
 417 
 418                 StringBuilder recipe = new StringBuilder(t.size());
 419                 ListBuffer<Type> dynamicArgs = new ListBuffer<>();
 420                 ListBuffer<Object> staticArgs = new ListBuffer<>();
 421 
 422                 for (JCTree arg : t) {
 423                     Object constVal = arg.type.constValue();
 424                     if ("".equals(constVal)) continue;
 425                     if (arg.type == syms.botType) {
 426                         // Concat the null into the recipe right away
 427                         recipe.append((String) null);
 428                     } else if (constVal != null) {
 429                         // Concat the String representation of the constant, except
 430                         // for the case it contains special tags, which requires us
 431                         // to expose it as detached constant.
 432                         String a = ConstFold.stringValue(arg.type.getTag(), arg.type.constValue());
 433                         if (a.indexOf(TAG_CONST) != -1 || a.indexOf(TAG_ARG) != -1) {
 434                             recipe.append(TAG_CONST);
 435                             staticArgs.add(a);
 436                         } else {
 437                             recipe.append(a);
 438                         }
 439                     } else {
 440                         // Ordinary arguments come through the dynamic arguments.
 441                         recipe.append(TAG_ARG);
 442                         dynamicArgs.add(sharpestAccessible(arg.type));
 443                         if (!first || generateFirstArg) {
 444                             gen.genExpr(arg, arg.type).load();
 445                         }
 446                         first = false;
 447                     }
 448                 }
 449 
 450                 doCall(type, pos, recipe.toString(), staticArgs.toList(), dynamicArgs.toList());
 451             }
 452 
 453             // More that one peel slice produced: concatenate the results
 454             // All arguments are assumed to be non-constant Strings.
 455             if (split.size() > 1) {
 456                 ListBuffer<Type> argTypes = new ListBuffer<>();
 457                 StringBuilder recipe = new StringBuilder();
 458                 for (int c = 0; c < split.size(); c++) {
 459                     argTypes.append(syms.stringType);
 460                     recipe.append(TAG_ARG);
 461                 }
 462                 doCall(type, pos, recipe.toString(), List.nil(), argTypes.toList());
 463             }
 464         }
 465 
 466         /** Produce the actual invokedynamic call to StringConcatFactory */
 467         private void doCall(Type type, JCDiagnostic.DiagnosticPosition pos, String recipe, List<Object> staticArgs, List<Type> dynamicArgTypes) {
 468             Type.MethodType indyType = new Type.MethodType(dynamicArgTypes,
 469                     type,
 470                     List.nil(),
 471                     syms.methodClass);
 472 
 473             int prevPos = make.pos;
 474             try {
 475                 make.at(pos);
 476 
 477                 ListBuffer<Type> constTypes = new ListBuffer<>();
 478                 ListBuffer<Object> constants = new ListBuffer<>();
 479                 for (Object t : staticArgs) {
 480                     constants.add(t);
 481                     constTypes.add(syms.stringType);
 482                 }
 483 
 484                 List<Type> bsm_staticArgs = List.of(syms.methodHandlesLookupType,
 485                         syms.stringType,
 486                         syms.methodTypeType)
 487                         .append(syms.stringType)
 488                         .appendList(constTypes);
 489 
 490                 Symbol bsm = rs.resolveInternalMethod(pos,
 491                         gen.getAttrEnv(),
 492                         syms.stringConcatFactory,
 493                         names.makeConcatWithConstants,
 494                         bsm_staticArgs,
 495                         null);
 496 
 497                 Symbol.DynamicMethodSymbol dynSym = new Symbol.DynamicMethodSymbol(names.makeConcatWithConstants,
 498                         syms.noSymbol,
 499                         ClassFile.REF_invokeStatic,
 500                         (Symbol.MethodSymbol)bsm,
 501                         indyType,
 502                         List.<Object>of(recipe).appendList(constants).toArray());
 503 
 504                 Items.Item item = gen.getItems().makeDynamicItem(dynSym);
 505                 item.invoke();
 506             } finally {
 507                 make.at(prevPos);
 508             }
 509         }
 510     }
 511 
 512 }