Search in sources :

Example 6 with BytecodeMethod

use of de.mirkosertic.bytecoder.core.BytecodeMethod in project Bytecoder by mirkosertic.

the class NaiveProgramGenerator method generateFrom.

@Override
public Program generateFrom(BytecodeClass aOwningClass, BytecodeMethod aMethod) {
    BytecodeCodeAttributeInfo theCode = aMethod.getCode(aOwningClass);
    Program theProgram = new Program();
    // Initialize programm arguments
    BytecodeLocalVariableTableAttributeInfo theDebugInfos = null;
    if (theCode != null) {
        theDebugInfos = theCode.attributeByType(BytecodeLocalVariableTableAttributeInfo.class);
    }
    int theCurrentIndex = 0;
    if (!aMethod.getAccessFlags().isStatic()) {
        theProgram.addArgument(new LocalVariableDescription(theCurrentIndex), Variable.createThisRef());
        theCurrentIndex++;
    }
    BytecodeTypeRef[] theTypes = aMethod.getSignature().getArguments();
    for (int i = 0; i < theTypes.length; i++) {
        BytecodeTypeRef theRef = theTypes[i];
        if (theDebugInfos != null) {
            BytecodeLocalVariableTableEntry theEntry = theDebugInfos.matchingEntryFor(BytecodeOpcodeAddress.START_AT_ZERO, theCurrentIndex);
            if (theEntry != null) {
                String theVariableName = theDebugInfos.resolveVariableName(theEntry);
                theProgram.addArgument(new LocalVariableDescription(theCurrentIndex), Variable.createMethodParameter(i + 1, theVariableName, TypeRef.toType(theTypes[i])));
            } else {
                theProgram.addArgument(new LocalVariableDescription(theCurrentIndex), Variable.createMethodParameter(i + 1, TypeRef.toType(theTypes[i])));
            }
        } else {
            theProgram.addArgument(new LocalVariableDescription(theCurrentIndex), Variable.createMethodParameter(i + 1, TypeRef.toType(theTypes[i])));
        }
        theCurrentIndex++;
        if (theRef == BytecodePrimitiveTypeRef.LONG || theRef == BytecodePrimitiveTypeRef.DOUBLE) {
            theCurrentIndex++;
        }
    }
    List<BytecodeBasicBlock> theBlocks = new ArrayList<>();
    Function<BytecodeOpcodeAddress, BytecodeBasicBlock> theBasicBlockByAddress = aValue -> {
        for (BytecodeBasicBlock theBlock : theBlocks) {
            if (Objects.equals(aValue, theBlock.getStartAddress())) {
                return theBlock;
            }
        }
        throw new IllegalStateException("No Block for " + aValue.getAddress());
    };
    if (aMethod.getAccessFlags().isAbstract() || aMethod.getAccessFlags().isNative()) {
        return theProgram;
    }
    BytecodeProgram theBytecode = theCode.getProgramm();
    Set<BytecodeOpcodeAddress> theJumpTarget = theBytecode.getJumpTargets();
    BytecodeBasicBlock currentBlock = null;
    for (BytecodeInstruction theInstruction : theBytecode.getInstructions()) {
        if (theJumpTarget.contains(theInstruction.getOpcodeAddress())) {
            // Jump target, start a new basic block
            currentBlock = null;
        }
        if (theBytecode.isStartOfTryBlock(theInstruction.getOpcodeAddress())) {
            // start of try block, hence new basic block
            currentBlock = null;
        }
        if (currentBlock == null) {
            BytecodeBasicBlock.Type theType = BytecodeBasicBlock.Type.NORMAL;
            for (BytecodeExceptionTableEntry theHandler : theBytecode.getExceptionHandlers()) {
                if (Objects.equals(theHandler.getHandlerPc(), theInstruction.getOpcodeAddress())) {
                    if (theHandler.isFinally()) {
                        theType = BytecodeBasicBlock.Type.FINALLY;
                    } else {
                        theType = BytecodeBasicBlock.Type.EXCEPTION_HANDLER;
                    }
                }
            }
            BytecodeBasicBlock theCurrentTemp = currentBlock;
            currentBlock = new BytecodeBasicBlock(theType);
            if (theCurrentTemp != null && !theCurrentTemp.endsWithReturn() && !theCurrentTemp.endsWithThrow() && theCurrentTemp.endsWithGoto() && !theCurrentTemp.endsWithConditionalJump()) {
                theCurrentTemp.addSuccessor(currentBlock);
            }
            theBlocks.add(currentBlock);
        }
        currentBlock.addInstruction(theInstruction);
        if (theInstruction.isJumpSource()) {
            // conditional or unconditional jump, start new basic block
            currentBlock = null;
        } else if (theInstruction instanceof BytecodeInstructionRET) {
            // returning, start new basic block
            currentBlock = null;
        } else if (theInstruction instanceof BytecodeInstructionRETURN) {
            // returning, start new basic block
            currentBlock = null;
        } else if (theInstruction instanceof BytecodeInstructionObjectRETURN) {
            // returning, start new basic block
            currentBlock = null;
        } else if (theInstruction instanceof BytecodeInstructionGenericRETURN) {
            // returning, start new basic block
            currentBlock = null;
        } else if (theInstruction instanceof BytecodeInstructionATHROW) {
            // thowing an exception, start new basic block
            currentBlock = null;
        } else if (theInstruction instanceof BytecodeInstructionInvoke) {
        // invocation, start new basic block
        // currentBlock = null;
        }
    }
    // Now, we have to build the successors of each block
    for (int i = 0; i < theBlocks.size(); i++) {
        BytecodeBasicBlock theBlock = theBlocks.get(i);
        if (!theBlock.endsWithReturn() && !theBlock.endsWithThrow()) {
            if (theBlock.endsWithJump()) {
                for (BytecodeInstruction theInstruction : theBlock.getInstructions()) {
                    if (theInstruction.isJumpSource()) {
                        for (BytecodeOpcodeAddress theBlockJumpTarget : theInstruction.getPotentialJumpTargets()) {
                            theBlock.addSuccessor(theBasicBlockByAddress.apply(theBlockJumpTarget));
                        }
                    }
                }
                if (theBlock.endsWithConditionalJump()) {
                    if (i < theBlocks.size() - 1) {
                        theBlock.addSuccessor(theBlocks.get(i + 1));
                    } else {
                        throw new IllegalStateException("Block at end with no jump target!");
                    }
                }
            } else {
                if (i < theBlocks.size() - 1) {
                    theBlock.addSuccessor(theBlocks.get(i + 1));
                } else {
                    throw new IllegalStateException("Block at end with no jump target!");
                }
            }
        }
    }
    // Ok, now we transform it to GraphNodes with yet empty content
    Map<BytecodeBasicBlock, RegionNode> theCreatedBlocks = new HashMap<>();
    ControlFlowGraph theGraph = theProgram.getControlFlowGraph();
    for (BytecodeBasicBlock theBlock : theBlocks) {
        RegionNode theSingleAssignmentBlock;
        switch(theBlock.getType()) {
            case NORMAL:
                theSingleAssignmentBlock = theGraph.createAt(theBlock.getStartAddress(), RegionNode.BlockType.NORMAL);
                break;
            case EXCEPTION_HANDLER:
                theSingleAssignmentBlock = theGraph.createAt(theBlock.getStartAddress(), RegionNode.BlockType.EXCEPTION_HANDLER);
                break;
            case FINALLY:
                theSingleAssignmentBlock = theGraph.createAt(theBlock.getStartAddress(), RegionNode.BlockType.FINALLY);
                break;
            default:
                throw new IllegalStateException("Unsupported block type : " + theBlock.getType());
        }
        theCreatedBlocks.put(theBlock, theSingleAssignmentBlock);
    }
    // Initialize Block dependency graph
    for (Map.Entry<BytecodeBasicBlock, RegionNode> theEntry : theCreatedBlocks.entrySet()) {
        for (BytecodeBasicBlock theSuccessor : theEntry.getKey().getSuccessors()) {
            RegionNode theSuccessorBlock = theCreatedBlocks.get(theSuccessor);
            if (theSuccessorBlock == null) {
                throw new IllegalStateException("Cannot find successor block");
            }
            theEntry.getValue().addSuccessor(theSuccessorBlock);
        }
    }
    // And add dependencies for exception handlers and finally blocks
    for (BytecodeExceptionTableEntry theHandler : theBytecode.getExceptionHandlers()) {
        RegionNode theStart = theProgram.getControlFlowGraph().nodeStartingAt(theHandler.getStartPC());
        RegionNode theHandlerNode = theProgram.getControlFlowGraph().nodeStartingAt(theHandler.getHandlerPc());
        theStart.addSuccessor(theHandlerNode);
    }
    // Now we can add the SSA instructions to the graph nodes
    Set<RegionNode> theVisited = new HashSet<>();
    RegionNode theStart = theProgram.getControlFlowGraph().startNode();
    // First of all, we need to mark the back-edges of the graph
    theProgram.getControlFlowGraph().calculateReachabilityAndMarkBackEdges();
    try {
        // Now we can continue to create the program flow
        ParsingHelperCache theParsingHelperCache = new ParsingHelperCache(theProgram, aMethod, theStart, theDebugInfos);
        // This will traverse the CFG from bottom to top
        for (RegionNode theNode : theProgram.getControlFlowGraph().finalNodes()) {
            initializeBlock(theProgram, aOwningClass, aMethod, theNode, theVisited, theParsingHelperCache, theBasicBlockByAddress);
        }
        // finally blocks
        for (Map.Entry<BytecodeBasicBlock, RegionNode> theEntry : theCreatedBlocks.entrySet()) {
            RegionNode theBlock = theEntry.getValue();
            if (theBlock.getType() != RegionNode.BlockType.NORMAL) {
                initializeBlock(theProgram, aOwningClass, aMethod, theBlock, theVisited, theParsingHelperCache, theBasicBlockByAddress);
            }
        }
        // Additionally, we have to add gotos
        for (RegionNode theNode : theProgram.getControlFlowGraph().getKnownNodes()) {
            ExpressionList theCurrentList = theNode.getExpressions();
            Expression theLast = theCurrentList.lastExpression();
            if (theLast instanceof GotoExpression) {
                GotoExpression theGoto = (GotoExpression) theLast;
                if (Objects.equals(theGoto.getJumpTarget(), theNode.getStartAddress())) {
                    theCurrentList.remove(theGoto);
                }
            }
            if (!theNode.getExpressions().endWithNeverReturningExpression()) {
                Map<RegionNode.Edge, RegionNode> theSuccessors = theNode.getSuccessors();
                for (Expression theExpression : theCurrentList.toList()) {
                    if (theExpression instanceof IFExpression) {
                        IFExpression theIF = (IFExpression) theExpression;
                        BytecodeOpcodeAddress theGoto = theIF.getGotoAddress();
                        theSuccessors = theSuccessors.entrySet().stream().filter(t -> !Objects.equals(t.getValue().getStartAddress(), theGoto)).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
                    }
                }
                List<RegionNode> theSuccessorRegions = theSuccessors.values().stream().filter(t -> t.getType() == RegionNode.BlockType.NORMAL).collect(Collectors.toList());
                if (theSuccessorRegions.size() == 1) {
                    theNode.getExpressions().add(new GotoExpression(theSuccessorRegions.get(0).getStartAddress()).withComment("Resolving pass thru direct"));
                } else {
                    // Special case, the node includes gotos and a fall thru to the same node
                    theSuccessors = theNode.getSuccessors();
                    theSuccessorRegions = theSuccessors.values().stream().filter(t -> t.getType() == RegionNode.BlockType.NORMAL).collect(Collectors.toList());
                    if (theSuccessorRegions.size() == 1) {
                        theNode.getExpressions().add(new GotoExpression(theSuccessorRegions.get(0).getStartAddress()).withComment("Resolving pass thru direct"));
                    } else {
                        throw new IllegalStateException("Invalid number of successors : " + theSuccessors.size() + " for " + theNode.getStartAddress().getAddress());
                    }
                }
            }
        }
        // Check that all PHI-propagations for back-edges are set
        for (RegionNode theNode : theProgram.getControlFlowGraph().getKnownNodes()) {
            ParsingHelper theHelper = theParsingHelperCache.resolveFinalStateForNode(theNode);
            for (Map.Entry<RegionNode.Edge, RegionNode> theEdge : theNode.getSuccessors().entrySet()) {
                if (theEdge.getKey().getType() == RegionNode.EdgeType.BACK) {
                    RegionNode theReceiving = theEdge.getValue();
                    BlockState theReceivingState = theReceiving.toStartState();
                    for (Map.Entry<VariableDescription, Value> theEntry : theReceivingState.getPorts().entrySet()) {
                        Value theExportingValue = theHelper.requestValue(theEntry.getKey());
                        if (theExportingValue == null) {
                            throw new IllegalStateException("No value for " + theEntry.getKey() + " to jump from " + theNode.getStartAddress().getAddress() + " to " + theReceiving.getStartAddress().getAddress());
                        }
                        Variable theReceivingTarget = (Variable) theEntry.getValue();
                        theReceivingTarget.initializeWith(theExportingValue);
                    }
                }
            }
        }
        // Make sure that all jump conditions are met
        for (RegionNode theNode : theProgram.getControlFlowGraph().getKnownNodes()) {
            forEachExpressionOf(theNode, aPoint -> {
                if (aPoint.expression instanceof GotoExpression) {
                    GotoExpression theGoto = (GotoExpression) aPoint.expression;
                    RegionNode theGotoNode = theProgram.getControlFlowGraph().nodeStartingAt(theGoto.getJumpTarget());
                    BlockState theImportingState = theGotoNode.toStartState();
                    for (Map.Entry<VariableDescription, Value> theImporting : theImportingState.getPorts().entrySet()) {
                        ParsingHelper theHelper = theParsingHelperCache.resolveFinalStateForNode(theNode);
                        Value theExportingValue = theHelper.requestValue(theImporting.getKey());
                        if (theExportingValue == null) {
                            throw new IllegalStateException("No value for " + theImporting.getKey() + " to jump from " + theNode.getStartAddress().getAddress() + " to " + theGotoNode.getStartAddress().getAddress());
                        }
                    }
                }
            });
        }
        // Insert PHI value resolving at required places
        for (RegionNode theNode : theProgram.getControlFlowGraph().getKnownNodes()) {
            forEachExpressionOf(theNode, aPoint -> {
                if (aPoint.expression instanceof GotoExpression) {
                    GotoExpression theGoto = (GotoExpression) aPoint.expression;
                    RegionNode theGotoNode = theProgram.getControlFlowGraph().nodeStartingAt(theGoto.getJumpTarget());
                    BlockState theImportingState = theGotoNode.toStartState();
                    String theComments = "";
                    for (Map.Entry<VariableDescription, Value> theImporting : theImportingState.getPorts().entrySet()) {
                        theComments = theComments + theImporting.getKey() + " is of type " + theImporting.getValue().resolveType().resolve() + " with values " + theImporting.getValue().incomingDataFlows();
                        Value theReceivingValue = theImporting.getValue();
                        ParsingHelper theHelper = theParsingHelperCache.resolveFinalStateForNode(theNode);
                        Value theExportingValue = theHelper.requestValue(theImporting.getKey());
                        if (theExportingValue == null) {
                            throw new IllegalStateException("No value for " + theImporting.getKey() + " to jump from " + theNode.getStartAddress().getAddress() + " to " + theGotoNode.getStartAddress().getAddress());
                        }
                        if (theReceivingValue != theExportingValue) {
                            VariableAssignmentExpression theInit = new VariableAssignmentExpression((Variable) theReceivingValue, theExportingValue);
                            aPoint.expressionList.addBefore(theInit, theGoto);
                        }
                    }
                    theGoto.withComment(theComments);
                }
            });
        }
    } catch (Exception e) {
        throw new ControlFlowProcessingException("Error processing CFG for " + aOwningClass.getThisInfo().getConstant().stringValue() + "." + aMethod.getName().stringValue(), e, theProgram.getControlFlowGraph());
    }
    return theProgram;
}
Also used : BytecodeInstructionGenericADD(de.mirkosertic.bytecoder.core.BytecodeInstructionGenericADD) BytecodeInstructionINVOKEINTERFACE(de.mirkosertic.bytecoder.core.BytecodeInstructionINVOKEINTERFACE) BytecodeLocalVariableTableAttributeInfo(de.mirkosertic.bytecoder.core.BytecodeLocalVariableTableAttributeInfo) BytecodeInstructionL2Generic(de.mirkosertic.bytecoder.core.BytecodeInstructionL2Generic) BytecodeInstructionARRAYLENGTH(de.mirkosertic.bytecoder.core.BytecodeInstructionARRAYLENGTH) BytecodeInstructionGenericREM(de.mirkosertic.bytecoder.core.BytecodeInstructionGenericREM) BytecodeLocalVariableTableEntry(de.mirkosertic.bytecoder.core.BytecodeLocalVariableTableEntry) BytecodeInstructionGenericDIV(de.mirkosertic.bytecoder.core.BytecodeInstructionGenericDIV) BytecodeExceptionTableEntry(de.mirkosertic.bytecoder.core.BytecodeExceptionTableEntry) Map(java.util.Map) BytecodeInstructionGETFIELD(de.mirkosertic.bytecoder.core.BytecodeInstructionGETFIELD) BytecodeInstructionD2Generic(de.mirkosertic.bytecoder.core.BytecodeInstructionD2Generic) BytecodeInstructionMONITORENTER(de.mirkosertic.bytecoder.core.BytecodeInstructionMONITORENTER) BytecodeInstructionGenericNEG(de.mirkosertic.bytecoder.core.BytecodeInstructionGenericNEG) BytecodeInstructionGOTO(de.mirkosertic.bytecoder.core.BytecodeInstructionGOTO) BytecodeInstructionGenericMUL(de.mirkosertic.bytecoder.core.BytecodeInstructionGenericMUL) BytecodeInstructionGenericLOAD(de.mirkosertic.bytecoder.core.BytecodeInstructionGenericLOAD) Set(java.util.Set) BytecodeLongConstant(de.mirkosertic.bytecoder.core.BytecodeLongConstant) BytecodeInstructionInvoke(de.mirkosertic.bytecoder.core.BytecodeInstructionInvoke) BytecodeArrayTypeRef(de.mirkosertic.bytecoder.core.BytecodeArrayTypeRef) BytecodeBasicBlock(de.mirkosertic.bytecoder.core.BytecodeBasicBlock) BytecodeInstructionGenericSHR(de.mirkosertic.bytecoder.core.BytecodeInstructionGenericSHR) BytecodeInstructionANEWARRAY(de.mirkosertic.bytecoder.core.BytecodeInstructionANEWARRAY) BytecodeInstructionGenericSTORE(de.mirkosertic.bytecoder.core.BytecodeInstructionGenericSTORE) BytecodeInstructionObjectRETURN(de.mirkosertic.bytecoder.core.BytecodeInstructionObjectRETURN) BytecodeMethodRefConstant(de.mirkosertic.bytecoder.core.BytecodeMethodRefConstant) BytecodeInstructionGenericSHL(de.mirkosertic.bytecoder.core.BytecodeInstructionGenericSHL) BytecodeInstructionLCMP(de.mirkosertic.bytecoder.core.BytecodeInstructionLCMP) BytecodeInstructionPOP(de.mirkosertic.bytecoder.core.BytecodeInstructionPOP) BytecodeInstructionObjectArrayLOAD(de.mirkosertic.bytecoder.core.BytecodeInstructionObjectArrayLOAD) BytecodeInstructionLCONST(de.mirkosertic.bytecoder.core.BytecodeInstructionLCONST) BytecodeInstructionALOAD(de.mirkosertic.bytecoder.core.BytecodeInstructionALOAD) MethodHandle(java.lang.invoke.MethodHandle) BytecodeReferenceIndex(de.mirkosertic.bytecoder.core.BytecodeReferenceIndex) BytecodeBootstrapMethod(de.mirkosertic.bytecoder.core.BytecodeBootstrapMethod) BytecodeBootstrapMethodsAttributeInfo(de.mirkosertic.bytecoder.core.BytecodeBootstrapMethodsAttributeInfo) BytecodeInstructionGenericRETURN(de.mirkosertic.bytecoder.core.BytecodeInstructionGenericRETURN) BytecodeInstructionGenericXOR(de.mirkosertic.bytecoder.core.BytecodeInstructionGenericXOR) BytecodeInstructionDUP2(de.mirkosertic.bytecoder.core.BytecodeInstructionDUP2) ArrayList(java.util.ArrayList) BytecodeInstructionINVOKESTATIC(de.mirkosertic.bytecoder.core.BytecodeInstructionINVOKESTATIC) BytecodeInstructionPUTSTATIC(de.mirkosertic.bytecoder.core.BytecodeInstructionPUTSTATIC) BytecodeInstructionLOOKUPSWITCH(de.mirkosertic.bytecoder.core.BytecodeInstructionLOOKUPSWITCH) BytecodeInstructionINVOKEVIRTUAL(de.mirkosertic.bytecoder.core.BytecodeInstructionINVOKEVIRTUAL) BytecodeClass(de.mirkosertic.bytecoder.core.BytecodeClass) BytecodeInstructionObjectArraySTORE(de.mirkosertic.bytecoder.core.BytecodeInstructionObjectArraySTORE) BytecodeStringConstant(de.mirkosertic.bytecoder.core.BytecodeStringConstant) BytecodeDoubleConstant(de.mirkosertic.bytecoder.core.BytecodeDoubleConstant) BytecodeInstructionINVOKESPECIAL(de.mirkosertic.bytecoder.core.BytecodeInstructionINVOKESPECIAL) BytecodeInstructionGenericArraySTORE(de.mirkosertic.bytecoder.core.BytecodeInstructionGenericArraySTORE) BytecodeObjectTypeRef(de.mirkosertic.bytecoder.core.BytecodeObjectTypeRef) BytecodeInstructionACONSTNULL(de.mirkosertic.bytecoder.core.BytecodeInstructionACONSTNULL) BytecodeInstructionRET(de.mirkosertic.bytecoder.core.BytecodeInstructionRET) Address(de.mirkosertic.bytecoder.classlib.Address) BytecodeInstructionNEW(de.mirkosertic.bytecoder.core.BytecodeInstructionNEW) BytecodeInstructionBIPUSH(de.mirkosertic.bytecoder.core.BytecodeInstructionBIPUSH) BytecodeInstructionCHECKCAST(de.mirkosertic.bytecoder.core.BytecodeInstructionCHECKCAST) BytecodeUtf8Constant(de.mirkosertic.bytecoder.core.BytecodeUtf8Constant) BytecodeOpcodeAddress(de.mirkosertic.bytecoder.core.BytecodeOpcodeAddress) BytecodeInstructionASTORE(de.mirkosertic.bytecoder.core.BytecodeInstructionASTORE) BytecodeInstructionIFNULL(de.mirkosertic.bytecoder.core.BytecodeInstructionIFNULL) BytecodeInstructionMONITOREXIT(de.mirkosertic.bytecoder.core.BytecodeInstructionMONITOREXIT) BytecodeIntegerConstant(de.mirkosertic.bytecoder.core.BytecodeIntegerConstant) BytecodeMethodTypeConstant(de.mirkosertic.bytecoder.core.BytecodeMethodTypeConstant) BytecodeInstructionPOP2(de.mirkosertic.bytecoder.core.BytecodeInstructionPOP2) Array(java.lang.reflect.Array) BytecodeInstructionDUP(de.mirkosertic.bytecoder.core.BytecodeInstructionDUP) BytecodeInstructionDUP2X1(de.mirkosertic.bytecoder.core.BytecodeInstructionDUP2X1) BytecodeInstructionINSTANCEOF(de.mirkosertic.bytecoder.core.BytecodeInstructionINSTANCEOF) BytecodeInstructionATHROW(de.mirkosertic.bytecoder.core.BytecodeInstructionATHROW) BytecodeInstructionTABLESWITCH(de.mirkosertic.bytecoder.core.BytecodeInstructionTABLESWITCH) BytecodeInstructionGenericOR(de.mirkosertic.bytecoder.core.BytecodeInstructionGenericOR) BytecodeInstructionF2Generic(de.mirkosertic.bytecoder.core.BytecodeInstructionF2Generic) BytecodeInstructionINVOKEDYNAMIC(de.mirkosertic.bytecoder.core.BytecodeInstructionINVOKEDYNAMIC) BytecodePrimitiveTypeRef(de.mirkosertic.bytecoder.core.BytecodePrimitiveTypeRef) BytecodeLinkerContext(de.mirkosertic.bytecoder.core.BytecodeLinkerContext) BytecodeInstructionGenericCMP(de.mirkosertic.bytecoder.core.BytecodeInstructionGenericCMP) Collection(java.util.Collection) BytecodeInstructionRETURN(de.mirkosertic.bytecoder.core.BytecodeInstructionRETURN) MemoryManager(de.mirkosertic.bytecoder.classlib.MemoryManager) BytecodeInstructionIFICMP(de.mirkosertic.bytecoder.core.BytecodeInstructionIFICMP) BytecodeMethodSignature(de.mirkosertic.bytecoder.core.BytecodeMethodSignature) Collectors(java.util.stream.Collectors) BytecodeInstructionPUTFIELD(de.mirkosertic.bytecoder.core.BytecodeInstructionPUTFIELD) BytecodeInstructionGenericSUB(de.mirkosertic.bytecoder.core.BytecodeInstructionGenericSUB) BytecodeProgram(de.mirkosertic.bytecoder.core.BytecodeProgram) Objects(java.util.Objects) BytecodeInstructionIFACMP(de.mirkosertic.bytecoder.core.BytecodeInstructionIFACMP) BytecodeMethodHandleConstant(de.mirkosertic.bytecoder.core.BytecodeMethodHandleConstant) List(java.util.List) BytecodeConstant(de.mirkosertic.bytecoder.core.BytecodeConstant) BytecodeInstructionIINC(de.mirkosertic.bytecoder.core.BytecodeInstructionIINC) BytecodeInstructionFCONST(de.mirkosertic.bytecoder.core.BytecodeInstructionFCONST) BytecodeInstructionICONST(de.mirkosertic.bytecoder.core.BytecodeInstructionICONST) BytecodeInstruction(de.mirkosertic.bytecoder.core.BytecodeInstruction) BytecodeInstructionGETSTATIC(de.mirkosertic.bytecoder.core.BytecodeInstructionGETSTATIC) BytecodeCodeAttributeInfo(de.mirkosertic.bytecoder.core.BytecodeCodeAttributeInfo) BytecodeInstructionNOP(de.mirkosertic.bytecoder.core.BytecodeInstructionNOP) BytecodeTypeRef(de.mirkosertic.bytecoder.core.BytecodeTypeRef) BytecodeClassinfoConstant(de.mirkosertic.bytecoder.core.BytecodeClassinfoConstant) BytecodeInstructionDUPX2(de.mirkosertic.bytecoder.core.BytecodeInstructionDUPX2) BytecodeInstructionDUPX1(de.mirkosertic.bytecoder.core.BytecodeInstructionDUPX1) BytecodeInstructionGenericArrayLOAD(de.mirkosertic.bytecoder.core.BytecodeInstructionGenericArrayLOAD) HashMap(java.util.HashMap) BytecodeFloatConstant(de.mirkosertic.bytecoder.core.BytecodeFloatConstant) Function(java.util.function.Function) Stack(java.util.Stack) BytecodeInstructionIFCOND(de.mirkosertic.bytecoder.core.BytecodeInstructionIFCOND) HashSet(java.util.HashSet) BytecodeInstructionGenericAND(de.mirkosertic.bytecoder.core.BytecodeInstructionGenericAND) BytecodeInstructionDCONST(de.mirkosertic.bytecoder.core.BytecodeInstructionDCONST) BytecodeInvokeDynamicConstant(de.mirkosertic.bytecoder.core.BytecodeInvokeDynamicConstant) BytecodeInstructionNEWMULTIARRAY(de.mirkosertic.bytecoder.core.BytecodeInstructionNEWMULTIARRAY) BytecodeMethod(de.mirkosertic.bytecoder.core.BytecodeMethod) VM(de.mirkosertic.bytecoder.classlib.VM) BytecodeLinkedClass(de.mirkosertic.bytecoder.core.BytecodeLinkedClass) BytecodeInstructionIFNONNULL(de.mirkosertic.bytecoder.core.BytecodeInstructionIFNONNULL) BytecodeInstructionNEWARRAY(de.mirkosertic.bytecoder.core.BytecodeInstructionNEWARRAY) Consumer(java.util.function.Consumer) BytecodeInstructionI2Generic(de.mirkosertic.bytecoder.core.BytecodeInstructionI2Generic) BytecodeInstructionGenericLDC(de.mirkosertic.bytecoder.core.BytecodeInstructionGenericLDC) Collections(java.util.Collections) BytecodeInstructionSIPUSH(de.mirkosertic.bytecoder.core.BytecodeInstructionSIPUSH) BytecodeInstructionGenericUSHR(de.mirkosertic.bytecoder.core.BytecodeInstructionGenericUSHR) HashMap(java.util.HashMap) BytecodeLocalVariableTableEntry(de.mirkosertic.bytecoder.core.BytecodeLocalVariableTableEntry) BytecodeInstructionATHROW(de.mirkosertic.bytecoder.core.BytecodeInstructionATHROW) ArrayList(java.util.ArrayList) BytecodeBasicBlock(de.mirkosertic.bytecoder.core.BytecodeBasicBlock) BytecodeOpcodeAddress(de.mirkosertic.bytecoder.core.BytecodeOpcodeAddress) HashSet(java.util.HashSet) BytecodeProgram(de.mirkosertic.bytecoder.core.BytecodeProgram) BytecodeLocalVariableTableAttributeInfo(de.mirkosertic.bytecoder.core.BytecodeLocalVariableTableAttributeInfo) BytecodeInstruction(de.mirkosertic.bytecoder.core.BytecodeInstruction) BytecodeTypeRef(de.mirkosertic.bytecoder.core.BytecodeTypeRef) BytecodeExceptionTableEntry(de.mirkosertic.bytecoder.core.BytecodeExceptionTableEntry) Map(java.util.Map) HashMap(java.util.HashMap) BytecodeInstructionGenericRETURN(de.mirkosertic.bytecoder.core.BytecodeInstructionGenericRETURN) BytecodeProgram(de.mirkosertic.bytecoder.core.BytecodeProgram) BytecodeInstructionInvoke(de.mirkosertic.bytecoder.core.BytecodeInstructionInvoke) BytecodeLocalVariableTableEntry(de.mirkosertic.bytecoder.core.BytecodeLocalVariableTableEntry) BytecodeExceptionTableEntry(de.mirkosertic.bytecoder.core.BytecodeExceptionTableEntry) BytecodeInstructionObjectRETURN(de.mirkosertic.bytecoder.core.BytecodeInstructionObjectRETURN) BytecodeInstructionRET(de.mirkosertic.bytecoder.core.BytecodeInstructionRET) BytecodeInstructionRETURN(de.mirkosertic.bytecoder.core.BytecodeInstructionRETURN) BytecodeCodeAttributeInfo(de.mirkosertic.bytecoder.core.BytecodeCodeAttributeInfo)

