1 /* 2 * Copyright (c) 2024, 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 jdk.incubator.code.internal; 27 28 import jdk.incubator.code.*; 29 import jdk.incubator.code.dialect.core.CoreType; 30 import jdk.incubator.code.dialect.core.FunctionType; 31 import jdk.incubator.code.dialect.java.*; 32 import jdk.incubator.code.extern.*; 33 34 import java.util.*; 35 import java.util.function.Function; 36 import java.util.stream.Stream; 37 38 import static jdk.incubator.code.dialect.core.CoreOp.*; 39 import static jdk.incubator.code.dialect.core.CoreType.functionType; 40 import static jdk.incubator.code.dialect.java.JavaOp.*; 41 import static jdk.incubator.code.dialect.java.JavaType.*; 42 43 /** 44 * A transformer of code models to models that build them. 45 * <p> 46 * A building code model when executed will construct the same code model it was transformed from. 47 * Such a building code model could be transformed to bytecode and stored in class files. 48 */ 49 public class OpBuilder { 50 51 static final JavaType J_C_E_EXTERNALIZED_OP = type(ExternalizedOp.class); 52 53 static final MethodRef DIALECT_FACTORY_OP_FACTORY = MethodRef.method(DialectFactory.class, "opFactory", 54 OpFactory.class); 55 56 static final MethodRef DIALECT_FACTORY_TYPE_ELEMENT_FACTORY = MethodRef.method(DialectFactory.class, "typeElementFactory", 57 TypeElementFactory.class); 58 59 static final MethodRef OP_FACTORY_CONSTRUCT = MethodRef.method(OpFactory.class, "constructOp", 60 Op.class, ExternalizedOp.class); 61 62 static final MethodRef TYPE_ELEMENT_FACTORY_CONSTRUCT = MethodRef.method(TypeElementFactory.class, "constructType", 63 TypeElement.class, ExternalizedTypeElement.class); 64 65 static final MethodRef BODY_BUILDER_OF = MethodRef.method(Body.Builder.class, "of", 66 Body.Builder.class, Body.Builder.class, FunctionType.class); 67 68 static final MethodRef BODY_BUILDER_ENTRY_BLOCK = MethodRef.method(Body.Builder.class, "entryBlock", 69 Block.Builder.class); 70 71 // instance varargs 72 static final MethodRef BLOCK_BUILDER_SUCCESSOR = MethodRef.method(Block.Builder.class, "successor", 73 Block.Reference.class, Value[].class); 74 75 static final MethodRef BLOCK_BUILDER_OP = MethodRef.method(Block.Builder.class, "op", 76 Op.Result.class, Op.class); 77 78 // instance varargs 79 static final MethodRef BLOCK_BUILDER_BLOCK = MethodRef.method(Block.Builder.class, "block", 80 Block.Builder.class, TypeElement[].class); 81 82 static final MethodRef BLOCK_BUILDER_PARAMETER = MethodRef.method(Block.Builder.class, "parameter", 83 Block.Parameter.class, TypeElement.class); 84 85 // static varargs 86 static final MethodRef FUNCTION_TYPE_FUNCTION_TYPE = MethodRef.method(CoreType.class, "functionType", 87 FunctionType.class, TypeElement.class, TypeElement[].class); 88 89 90 static final JavaType J_U_LIST = type(List.class); 91 92 static final MethodRef LIST_OF_ARRAY = MethodRef.method(J_U_LIST, "of", 93 J_U_LIST, array(J_L_OBJECT, 1)); 94 95 static final JavaType J_U_MAP = type(Map.class); 96 97 static final JavaType J_U_MAP_ENTRY = type(Map.Entry.class); 98 99 static final MethodRef MAP_ENTRY = MethodRef.method(J_U_MAP, "entry", 100 J_U_MAP, J_L_OBJECT, J_L_OBJECT); 101 102 static final MethodRef MAP_OF_ARRAY = MethodRef.method(J_U_MAP, "of", 103 J_U_MAP, array(J_U_MAP_ENTRY, 1)); 104 105 106 static final JavaType EX_TYPE_ELEM = type(ExternalizedTypeElement.class); 107 108 static final MethodRef EX_TYPE_ELEM_OF_LIST = MethodRef.method(EX_TYPE_ELEM, "of", 109 EX_TYPE_ELEM, J_L_STRING, J_U_LIST); 110 111 112 static final JavaType J_C_LOCATION = type(Location.class); 113 114 static final MethodRef LOCATION_FROM_STRING = MethodRef.method(J_C_LOCATION, "fromString", 115 J_C_LOCATION, J_L_STRING); 116 117 static final FunctionType EXTERNALIZED_OP_F_TYPE = functionType( 118 J_C_E_EXTERNALIZED_OP, 119 J_L_STRING, 120 J_C_LOCATION, 121 J_U_LIST, 122 J_U_LIST, 123 type(TypeElement.class), 124 J_U_MAP, 125 J_U_LIST); 126 127 static final FunctionType BUILDER_F_TYPE = functionType(type(Op.class)); 128 129 130 final Map<Value, Value> valueMap; 131 132 final Map<Block, Value> blockMap; 133 134 final Map<ExternalizedTypeElement, Value> exTypeElementMap; 135 136 final Map<TypeElement, Value> typeElementMap; 137 138 final Block.Builder builder; 139 140 final Value dialectFactory; 141 142 final Value opFactory; 143 144 final Value typeElementFactory; 145 146 /** 147 * Transform the given code model to one that builds it. 148 * <p> 149 * This method initially applies the function {@code dialectFactoryF} to 150 * the block builder that is used to build resulting code model. The result 151 * is a dialect factory value which is subsequently used to build operations 152 * that construct type elements and operations present in the given code model. 153 * 154 * @param op the code model. 155 * @param dialectFactoryF a function that builds code items to produce a dialect factory value. 156 * @return the building code model. 157 */ 158 public static FuncOp createBuilderFunction(Op op, Function<Block.Builder, Value> dialectFactoryF) { 159 return new OpBuilder(dialectFactoryF).build(op); 160 } 161 162 OpBuilder(Function<Block.Builder, Value> dialectFactoryF) { 163 this.valueMap = new HashMap<>(); 164 this.blockMap = new HashMap<>(); 165 this.exTypeElementMap = new HashMap<>(); 166 this.typeElementMap = new HashMap<>(); 167 168 Body.Builder body = Body.Builder.of(null, BUILDER_F_TYPE); 169 this.builder = body.entryBlock(); 170 this.dialectFactory = dialectFactoryF.apply(builder); 171 this.opFactory = builder.op(invoke(DIALECT_FACTORY_OP_FACTORY, dialectFactory)); 172 this.typeElementFactory = builder.op(invoke(DIALECT_FACTORY_TYPE_ELEMENT_FACTORY, dialectFactory)); 173 } 174 175 FuncOp build(Op op) { 176 Value ancestorBody = builder.op(constant(type(Body.Builder.class), null)); 177 Value result = buildOp(ancestorBody, op); 178 builder.op(return_(result)); 179 180 return func("builder." + op.opName(), builder.parentBody()); 181 } 182 183 184 Value buildOp(Value ancestorBody, Op inputOp) { 185 List<Value> bodies = new ArrayList<>(); 186 for (Body inputBody : inputOp.bodies()) { 187 Value body = buildBody(ancestorBody, inputBody); 188 bodies.add(body); 189 } 190 191 List<Value> operands = new ArrayList<>(); 192 for (Value inputOperand : inputOp.operands()) { 193 Value operand = valueMap.get(inputOperand); 194 operands.add(operand); 195 } 196 197 List<Value> successors = new ArrayList<>(); 198 for (Block.Reference inputSuccessor : inputOp.successors()) { 199 List<Value> successorArgs = new ArrayList<>(); 200 for (Value inputOperand : inputSuccessor.arguments()) { 201 Value operand = valueMap.get(inputOperand); 202 successorArgs.add(operand); 203 } 204 Value referencedBlock = blockMap.get(inputSuccessor.targetBlock()); 205 206 List<Value> args = new ArrayList<>(); 207 args.add(referencedBlock); 208 args.addAll(successorArgs); 209 Value successor = builder.op(invoke( 210 InvokeOp.InvokeKind.INSTANCE, true, 211 BLOCK_BUILDER_SUCCESSOR.type().returnType(), 212 BLOCK_BUILDER_SUCCESSOR, args)); 213 successors.add(successor); 214 } 215 216 Value opDef = buildOpDefinition( 217 inputOp, 218 inputOp.opName(), 219 inputOp.location(), 220 operands, 221 successors, 222 inputOp.resultType(), 223 inputOp.externalize(), 224 bodies); 225 return builder.op(invoke(OP_FACTORY_CONSTRUCT, opFactory, opDef)); 226 } 227 228 229 Value buildOpDefinition(Op inputOp, 230 String name, 231 Location location, 232 List<Value> operands, 233 List<Value> successors, 234 TypeElement resultType, 235 Map<String, Object> attributes, 236 List<Value> bodies) { 237 List<Value> args = List.of( 238 builder.op(constant(J_L_STRING, name)), 239 buildLocation(location), 240 buildList(type(Value.class), operands), 241 buildList(type(Block.Reference.class), successors), 242 buildType(resultType), 243 buildAttributeMap(inputOp, attributes), 244 buildList(type(Body.Builder.class), bodies)); 245 return builder.op(new_(ConstructorRef.constructor(EXTERNALIZED_OP_F_TYPE), args)); 246 } 247 248 Value buildLocation(Location l) { 249 if (l == null) { 250 return builder.op(constant(J_C_LOCATION, null)); 251 } else { 252 return builder.op(invoke(LOCATION_FROM_STRING, 253 builder.op(constant(J_L_STRING, l.toString())))); 254 } 255 } 256 257 Value buildBody(Value ancestorBodyValue, Body inputBody) { 258 Value yieldType = buildType(inputBody.yieldType()); 259 Value bodyType = builder.op(invoke( 260 InvokeOp.InvokeKind.STATIC, true, 261 FUNCTION_TYPE_FUNCTION_TYPE.type().returnType(), 262 FUNCTION_TYPE_FUNCTION_TYPE, List.of(yieldType))); 263 Value body = builder.op(invoke(BODY_BUILDER_OF, ancestorBodyValue, bodyType)); 264 265 Value entryBlock = null; 266 for (Block inputBlock : inputBody.blocks()) { 267 Value block; 268 if (inputBlock.isEntryBlock()) { 269 block = entryBlock = builder.op(invoke(BODY_BUILDER_ENTRY_BLOCK, body)); 270 } else { 271 assert entryBlock != null; 272 block = builder.op(invoke(InvokeOp.InvokeKind.INSTANCE, true, 273 BLOCK_BUILDER_BLOCK.type().returnType(), 274 BLOCK_BUILDER_BLOCK, List.of(entryBlock))); 275 } 276 blockMap.put(inputBlock, block); 277 278 for (Block.Parameter inputP : inputBlock.parameters()) { 279 Value type = buildType(inputP.type()); 280 Value blockParameter = builder.op(invoke(BLOCK_BUILDER_PARAMETER, block, type)); 281 valueMap.put(inputP, blockParameter); 282 } 283 } 284 285 for (Block inputBlock : inputBody.blocks()) { 286 Value block = blockMap.get(inputBlock); 287 for (Op inputOp : inputBlock.ops()) { 288 Value op = buildOp(body, inputOp); 289 Value result = builder.op(invoke(BLOCK_BUILDER_OP, block, op)); 290 valueMap.put(inputOp.result(), result); 291 } 292 } 293 294 return body; 295 } 296 297 Value buildType(TypeElement _t) { 298 return typeElementMap.computeIfAbsent(_t, t -> { 299 Value exTypeElem = buildExternalizedType(t.externalize()); 300 return builder.op(invoke(TYPE_ELEMENT_FACTORY_CONSTRUCT, typeElementFactory, exTypeElem)); 301 }); 302 } 303 304 Value buildExternalizedType(ExternalizedTypeElement e) { 305 // Cannot use computeIfAbsent due to recursion 306 if (exTypeElementMap.get(e) instanceof Value v) { 307 return v; 308 } 309 310 List<Value> arguments = new ArrayList<>(); 311 for (ExternalizedTypeElement a : e.arguments()) { 312 arguments.add(buildExternalizedType(a)); 313 } 314 315 Value identifier = builder.op(constant(J_L_STRING, e.identifier())); 316 Value ve; 317 if (e.arguments().size() < 5) { 318 MethodRef elemOf = MethodRef.method(EX_TYPE_ELEM, "of", 319 EX_TYPE_ELEM, Stream.concat(Stream.of(J_L_STRING), 320 Collections.nCopies(e.arguments().size(), EX_TYPE_ELEM).stream()).toList()); 321 arguments.addFirst(identifier); 322 ve = builder.op(invoke(elemOf, arguments)); 323 } else { 324 Value list = buildList(EX_TYPE_ELEM, arguments); 325 ve = builder.op(invoke(EX_TYPE_ELEM_OF_LIST, identifier, list)); 326 } 327 328 exTypeElementMap.put(e, ve); 329 return ve; 330 } 331 332 Value buildAttributeMap(Op inputOp, Map<String, Object> attributes) { 333 List<Value> keysAndValues = new ArrayList<>(); 334 for (Map.Entry<String, Object> entry : attributes.entrySet()) { 335 Value key = builder.op(constant(J_L_STRING, entry.getKey())); 336 Value value = buildAttributeValue(entry.getValue()); 337 keysAndValues.add(key); 338 keysAndValues.add(value); 339 } 340 return buildMap(J_L_STRING, J_L_OBJECT, keysAndValues); 341 } 342 343 Value buildAttributeValue(Object value) { 344 return switch (value) { 345 case Boolean v -> { 346 yield builder.op(constant(BOOLEAN, value)); 347 } 348 case Byte v -> { 349 yield builder.op(constant(BYTE, value)); 350 } 351 case Short v -> { 352 yield builder.op(constant(SHORT, value)); 353 } 354 case Character v -> { 355 yield builder.op(constant(CHAR, value)); 356 } 357 case Integer v -> { 358 yield builder.op(constant(INT, value)); 359 } 360 case Long v -> { 361 yield builder.op(constant(LONG, value)); 362 } 363 case Float v -> { 364 yield builder.op(constant(FLOAT, value)); 365 } 366 case Double v -> { 367 yield builder.op(constant(DOUBLE, value)); 368 } 369 case Class<?> v -> { 370 yield buildType(JavaType.type(v)); 371 } 372 case String s -> { 373 yield builder.op(constant(J_L_STRING, value)); 374 } 375 case TypeElement f -> { 376 yield buildType(f); 377 } 378 case InvokeOp.InvokeKind ik -> { 379 FieldRef enumValueRef = FieldRef.field(InvokeOp.InvokeKind.class, ik.name(), InvokeOp.InvokeKind.class); 380 yield builder.op(fieldLoad(enumValueRef)); 381 } 382 case Object o when value == ExternalizedOp.NULL_ATTRIBUTE_VALUE -> { 383 yield builder.op(fieldLoad(FieldRef.field(ExternalizedOp.class, 384 "NULL_ATTRIBUTE_VALUE", Object.class))); 385 } 386 default -> { 387 // @@@ use the result of value.toString()? 388 throw new UnsupportedOperationException("Unsupported attribute value: " + value); 389 } 390 }; 391 } 392 393 394 Value buildMap(JavaType keyType, JavaType valueType, List<Value> keysAndValues) { 395 JavaType mapType = parameterized(J_U_MAP, keyType, valueType); 396 if (keysAndValues.size() < 21) { 397 MethodRef mapOf = MethodRef.method(J_U_MAP, "of", 398 J_U_MAP, Collections.nCopies(keysAndValues.size(), J_L_OBJECT)); 399 return builder.op(invoke(mapType, mapOf, keysAndValues)); 400 } else { 401 JavaType mapEntryType = parameterized(J_U_MAP_ENTRY, keyType, valueType); 402 List<Value> elements = new ArrayList<>(keysAndValues.size() / 2); 403 for (int i = 0; i < keysAndValues.size(); i += 2) { 404 Value key = keysAndValues.get(i); 405 Value value = keysAndValues.get(i + 1); 406 Value entry = builder.op(invoke(mapEntryType, MAP_ENTRY, key, value)); 407 elements.add(entry); 408 } 409 Value array = buildArray(mapEntryType, elements); 410 return builder.op(invoke(mapType, MAP_OF_ARRAY, array)); 411 } 412 } 413 414 415 Value buildList(JavaType elementType, List<Value> elements) { 416 JavaType listType = parameterized(J_U_LIST, elementType); 417 if (elements.size() < 11) { 418 MethodRef listOf = MethodRef.method(J_U_LIST, "of", 419 J_U_LIST, Collections.nCopies(elements.size(), J_L_OBJECT)); 420 return builder.op(invoke(listType, listOf, elements)); 421 } else { 422 Value array = buildArray(elementType, elements); 423 return builder.op(invoke(listType, LIST_OF_ARRAY, array)); 424 } 425 } 426 427 428 Value buildArray(JavaType elementType, List<Value> elements) { 429 Value array = builder.op(newArray(JavaType.array(elementType), 430 builder.op(constant(INT, elements.size())))); 431 for (int i = 0; i < elements.size(); i++) { 432 builder.op(arrayStoreOp( 433 array, 434 builder.op(constant(INT, i)), 435 elements.get(i))); 436 } 437 return array; 438 } 439 }