1 /* 2 * Copyright (c) 2016, 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 package org.graalvm.compiler.replacements.nodes; 24 25 import java.nio.ByteBuffer; 26 import java.nio.charset.Charset; 27 28 import org.graalvm.compiler.core.common.type.DataPointerConstant; 29 import org.graalvm.compiler.core.common.type.StampFactory; 30 import org.graalvm.compiler.graph.Node.ConstantNodeParameter; 31 import org.graalvm.compiler.graph.Node.NodeIntrinsic; 32 import org.graalvm.compiler.nodes.ConstantNode; 33 import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderContext; 34 import org.graalvm.compiler.word.Word; 35 36 import jdk.vm.ci.meta.JavaKind; 37 import jdk.vm.ci.meta.ResolvedJavaMethod; 38 39 /** 40 * Represents a compile-time constant zero-terminated UTF-8 string installed with the generated 41 * code. 42 */ 43 public final class CStringConstant extends DataPointerConstant { 44 45 private static final Charset UTF8 = Charset.forName("utf8"); 46 47 private final String string; 48 49 public CStringConstant(String string) { 50 super(1); 51 assert string != null; 52 this.string = string; 53 } 54 55 @Override 56 public int getSerializedSize() { 57 return string.getBytes(UTF8).length + 1; 58 } 59 60 @Override 61 public void serialize(ByteBuffer buffer) { 62 byte[] bytes = string.getBytes(UTF8); 63 buffer.put(bytes); 64 buffer.put((byte) 0); 65 } 66 67 @Override 68 public String toValueString() { 69 return "c\"" + string + "\""; 70 } 71 72 public static boolean intrinsify(GraphBuilderContext b, @SuppressWarnings("unused") ResolvedJavaMethod targetMethod, String string) { 73 b.addPush(JavaKind.Object, new ConstantNode(new CStringConstant(string), StampFactory.pointer())); 74 return true; 75 } 76 77 @NodeIntrinsic 78 public static native Word cstring(@ConstantNodeParameter String string); 79 }