Example 7 with BytecodeMethod

use of de.mirkosertic.bytecoder.core.BytecodeMethod in project Bytecoder by mirkosertic.

the class WASMSSACompilerBackend method generateCodeFor.

@Override
public WASMCompileResult generateCodeFor(CompileOptions aOptions, BytecodeLinkerContext aLinkerContext, Class aEntryPointClass, String aEntryPointMethodName, BytecodeMethodSignature aEntryPointSignatue) {
    // Link required mamory management code
    BytecodeLinkedClass theArrayClass = aLinkerContext.resolveClass(BytecodeObjectTypeRef.fromRuntimeClass(Array.class));
    BytecodeLinkedClass theManagerClass = aLinkerContext.resolveClass(BytecodeObjectTypeRef.fromRuntimeClass(MemoryManager.class));
    theManagerClass.resolveStaticMethod("freeMem", new BytecodeMethodSignature(BytecodePrimitiveTypeRef.LONG, new BytecodeTypeRef[0]));
    theManagerClass.resolveStaticMethod("usedMem", new BytecodeMethodSignature(BytecodePrimitiveTypeRef.LONG, new BytecodeTypeRef[0]));
    theManagerClass.resolveStaticMethod("free", new BytecodeMethodSignature(BytecodePrimitiveTypeRef.VOID, new BytecodeTypeRef[] { BytecodeObjectTypeRef.fromRuntimeClass(Address.class) }));
    theManagerClass.resolveStaticMethod("malloc", new BytecodeMethodSignature(BytecodeObjectTypeRef.fromRuntimeClass(Address.class), new BytecodeTypeRef[] { BytecodePrimitiveTypeRef.INT }));
    theManagerClass.resolveStaticMethod("newObject", new BytecodeMethodSignature(BytecodeObjectTypeRef.fromRuntimeClass(Address.class), new BytecodeTypeRef[] { BytecodePrimitiveTypeRef.INT, BytecodePrimitiveTypeRef.INT, BytecodePrimitiveTypeRef.INT }));
    theManagerClass.resolveStaticMethod("newArray", new BytecodeMethodSignature(BytecodeObjectTypeRef.fromRuntimeClass(Address.class), new BytecodeTypeRef[] { BytecodePrimitiveTypeRef.INT, BytecodePrimitiveTypeRef.INT, BytecodePrimitiveTypeRef.INT }));
    theManagerClass.resolveStaticMethod("newArray", new BytecodeMethodSignature(BytecodeObjectTypeRef.fromRuntimeClass(Address.class), new BytecodeTypeRef[] { BytecodePrimitiveTypeRef.INT, BytecodePrimitiveTypeRef.INT, BytecodePrimitiveTypeRef.INT, BytecodePrimitiveTypeRef.INT }));
    BytecodeLinkedClass theStringClass = aLinkerContext.resolveClass(BytecodeObjectTypeRef.fromRuntimeClass(String.class));
    if (!theStringClass.resolveConstructorInvocation(new BytecodeMethodSignature(BytecodePrimitiveTypeRef.VOID, new BytecodeTypeRef[] { new BytecodeArrayTypeRef(BytecodePrimitiveTypeRef.BYTE, 1) }))) {
        throw new IllegalStateException("No matching constructor!");
    }
    StringWriter theStringWriter = new StringWriter();
    PrintWriter theWriter = new PrintWriter(theStringWriter);
    theWriter.println("(module");
    theWriter.println("   (func $float_remainder (import \"math\" \"float_rem\") (param $p1 f32) (param $p2 f32) (result f32))\n");
    // Print imported functions first
    aLinkerContext.linkedClasses().forEach(aEntry -> {
        if (aEntry.targetNode().getBytecodeClass().getAccessFlags().isInterface()) {
            return;
        }
        if (Objects.equals(aEntry.edgeType().objectTypeRef(), BytecodeObjectTypeRef.fromRuntimeClass(Address.class))) {
            return;
        }
        BytecodeResolvedMethods theMethodMap = aEntry.targetNode().resolvedMethods();
        theMethodMap.stream().forEach(aMethodMapEntry -> {
            // Only add implementation methods
            if (!(aMethodMapEntry.getProvidingClass() == aEntry.targetNode())) {
                return;
            }
            BytecodeMethod t = aMethodMapEntry.getValue();
            BytecodeMethodSignature theSignature = t.getSignature();
            if (t.getAccessFlags().isNative()) {
                if (aMethodMapEntry.getProvidingClass().getBytecodeClass().getAttributes().getAnnotationByType(EmulatedByRuntime.class.getName()) != null) {
                    return;
                }
                BytecodeImportedLink theLink = aMethodMapEntry.getProvidingClass().linkfor(t);
                // Imported function
                theWriter.print("   (func ");
                theWriter.print("$");
                theWriter.print(WASMWriterUtils.toMethodName(aMethodMapEntry.getProvidingClass().getClassName(), t.getName(), theSignature));
                theWriter.print(" (import \"");
                theWriter.print(theLink.getModuleName());
                theWriter.print("\" \"");
                theWriter.print(theLink.getLinkName());
                theWriter.print("\") ");
                theWriter.print("(param $thisRef");
                theWriter.print(" ");
                theWriter.print(WASMWriterUtils.toType(TypeRef.Native.REFERENCE));
                theWriter.print(") ");
                for (int i = 0; i < theSignature.getArguments().length; i++) {
                    BytecodeTypeRef theParamType = theSignature.getArguments()[i];
                    theWriter.print("(param $p");
                    theWriter.print((i + 1));
                    theWriter.print(" ");
                    theWriter.print(WASMWriterUtils.toType(TypeRef.toType(theParamType)));
                    theWriter.print(") ");
                }
                if (!theSignature.getReturnType().isVoid()) {
                    // result
                    theWriter.print("(result ");
                    theWriter.print(WASMWriterUtils.toType(TypeRef.toType(theSignature.getReturnType())));
                    theWriter.print(")");
                }
                theWriter.println(")");
            }
        });
    });
    Map<String, String> theGlobalTypes = new HashMap<>();
    theGlobalTypes.put("RESOLVEMETHOD", "(func (param i32) (param i32) (result i32))");
    theGlobalTypes.put("INSTANCEOF", "(func (param i32) (param i32) (result i32))");
    theWriter.println();
    List<String> theGeneratedFunctions = new ArrayList<>();
    theGeneratedFunctions.add("LAMBDA__resolvevtableindex");
    theGeneratedFunctions.add("RUNTIMECLASS__resolvevtableindex");
    theGeneratedFunctions.add("jlClass_A1jlObjectgetEnumConstants");
    theGeneratedFunctions.add("jlClass_BOOLEANdesiredAssertionStatus");
    List<BytecodeLinkedClass> theLinkedClasses = new ArrayList<>();
    ConstantPool theConstantPool = new ConstantPool();
    Map<String, CallSite> theCallsites = new HashMap<>();
    WASMSSAWriter.IDResolver theResolver = new WASMSSAWriter.IDResolver() {

        @Override
        public int resolveVTableMethodByType(BytecodeObjectTypeRef aObjectType) {
            String theClassName = WASMWriterUtils.toClassName(aObjectType);
            String theMethodName = theClassName + "__resolvevtableindex";
            int theIndex = theGeneratedFunctions.indexOf(theMethodName);
            if (theIndex < 0) {
                throw new IllegalStateException("Cannot resolve vtable method for " + theClassName);
            }
            return theIndex;
        }

        @Override
        public String resolveStringPoolFunctionName(StringValue aValue) {
            return "stringPool" + theConstantPool.register(aValue);
        }

        @Override
        public String resolveCallsiteBootstrapFor(BytecodeClass aOwningClass, String aCallsiteId, Program aProgram, RegionNode aBootstrapMethod) {
            String theID = "callsite_" + aCallsiteId.replace("/", "_");
            CallSite theCallsite = theCallsites.computeIfAbsent(theID, k -> new CallSite(aProgram, aBootstrapMethod));
            return theID;
        }

        @Override
        public int resolveMethodIDByName(String aMethodName) {
            int theIndex = theGeneratedFunctions.indexOf(aMethodName);
            if (theIndex < 0) {
                throw new IllegalStateException("Cannot resolve method " + aMethodName);
            }
            return theIndex;
        }

        @Override
        public void registerGlobalType(BytecodeMethodSignature aSignature, boolean aStatic) {
            String theMethodSignature = WASMWriterUtils.toMethodSignature(aSignature, aStatic);
            if (!theGlobalTypes.containsKey(theMethodSignature)) {
                String theTypeDefinition = WASMWriterUtils.toWASMMethodSignature(aSignature);
                theGlobalTypes.put(theMethodSignature, theTypeDefinition);
            }
        }
    };
    aLinkerContext.linkedClasses().forEach(aEntry -> {
        if (Objects.equals(aEntry.edgeType().objectTypeRef(), BytecodeObjectTypeRef.fromRuntimeClass(Address.class))) {
            return;
        }
        theLinkedClasses.add(aEntry.targetNode());
        String theClassName = WASMWriterUtils.toClassName(aEntry.edgeType().objectTypeRef());
        if (!aEntry.targetNode().getBytecodeClass().getAccessFlags().isInterface()) {
            theGeneratedFunctions.add(theClassName + "__resolvevtableindex");
            theGeneratedFunctions.add(theClassName + "__instanceof");
        }
        BytecodeResolvedMethods theMethodMap = aEntry.targetNode().resolvedMethods();
        theMethodMap.stream().forEach(aMapEntry -> {
            BytecodeMethod t = aMapEntry.getValue();
            // If the method is provided by the runtime, we do not need to generate the implementation
            if (t.getAttributes().getAnnotationByType(EmulatedByRuntime.class.getName()) != null) {
                return;
            }
            // Do not generate code for abstract methods
            if (t.getAccessFlags().isAbstract()) {
                return;
            }
            // Constructors for the same reason
            if (t.isConstructor()) {
                return;
            }
            // Class initializer also
            if (t.isClassInitializer()) {
                return;
            }
            // Only write real methods
            if (!(aMapEntry.getProvidingClass() == aEntry.targetNode())) {
                return;
            }
            BytecodeMethodSignature theSignature = t.getSignature();
            theResolver.registerGlobalType(theSignature, t.getAccessFlags().isStatic());
            if (aEntry.targetNode().getBytecodeClass().getAttributes().getAnnotationByType(EmulatedByRuntime.class.getName()) != null) {
                return;
            }
            String theMethodName = WASMWriterUtils.toMethodName(aEntry.edgeType().objectTypeRef(), t.getName(), theSignature);
            if (!theGeneratedFunctions.contains(theMethodName)) {
                theGeneratedFunctions.add(theMethodName);
            }
        });
    });
    theWriter.println("   (memory (export \"memory\") 512 512)");
    // Write virtual method table
    if (!theGeneratedFunctions.isEmpty()) {
        theWriter.println();
        theWriter.print("   (table ");
        theWriter.print(theGeneratedFunctions.size());
        theWriter.println(" anyfunc)");
        for (int i = 0; i < theGeneratedFunctions.size(); i++) {
            theWriter.print("   (elem (i32.const ");
            theWriter.print(i);
            theWriter.print(") $");
            theWriter.print(theGeneratedFunctions.get(i));
            theWriter.println(")");
        }
        theWriter.println();
    }
    // Initialize memory layout for classes and instances
    WASMMemoryLayouter theMemoryLayout = new WASMMemoryLayouter(aLinkerContext);
    // Now everything else
    aLinkerContext.linkedClasses().forEach(aEntry -> {
        BytecodeLinkedClass theLinkedClass = aEntry.targetNode();
        if (Objects.equals(aEntry.edgeType().objectTypeRef(), BytecodeObjectTypeRef.fromRuntimeClass(Address.class))) {
            return;
        }
        if (theLinkedClass.getBytecodeClass().getAttributes().getAnnotationByType(EmulatedByRuntime.class.getName()) != null) {
            return;
        }
        Set<BytecodeObjectTypeRef> theStaticReferences = new HashSet<>();
        BytecodeResolvedMethods theMethodMap = theLinkedClass.resolvedMethods();
        theMethodMap.stream().forEach(aMethodMapEntry -> {
            BytecodeMethod theMethod = aMethodMapEntry.getValue();
            BytecodeMethodSignature theSignature = theMethod.getSignature();
            // If the method is provided by the runtime, we do not need to generate the implementation
            if (theMethod.getAttributes().getAnnotationByType(EmulatedByRuntime.class.getName()) != null) {
                return;
            }
            // Do not generate code for abstract methods
            if (theMethod.getAccessFlags().isAbstract()) {
                return;
            }
            if (theMethod.getAccessFlags().isNative()) {
                // Already written
                return;
            }
            if (!(aMethodMapEntry.getProvidingClass() == theLinkedClass)) {
                // But include static methods, as they are inherited from the base classes
                if (aMethodMapEntry.getValue().getAccessFlags().isStatic() && !aMethodMapEntry.getValue().isClassInitializer()) {
                    // We need to create a delegate function here
                    if (!theMethodMap.isImplementedBy(aMethodMapEntry.getValue(), theLinkedClass)) {
                        theWriter.print("   (func ");
                        theWriter.print("$");
                        theWriter.print(WASMWriterUtils.toMethodName(theLinkedClass.getClassName(), theMethod.getName(), theSignature));
                        theWriter.print(" ");
                        theWriter.print("(param $UNUSED");
                        theWriter.print(" ");
                        theWriter.print(WASMWriterUtils.toType(TypeRef.Native.REFERENCE));
                        theWriter.print(") ");
                        StringBuilder theArguments = new StringBuilder();
                        theArguments.append("(get_local $UNUSED)");
                        for (int i = 0; i < theSignature.getArguments().length; i++) {
                            theWriter.print("(param $p");
                            theWriter.print(i);
                            theWriter.print(" ");
                            theWriter.print(WASMWriterUtils.toType(TypeRef.toType(theSignature.getArguments()[i])));
                            theWriter.print(") ");
                            theArguments.append(" (get_local $p");
                            theArguments.append(i);
                            theArguments.append(")");
                        }
                        if (!theSignature.getReturnType().isVoid()) {
                            // result
                            theWriter.print("(result ");
                            theWriter.print(WASMWriterUtils.toType(TypeRef.toType(theSignature.getReturnType())));
                            theWriter.print(")");
                        }
                        theWriter.println();
                        // Static methods will just delegate to the implementation in the class
                        theWriter.println();
                        if (!theSignature.getReturnType().isVoid()) {
                            theWriter.print("         (return ");
                            theWriter.print("(call $");
                            theWriter.print(WASMWriterUtils.toMethodName(aMethodMapEntry.getProvidingClass().getClassName(), theMethod.getName(), theSignature));
                            theWriter.print(" ");
                            theWriter.print(theArguments);
                            theWriter.println(")))");
                        } else {
                            theWriter.print("         (call $");
                            theWriter.print(WASMWriterUtils.toMethodName(aMethodMapEntry.getProvidingClass().getClassName(), theMethod.getName(), theSignature));
                            theWriter.print(" ");
                            theWriter.print(theArguments);
                            theWriter.println("))");
                        }
                    }
                }
                return;
            }
            ProgramGenerator theGenerator = programGeneratorFactory.createFor(aLinkerContext);
            Program theSSAProgram = theGenerator.generateFrom(aMethodMapEntry.getProvidingClass().getBytecodeClass(), theMethod);
            // Run optimizer
            aOptions.getOptimizer().optimize(theSSAProgram.getControlFlowGraph(), aLinkerContext);
            theWriter.print("   (func ");
            theWriter.print("$");
            theWriter.print(WASMWriterUtils.toMethodName(theLinkedClass.getClassName(), theMethod.getName(), theSignature));
            theWriter.print(" ");
            if (theMethod.getAccessFlags().isStatic()) {
                theWriter.print("(param $UNUSED");
                theWriter.print(" ");
                theWriter.print(WASMWriterUtils.toType(TypeRef.Native.REFERENCE));
                theWriter.print(") ");
            }
            for (Program.Argument theArgument : theSSAProgram.getArguments()) {
                Variable theVariable = theArgument.getVariable();
                theWriter.print("(param $");
                theWriter.print(theVariable.getName());
                theWriter.print(" ");
                theWriter.print(WASMWriterUtils.toType(theVariable.resolveType()));
                theWriter.print(") ");
            }
            if (!theSignature.getReturnType().isVoid()) {
                // result
                theWriter.print("(result ");
                theWriter.print(WASMWriterUtils.toType(TypeRef.toType(theSignature.getReturnType())));
                theWriter.print(")");
            }
            theWriter.println();
            theStaticReferences.addAll(theSSAProgram.getStaticReferences());
            WASMSSAWriter theSSAWriter = new WASMSSAWriter(aOptions, theSSAProgram, "         ", theWriter, aLinkerContext, theResolver, theMemoryLayout);
            for (Variable theVariable : theSSAProgram.getVariables()) {
                if (!(theVariable.isSynthetic()) && !theSSAWriter.isStackVariable(theVariable)) {
                    theSSAWriter.print("(local $");
                    theSSAWriter.print(theVariable.getName());
                    theSSAWriter.print(" ");
                    theSSAWriter.print(WASMWriterUtils.toType(theVariable.resolveType()));
                    theSSAWriter.print(") ;; ");
                    theSSAWriter.println(theVariable.resolveType().resolve().name());
                }
            }
            // Try to reloop it!
            try {
                Relooper theRelooper = new Relooper();
                Relooper.Block theReloopedBlock = theRelooper.reloop(theSSAProgram.getControlFlowGraph());
                theSSAWriter.writeRelooped(theReloopedBlock);
            } catch (Exception e) {
                throw new IllegalStateException("Error relooping cfg", e);
            }
            theWriter.println("   )");
            theWriter.println();
        });
        String theClassName = WASMWriterUtils.toClassName(aEntry.edgeType().objectTypeRef());
        if (!theLinkedClass.getBytecodeClass().getAccessFlags().isInterface()) {
            theWriter.print("   (func ");
            theWriter.print("$");
            theWriter.print(theClassName);
            theWriter.println("__resolvevtableindex (param $thisRef i32) (param $p1 i32) (result i32)");
            List<BytecodeResolvedMethods.MethodEntry> theEntries = theMethodMap.stream().collect(Collectors.toList());
            Set<BytecodeVirtualMethodIdentifier> theVisitedMethods = new HashSet<>();
            for (int i = theEntries.size() - 1; i >= 0; i--) {
                BytecodeResolvedMethods.MethodEntry aMethodMapEntry = theEntries.get(i);
                BytecodeMethod theMethod = aMethodMapEntry.getValue();
                if (!theMethod.getAccessFlags().isStatic() && !theMethod.getAccessFlags().isPrivate() && !theMethod.isConstructor() && !theMethod.getAccessFlags().isAbstract() && (theMethod != BytecodeLinkedClass.GET_CLASS_PLACEHOLDER)) {
                    BytecodeVirtualMethodIdentifier theMethodIdentifier = aLinkerContext.getMethodCollection().identifierFor(theMethod);
                    if (theVisitedMethods.add(theMethodIdentifier)) {
                        theWriter.println("         (block $b");
                        theWriter.print("             (br_if $b (i32.ne (get_local $p1) (i32.const ");
                        theWriter.print(theMethodIdentifier.getIdentifier());
                        theWriter.println(")))");
                        String theFullMethodName = WASMWriterUtils.toMethodName(aMethodMapEntry.getProvidingClass().getClassName(), theMethod.getName(), theMethod.getSignature());
                        int theIndex = theGeneratedFunctions.indexOf(theFullMethodName);
                        if (theIndex < 0) {
                            throw new IllegalStateException("Unknown index : " + theFullMethodName);
                        }
                        theWriter.print("             (return (i32.const ");
                        theWriter.print(theIndex);
                        theWriter.println("))");
                        theWriter.println("         )");
                    }
                }
            }
            ;
            theWriter.println("         (block $b");
            theWriter.print("             (br_if $b (i32.ne (get_local $p1) (i32.const ");
            theWriter.print(WASMSSAWriter.GENERATED_INSTANCEOF_METHOD_ID);
            theWriter.println(")))");
            String theFullMethodName = theClassName + "__instanceof";
            int theIndex = theGeneratedFunctions.indexOf(theFullMethodName);
            if (theIndex < 0) {
                throw new IllegalStateException("Unknown index : " + theFullMethodName);
            }
            theWriter.print("             (return (i32.const ");
            theWriter.print(theIndex);
            theWriter.println("))");
            theWriter.println("         )");
            theWriter.println("         (unreachable)");
            theWriter.println("   )");
            theWriter.println();
            // Instanceof method
            theWriter.print("   (func ");
            theWriter.print("$");
            theWriter.print(theClassName);
            theWriter.println("__instanceof (param $thisRef i32) (param $p1 i32) (result i32)");
            for (BytecodeLinkedClass theType : theLinkedClass.getImplementingTypes()) {
                theWriter.print("         (block $block");
                theWriter.print(theType.getUniqueId());
                theWriter.println();
                theWriter.print("             (br_if $block");
                theWriter.print(theType.getUniqueId());
                theWriter.print(" (i32.ne (get_local $p1) (i32.const ");
                theWriter.print(theType.getUniqueId());
                theWriter.println(")))");
                theWriter.println("             (return (i32.const 1))");
                theWriter.println("         )");
            }
            theWriter.println("         (return (i32.const 0))");
            theWriter.println("   )");
            theWriter.println();
        }
        theWriter.print("   (func ");
        theWriter.print("$");
        theWriter.print(theClassName);
        theWriter.println("__classinitcheck");
        theWriter.println("      (block $check");
        theWriter.print("         (br_if $check (i32.eq (i32.load offset=8 (get_global $");
        theWriter.print(theClassName);
        theWriter.println("__runtimeClass)) (i32.const 1)))");
        theWriter.print("         (i32.store offset=8 (get_global $");
        theWriter.print(theClassName);
        theWriter.println("__runtimeClass) (i32.const 1))");
        for (BytecodeObjectTypeRef theRef : theStaticReferences) {
            if (!Objects.equals(theRef, aEntry.edgeType().objectTypeRef())) {
                theWriter.print("         (call $");
                theWriter.print(WASMWriterUtils.toClassName(theRef));
                theWriter.println("__classinitcheck)");
            }
        }
        if (theLinkedClass.hasClassInitializer()) {
            theWriter.print("         (call $");
            theWriter.print(theClassName);
            theWriter.println("_VOIDclinit (i32.const 0))");
        }
        theWriter.println("      )");
        theWriter.println("   )");
        theWriter.println();
    });
    // Render callsites
    for (Map.Entry<String, CallSite> theEntry : theCallsites.entrySet()) {
        theWriter.print("   (func ");
        theWriter.print("$");
        theWriter.print(theEntry.getKey());
        theWriter.print(" ");
        // result
        theWriter.print("(result ");
        theWriter.print(WASMWriterUtils.toType(TypeRef.Native.REFERENCE));
        theWriter.print(")");
        theWriter.println();
        Program theSSAProgram = theEntry.getValue().program;
        WASMSSAWriter theSSAWriter = new WASMSSAWriter(aOptions, theSSAProgram, "         ", theWriter, aLinkerContext, theResolver, theMemoryLayout);
        for (Variable theVariable : theSSAProgram.getVariables()) {
            if (!(theVariable.isSynthetic()) && !(theSSAWriter.isStackVariable(theVariable))) {
                theSSAWriter.print("(local $");
                theSSAWriter.print(theVariable.getName());
                theSSAWriter.print(" ");
                theSSAWriter.print(WASMWriterUtils.toType(theVariable.resolveType()));
                theSSAWriter.print(") ;; ");
                theSSAWriter.println(theVariable.resolveType().resolve().name());
            }
        }
        theSSAWriter.printStackEnter();
        theSSAWriter.writeExpressionList(theEntry.getValue().bootstrapMethod.getExpressions());
        theWriter.println("   )");
        theWriter.println();
    }
    theWriter.println("   (func $newRuntimeClass (param $type i32) (param $staticSize i32) (param $enumValuesOffset i32) (result i32)");
    theWriter.println("         (local $newRef i32)");
    theWriter.println("         (set_local $newRef");
    theWriter.print("              (call $");
    theWriter.print(WASMWriterUtils.toClassName(theManagerClass.getClassName()));
    theWriter.print("_dmbcAddressnewObjectINTINTINT (i32.const 0) (get_local $staticSize) (i32.const -1) (i32.const ");
    theWriter.print(theGeneratedFunctions.indexOf("RUNTIMECLASS__resolvevtableindex"));
    theWriter.println("))");
    theWriter.println("         )");
    theWriter.println("         (i32.store offset=12 (get_local $newRef) (i32.add (get_local $newRef) (get_local $enumValuesOffset)))");
    theWriter.println("         (return (get_local $newRef))");
    theWriter.println("   )");
    theWriter.println();
    theWriter.println("   (func $LAMBDA__resolvevtableindex (param $thisRef i32) (param $methodId i32) (result i32)");
    theWriter.println("         (return (i32.load offset=8 (get_local $thisRef)))");
    theWriter.println("   )");
    theWriter.println();
    int theLambdaVTableResolveIndex = theGeneratedFunctions.indexOf("LAMBDA__resolvevtableindex");
    if (theLambdaVTableResolveIndex < 0) {
        throw new IllegalStateException("Cannot resolve LAMBDA__resolvevtableindex");
    }
    theWriter.println("   (func $newLambda (param $type i32) (param $implMethodNumber i32) (result i32)");
    theWriter.println("         (local $newRef i32)");
    theWriter.println("         (set_local $newRef");
    theWriter.print("            (call $");
    theWriter.print(WASMWriterUtils.toClassName(theManagerClass.getClassName()));
    theWriter.print("_dmbcAddressnewObjectINTINTINT (i32.const 0) (i32.const 12) (get_local $type) (i32.const ");
    theWriter.print(theLambdaVTableResolveIndex);
    theWriter.println("))");
    theWriter.println("         )");
    theWriter.println("         (i32.store offset=8 (get_local $newRef) (get_local $implMethodNumber))");
    theWriter.println("         (return (get_local $newRef))");
    theWriter.println("   )");
    theWriter.println();
    theWriter.println("   (func $compareValueI32 (param $p1 i32) (param $p2 i32) (result i32)");
    theWriter.println("     (block $b1");
    theWriter.println("         (br_if $b1");
    theWriter.println("             (i32.ne (get_local $p1) (get_local $p2))");
    theWriter.println("         )");
    theWriter.println("         (return (i32.const 0))");
    theWriter.println("     )");
    theWriter.println("     (block $b2");
    theWriter.println("         (br_if $b2");
    theWriter.println("             (i32.ge_s (get_local $p1) (get_local $p2))");
    theWriter.println("         )");
    theWriter.println("         (return (i32.const -1))");
    theWriter.println("     )");
    theWriter.println("     (return (i32.const 1))");
    theWriter.println("   )");
    theWriter.println();
    theWriter.println("   (func $compareValueF32 (param $p1 f32) (param $p2 f32) (result i32)");
    theWriter.println("     (block $b1");
    theWriter.println("         (br_if $b1");
    theWriter.println("             (f32.ne (get_local $p1) (get_local $p2))");
    theWriter.println("         )");
    theWriter.println("         (return (i32.const 0))");
    theWriter.println("     )");
    theWriter.println("     (block $b2");
    theWriter.println("         (br_if $b2");
    theWriter.println("             (f32.ge (get_local $p1) (get_local $p2))");
    theWriter.println("         )");
    theWriter.println("         (return (i32.const -1))");
    theWriter.println("     )");
    theWriter.println("     (return (i32.const 1))");
    theWriter.println("   )");
    theWriter.println();
    theWriter.println("   (func $INSTANCEOF_CHECK (param $thisRef i32) (param $type i32) (result i32)");
    theWriter.println("     (block $nullcheck");
    theWriter.println("         (br_if $nullcheck");
    theWriter.println("             (i32.ne (get_local $thisRef) (i32.const 0))");
    theWriter.println("         )");
    theWriter.println("         (return (i32.const 0))");
    theWriter.println("     )");
    theWriter.println("     (call_indirect $t_INSTANCEOF");
    theWriter.println("         (get_local $thisRef)");
    theWriter.println("         (get_local $type)");
    theWriter.println("         (call_indirect $t_RESOLVEMETHOD");
    theWriter.println("             (get_local $thisRef)");
    theWriter.print("             (i32.const ");
    theWriter.print(WASMSSAWriter.GENERATED_INSTANCEOF_METHOD_ID);
    theWriter.println(")");
    theWriter.println("             (i32.load offset=4 (get_local $thisRef))");
    theWriter.println("         )");
    theWriter.println("      )");
    theWriter.println("   )");
    theWriter.println();
    theWriter.println("   (func $jlClass_A1jlObjectgetEnumConstants (param $thisRef i32) (result i32)");
    theWriter.println("     (return (i32.load (i32.load offset=12 (get_local $thisRef))))");
    theWriter.println("   )");
    theWriter.println();
    theWriter.println("   (func $jlClass_BOOLEANdesiredAssertionStatus (param $thisRef i32) (result i32)");
    theWriter.println("     (return (i32.const 0))");
    theWriter.println("   )");
    theWriter.println();
    theWriter.println("   (func $RUNTIMECLASS__resolvevtableindex (param $thisRef i32) (param $methodId i32) (result i32)");
    BytecodeLinkedClass theClassLinkedCass = aLinkerContext.resolveClass(BytecodeObjectTypeRef.fromRuntimeClass(Class.class));
    BytecodeResolvedMethods theRuntimeMethodMap = theClassLinkedCass.resolvedMethods();
    theRuntimeMethodMap.stream().forEach(aMethodMapEntry -> {
        BytecodeMethod theMethod = aMethodMapEntry.getValue();
        if (!theMethod.getAccessFlags().isStatic()) {
            BytecodeVirtualMethodIdentifier theMethodIdentifier = aLinkerContext.getMethodCollection().identifierFor(theMethod);
            theWriter.println("     (block $m" + theMethodIdentifier.getIdentifier());
            theWriter.println("         (br_if $m" + theMethodIdentifier.getIdentifier() + " (i32.ne (get_local $methodId) (i32.const " + theMethodIdentifier.getIdentifier() + ")))");
            if (Objects.equals("getClass", theMethod.getName().stringValue())) {
                theWriter.println("         (unreachable)");
            } else if (Objects.equals("toString", theMethod.getName().stringValue())) {
                theWriter.println("         (unreachable)");
            } else if (Objects.equals("equals", theMethod.getName().stringValue())) {
                theWriter.println("         (unreachable)");
            } else if (Objects.equals("hashCode", theMethod.getName().stringValue())) {
                theWriter.println("         (unreachable)");
            } else if (Objects.equals("desiredAssertionStatus", theMethod.getName().stringValue())) {
                theWriter.println("         (return (i32.const " + theGeneratedFunctions.indexOf("Class_BOOLEANdesiredAssertionStatus") + "))");
            } else if (Objects.equals("getEnumConstants", theMethod.getName().stringValue())) {
                theWriter.println("         (return (i32.const " + theGeneratedFunctions.indexOf("Class_A1TObjectgetEnumConstants") + "))");
            } else {
                theWriter.println("         (unreachable)");
            }
            theWriter.println("     )");
        }
    });
    theWriter.println("     (unreachable)");
    theWriter.println("   )");
    theWriter.println();
    List<String> theGlobalVariables = new ArrayList<>();
    theWriter.println("   (func $bootstrap");
    theWriter.println("      (set_global $STACKTOP (i32.sub (i32.mul (current_memory) (i32.const 65536)) (i32.const 1)))");
    // Globals for static class data
    aLinkerContext.linkedClasses().forEach(aEntry -> {
        BytecodeLinkedClass theLinkedClass = aEntry.targetNode();
        if (Objects.equals(aEntry.edgeType().objectTypeRef(), BytecodeObjectTypeRef.fromRuntimeClass(Address.class))) {
            return;
        }
        if (theLinkedClass.getBytecodeClass().getAttributes().getAnnotationByType(EmulatedByRuntime.class.getName()) != null) {
            return;
        }
        theGlobalVariables.add(WASMWriterUtils.toClassName(aEntry.edgeType().objectTypeRef()) + "__runtimeClass");
        theWriter.print("      (set_global $");
        theWriter.print(WASMWriterUtils.toClassName(aEntry.edgeType().objectTypeRef()));
        theWriter.print("__runtimeClass (call $newRuntimeClass");
        theWriter.print(" (i32.const ");
        theWriter.print(theLinkedClass.getUniqueId());
        theWriter.print(")");
        WASMMemoryLayouter.MemoryLayout theLayout = theMemoryLayout.layoutFor(aEntry.edgeType().objectTypeRef());
        theWriter.print(" (i32.const ");
        theWriter.print(theLayout.classSize());
        theWriter.print(")");
        BytecodeResolvedFields theStaticFields = theLinkedClass.resolvedFields();
        if (theStaticFields.fieldByName("$VALUES") != null) {
            theWriter.print(" (i32.const ");
            theWriter.print(theLayout.offsetForClassMember("$VALUES"));
            theWriter.println(")");
        } else {
            theWriter.print(" (i32.const -1)");
        }
        theWriter.println("))");
    });
    WASMMemoryLayouter.MemoryLayout theStringMemoryLayout = theMemoryLayout.layoutFor(theStringClass.getClassName());
    aLinkerContext.linkedClasses().forEach(aEntry -> {
        if (aEntry.targetNode().getBytecodeClass().getAttributes().getAnnotationByType(EmulatedByRuntime.class.getName()) != null) {
            return;
        }
        if (!Objects.equals(aEntry.edgeType().objectTypeRef(), BytecodeObjectTypeRef.fromRuntimeClass(Address.class))) {
            theWriter.print("      (call $");
            theWriter.print(WASMWriterUtils.toClassName(aEntry.edgeType().objectTypeRef()));
            theWriter.println("__classinitcheck)");
        }
    });
    List<StringValue> thePoolValues = theConstantPool.stringValues();
    for (int i = 0; i < thePoolValues.size(); i++) {
        StringValue theConstantInPool = thePoolValues.get(i);
        String theData = theConstantInPool.getStringValue();
        byte[] theDataBytes = theData.getBytes();
        theGlobalVariables.add("stringPool" + i);
        theGlobalVariables.add("stringPool" + i + "__array");
        theWriter.print("      (set_global $stringPool");
        theWriter.print(i);
        theWriter.print("__array ");
        String theMethodName = WASMWriterUtils.toMethodName(BytecodeObjectTypeRef.fromRuntimeClass(MemoryManager.class), "newArray", new BytecodeMethodSignature(BytecodeObjectTypeRef.fromRuntimeClass(Address.class), new BytecodeTypeRef[] { BytecodePrimitiveTypeRef.INT, BytecodePrimitiveTypeRef.INT, BytecodePrimitiveTypeRef.INT }));
        theWriter.print("(call $");
        theWriter.print(theMethodName);
        // UNUSED argument
        theWriter.print(" (i32.const 0) ");
        // Length
        theWriter.print(" (i32.const ");
        theWriter.print(theDataBytes.length);
        theWriter.print(")");
        // We also need the runtime class
        theWriter.print(" (get_global $");
        theWriter.print(WASMWriterUtils.toClassName(theArrayClass.getClassName()));
        theWriter.print("__runtimeClass");
        theWriter.print(")");
        // Plus the vtable index
        theWriter.print(" (i32.const ");
        theWriter.print(theResolver.resolveVTableMethodByType(BytecodeObjectTypeRef.fromRuntimeClass(Array.class)));
        theWriter.println(")))");
        // Set array value
        for (int j = 0; j < theDataBytes.length; j++) {
            // 
            int offset = 20 + j * 4;
            theWriter.print("      (i32.store ");
            theWriter.print("offset=" + offset + " ");
            theWriter.print("(get_global $stringPool");
            theWriter.print(i);
            theWriter.print("__array) ");
            theWriter.print("(i32.const ");
            theWriter.print(theDataBytes[j]);
            theWriter.println("))");
        }
        theWriter.print("      (set_global $stringPool");
        theWriter.print(i);
        theWriter.print(" (call $");
        theWriter.print(WASMWriterUtils.toClassName(theManagerClass.getClassName()));
        theWriter.print("_dmbcAddressnewObjectINTINTINT");
        // Unused argument
        theWriter.print(" (i32.const 0)");
        theWriter.print(" (i32.const ");
        theWriter.print(theStringMemoryLayout.instanceSize());
        theWriter.print(")");
        theWriter.print(" (i32.const ");
        theWriter.print(theStringClass.getUniqueId());
        theWriter.print(")");
        theWriter.print(" (i32.const ");
        theWriter.print(theResolver.resolveVTableMethodByType(theStringClass.getClassName()));
        theWriter.print(")");
        theWriter.println("))");
        theWriter.print("      (call $");
        theWriter.print(WASMWriterUtils.toClassName(theStringClass.getClassName()));
        theWriter.print("_VOIDinitA1BYTE ");
        theWriter.print(" (get_global $stringPool");
        theWriter.print(i);
        theWriter.print(")");
        theWriter.print(" (get_global $stringPool");
        theWriter.print(i);
        theWriter.println("__array))");
    }
    // After the Bootstrap, we need to all the static stuff on the stack, so it is not garbage collected
    theWriter.print("      (set_global $STACKTOP (i32.sub (get_global $STACKTOP) (i32.const ");
    theWriter.print(theGlobalVariables.size() * 4);
    theWriter.println(")))");
    for (int i = 0; i < theGlobalVariables.size(); i++) {
        theWriter.print("      (i32.store offset=");
        theWriter.print(i * 4);
        theWriter.print(" (get_global $STACKTOP) (get_global $");
        theWriter.print(theGlobalVariables.get(i));
        theWriter.println("))");
    }
    theWriter.println("   )");
    theWriter.println();
    for (int i = 0; i < thePoolValues.size(); i++) {
        theWriter.print("   (global $stringPool");
        theWriter.print(i);
        theWriter.println(" (mut i32) (i32.const 0))");
        theWriter.print("   (global $stringPool");
        theWriter.print(i);
        theWriter.println("__array (mut i32) (i32.const 0))");
    }
    theWriter.println("   (global $STACKTOP (mut i32) (i32.const 0))");
    // Globals for static class data
    aLinkerContext.linkedClasses().forEach(aEntry -> {
        if (Objects.equals(aEntry.edgeType().objectTypeRef(), BytecodeObjectTypeRef.fromRuntimeClass(Address.class))) {
            return;
        }
        if (aEntry.targetNode().getBytecodeClass().getAttributes().getAnnotationByType(EmulatedByRuntime.class.getName()) != null) {
            return;
        }
        theWriter.print("   (global $");
        theWriter.print(WASMWriterUtils.toClassName(aEntry.edgeType().objectTypeRef()));
        theWriter.println("__runtimeClass (mut i32) (i32.const 0))");
    });
    theWriter.println();
    theWriter.println("   (export \"bootstrap\" (func $bootstrap))");
    // Write exports
    aLinkerContext.linkedClasses().forEach(aEntry -> {
        BytecodeLinkedClass theLinkedClass = aEntry.targetNode();
        if (theLinkedClass.getBytecodeClass().getAccessFlags().isInterface()) {
            return;
        }
        BytecodeResolvedMethods theMethodMap = theLinkedClass.resolvedMethods();
        theMethodMap.stream().forEach(aMethodMapEntry -> {
            BytecodeMethod t = aMethodMapEntry.getValue();
            BytecodeAnnotation theExport = t.getAttributes().getAnnotationByType(Export.class.getName());
            if (theExport != null) {
                theWriter.print("   (export \"");
                theWriter.print(theExport.getElementValueByName("value").stringValue());
                theWriter.print("\" (func $");
                theWriter.print(WASMWriterUtils.toMethodName(aEntry.edgeType().objectTypeRef(), t.getName(), t.getSignature()));
                theWriter.println("))");
            }
        });
    });
    theWriter.print("   (export \"main\" (func $");
    theWriter.print(WASMWriterUtils.toMethodName(BytecodeObjectTypeRef.fromRuntimeClass(aEntryPointClass), aEntryPointMethodName, aEntryPointSignatue));
    theWriter.println("))");
    theWriter.println();
    for (Map.Entry<String, String> theEntry : theGlobalTypes.entrySet()) {
        theWriter.print("   (type $t_");
        theWriter.print(theEntry.getKey());
        theWriter.print(" ");
        theWriter.print(theEntry.getValue());
        theWriter.println(")");
    }
    theWriter.println(")");
    theWriter.flush();
    return new WASMCompileResult(aLinkerContext, theGeneratedFunctions, theStringWriter.toString(), theMemoryLayout);
}
Also used : BytecodeMethodSignature(de.mirkosertic.bytecoder.core.BytecodeMethodSignature) Address(de.mirkosertic.bytecoder.classlib.Address) HashMap(java.util.HashMap) BytecodeMethod(de.mirkosertic.bytecoder.core.BytecodeMethod) ArrayList(java.util.ArrayList) ProgramGenerator(de.mirkosertic.bytecoder.ssa.ProgramGenerator) BytecodeResolvedMethods(de.mirkosertic.bytecoder.core.BytecodeResolvedMethods) BytecodeLinkedClass(de.mirkosertic.bytecoder.core.BytecodeLinkedClass) StringValue(de.mirkosertic.bytecoder.ssa.StringValue) RegionNode(de.mirkosertic.bytecoder.ssa.RegionNode) BytecodeResolvedFields(de.mirkosertic.bytecoder.core.BytecodeResolvedFields) HashSet(java.util.HashSet) Program(de.mirkosertic.bytecoder.ssa.Program) BytecodeTypeRef(de.mirkosertic.bytecoder.core.BytecodeTypeRef) BytecodeArrayTypeRef(de.mirkosertic.bytecoder.core.BytecodeArrayTypeRef) BytecodeClass(de.mirkosertic.bytecoder.core.BytecodeClass) BytecodeLinkedClass(de.mirkosertic.bytecoder.core.BytecodeLinkedClass) HashMap(java.util.HashMap) Map(java.util.Map) BytecodeAnnotation(de.mirkosertic.bytecoder.core.BytecodeAnnotation) BytecodeVirtualMethodIdentifier(de.mirkosertic.bytecoder.core.BytecodeVirtualMethodIdentifier) Variable(de.mirkosertic.bytecoder.ssa.Variable) StringWriter(java.io.StringWriter) Export(de.mirkosertic.bytecoder.api.Export) PrintWriter(java.io.PrintWriter) MemoryManager(de.mirkosertic.bytecoder.classlib.MemoryManager) Array(java.lang.reflect.Array) BytecodeObjectTypeRef(de.mirkosertic.bytecoder.core.BytecodeObjectTypeRef) Relooper(de.mirkosertic.bytecoder.relooper.Relooper) ConstantPool(de.mirkosertic.bytecoder.backend.ConstantPool) BytecodeImportedLink(de.mirkosertic.bytecoder.core.BytecodeImportedLink) BytecodeClass(de.mirkosertic.bytecoder.core.BytecodeClass)

