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 24 25 package org.graalvm.compiler.hotspot.replacements; 26 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.arrayAllocationSize; 37 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.arrayKlassOffset; 38 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.arrayLengthOffset; 39 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.config; 40 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.initializeObjectHeader; 41 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.instanceHeaderSize; 42 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.isInstanceKlassFullyInitialized; 43 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.layoutHelperHeaderSizeMask; 44 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.layoutHelperHeaderSizeShift; 45 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.layoutHelperLog2ElementSizeMask; 46 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.layoutHelperLog2ElementSizeShift; 47 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.loadKlassFromObject; 48 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.prototypeMarkWordOffset; 49 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.readLayoutHelper; 50 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.readTlabEnd; 51 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.readTlabTop; 52 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.registerAsWord; 53 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.useBiasedLocking; 54 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.useTLAB; 55 import static org.graalvm.compiler.hotspot.replacements.HotSpotReplacementsUtil.verifyOop; 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.runtimeAssert; 67 import static org.graalvm.compiler.replacements.ReplacementsUtil.staticAssert; 68 import static org.graalvm.compiler.replacements.SnippetTemplate.DEFAULT_REPLACER; 69 import static org.graalvm.compiler.replacements.nodes.CStringConstant.cstring; 70 import static org.graalvm.compiler.replacements.nodes.ExplodeLoopNode.explodeLoop; 71 72 import org.graalvm.compiler.api.replacements.Fold; 73 import org.graalvm.compiler.api.replacements.Snippet; 74 import org.graalvm.compiler.api.replacements.Snippet.ConstantParameter; 75 import org.graalvm.compiler.api.replacements.Snippet.VarargsParameter; 76 import org.graalvm.compiler.core.common.spi.ForeignCallDescriptor; 77 import org.graalvm.compiler.core.common.type.StampFactory; 78 import org.graalvm.compiler.debug.DebugHandlersFactory; 79 import org.graalvm.compiler.debug.GraalError; 80 import org.graalvm.compiler.graph.Node.ConstantNodeParameter; 81 import org.graalvm.compiler.graph.Node.NodeIntrinsic; 82 import org.graalvm.compiler.hotspot.GraalHotSpotVMConfig; 83 import org.graalvm.compiler.hotspot.HotSpotBackend; 84 import org.graalvm.compiler.hotspot.meta.HotSpotProviders; 85 import org.graalvm.compiler.hotspot.meta.HotSpotRegistersProvider; 86 import org.graalvm.compiler.hotspot.nodes.DimensionsNode; 87 import org.graalvm.compiler.hotspot.nodes.aot.LoadConstantIndirectlyFixedNode; 88 import org.graalvm.compiler.hotspot.nodes.aot.LoadConstantIndirectlyNode; 89 import org.graalvm.compiler.hotspot.nodes.type.KlassPointerStamp; 90 import org.graalvm.compiler.hotspot.word.KlassPointer; 91 import org.graalvm.compiler.nodes.ConstantNode; 92 import org.graalvm.compiler.nodes.DeoptimizeNode; 93 import org.graalvm.compiler.nodes.PiNode; 94 import org.graalvm.compiler.nodes.PrefetchAllocateNode; 95 import org.graalvm.compiler.nodes.SnippetAnchorNode; 96 import org.graalvm.compiler.nodes.StructuredGraph; 97 import org.graalvm.compiler.nodes.ValueNode; 98 import org.graalvm.compiler.nodes.debug.DynamicCounterNode; 99 import org.graalvm.compiler.nodes.debug.VerifyHeapNode; 100 import org.graalvm.compiler.nodes.extended.ForeignCallNode; 101 import org.graalvm.compiler.nodes.extended.MembarNode; 102 import org.graalvm.compiler.nodes.java.DynamicNewArrayNode; 103 import org.graalvm.compiler.nodes.java.DynamicNewInstanceNode; 104 import org.graalvm.compiler.nodes.java.NewArrayNode; 105 import org.graalvm.compiler.nodes.java.NewInstanceNode; 106 import org.graalvm.compiler.nodes.java.NewMultiArrayNode; 107 import org.graalvm.compiler.nodes.memory.address.OffsetAddressNode; 108 import org.graalvm.compiler.nodes.spi.LoweringTool; 109 import org.graalvm.compiler.nodes.util.GraphUtil; 110 import org.graalvm.compiler.options.OptionValues; 111 import org.graalvm.compiler.replacements.ReplacementsUtil; 112 import org.graalvm.compiler.replacements.SnippetCounter; 113 import org.graalvm.compiler.replacements.SnippetCounter.Group; 114 import org.graalvm.compiler.replacements.SnippetTemplate; 115 import org.graalvm.compiler.replacements.SnippetTemplate.AbstractTemplates; 116 import org.graalvm.compiler.replacements.SnippetTemplate.Arguments; 117 import org.graalvm.compiler.replacements.SnippetTemplate.SnippetInfo; 118 import org.graalvm.compiler.replacements.Snippets; 119 import org.graalvm.compiler.replacements.nodes.ExplodeLoopNode; 120 import org.graalvm.compiler.word.Word; 121 import jdk.internal.vm.compiler.word.LocationIdentity; 122 import jdk.internal.vm.compiler.word.WordFactory; 123 124 import jdk.vm.ci.code.CodeUtil; 125 import jdk.vm.ci.code.MemoryBarriers; 126 import jdk.vm.ci.code.Register; 127 import jdk.vm.ci.code.TargetDescription; 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("number of bytes allocated", name, size, context); 181 DynamicCounterNode.counter("number of allocations", name, 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 } else { 280 DeoptimizeNode.deopt(DeoptimizationAction.None, DeoptimizationReason.RuntimeConstraint); 281 } 282 } 283 return dynamicNewInstanceStub(type); 284 } 285 286 /** 287 * Maximum array length for which fast path allocation is used. 288 */ 289 public static final int MAX_ARRAY_FAST_PATH_ALLOCATION_LENGTH = 0x00FFFFFF; 290 291 @Snippet 292 public static Object allocatePrimitiveArrayPIC(KlassPointer hub, int length, Word prototypeMarkWord, @ConstantParameter int headerSize, @ConstantParameter int log2ElementSize, 293 @ConstantParameter boolean fillContents, @ConstantParameter Register threadRegister, @ConstantParameter boolean maybeUnroll, @ConstantParameter String typeContext, 294 @ConstantParameter OptionValues options, @ConstantParameter Counters counters) { 295 // Primitive array types are eagerly pre-resolved. We can use a floating load. 296 KlassPointer picHub = LoadConstantIndirectlyNode.loadKlass(hub); 297 return allocateArrayImpl(picHub, length, prototypeMarkWord, headerSize, log2ElementSize, fillContents, threadRegister, maybeUnroll, typeContext, false, options, counters); 298 } 299 300 @Snippet 301 public static Object allocateArrayPIC(KlassPointer hub, int length, Word prototypeMarkWord, @ConstantParameter int headerSize, @ConstantParameter int log2ElementSize, 302 @ConstantParameter boolean fillContents, @ConstantParameter Register threadRegister, @ConstantParameter boolean maybeUnroll, @ConstantParameter String typeContext, 303 @ConstantParameter OptionValues options, @ConstantParameter Counters counters) { 304 // Array type would be resolved by dominating resolution. 305 KlassPointer picHub = LoadConstantIndirectlyFixedNode.loadKlass(hub); 306 return allocateArrayImpl(picHub, length, prototypeMarkWord, headerSize, log2ElementSize, fillContents, threadRegister, maybeUnroll, typeContext, false, options, counters); 307 } 308 309 @Snippet 310 public static Object allocateArray(KlassPointer hub, int length, Word prototypeMarkWord, @ConstantParameter int headerSize, @ConstantParameter int log2ElementSize, 311 @ConstantParameter boolean fillContents, @ConstantParameter Register threadRegister, @ConstantParameter boolean maybeUnroll, @ConstantParameter String typeContext, 312 @ConstantParameter OptionValues options, @ConstantParameter Counters counters) { 313 Object result = allocateArrayImpl(hub, length, prototypeMarkWord, headerSize, log2ElementSize, fillContents, threadRegister, maybeUnroll, typeContext, false, options, counters); 314 return piArrayCastToSnippetReplaceeStamp(verifyOop(result), length); 315 } 316 317 private static Object allocateArrayImpl(KlassPointer hub, int length, Word prototypeMarkWord, int headerSize, int log2ElementSize, boolean fillContents, Register threadRegister, 318 boolean maybeUnroll, String typeContext, boolean skipNegativeCheck, OptionValues options, Counters counters) { 319 Object result; 320 int allocationSize = arrayAllocationSize(length, headerSize, log2ElementSize); 321 Word thread = registerAsWord(threadRegister); 322 Word top = readTlabTop(thread); 323 Word end = readTlabEnd(thread); 324 Word newTop = top.add(allocationSize); 325 if (probability(FREQUENT_PROBABILITY, skipNegativeCheck || belowThan(length, MAX_ARRAY_FAST_PATH_ALLOCATION_LENGTH)) && useTLAB(INJECTED_VMCONFIG) && 326 probability(FAST_PATH_PROBABILITY, newTop.belowOrEqual(end))) { 327 writeTlabTop(thread, newTop); 328 emitPrefetchAllocate(newTop, true); 329 if (counters != null && counters.arrayLoopInit != null) { 330 counters.arrayLoopInit.inc(); 331 } 332 result = formatArray(hub, allocationSize, length, headerSize, top, prototypeMarkWord, fillContents, maybeUnroll, counters); 333 } else { 334 result = newArray(HotSpotBackend.NEW_ARRAY, hub, length); 335 } 336 profileAllocation("array", allocationSize, typeContext, options); 337 return result; 338 } 339 340 @NodeIntrinsic(value = ForeignCallNode.class, injectedStampIsNonNull = true) 341 public static native Object newArray(@ConstantNodeParameter ForeignCallDescriptor descriptor, KlassPointer hub, int length); 342 343 public static final ForeignCallDescriptor DYNAMIC_NEW_ARRAY = new ForeignCallDescriptor("dynamic_new_array", Object.class, Class.class, int.class); 344 public static final ForeignCallDescriptor DYNAMIC_NEW_INSTANCE = new ForeignCallDescriptor("dynamic_new_instance", Object.class, Class.class); 345 346 @NodeIntrinsic(value = ForeignCallNode.class, injectedStampIsNonNull = true) 347 public static native Object dynamicNewArrayStub(@ConstantNodeParameter ForeignCallDescriptor descriptor, Class<?> elementType, int length); 348 349 public static Object dynamicNewInstanceStub(Class<?> elementType) { 350 return dynamicNewInstanceStubCall(DYNAMIC_NEW_INSTANCE, elementType); 351 } 352 353 @NodeIntrinsic(value = ForeignCallNode.class, injectedStampIsNonNull = true) 354 public static native Object dynamicNewInstanceStubCall(@ConstantNodeParameter ForeignCallDescriptor descriptor, Class<?> elementType); 355 356 @Snippet 357 public static Object allocateArrayDynamic(Class<?> elementType, Class<?> voidClass, int length, @ConstantParameter boolean fillContents, @ConstantParameter Register threadRegister, 358 @ConstantParameter JavaKind knownElementKind, @ConstantParameter int knownLayoutHelper, Word prototypeMarkWord, @ConstantParameter OptionValues options, 359 @ConstantParameter Counters counters) { 360 Object result = allocateArrayDynamicImpl(elementType, voidClass, length, fillContents, threadRegister, knownElementKind, knownLayoutHelper, prototypeMarkWord, options, counters); 361 return result; 362 } 363 364 private static Object allocateArrayDynamicImpl(Class<?> elementType, Class<?> voidClass, int length, boolean fillContents, Register threadRegister, JavaKind knownElementKind, 365 int knownLayoutHelper, Word prototypeMarkWord, OptionValues options, Counters counters) { 366 /* 367 * We only need the dynamic check for void when we have no static information from 368 * knownElementKind. 369 */ 370 staticAssert(knownElementKind != JavaKind.Void, "unsupported knownElementKind"); 371 if (knownElementKind == JavaKind.Illegal && probability(SLOW_PATH_PROBABILITY, elementType == null || DynamicNewArrayNode.throwsIllegalArgumentException(elementType, voidClass))) { 372 DeoptimizeNode.deopt(DeoptimizationAction.None, DeoptimizationReason.RuntimeConstraint); 373 } 374 375 KlassPointer klass = loadKlassFromObject(elementType, arrayKlassOffset(INJECTED_VMCONFIG), CLASS_ARRAY_KLASS_LOCATION); 376 if (klass.isNull()) { 377 DeoptimizeNode.deopt(DeoptimizationAction.None, DeoptimizationReason.RuntimeConstraint); 378 } 379 KlassPointer nonNullKlass = ClassGetHubNode.piCastNonNull(klass, SnippetAnchorNode.anchor()); 380 381 if (length < 0) { 382 DeoptimizeNode.deopt(DeoptimizationAction.None, DeoptimizationReason.RuntimeConstraint); 383 } 384 int layoutHelper; 385 if (knownElementKind == JavaKind.Illegal) { 386 layoutHelper = readLayoutHelper(nonNullKlass); 387 } else { 388 runtimeAssert(knownLayoutHelper == readLayoutHelper(nonNullKlass), "layout mismatch"); 389 layoutHelper = knownLayoutHelper; 390 } 391 //@formatter:off 392 // from src/share/vm/oops/klass.hpp: 393 // 394 // For arrays, layout helper is a negative number, containing four 395 // distinct bytes, as follows: 396 // MSB:[tag, hsz, ebt, log2(esz)]:LSB 397 // where: 398 // tag is 0x80 if the elements are oops, 0xC0 if non-oops 399 // hsz is array header size in bytes (i.e., offset of first element) 400 // ebt is the BasicType of the elements 401 // esz is the element size in bytes 402 //@formatter:on 403 404 int headerSize = (layoutHelper >> layoutHelperHeaderSizeShift(INJECTED_VMCONFIG)) & layoutHelperHeaderSizeMask(INJECTED_VMCONFIG); 405 int log2ElementSize = (layoutHelper >> layoutHelperLog2ElementSizeShift(INJECTED_VMCONFIG)) & layoutHelperLog2ElementSizeMask(INJECTED_VMCONFIG); 406 407 Object result = allocateArrayImpl(nonNullKlass, length, prototypeMarkWord, headerSize, log2ElementSize, fillContents, threadRegister, false, "dynamic type", true, options, counters); 408 return piArrayCastToSnippetReplaceeStamp(verifyOop(result), length); 409 } 410 411 /** 412 * Calls the runtime stub for implementing MULTIANEWARRAY. 413 */ 414 @Snippet 415 public static Object newmultiarray(KlassPointer hub, @ConstantParameter int rank, @VarargsParameter int[] dimensions) { 416 Word dims = DimensionsNode.allocaDimsArray(rank); 417 ExplodeLoopNode.explodeLoop(); 418 for (int i = 0; i < rank; i++) { 419 dims.writeInt(i * 4, dimensions[i], LocationIdentity.init()); 420 } 421 return newArrayCall(HotSpotBackend.NEW_MULTI_ARRAY, hub, rank, dims); 422 } 423 424 @Snippet 425 public static Object newmultiarrayPIC(KlassPointer hub, @ConstantParameter int rank, @VarargsParameter int[] dimensions) { 426 // Array type would be resolved by dominating resolution. 427 KlassPointer picHub = LoadConstantIndirectlyFixedNode.loadKlass(hub); 428 return newmultiarray(picHub, rank, dimensions); 429 } 430 431 @NodeIntrinsic(value = ForeignCallNode.class, injectedStampIsNonNull = true) 432 public static native Object newArrayCall(@ConstantNodeParameter ForeignCallDescriptor descriptor, KlassPointer hub, int rank, Word dims); 433 434 /** 435 * Maximum number of long stores to emit when zeroing an object with a constant size. Larger 436 * objects have their bodies initialized in a loop. 437 */ 438 private static final int MAX_UNROLLED_OBJECT_ZEROING_STORES = 8; 439 440 /** 441 * Zero uninitialized memory in a newly allocated object, unrolling as necessary and ensuring 442 * that stores are aligned. 443 * 444 * @param size number of bytes to zero 445 * @param memory beginning of object which is being zeroed 446 * @param constantSize is {@code size} known to be constant in the snippet 447 * @param startOffset offset to begin zeroing. May not be word aligned. 448 * @param manualUnroll maximally unroll zeroing 449 */ 450 private static void zeroMemory(int size, Word memory, boolean constantSize, int startOffset, boolean manualUnroll, Counters counters) { 451 fillMemory(0, size, memory, constantSize, startOffset, manualUnroll, counters); 452 } 453 454 private static void fillMemory(long value, int size, Word memory, boolean constantSize, int startOffset, boolean manualUnroll, Counters counters) { 455 ReplacementsUtil.runtimeAssert((size & 0x7) == 0, "unaligned object size"); 456 int offset = startOffset; 457 if ((offset & 0x7) != 0) { 458 memory.writeInt(offset, (int) value, LocationIdentity.init()); 459 offset += 4; 460 } 461 ReplacementsUtil.runtimeAssert((offset & 0x7) == 0, "unaligned offset"); 462 if (manualUnroll && ((size - offset) / 8) <= MAX_UNROLLED_OBJECT_ZEROING_STORES) { 463 ReplacementsUtil.staticAssert(!constantSize, "size shouldn't be constant at instantiation time"); 464 // This case handles arrays of constant length. Instead of having a snippet variant for 465 // each length, generate a chain of stores of maximum length. Once it's inlined the 466 // break statement will trim excess stores. 467 if (counters != null && counters.instanceSeqInit != null) { 468 counters.instanceSeqInit.inc(); 469 } 470 471 explodeLoop(); 472 for (int i = 0; i < MAX_UNROLLED_OBJECT_ZEROING_STORES; i++, offset += 8) { 473 if (offset == size) { 474 break; 475 } 476 memory.initializeLong(offset, value, LocationIdentity.init()); 477 } 478 } else { 479 // Use Word instead of int to avoid extension to long in generated code 480 Word off = WordFactory.signed(offset); 481 if (constantSize && ((size - offset) / 8) <= MAX_UNROLLED_OBJECT_ZEROING_STORES) { 482 if (counters != null && counters.instanceSeqInit != null) { 483 counters.instanceSeqInit.inc(); 484 } 485 explodeLoop(); 486 } else { 487 if (counters != null && counters.instanceLoopInit != null) { 488 counters.instanceLoopInit.inc(); 489 } 490 } 491 for (; off.rawValue() < size; off = off.add(8)) { 492 memory.initializeLong(off, value, LocationIdentity.init()); 493 } 494 } 495 } 496 497 /** 498 * Fill uninitialized memory with garbage value in a newly allocated object, unrolling as 499 * necessary and ensuring that stores are aligned. 500 * 501 * @param size number of bytes to zero 502 * @param memory beginning of object which is being zeroed 503 * @param constantSize is {@code size} known to be constant in the snippet 504 * @param startOffset offset to begin zeroing. May not be word aligned. 505 * @param manualUnroll maximally unroll zeroing 506 */ 507 private static void fillWithGarbage(int size, Word memory, boolean constantSize, int startOffset, boolean manualUnroll, Counters counters) { 508 fillMemory(0xfefefefefefefefeL, size, memory, constantSize, startOffset, manualUnroll, counters); 509 } 510 511 /** 512 * Formats some allocated memory with an object header and zeroes out the rest. Disables asserts 513 * since they can't be compiled in stubs. 514 */ 515 public static Object formatObjectForStub(KlassPointer hub, int size, Word memory, Word compileTimePrototypeMarkWord) { 516 return formatObject(hub, size, memory, compileTimePrototypeMarkWord, true, false, null); 517 } 518 519 /** 520 * Formats some allocated memory with an object header and zeroes out the rest. 521 */ 522 protected static Object formatObject(KlassPointer hub, int size, Word memory, Word compileTimePrototypeMarkWord, boolean fillContents, boolean constantSize, Counters counters) { 523 Word prototypeMarkWord = useBiasedLocking(INJECTED_VMCONFIG) ? hub.readWord(prototypeMarkWordOffset(INJECTED_VMCONFIG), PROTOTYPE_MARK_WORD_LOCATION) : compileTimePrototypeMarkWord; 524 initializeObjectHeader(memory, prototypeMarkWord, hub); 525 if (fillContents) { 526 zeroMemory(size, memory, constantSize, instanceHeaderSize(INJECTED_VMCONFIG), false, counters); 527 } else if (REPLACEMENTS_ASSERTIONS_ENABLED) { 528 fillWithGarbage(size, memory, constantSize, instanceHeaderSize(INJECTED_VMCONFIG), false, counters); 529 } 530 MembarNode.memoryBarrier(MemoryBarriers.STORE_STORE, LocationIdentity.init()); 531 return memory.toObjectNonNull(); 532 } 533 534 @Snippet 535 protected static void verifyHeap(@ConstantParameter Register threadRegister) { 536 Word thread = registerAsWord(threadRegister); 537 Word topValue = readTlabTop(thread); 538 if (!topValue.equal(WordFactory.zero())) { 539 Word topValueContents = topValue.readWord(0, MARK_WORD_LOCATION); 540 if (topValueContents.equal(WordFactory.zero())) { 541 AssertionSnippets.vmMessageC(AssertionSnippets.ASSERTION_VM_MESSAGE_C, true, cstring("overzeroing of TLAB detected"), 0L, 0L, 0L); 542 } 543 } 544 } 545 546 /** 547 * Formats some allocated memory with an object header and zeroes out the rest. 548 */ 549 public static Object formatArray(KlassPointer hub, int allocationSize, int length, int headerSize, Word memory, Word prototypeMarkWord, boolean fillContents, boolean maybeUnroll, 550 Counters counters) { 551 memory.writeInt(arrayLengthOffset(INJECTED_VMCONFIG), length, LocationIdentity.init()); 552 /* 553 * store hub last as the concurrent garbage collectors assume length is valid if hub field 554 * is not null 555 */ 556 initializeObjectHeader(memory, prototypeMarkWord, hub); 557 if (fillContents) { 558 zeroMemory(allocationSize, memory, false, headerSize, maybeUnroll, counters); 559 } else if (REPLACEMENTS_ASSERTIONS_ENABLED) { 560 fillWithGarbage(allocationSize, memory, false, headerSize, maybeUnroll, counters); 561 } 562 MembarNode.memoryBarrier(MemoryBarriers.STORE_STORE, LocationIdentity.init()); 563 return memory.toObjectNonNull(); 564 } 565 566 static class Counters { 567 Counters(SnippetCounter.Group.Factory factory) { 568 Group newInstance = factory.createSnippetCounterGroup("NewInstance"); 569 Group newArray = factory.createSnippetCounterGroup("NewArray"); 570 instanceSeqInit = new SnippetCounter(newInstance, "tlabSeqInit", "TLAB alloc with unrolled zeroing"); 571 instanceLoopInit = new SnippetCounter(newInstance, "tlabLoopInit", "TLAB alloc with zeroing in a loop"); 572 arrayLoopInit = new SnippetCounter(newArray, "tlabLoopInit", "TLAB alloc with zeroing in a loop"); 573 stub = new SnippetCounter(newInstance, "stub", "alloc and zeroing via stub"); 574 } 575 576 final SnippetCounter instanceSeqInit; 577 final SnippetCounter instanceLoopInit; 578 final SnippetCounter arrayLoopInit; 579 final SnippetCounter stub; 580 } 581 582 public static class Templates extends AbstractTemplates { 583 584 private final SnippetInfo allocateInstance = snippet(NewObjectSnippets.class, "allocateInstance", MARK_WORD_LOCATION, HUB_WRITE_LOCATION, TLAB_TOP_LOCATION, TLAB_END_LOCATION); 585 private final SnippetInfo allocateInstancePIC = snippet(NewObjectSnippets.class, "allocateInstancePIC", MARK_WORD_LOCATION, HUB_WRITE_LOCATION, TLAB_TOP_LOCATION, 586 TLAB_END_LOCATION); 587 private final SnippetInfo allocateArray = snippet(NewObjectSnippets.class, "allocateArray", MARK_WORD_LOCATION, HUB_WRITE_LOCATION, TLAB_TOP_LOCATION, TLAB_END_LOCATION); 588 private final SnippetInfo allocateArrayPIC = snippet(NewObjectSnippets.class, "allocateArrayPIC", MARK_WORD_LOCATION, HUB_WRITE_LOCATION, TLAB_TOP_LOCATION, TLAB_END_LOCATION); 589 private final SnippetInfo allocatePrimitiveArrayPIC = snippet(NewObjectSnippets.class, "allocatePrimitiveArrayPIC", MARK_WORD_LOCATION, HUB_WRITE_LOCATION, TLAB_TOP_LOCATION, 590 TLAB_END_LOCATION); 591 private final SnippetInfo allocateArrayDynamic = snippet(NewObjectSnippets.class, "allocateArrayDynamic", MARK_WORD_LOCATION, HUB_WRITE_LOCATION, TLAB_TOP_LOCATION, 592 TLAB_END_LOCATION); 593 private final SnippetInfo allocateInstanceDynamic = snippet(NewObjectSnippets.class, "allocateInstanceDynamic", MARK_WORD_LOCATION, HUB_WRITE_LOCATION, TLAB_TOP_LOCATION, 594 TLAB_END_LOCATION); 595 private final SnippetInfo newmultiarray = snippet(NewObjectSnippets.class, "newmultiarray", TLAB_TOP_LOCATION, TLAB_END_LOCATION); 596 private final SnippetInfo newmultiarrayPIC = snippet(NewObjectSnippets.class, "newmultiarrayPIC", TLAB_TOP_LOCATION, TLAB_END_LOCATION); 597 private final SnippetInfo verifyHeap = snippet(NewObjectSnippets.class, "verifyHeap"); 598 private final GraalHotSpotVMConfig config; 599 private final Counters counters; 600 601 public Templates(OptionValues options, Iterable<DebugHandlersFactory> factories, SnippetCounter.Group.Factory factory, HotSpotProviders providers, TargetDescription target, 602 GraalHotSpotVMConfig config) { 603 super(options, factories, providers, providers.getSnippetReflection(), target); 604 this.config = config; 605 counters = new Counters(factory); 606 } 607 608 /** 609 * Lowers a {@link NewInstanceNode}. 610 */ 611 public void lower(NewInstanceNode newInstanceNode, HotSpotRegistersProvider registers, LoweringTool tool) { 612 StructuredGraph graph = newInstanceNode.graph(); 613 HotSpotResolvedObjectType type = (HotSpotResolvedObjectType) newInstanceNode.instanceClass(); 614 assert !type.isArray(); 615 ConstantNode hub = ConstantNode.forConstant(KlassPointerStamp.klassNonNull(), type.klass(), providers.getMetaAccess(), graph); 616 int size = instanceSize(type); 617 618 OptionValues localOptions = graph.getOptions(); 619 SnippetInfo snippet = GeneratePIC.getValue(localOptions) ? allocateInstancePIC : allocateInstance; 620 Arguments args = new Arguments(snippet, graph.getGuardsStage(), tool.getLoweringStage()); 621 args.addConst("size", size); 622 args.add("hub", hub); 623 args.add("prototypeMarkWord", type.prototypeMarkWord()); 624 args.addConst("fillContents", newInstanceNode.fillContents()); 625 args.addConst("threadRegister", registers.getThreadRegister()); 626 args.addConst("constantSize", true); 627 args.addConst("typeContext", ProfileAllocations.getValue(localOptions) ? type.toJavaName(false) : ""); 628 args.addConst("options", localOptions); 629 args.addConst("counters", counters); 630 631 SnippetTemplate template = template(newInstanceNode, args); 632 graph.getDebug().log("Lowering allocateInstance in %s: node=%s, template=%s, arguments=%s", graph, newInstanceNode, template, args); 633 template.instantiate(providers.getMetaAccess(), newInstanceNode, DEFAULT_REPLACER, args); 634 } 635 636 /** 637 * Lowers a {@link NewArrayNode}. 638 */ 639 public void lower(NewArrayNode newArrayNode, HotSpotRegistersProvider registers, LoweringTool tool) { 640 StructuredGraph graph = newArrayNode.graph(); 641 ResolvedJavaType elementType = newArrayNode.elementType(); 642 HotSpotResolvedObjectType arrayType = (HotSpotResolvedObjectType) elementType.getArrayClass(); 643 JavaKind elementKind = elementType.getJavaKind(); 644 ConstantNode hub = ConstantNode.forConstant(KlassPointerStamp.klassNonNull(), arrayType.klass(), providers.getMetaAccess(), graph); 645 final int headerSize = tool.getMetaAccess().getArrayBaseOffset(elementKind); 646 int log2ElementSize = CodeUtil.log2(tool.getMetaAccess().getArrayIndexScale(elementKind)); 647 648 OptionValues localOptions = graph.getOptions(); 649 SnippetInfo snippet; 650 if (GeneratePIC.getValue(localOptions)) { 651 if (elementType.isPrimitive()) { 652 snippet = allocatePrimitiveArrayPIC; 653 } else { 654 snippet = allocateArrayPIC; 655 } 656 } else { 657 snippet = allocateArray; 658 } 659 660 Arguments args = new Arguments(snippet, graph.getGuardsStage(), tool.getLoweringStage()); 661 args.add("hub", hub); 662 ValueNode length = newArrayNode.length(); 663 args.add("length", length.isAlive() ? length : graph.addOrUniqueWithInputs(length)); 664 assert arrayType.prototypeMarkWord() == lookupArrayClass(tool, JavaKind.Object).prototypeMarkWord() : "all array types are assumed to have the same prototypeMarkWord"; 665 args.add("prototypeMarkWord", arrayType.prototypeMarkWord()); 666 args.addConst("headerSize", headerSize); 667 args.addConst("log2ElementSize", log2ElementSize); 668 args.addConst("fillContents", newArrayNode.fillContents()); 669 args.addConst("threadRegister", registers.getThreadRegister()); 670 args.addConst("maybeUnroll", length.isConstant()); 671 args.addConst("typeContext", ProfileAllocations.getValue(localOptions) ? arrayType.toJavaName(false) : ""); 672 args.addConst("options", localOptions); 673 args.addConst("counters", counters); 674 SnippetTemplate template = template(newArrayNode, args); 675 graph.getDebug().log("Lowering allocateArray in %s: node=%s, template=%s, arguments=%s", graph, newArrayNode, template, args); 676 template.instantiate(providers.getMetaAccess(), newArrayNode, DEFAULT_REPLACER, args); 677 } 678 679 public void lower(DynamicNewInstanceNode newInstanceNode, HotSpotRegistersProvider registers, LoweringTool tool) { 680 Arguments args = new Arguments(allocateInstanceDynamic, newInstanceNode.graph().getGuardsStage(), tool.getLoweringStage()); 681 OptionValues localOptions = newInstanceNode.getOptions(); 682 args.add("type", newInstanceNode.getInstanceType()); 683 ValueNode classClass = newInstanceNode.getClassClass(); 684 assert classClass != null; 685 args.add("classClass", classClass); 686 args.addConst("fillContents", newInstanceNode.fillContents()); 687 args.addConst("threadRegister", registers.getThreadRegister()); 688 args.addConst("options", localOptions); 689 args.addConst("counters", counters); 690 691 SnippetTemplate template = template(newInstanceNode, args); 692 template.instantiate(providers.getMetaAccess(), newInstanceNode, DEFAULT_REPLACER, args); 693 } 694 695 public void lower(DynamicNewArrayNode newArrayNode, HotSpotRegistersProvider registers, LoweringTool tool) { 696 StructuredGraph graph = newArrayNode.graph(); 697 OptionValues localOptions = graph.getOptions(); 698 Arguments args = new Arguments(allocateArrayDynamic, newArrayNode.graph().getGuardsStage(), tool.getLoweringStage()); 699 args.add("elementType", newArrayNode.getElementType()); 700 ValueNode voidClass = newArrayNode.getVoidClass(); 701 assert voidClass != null; 702 args.add("voidClass", voidClass); 703 ValueNode length = newArrayNode.length(); 704 args.add("length", length.isAlive() ? length : graph.addOrUniqueWithInputs(length)); 705 args.addConst("fillContents", newArrayNode.fillContents()); 706 args.addConst("threadRegister", registers.getThreadRegister()); 707 /* 708 * We use Kind.Illegal as a marker value instead of null because constant snippet 709 * parameters cannot be null. 710 */ 711 args.addConst("knownElementKind", newArrayNode.getKnownElementKind() == null ? JavaKind.Illegal : newArrayNode.getKnownElementKind()); 712 if (newArrayNode.getKnownElementKind() != null) { 713 args.addConst("knownLayoutHelper", lookupArrayClass(tool, newArrayNode.getKnownElementKind()).layoutHelper()); 714 } else { 715 args.addConst("knownLayoutHelper", 0); 716 } 717 args.add("prototypeMarkWord", lookupArrayClass(tool, JavaKind.Object).prototypeMarkWord()); 718 args.addConst("options", localOptions); 719 args.addConst("counters", counters); 720 SnippetTemplate template = template(newArrayNode, args); 721 template.instantiate(providers.getMetaAccess(), newArrayNode, DEFAULT_REPLACER, args); 722 } 723 724 private static HotSpotResolvedObjectType lookupArrayClass(LoweringTool tool, JavaKind kind) { 725 return (HotSpotResolvedObjectType) tool.getMetaAccess().lookupJavaType(kind == JavaKind.Object ? Object.class : kind.toJavaClass()).getArrayClass(); 726 } 727 728 public void lower(NewMultiArrayNode newmultiarrayNode, LoweringTool tool) { 729 StructuredGraph graph = newmultiarrayNode.graph(); 730 OptionValues localOptions = graph.getOptions(); 731 int rank = newmultiarrayNode.dimensionCount(); 732 ValueNode[] dims = new ValueNode[rank]; 733 for (int i = 0; i < newmultiarrayNode.dimensionCount(); i++) { 734 dims[i] = newmultiarrayNode.dimension(i); 735 } 736 HotSpotResolvedObjectType type = (HotSpotResolvedObjectType) newmultiarrayNode.type(); 737 ConstantNode hub = ConstantNode.forConstant(KlassPointerStamp.klassNonNull(), type.klass(), providers.getMetaAccess(), graph); 738 739 SnippetInfo snippet = GeneratePIC.getValue(localOptions) ? newmultiarrayPIC : newmultiarray; 740 Arguments args = new Arguments(snippet, graph.getGuardsStage(), tool.getLoweringStage()); 741 args.add("hub", hub); 742 args.addConst("rank", rank); 743 args.addVarargs("dimensions", int.class, StampFactory.forKind(JavaKind.Int), dims); 744 template(newmultiarrayNode, args).instantiate(providers.getMetaAccess(), newmultiarrayNode, DEFAULT_REPLACER, args); 745 } 746 747 private static int instanceSize(HotSpotResolvedObjectType type) { 748 int size = type.instanceSize(); 749 assert size >= 0; 750 return size; 751 } 752 753 public void lower(VerifyHeapNode verifyHeapNode, HotSpotRegistersProvider registers, LoweringTool tool) { 754 if (config.cAssertions) { 755 Arguments args = new Arguments(verifyHeap, verifyHeapNode.graph().getGuardsStage(), tool.getLoweringStage()); 756 args.addConst("threadRegister", registers.getThreadRegister()); 757 758 SnippetTemplate template = template(verifyHeapNode, args); 759 template.instantiate(providers.getMetaAccess(), verifyHeapNode, DEFAULT_REPLACER, args); 760 } else { 761 GraphUtil.removeFixedWithUnusedInputs(verifyHeapNode); 762 } 763 } 764 } 765 }