1 /* 2 * Copyright (c) 2012, 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.hotspot.replacements; 24 25 import static jdk.vm.ci.hotspot.HotSpotJVMCIRuntimeProvider.getArrayBaseOffset; 26 import static jdk.vm.ci.hotspot.HotSpotMetaAccessProvider.computeArrayAllocationSize; 27 import static org.graalvm.compiler.core.common.GraalOptions.GeneratePIC; 28 import static org.graalvm.compiler.core.common.calc.UnsignedMath.belowThan; 29 import static org.graalvm.compiler.hotspot.GraalHotSpotVMConfig.INJECTED_VMCONFIG; 30 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.CLASS_ARRAY_KLASS_LOCATION; 31 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.HUB_WRITE_LOCATION; 32 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.MARK_WORD_LOCATION; 33 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.PROTOTYPE_MARK_WORD_LOCATION; 34 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.TLAB_END_LOCATION; 35 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.TLAB_TOP_LOCATION; 36 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.arrayKlassOffset; 37 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.arrayLengthOffset; 38 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.config; 39 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.initializeObjectHeader; 40 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.instanceHeaderSize; 41 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.isInstanceKlassFullyInitialized; 42 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.layoutHelperHeaderSizeMask; 43 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.layoutHelperHeaderSizeShift; 44 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.layoutHelperLog2ElementSizeMask; 45 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.layoutHelperLog2ElementSizeShift; 46 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.loadKlassFromObject; 47 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.prototypeMarkWordOffset; 48 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.readLayoutHelper; 49 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.readTlabEnd; 50 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.readTlabTop; 51 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.registerAsWord; 52 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.useBiasedLocking; 53 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.useTLAB; 54 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.verifyOop; 55 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.wordSize; 56 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.writeTlabTop; 57 import static org.graalvm.compiler.hotspot.replacements.HotspotSnippetsOptions.ProfileAllocations; 58 import static org.graalvm.compiler.hotspot.replacements.HotspotSnippetsOptions.ProfileAllocationsContext; 59 import static org.graalvm.compiler.nodes.PiArrayNode.piArrayCastToSnippetReplaceeStamp; 60 import static org.graalvm.compiler.nodes.PiNode.piCastToSnippetReplaceeStamp; 61 import static org.graalvm.compiler.nodes.extended.BranchProbabilityNode.FAST_PATH_PROBABILITY; 62 import static org.graalvm.compiler.nodes.extended.BranchProbabilityNode.FREQUENT_PROBABILITY; 63 import static org.graalvm.compiler.nodes.extended.BranchProbabilityNode.SLOW_PATH_PROBABILITY; 64 import static org.graalvm.compiler.nodes.extended.BranchProbabilityNode.probability; 65 import static org.graalvm.compiler.replacements.ReplacementsUtil.REPLACEMENTS_ASSERTIONS_ENABLED; 66 import static org.graalvm.compiler.replacements.ReplacementsUtil.staticAssert; 67 import static org.graalvm.compiler.replacements.SnippetTemplate.DEFAULT_REPLACER; 68 import static org.graalvm.compiler.replacements.nodes.CStringConstant.cstring; 69 import static org.graalvm.compiler.replacements.nodes.ExplodeLoopNode.explodeLoop; 70 71 import org.graalvm.compiler.api.replacements.Fold; 72 import org.graalvm.compiler.api.replacements.Snippet; 73 import org.graalvm.compiler.api.replacements.Snippet.ConstantParameter; 74 import org.graalvm.compiler.api.replacements.Snippet.VarargsParameter; 75 import org.graalvm.compiler.core.common.spi.ForeignCallDescriptor; 76 import org.graalvm.compiler.core.common.type.StampFactory; 77 import org.graalvm.compiler.debug.Debug; 78 import org.graalvm.compiler.debug.GraalError; 79 import org.graalvm.compiler.graph.Node.ConstantNodeParameter; 80 import org.graalvm.compiler.graph.Node.NodeIntrinsic; 81 import org.graalvm.compiler.hotspot.GraalHotSpotVMConfig; 82 import org.graalvm.compiler.hotspot.HotSpotBackend; 83 import org.graalvm.compiler.hotspot.meta.HotSpotProviders; 84 import org.graalvm.compiler.hotspot.meta.HotSpotRegistersProvider; 85 import org.graalvm.compiler.hotspot.nodes.DimensionsNode; 86 import org.graalvm.compiler.hotspot.nodes.aot.LoadConstantIndirectlyFixedNode; 87 import org.graalvm.compiler.hotspot.nodes.aot.LoadConstantIndirectlyNode; 88 import org.graalvm.compiler.hotspot.nodes.type.KlassPointerStamp; 89 import org.graalvm.compiler.hotspot.word.KlassPointer; 90 import org.graalvm.compiler.nodes.ConstantNode; 91 import org.graalvm.compiler.nodes.DeoptimizeNode; 92 import org.graalvm.compiler.nodes.PiNode; 93 import org.graalvm.compiler.nodes.PrefetchAllocateNode; 94 import org.graalvm.compiler.nodes.SnippetAnchorNode; 95 import org.graalvm.compiler.nodes.StructuredGraph; 96 import org.graalvm.compiler.nodes.ValueNode; 97 import org.graalvm.compiler.nodes.debug.DynamicCounterNode; 98 import org.graalvm.compiler.nodes.debug.VerifyHeapNode; 99 import org.graalvm.compiler.nodes.extended.ForeignCallNode; 100 import org.graalvm.compiler.nodes.extended.MembarNode; 101 import org.graalvm.compiler.nodes.java.DynamicNewArrayNode; 102 import org.graalvm.compiler.nodes.java.DynamicNewInstanceNode; 103 import org.graalvm.compiler.nodes.java.NewArrayNode; 104 import org.graalvm.compiler.nodes.java.NewInstanceNode; 105 import org.graalvm.compiler.nodes.java.NewMultiArrayNode; 106 import org.graalvm.compiler.nodes.memory.address.OffsetAddressNode; 107 import org.graalvm.compiler.nodes.spi.LoweringTool; 108 import org.graalvm.compiler.nodes.util.GraphUtil; 109 import org.graalvm.compiler.options.OptionValues; 110 import org.graalvm.compiler.replacements.ReplacementsUtil; 111 import org.graalvm.compiler.replacements.SnippetCounter; 112 import org.graalvm.compiler.replacements.SnippetCounter.Group; 113 import org.graalvm.compiler.replacements.SnippetTemplate; 114 import org.graalvm.compiler.replacements.SnippetTemplate.AbstractTemplates; 115 import org.graalvm.compiler.replacements.SnippetTemplate.Arguments; 116 import org.graalvm.compiler.replacements.SnippetTemplate.SnippetInfo; 117 import org.graalvm.compiler.replacements.Snippets; 118 import org.graalvm.compiler.replacements.nodes.ExplodeLoopNode; 119 import org.graalvm.compiler.word.Word; 120 import org.graalvm.word.LocationIdentity; 121 import org.graalvm.word.WordFactory; 122 123 import jdk.vm.ci.code.CodeUtil; 124 import jdk.vm.ci.code.MemoryBarriers; 125 import jdk.vm.ci.code.Register; 126 import jdk.vm.ci.code.TargetDescription; 127 import jdk.vm.ci.hotspot.HotSpotJVMCIRuntimeProvider; 128 import jdk.vm.ci.hotspot.HotSpotResolvedObjectType; 129 import jdk.vm.ci.meta.DeoptimizationAction; 130 import jdk.vm.ci.meta.DeoptimizationReason; 131 import jdk.vm.ci.meta.JavaKind; 132 import jdk.vm.ci.meta.ResolvedJavaType; 133 134 /** 135 * Snippets used for implementing NEW, ANEWARRAY and NEWARRAY. 136 */ 137 public class NewObjectSnippets implements Snippets { 138 139 enum ProfileContext { 140 AllocatingMethod, 141 InstanceOrArray, 142 AllocatedType, 143 AllocatedTypesInMethod, 144 Total 145 } 146 147 @Fold 148 static String createName(String path, String typeContext, OptionValues options) { 149 switch (ProfileAllocationsContext.getValue(options)) { 150 case AllocatingMethod: 151 return ""; 152 case InstanceOrArray: 153 return path; 154 case AllocatedType: 155 case AllocatedTypesInMethod: 156 return typeContext; 157 case Total: 158 return "bytes"; 159 default: 160 throw GraalError.shouldNotReachHere(); 161 } 162 } 163 164 @Fold 165 static boolean doProfile(OptionValues options) { 166 return ProfileAllocations.getValue(options); 167 } 168 169 @Fold 170 static boolean withContext(OptionValues options) { 171 ProfileContext context = ProfileAllocationsContext.getValue(options); 172 return context == ProfileContext.AllocatingMethod || context == ProfileContext.AllocatedTypesInMethod; 173 } 174 175 protected static void profileAllocation(String path, long size, String typeContext, OptionValues options) { 176 if (doProfile(options)) { 177 String name = createName(path, typeContext, options); 178 179 boolean context = withContext(options); 180 DynamicCounterNode.counter(name, "number of bytes allocated", size, context); 181 DynamicCounterNode.counter(name, "number of allocations", 1, context); 182 } 183 } 184 185 public static void emitPrefetchAllocate(Word address, boolean isArray) { 186 GraalHotSpotVMConfig config = config(INJECTED_VMCONFIG); 187 if (config.allocatePrefetchStyle > 0) { 188 // Insert a prefetch for each allocation only on the fast-path 189 // Generate several prefetch instructions. 190 int lines = isArray ? config.allocatePrefetchLines : config.allocateInstancePrefetchLines; 191 int stepSize = config.allocatePrefetchStepSize; 192 int distance = config.allocatePrefetchDistance; 193 ExplodeLoopNode.explodeLoop(); 194 for (int i = 0; i < lines; i++) { 195 PrefetchAllocateNode.prefetch(OffsetAddressNode.address(address, distance)); 196 distance += stepSize; 197 } 198 } 199 } 200 201 @Snippet 202 public static Object allocateInstance(@ConstantParameter int size, KlassPointer hub, Word prototypeMarkWord, @ConstantParameter boolean fillContents, 203 @ConstantParameter Register threadRegister, @ConstantParameter boolean constantSize, @ConstantParameter String typeContext, @ConstantParameter OptionValues options, 204 @ConstantParameter Counters counters) { 205 return piCastToSnippetReplaceeStamp(allocateInstanceHelper(size, hub, prototypeMarkWord, fillContents, threadRegister, constantSize, typeContext, options, counters)); 206 } 207 208 public static Object allocateInstanceHelper(int size, KlassPointer hub, Word prototypeMarkWord, boolean fillContents, 209 Register threadRegister, boolean constantSize, String typeContext, OptionValues options, Counters counters) { 210 Object result; 211 Word thread = registerAsWord(threadRegister); 212 Word top = readTlabTop(thread); 213 Word end = readTlabEnd(thread); 214 Word newTop = top.add(size); 215 if (useTLAB(INJECTED_VMCONFIG) && probability(FAST_PATH_PROBABILITY, newTop.belowOrEqual(end))) { 216 writeTlabTop(thread, newTop); 217 emitPrefetchAllocate(newTop, false); 218 result = formatObject(hub, size, top, prototypeMarkWord, fillContents, constantSize, counters); 219 } else { 220 if (counters != null && counters.stub != null) { 221 counters.stub.inc(); 222 } 223 result = newInstance(HotSpotBackend.NEW_INSTANCE, hub); 224 } 225 profileAllocation("instance", size, typeContext, options); 226 return verifyOop(result); 227 } 228 229 @NodeIntrinsic(value = ForeignCallNode.class, injectedStampIsNonNull = true) 230 public static native Object newInstance(@ConstantNodeParameter ForeignCallDescriptor descriptor, KlassPointer hub); 231 232 @Snippet 233 public static Object allocateInstancePIC(@ConstantParameter int size, KlassPointer hub, Word prototypeMarkWord, @ConstantParameter boolean fillContents, 234 @ConstantParameter Register threadRegister, @ConstantParameter boolean constantSize, @ConstantParameter String typeContext, @ConstantParameter OptionValues options, 235 @ConstantParameter Counters counters) { 236 // Klass must be initialized by the time the first instance is allocated, therefore we can 237 // just load it from the corresponding cell and avoid the resolution check. We have to use a 238 // fixed load though, to prevent it from floating above the initialization. 239 KlassPointer picHub = LoadConstantIndirectlyFixedNode.loadKlass(hub); 240 return piCastToSnippetReplaceeStamp(allocateInstanceHelper(size, picHub, prototypeMarkWord, fillContents, threadRegister, constantSize, typeContext, options, counters)); 241 } 242 243 @Snippet 244 public static Object allocateInstanceDynamic(Class<?> type, Class<?> classClass, @ConstantParameter boolean fillContents, @ConstantParameter Register threadRegister, 245 @ConstantParameter OptionValues options, @ConstantParameter Counters counters) { 246 if (probability(SLOW_PATH_PROBABILITY, type == null)) { 247 DeoptimizeNode.deopt(DeoptimizationAction.None, DeoptimizationReason.RuntimeConstraint); 248 } 249 Class<?> nonNullType = PiNode.piCastNonNullClass(type, SnippetAnchorNode.anchor()); 250 251 if (probability(SLOW_PATH_PROBABILITY, DynamicNewInstanceNode.throwsInstantiationException(type, classClass))) { 252 DeoptimizeNode.deopt(DeoptimizationAction.None, DeoptimizationReason.RuntimeConstraint); 253 } 254 255 return PiNode.piCastToSnippetReplaceeStamp(allocateInstanceDynamicHelper(type, fillContents, threadRegister, options, counters, nonNullType)); 256 } 257 258 private static Object allocateInstanceDynamicHelper(Class<?> type, boolean fillContents, Register threadRegister, OptionValues options, Counters counters, Class<?> nonNullType) { 259 KlassPointer hub = ClassGetHubNode.readClass(nonNullType); 260 if (probability(FAST_PATH_PROBABILITY, !hub.isNull())) { 261 KlassPointer nonNullHub = ClassGetHubNode.piCastNonNull(hub, SnippetAnchorNode.anchor()); 262 263 if (probability(FAST_PATH_PROBABILITY, isInstanceKlassFullyInitialized(nonNullHub))) { 264 int layoutHelper = readLayoutHelper(nonNullHub); 265 /* 266 * src/share/vm/oops/klass.hpp: For instances, layout helper is a positive number, 267 * the instance size. This size is already passed through align_object_size and 268 * scaled to bytes. The low order bit is set if instances of this class cannot be 269 * allocated using the fastpath. 270 */ 271 if (probability(FAST_PATH_PROBABILITY, (layoutHelper & 1) == 0)) { 272 Word prototypeMarkWord = nonNullHub.readWord(prototypeMarkWordOffset(INJECTED_VMCONFIG), PROTOTYPE_MARK_WORD_LOCATION); 273 /* 274 * FIXME(je,ds): we should actually pass typeContext instead of "" but late 275 * binding of parameters is not yet supported by the GraphBuilderPlugin system. 276 */ 277 return allocateInstanceHelper(layoutHelper, nonNullHub, prototypeMarkWord, fillContents, threadRegister, false, "", options, counters); 278 } 279 } 280 } 281 return dynamicNewInstanceStub(type); 282 } 283 284 /** 285 * Maximum array length for which fast path allocation is used. 286 */ 287 public static final int MAX_ARRAY_FAST_PATH_ALLOCATION_LENGTH = 0x00FFFFFF; 288 289 @Snippet 290 public static Object allocatePrimitiveArrayPIC(KlassPointer hub, int length, Word prototypeMarkWord, @ConstantParameter int headerSize, @ConstantParameter int log2ElementSize, 291 @ConstantParameter boolean fillContents, @ConstantParameter Register threadRegister, @ConstantParameter boolean maybeUnroll, @ConstantParameter String typeContext, 292 @ConstantParameter OptionValues options, @ConstantParameter Counters counters) { 293 // Primitive array types are eagerly pre-resolved. We can use a floating load. 294 KlassPointer picHub = LoadConstantIndirectlyNode.loadKlass(hub); 295 return allocateArrayImpl(picHub, length, prototypeMarkWord, headerSize, log2ElementSize, fillContents, threadRegister, maybeUnroll, typeContext, false, options, counters); 296 } 297 298 @Snippet 299 public static Object allocateArrayPIC(KlassPointer hub, int length, Word prototypeMarkWord, @ConstantParameter int headerSize, @ConstantParameter int log2ElementSize, 300 @ConstantParameter boolean fillContents, @ConstantParameter Register threadRegister, @ConstantParameter boolean maybeUnroll, @ConstantParameter String typeContext, 301 @ConstantParameter OptionValues options, @ConstantParameter Counters counters) { 302 // Array type would be resolved by dominating resolution. 303 KlassPointer picHub = LoadConstantIndirectlyFixedNode.loadKlass(hub); 304 return allocateArrayImpl(picHub, length, prototypeMarkWord, headerSize, log2ElementSize, fillContents, threadRegister, maybeUnroll, typeContext, false, options, counters); 305 } 306 307 @Snippet 308 public static Object allocateArray(KlassPointer hub, int length, Word prototypeMarkWord, @ConstantParameter int headerSize, @ConstantParameter int log2ElementSize, 309 @ConstantParameter boolean fillContents, @ConstantParameter Register threadRegister, @ConstantParameter boolean maybeUnroll, @ConstantParameter String typeContext, 310 @ConstantParameter OptionValues options, @ConstantParameter Counters counters) { 311 Object result = allocateArrayImpl(hub, length, prototypeMarkWord, headerSize, log2ElementSize, fillContents, threadRegister, maybeUnroll, typeContext, false, options, counters); 312 return piArrayCastToSnippetReplaceeStamp(verifyOop(result), length); 313 } 314 315 private static Object allocateArrayImpl(KlassPointer hub, int length, Word prototypeMarkWord, int headerSize, int log2ElementSize, boolean fillContents, Register threadRegister, 316 boolean maybeUnroll, String typeContext, boolean skipNegativeCheck, OptionValues options, Counters counters) { 317 Object result; 318 int alignment = wordSize(); 319 int allocationSize = computeArrayAllocationSize(length, alignment, headerSize, log2ElementSize); 320 Word thread = registerAsWord(threadRegister); 321 Word top = readTlabTop(thread); 322 Word end = readTlabEnd(thread); 323 Word newTop = top.add(allocationSize); 324 if (probability(FREQUENT_PROBABILITY, skipNegativeCheck || belowThan(length, MAX_ARRAY_FAST_PATH_ALLOCATION_LENGTH)) && useTLAB(INJECTED_VMCONFIG) && 325 probability(FAST_PATH_PROBABILITY, newTop.belowOrEqual(end))) { 326 writeTlabTop(thread, newTop); 327 emitPrefetchAllocate(newTop, true); 328 if (counters != null && counters.arrayLoopInit != null) { 329 counters.arrayLoopInit.inc(); 330 } 331 result = formatArray(hub, allocationSize, length, headerSize, top, prototypeMarkWord, fillContents, maybeUnroll, counters); 332 } else { 333 result = newArray(HotSpotBackend.NEW_ARRAY, hub, length, fillContents); 334 } 335 profileAllocation("array", allocationSize, typeContext, options); 336 return result; 337 } 338 339 @NodeIntrinsic(value = ForeignCallNode.class, injectedStampIsNonNull = true) 340 public static native Object newArray(@ConstantNodeParameter ForeignCallDescriptor descriptor, KlassPointer hub, int length, boolean fillContents); 341 342 public static final ForeignCallDescriptor DYNAMIC_NEW_ARRAY = new ForeignCallDescriptor("dynamic_new_array", Object.class, Class.class, int.class); 343 public static final ForeignCallDescriptor DYNAMIC_NEW_INSTANCE = new ForeignCallDescriptor("dynamic_new_instance", Object.class, Class.class); 344 345 @NodeIntrinsic(value = ForeignCallNode.class, injectedStampIsNonNull = true) 346 public static native Object dynamicNewArrayStub(@ConstantNodeParameter ForeignCallDescriptor descriptor, Class<?> elementType, int length); 347 348 public static Object dynamicNewInstanceStub(Class<?> elementType) { 349 return dynamicNewInstanceStubCall(DYNAMIC_NEW_INSTANCE, elementType); 350 } 351 352 @NodeIntrinsic(value = ForeignCallNode.class, injectedStampIsNonNull = true) 353 public static native Object dynamicNewInstanceStubCall(@ConstantNodeParameter ForeignCallDescriptor descriptor, Class<?> elementType); 354 355 @Snippet 356 public static Object allocateArrayDynamic(Class<?> elementType, Class<?> voidClass, int length, @ConstantParameter boolean fillContents, @ConstantParameter Register threadRegister, 357 @ConstantParameter JavaKind knownElementKind, @ConstantParameter int knownLayoutHelper, Word prototypeMarkWord, @ConstantParameter OptionValues options, 358 @ConstantParameter Counters counters) { 359 Object result = allocateArrayDynamicImpl(elementType, voidClass, length, fillContents, threadRegister, knownElementKind, knownLayoutHelper, prototypeMarkWord, options, counters); 360 return result; 361 } 362 363 private static Object allocateArrayDynamicImpl(Class<?> elementType, Class<?> voidClass, int length, boolean fillContents, Register threadRegister, JavaKind knownElementKind, 364 int knownLayoutHelper, Word prototypeMarkWord, OptionValues options, Counters counters) { 365 /* 366 * We only need the dynamic check for void when we have no static information from 367 * knownElementKind. 368 */ 369 staticAssert(knownElementKind != JavaKind.Void, "unsupported knownElementKind"); 370 if (knownElementKind == JavaKind.Illegal && probability(SLOW_PATH_PROBABILITY, elementType == null || DynamicNewArrayNode.throwsIllegalArgumentException(elementType, voidClass))) { 371 DeoptimizeNode.deopt(DeoptimizationAction.None, DeoptimizationReason.RuntimeConstraint); 372 } 373 374 KlassPointer klass = loadKlassFromObject(elementType, arrayKlassOffset(INJECTED_VMCONFIG), CLASS_ARRAY_KLASS_LOCATION); 375 if (klass.isNull()) { 376 DeoptimizeNode.deopt(DeoptimizationAction.None, DeoptimizationReason.RuntimeConstraint); 377 } 378 KlassPointer nonNullKlass = ClassGetHubNode.piCastNonNull(klass, SnippetAnchorNode.anchor()); 379 380 if (length < 0) { 381 DeoptimizeNode.deopt(DeoptimizationAction.None, DeoptimizationReason.RuntimeConstraint); 382 } 383 int layoutHelper = knownElementKind != JavaKind.Illegal ? knownLayoutHelper : readLayoutHelper(nonNullKlass); 384 //@formatter:off 385 // from src/share/vm/oops/klass.hpp: 386 // 387 // For arrays, layout helper is a negative number, containing four 388 // distinct bytes, as follows: 389 // MSB:[tag, hsz, ebt, log2(esz)]:LSB 390 // where: 391 // tag is 0x80 if the elements are oops, 0xC0 if non-oops 392 // hsz is array header size in bytes (i.e., offset of first element) 393 // ebt is the BasicType of the elements 394 // esz is the element size in bytes 395 //@formatter:on 396 397 int headerSize = (layoutHelper >> layoutHelperHeaderSizeShift(INJECTED_VMCONFIG)) & layoutHelperHeaderSizeMask(INJECTED_VMCONFIG); 398 int log2ElementSize = (layoutHelper >> layoutHelperLog2ElementSizeShift(INJECTED_VMCONFIG)) & layoutHelperLog2ElementSizeMask(INJECTED_VMCONFIG); 399 400 Object result = allocateArrayImpl(nonNullKlass, length, prototypeMarkWord, headerSize, log2ElementSize, fillContents, threadRegister, false, "dynamic type", true, options, counters); 401 return piArrayCastToSnippetReplaceeStamp(verifyOop(result), length); 402 } 403 404 /** 405 * Calls the runtime stub for implementing MULTIANEWARRAY. 406 */ 407 @Snippet 408 public static Object newmultiarray(KlassPointer hub, @ConstantParameter int rank, @VarargsParameter int[] dimensions) { 409 Word dims = DimensionsNode.allocaDimsArray(rank); 410 ExplodeLoopNode.explodeLoop(); 411 for (int i = 0; i < rank; i++) { 412 dims.writeInt(i * 4, dimensions[i], LocationIdentity.init()); 413 } 414 return newArrayCall(HotSpotBackend.NEW_MULTI_ARRAY, hub, rank, dims); 415 } 416 417 @Snippet 418 public static Object newmultiarrayPIC(KlassPointer hub, @ConstantParameter int rank, @VarargsParameter int[] dimensions) { 419 // Array type would be resolved by dominating resolution. 420 KlassPointer picHub = LoadConstantIndirectlyFixedNode.loadKlass(hub); 421 return newmultiarray(picHub, rank, dimensions); 422 } 423 424 @NodeIntrinsic(value = ForeignCallNode.class, injectedStampIsNonNull = true) 425 public static native Object newArrayCall(@ConstantNodeParameter ForeignCallDescriptor descriptor, KlassPointer hub, int rank, Word dims); 426 427 /** 428 * Maximum number of long stores to emit when zeroing an object with a constant size. Larger 429 * objects have their bodies initialized in a loop. 430 */ 431 private static final int MAX_UNROLLED_OBJECT_ZEROING_STORES = 8; 432 433 /** 434 * Zero uninitialized memory in a newly allocated object, unrolling as necessary and ensuring 435 * that stores are aligned. 436 * 437 * @param size number of bytes to zero 438 * @param memory beginning of object which is being zeroed 439 * @param constantSize is {@code size} known to be constant in the snippet 440 * @param startOffset offset to begin zeroing. May not be word aligned. 441 * @param manualUnroll maximally unroll zeroing 442 */ 443 private static void zeroMemory(int size, Word memory, boolean constantSize, int startOffset, boolean manualUnroll, Counters counters) { 444 fillMemory(0, size, memory, constantSize, startOffset, manualUnroll, counters); 445 } 446 447 private static void fillMemory(long value, int size, Word memory, boolean constantSize, int startOffset, boolean manualUnroll, Counters counters) { 448 ReplacementsUtil.runtimeAssert((size & 0x7) == 0, "unaligned object size"); 449 int offset = startOffset; 450 if ((offset & 0x7) != 0) { 451 memory.writeInt(offset, (int) value, LocationIdentity.init()); 452 offset += 4; 453 } 454 ReplacementsUtil.runtimeAssert((offset & 0x7) == 0, "unaligned offset"); 455 if (manualUnroll && ((size - offset) / 8) <= MAX_UNROLLED_OBJECT_ZEROING_STORES) { 456 ReplacementsUtil.staticAssert(!constantSize, "size shouldn't be constant at instantiation time"); 457 // This case handles arrays of constant length. Instead of having a snippet variant for 458 // each length, generate a chain of stores of maximum length. Once it's inlined the 459 // break statement will trim excess stores. 460 if (counters != null && counters.instanceSeqInit != null) { 461 counters.instanceSeqInit.inc(); 462 } 463 464 explodeLoop(); 465 for (int i = 0; i < MAX_UNROLLED_OBJECT_ZEROING_STORES; i++, offset += 8) { 466 if (offset == size) { 467 break; 468 } 469 memory.initializeLong(offset, value, LocationIdentity.init()); 470 } 471 } else { 472 // Use Word instead of int to avoid extension to long in generated code 473 Word off = WordFactory.signed(offset); 474 if (constantSize && ((size - offset) / 8) <= MAX_UNROLLED_OBJECT_ZEROING_STORES) { 475 if (counters != null && counters.instanceSeqInit != null) { 476 counters.instanceSeqInit.inc(); 477 } 478 explodeLoop(); 479 } else { 480 if (counters != null && counters.instanceLoopInit != null) { 481 counters.instanceLoopInit.inc(); 482 } 483 } 484 for (; off.rawValue() < size; off = off.add(8)) { 485 memory.initializeLong(off, value, LocationIdentity.init()); 486 } 487 } 488 } 489 490 /** 491 * Fill uninitialized memory with garbage value in a newly allocated object, unrolling as 492 * necessary and ensuring that stores are aligned. 493 * 494 * @param size number of bytes to zero 495 * @param memory beginning of object which is being zeroed 496 * @param constantSize is {@code size} known to be constant in the snippet 497 * @param startOffset offset to begin zeroing. May not be word aligned. 498 * @param manualUnroll maximally unroll zeroing 499 */ 500 private static void fillWithGarbage(int size, Word memory, boolean constantSize, int startOffset, boolean manualUnroll, Counters counters) { 501 fillMemory(0xfefefefefefefefeL, size, memory, constantSize, startOffset, manualUnroll, counters); 502 } 503 504 /** 505 * Formats some allocated memory with an object header and zeroes out the rest. Disables asserts 506 * since they can't be compiled in stubs. 507 */ 508 public static Object formatObjectForStub(KlassPointer hub, int size, Word memory, Word compileTimePrototypeMarkWord) { 509 return formatObject(hub, size, memory, compileTimePrototypeMarkWord, true, false, null); 510 } 511 512 /** 513 * Formats some allocated memory with an object header and zeroes out the rest. 514 */ 515 protected static Object formatObject(KlassPointer hub, int size, Word memory, Word compileTimePrototypeMarkWord, boolean fillContents, boolean constantSize, Counters counters) { 516 Word prototypeMarkWord = useBiasedLocking(INJECTED_VMCONFIG) ? hub.readWord(prototypeMarkWordOffset(INJECTED_VMCONFIG), PROTOTYPE_MARK_WORD_LOCATION) : compileTimePrototypeMarkWord; 517 initializeObjectHeader(memory, prototypeMarkWord, hub); 518 if (fillContents) { 519 zeroMemory(size, memory, constantSize, instanceHeaderSize(INJECTED_VMCONFIG), false, counters); 520 } else if (REPLACEMENTS_ASSERTIONS_ENABLED) { 521 fillWithGarbage(size, memory, constantSize, instanceHeaderSize(INJECTED_VMCONFIG), false, counters); 522 } 523 MembarNode.memoryBarrier(MemoryBarriers.STORE_STORE, LocationIdentity.init()); 524 return memory.toObjectNonNull(); 525 } 526 527 @Snippet 528 protected static void verifyHeap(@ConstantParameter Register threadRegister) { 529 Word thread = registerAsWord(threadRegister); 530 Word topValue = readTlabTop(thread); 531 if (!topValue.equal(WordFactory.zero())) { 532 Word topValueContents = topValue.readWord(0, MARK_WORD_LOCATION); 533 if (topValueContents.equal(WordFactory.zero())) { 534 AssertionSnippets.vmMessageC(AssertionSnippets.ASSERTION_VM_MESSAGE_C, true, cstring("overzeroing of TLAB detected"), 0L, 0L, 0L); 535 } 536 } 537 } 538 539 /** 540 * Formats some allocated memory with an object header and zeroes out the rest. 541 */ 542 public static Object formatArray(KlassPointer hub, int allocationSize, int length, int headerSize, Word memory, Word prototypeMarkWord, boolean fillContents, boolean maybeUnroll, 543 Counters counters) { 544 memory.writeInt(arrayLengthOffset(INJECTED_VMCONFIG), length, LocationIdentity.init()); 545 /* 546 * store hub last as the concurrent garbage collectors assume length is valid if hub field 547 * is not null 548 */ 549 initializeObjectHeader(memory, prototypeMarkWord, hub); 550 if (fillContents) { 551 zeroMemory(allocationSize, memory, false, headerSize, maybeUnroll, counters); 552 } else if (REPLACEMENTS_ASSERTIONS_ENABLED) { 553 fillWithGarbage(allocationSize, memory, false, headerSize, maybeUnroll, counters); 554 } 555 MembarNode.memoryBarrier(MemoryBarriers.STORE_STORE, LocationIdentity.init()); 556 return memory.toObjectNonNull(); 557 } 558 559 static class Counters { 560 Counters(SnippetCounter.Group.Factory factory) { 561 Group newInstance = factory.createSnippetCounterGroup("NewInstance"); 562 Group newArray = factory.createSnippetCounterGroup("NewArray"); 563 instanceSeqInit = new SnippetCounter(newInstance, "tlabSeqInit", "TLAB alloc with unrolled zeroing"); 564 instanceLoopInit = new SnippetCounter(newInstance, "tlabLoopInit", "TLAB alloc with zeroing in a loop"); 565 arrayLoopInit = new SnippetCounter(newArray, "tlabLoopInit", "TLAB alloc with zeroing in a loop"); 566 stub = new SnippetCounter(newInstance, "stub", "alloc and zeroing via stub"); 567 } 568 569 final SnippetCounter instanceSeqInit; 570 final SnippetCounter instanceLoopInit; 571 final SnippetCounter arrayLoopInit; 572 final SnippetCounter stub; 573 } 574 575 public static class Templates extends AbstractTemplates { 576 577 private final SnippetInfo allocateInstance = snippet(NewObjectSnippets.class, "allocateInstance", MARK_WORD_LOCATION, HUB_WRITE_LOCATION, TLAB_TOP_LOCATION, TLAB_END_LOCATION); 578 private final SnippetInfo allocateInstancePIC = snippet(NewObjectSnippets.class, "allocateInstancePIC", MARK_WORD_LOCATION, HUB_WRITE_LOCATION, TLAB_TOP_LOCATION, 579 TLAB_END_LOCATION); 580 private final SnippetInfo allocateArray = snippet(NewObjectSnippets.class, "allocateArray", MARK_WORD_LOCATION, HUB_WRITE_LOCATION, TLAB_TOP_LOCATION, TLAB_END_LOCATION); 581 private final SnippetInfo allocateArrayPIC = snippet(NewObjectSnippets.class, "allocateArrayPIC", MARK_WORD_LOCATION, HUB_WRITE_LOCATION, TLAB_TOP_LOCATION, TLAB_END_LOCATION); 582 private final SnippetInfo allocatePrimitiveArrayPIC = snippet(NewObjectSnippets.class, "allocatePrimitiveArrayPIC", MARK_WORD_LOCATION, HUB_WRITE_LOCATION, TLAB_TOP_LOCATION, 583 TLAB_END_LOCATION); 584 private final SnippetInfo allocateArrayDynamic = snippet(NewObjectSnippets.class, "allocateArrayDynamic", MARK_WORD_LOCATION, HUB_WRITE_LOCATION, TLAB_TOP_LOCATION, 585 TLAB_END_LOCATION); 586 private final SnippetInfo allocateInstanceDynamic = snippet(NewObjectSnippets.class, "allocateInstanceDynamic", MARK_WORD_LOCATION, HUB_WRITE_LOCATION, TLAB_TOP_LOCATION, 587 TLAB_END_LOCATION); 588 private final SnippetInfo newmultiarray = snippet(NewObjectSnippets.class, "newmultiarray", TLAB_TOP_LOCATION, TLAB_END_LOCATION); 589 private final SnippetInfo newmultiarrayPIC = snippet(NewObjectSnippets.class, "newmultiarrayPIC", TLAB_TOP_LOCATION, TLAB_END_LOCATION); 590 private final SnippetInfo verifyHeap = snippet(NewObjectSnippets.class, "verifyHeap"); 591 private final GraalHotSpotVMConfig config; 592 private final Counters counters; 593 594 public Templates(OptionValues options, SnippetCounter.Group.Factory factory, HotSpotProviders providers, TargetDescription target, GraalHotSpotVMConfig config) { 595 super(options, providers, providers.getSnippetReflection(), target); 596 this.config = config; 597 counters = new Counters(factory); 598 } 599 600 /** 601 * Lowers a {@link NewInstanceNode}. 602 */ 603 public void lower(NewInstanceNode newInstanceNode, HotSpotRegistersProvider registers, LoweringTool tool) { 604 StructuredGraph graph = newInstanceNode.graph(); 605 HotSpotResolvedObjectType type = (HotSpotResolvedObjectType) newInstanceNode.instanceClass(); 606 assert !type.isArray(); 607 ConstantNode hub = ConstantNode.forConstant(KlassPointerStamp.klassNonNull(), type.klass(), providers.getMetaAccess(), graph); 608 int size = instanceSize(type); 609 610 OptionValues localOptions = graph.getOptions(); 611 SnippetInfo snippet = GeneratePIC.getValue(localOptions) ? allocateInstancePIC : allocateInstance; 612 Arguments args = new Arguments(snippet, graph.getGuardsStage(), tool.getLoweringStage()); 613 args.addConst("size", size); 614 args.add("hub", hub); 615 args.add("prototypeMarkWord", type.prototypeMarkWord()); 616 args.addConst("fillContents", newInstanceNode.fillContents()); 617 args.addConst("threadRegister", registers.getThreadRegister()); 618 args.addConst("constantSize", true); 619 args.addConst("typeContext", ProfileAllocations.getValue(localOptions) ? type.toJavaName(false) : ""); 620 args.addConst("options", localOptions); 621 args.addConst("counters", counters); 622 623 SnippetTemplate template = template(args); 624 Debug.log("Lowering allocateInstance in %s: node=%s, template=%s, arguments=%s", graph, newInstanceNode, template, args); 625 template.instantiate(providers.getMetaAccess(), newInstanceNode, DEFAULT_REPLACER, args); 626 } 627 628 /** 629 * Lowers a {@link NewArrayNode}. 630 */ 631 public void lower(NewArrayNode newArrayNode, HotSpotRegistersProvider registers, LoweringTool tool) { 632 StructuredGraph graph = newArrayNode.graph(); 633 ResolvedJavaType elementType = newArrayNode.elementType(); 634 HotSpotResolvedObjectType arrayType = (HotSpotResolvedObjectType) elementType.getArrayClass(); 635 JavaKind elementKind = elementType.getJavaKind(); 636 ConstantNode hub = ConstantNode.forConstant(KlassPointerStamp.klassNonNull(), arrayType.klass(), providers.getMetaAccess(), graph); 637 final int headerSize = getArrayBaseOffset(elementKind); 638 int log2ElementSize = CodeUtil.log2(HotSpotJVMCIRuntimeProvider.getArrayIndexScale(elementKind)); 639 640 OptionValues localOptions = graph.getOptions(); 641 SnippetInfo snippet; 642 if (GeneratePIC.getValue(localOptions)) { 643 if (elementType.isPrimitive()) { 644 snippet = allocatePrimitiveArrayPIC; 645 } else { 646 snippet = allocateArrayPIC; 647 } 648 } else { 649 snippet = allocateArray; 650 } 651 652 Arguments args = new Arguments(snippet, graph.getGuardsStage(), tool.getLoweringStage()); 653 args.add("hub", hub); 654 ValueNode length = newArrayNode.length(); 655 args.add("length", length.isAlive() ? length : graph.addOrUniqueWithInputs(length)); 656 assert arrayType.prototypeMarkWord() == lookupArrayClass(tool, JavaKind.Object).prototypeMarkWord() : "all array types are assumed to have the same prototypeMarkWord"; 657 args.add("prototypeMarkWord", arrayType.prototypeMarkWord()); 658 args.addConst("headerSize", headerSize); 659 args.addConst("log2ElementSize", log2ElementSize); 660 args.addConst("fillContents", newArrayNode.fillContents()); 661 args.addConst("threadRegister", registers.getThreadRegister()); 662 args.addConst("maybeUnroll", length.isConstant()); 663 args.addConst("typeContext", ProfileAllocations.getValue(localOptions) ? arrayType.toJavaName(false) : ""); 664 args.addConst("options", localOptions); 665 args.addConst("counters", counters); 666 SnippetTemplate template = template(args); 667 Debug.log("Lowering allocateArray in %s: node=%s, template=%s, arguments=%s", graph, newArrayNode, template, args); 668 template.instantiate(providers.getMetaAccess(), newArrayNode, DEFAULT_REPLACER, args); 669 } 670 671 public void lower(DynamicNewInstanceNode newInstanceNode, HotSpotRegistersProvider registers, LoweringTool tool) { 672 Arguments args = new Arguments(allocateInstanceDynamic, newInstanceNode.graph().getGuardsStage(), tool.getLoweringStage()); 673 OptionValues localOptions = newInstanceNode.getOptions(); 674 args.add("type", newInstanceNode.getInstanceType()); 675 ValueNode classClass = newInstanceNode.getClassClass(); 676 assert classClass != null; 677 args.add("classClass", classClass); 678 args.addConst("fillContents", newInstanceNode.fillContents()); 679 args.addConst("threadRegister", registers.getThreadRegister()); 680 args.addConst("options", localOptions); 681 args.addConst("counters", counters); 682 683 SnippetTemplate template = template(args); 684 template.instantiate(providers.getMetaAccess(), newInstanceNode, DEFAULT_REPLACER, args); 685 } 686 687 public void lower(DynamicNewArrayNode newArrayNode, HotSpotRegistersProvider registers, LoweringTool tool) { 688 StructuredGraph graph = newArrayNode.graph(); 689 OptionValues localOptions = graph.getOptions(); 690 Arguments args = new Arguments(allocateArrayDynamic, newArrayNode.graph().getGuardsStage(), tool.getLoweringStage()); 691 args.add("elementType", newArrayNode.getElementType()); 692 ValueNode voidClass = newArrayNode.getVoidClass(); 693 assert voidClass != null; 694 args.add("voidClass", voidClass); 695 ValueNode length = newArrayNode.length(); 696 args.add("length", length.isAlive() ? length : graph.addOrUniqueWithInputs(length)); 697 args.addConst("fillContents", newArrayNode.fillContents()); 698 args.addConst("threadRegister", registers.getThreadRegister()); 699 /* 700 * We use Kind.Illegal as a marker value instead of null because constant snippet 701 * parameters cannot be null. 702 */ 703 args.addConst("knownElementKind", newArrayNode.getKnownElementKind() == null ? JavaKind.Illegal : newArrayNode.getKnownElementKind()); 704 if (newArrayNode.getKnownElementKind() != null) { 705 args.addConst("knownLayoutHelper", lookupArrayClass(tool, newArrayNode.getKnownElementKind()).layoutHelper()); 706 } else { 707 args.addConst("knownLayoutHelper", 0); 708 } 709 args.add("prototypeMarkWord", lookupArrayClass(tool, JavaKind.Object).prototypeMarkWord()); 710 args.addConst("options", localOptions); 711 args.addConst("counters", counters); 712 SnippetTemplate template = template(args); 713 template.instantiate(providers.getMetaAccess(), newArrayNode, DEFAULT_REPLACER, args); 714 } 715 716 private static HotSpotResolvedObjectType lookupArrayClass(LoweringTool tool, JavaKind kind) { 717 return (HotSpotResolvedObjectType) tool.getMetaAccess().lookupJavaType(kind == JavaKind.Object ? Object.class : kind.toJavaClass()).getArrayClass(); 718 } 719 720 public void lower(NewMultiArrayNode newmultiarrayNode, LoweringTool tool) { 721 StructuredGraph graph = newmultiarrayNode.graph(); 722 OptionValues localOptions = graph.getOptions(); 723 int rank = newmultiarrayNode.dimensionCount(); 724 ValueNode[] dims = new ValueNode[rank]; 725 for (int i = 0; i < newmultiarrayNode.dimensionCount(); i++) { 726 dims[i] = newmultiarrayNode.dimension(i); 727 } 728 HotSpotResolvedObjectType type = (HotSpotResolvedObjectType) newmultiarrayNode.type(); 729 ConstantNode hub = ConstantNode.forConstant(KlassPointerStamp.klassNonNull(), type.klass(), providers.getMetaAccess(), graph); 730 731 SnippetInfo snippet = GeneratePIC.getValue(localOptions) ? newmultiarrayPIC : newmultiarray; 732 Arguments args = new Arguments(snippet, graph.getGuardsStage(), tool.getLoweringStage()); 733 args.add("hub", hub); 734 args.addConst("rank", rank); 735 args.addVarargs("dimensions", int.class, StampFactory.forKind(JavaKind.Int), dims); 736 template(args).instantiate(providers.getMetaAccess(), newmultiarrayNode, DEFAULT_REPLACER, args); 737 } 738 739 private static int instanceSize(HotSpotResolvedObjectType type) { 740 int size = type.instanceSize(); 741 assert size >= 0; 742 return size; 743 } 744 745 public void lower(VerifyHeapNode verifyHeapNode, HotSpotRegistersProvider registers, LoweringTool tool) { 746 if (config.cAssertions) { 747 Arguments args = new Arguments(verifyHeap, verifyHeapNode.graph().getGuardsStage(), tool.getLoweringStage()); 748 args.addConst("threadRegister", registers.getThreadRegister()); 749 750 SnippetTemplate template = template(args); 751 template.instantiate(providers.getMetaAccess(), verifyHeapNode, DEFAULT_REPLACER, args); 752 } else { 753 GraphUtil.removeFixedWithUnusedInputs(verifyHeapNode); 754 } 755 } 756 } 757 }