Example 8 with BytecodeMethod

use of de.mirkosertic.bytecoder.core.BytecodeMethod in project Bytecoder by mirkosertic.

the class CompileTarget method compileToJS.

public CompileResult compileToJS(CompileOptions aOptions, Class aClass, String aMethodName, BytecodeMethodSignature aSignature) {
    BytecodeLinkerContext theLinkerContext = new BytecodeLinkerContext(bytecodeLoader, aOptions.getLogger());
    BytecodeLinkedClass theClassLinkedCass = theLinkerContext.resolveClass(BytecodeObjectTypeRef.fromRuntimeClass(Class.class));
    theClassLinkedCass.resolveConstructorInvocation(new BytecodeMethodSignature(BytecodePrimitiveTypeRef.VOID, new BytecodeTypeRef[] {}));
    // Lambda handling
    BytecodeLinkedClass theCallsite = theLinkerContext.resolveClass(BytecodeObjectTypeRef.fromRuntimeClass(VM.ImplementingCallsite.class));
    theCallsite.resolveVirtualMethod("invokeExact", new BytecodeMethodSignature(BytecodeObjectTypeRef.fromRuntimeClass(Object.class), new BytecodeTypeRef[] { new BytecodeArrayTypeRef(BytecodeObjectTypeRef.fromRuntimeClass(Object.class), 1) }));
    BytecodeObjectTypeRef theTypeRef = BytecodeObjectTypeRef.fromRuntimeClass(aClass);
    BytecodeLinkedClass theClass = theLinkerContext.resolveClass(theTypeRef);
    BytecodeMethod theMethod = theClass.getBytecodeClass().methodByNameAndSignatureOrNull(aMethodName, aSignature);
    if (theMethod.getAccessFlags().isStatic()) {
        theClass.resolveStaticMethod(aMethodName, aSignature);
    } else {
        theClass.resolveVirtualMethod(aMethodName, aSignature);
    }
    // Before code generation we have to make sure that all abstract method implementations are linked correctly
    aOptions.getLogger().info("Resolving abstract method hierarchy");
    theLinkerContext.resolveAbstractMethodsInSubclasses();
    return backend.generateCodeFor(aOptions, theLinkerContext, aClass, aMethodName, aSignature);
}
Also used : BytecodeTypeRef(de.mirkosertic.bytecoder.core.BytecodeTypeRef) BytecodeMethodSignature(de.mirkosertic.bytecoder.core.BytecodeMethodSignature) BytecodeObjectTypeRef(de.mirkosertic.bytecoder.core.BytecodeObjectTypeRef) BytecodeLinkerContext(de.mirkosertic.bytecoder.core.BytecodeLinkerContext) BytecodeArrayTypeRef(de.mirkosertic.bytecoder.core.BytecodeArrayTypeRef) BytecodeMethod(de.mirkosertic.bytecoder.core.BytecodeMethod) BytecodeLinkedClass(de.mirkosertic.bytecoder.core.BytecodeLinkedClass) BytecodeLinkedClass(de.mirkosertic.bytecoder.core.BytecodeLinkedClass)

