1/*
2 * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23package org.graalvm.compiler.core.match;
24
25import static org.graalvm.compiler.debug.DebugOptions.LogVerbose;
26
27import java.util.List;
28
29import org.graalvm.compiler.core.gen.NodeLIRBuilder;
30import org.graalvm.compiler.core.match.MatchPattern.MatchResultCode;
31import org.graalvm.compiler.core.match.MatchPattern.Result;
32import org.graalvm.compiler.debug.CounterKey;
33import org.graalvm.compiler.debug.DebugContext;
34import org.graalvm.compiler.graph.GraalGraphError;
35import org.graalvm.compiler.graph.Node;
36import org.graalvm.compiler.nodeinfo.Verbosity;
37
38import jdk.vm.ci.meta.Value;
39
40/**
41 * A named {@link MatchPattern} along with a {@link MatchGenerator} that can be evaluated to replace
42 * one or more {@link Node}s with a single {@link Value}.
43 */
44
45public class MatchStatement {
46    private static final CounterKey MatchStatementSuccess = DebugContext.counter("MatchStatementSuccess");
47
48    /**
49     * A printable name for this statement. Usually it's just the name of the method doing the
50     * emission.
51     */
52    private final String name;
53
54    /**
55     * The actual match pattern.
56     */
57    private final MatchPattern pattern;
58
59    /**
60     * The method in the {@link NodeLIRBuilder} subclass that will actually do the code emission.
61     */
62    private MatchGenerator generatorMethod;
63
64    /**
65     * The name of arguments in the order they are expected to be passed to the generator method.
66     */
67    private String[] arguments;
68
69    public MatchStatement(String name, MatchPattern pattern, MatchGenerator generator, String[] arguments) {
70        this.name = name;
71        this.pattern = pattern;
72        this.generatorMethod = generator;
73        this.arguments = arguments;
74    }
75
76    /**
77     * Attempt to match the current statement against a Node.
78     *
79     * @param builder the current builder instance.
80     * @param node the node to be matched
81     * @param nodes the nodes in the current block
82     * @return true if the statement matched something and set a {@link ComplexMatchResult} to be
83     *         evaluated by the NodeLIRBuilder.
84     */
85    public boolean generate(NodeLIRBuilder builder, int index, Node node, List<Node> nodes) {
86        DebugContext debug = node.getDebug();
87        assert index == nodes.indexOf(node);
88        // Check that the basic shape matches
89        Result result = pattern.matchShape(node, this);
90        if (result != Result.OK) {
91            return false;
92        }
93        // Now ensure that the other safety constraints are matched.
94        MatchContext context = new MatchContext(builder, this, index, node, nodes);
95        result = pattern.matchUsage(node, context);
96        if (result == Result.OK) {
97            // Invoke the generator method and set the result if it's non null.
98            ComplexMatchResult value = generatorMethod.match(builder.getNodeMatchRules(), buildArgList(context));
99            if (value != null) {
100                context.setResult(value);
101                MatchStatementSuccess.increment(debug);
102                DebugContext.counter("MatchStatement[%s]", getName()).increment(debug);
103                return true;
104            }
105            // The pattern matched but some other code generation constraint disallowed code
106            // generation for the pattern.
107            if (LogVerbose.getValue(node.getOptions())) {
108                debug.log("while matching %s|%s %s %s returned null", context.getRoot().toString(Verbosity.Id), context.getRoot().getClass().getSimpleName(), getName(), generatorMethod.getName());
109                debug.log("with nodes %s", formatMatch(node));
110            }
111        } else {
112            if (LogVerbose.getValue(node.getOptions()) && result.code != MatchResultCode.WRONG_CLASS) {
113                debug.log("while matching %s|%s %s %s", context.getRoot().toString(Verbosity.Id), context.getRoot().getClass().getSimpleName(), getName(), result);
114            }
115        }
116        return false;
117    }
118
119    /**
120     * @param context
121     * @return the Nodes captured by the match rule in the order expected by the generatorMethod
122     */
123    private Object[] buildArgList(MatchContext context) {
124        Object[] result = new Object[arguments.length];
125        for (int i = 0; i < arguments.length; i++) {
126            if ("root".equals(arguments[i])) {
127                result[i] = context.getRoot();
128            } else {
129                result[i] = context.namedNode(arguments[i]);
130                if (result[i] == null) {
131                    throw new GraalGraphError("Can't find named node %s", arguments[i]);
132                }
133            }
134        }
135        return result;
136    }
137
138    public String formatMatch(Node root) {
139        return pattern.formatMatch(root);
140    }
141
142    public MatchPattern getPattern() {
143        return pattern;
144    }
145
146    public String getName() {
147        return name;
148    }
149
150    @Override
151    public String toString() {
152        return pattern.toString();
153    }
154}
155