Aggregations

BytecodeMethod (de.mirkosertic.bytecoder.core.BytecodeMethod)8 BytecodeLinkedClass (de.mirkosertic.bytecoder.core.BytecodeLinkedClass)7 BytecodeMethodSignature (de.mirkosertic.bytecoder.core.BytecodeMethodSignature)7 BytecodeObjectTypeRef (de.mirkosertic.bytecoder.core.BytecodeObjectTypeRef)5 BytecodeTypeRef (de.mirkosertic.bytecoder.core.BytecodeTypeRef)5 BytecodeArrayTypeRef (de.mirkosertic.bytecoder.core.BytecodeArrayTypeRef)4 BytecodeLinkerContext (de.mirkosertic.bytecoder.core.BytecodeLinkerContext)4 BytecodeClass (de.mirkosertic.bytecoder.core.BytecodeClass)3 BytecodeResolvedMethods (de.mirkosertic.bytecoder.core.BytecodeResolvedMethods)3 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)3 ConstantPool (de.mirkosertic.bytecoder.backend.ConstantPool)2 Address (de.mirkosertic.bytecoder.classlib.Address)2 MemoryManager (de.mirkosertic.bytecoder.classlib.MemoryManager)2 BytecodeAnnotation (de.mirkosertic.bytecoder.core.BytecodeAnnotation)2 BytecodeCodeAttributeInfo (de.mirkosertic.bytecoder.core.BytecodeCodeAttributeInfo)2 BytecodeImportedLink (de.mirkosertic.bytecoder.core.BytecodeImportedLink)2 Relooper (de.mirkosertic.bytecoder.relooper.Relooper)2 Program (de.mirkosertic.bytecoder.ssa.Program)2 ProgramGenerator (de.mirkosertic.bytecoder.ssa.ProgramGenerator)2