/
JITCompiler.java
443 lines (372 loc) · 18.4 KB
/
JITCompiler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
/***** BEGIN LICENSE BLOCK *****
* Version: EPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Eclipse Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/epl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2006-2008 Charles O Nutter <headius@headius.com>
* Copyright (C) 2008 Thomas E Enebo <enebo@acm.org>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the EPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the EPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.compiler;
import org.jruby.MetaClass;
import org.jruby.Ruby;
import org.jruby.RubyEncoding;
import org.jruby.RubyInstanceConfig;
import org.jruby.RubyModule;
import org.jruby.ast.util.SexpMaker;
import org.jruby.internal.runtime.methods.CompiledIRMethod;
import org.jruby.internal.runtime.methods.MixedModeIRMethod;
import org.jruby.ir.IRMethod;
import org.jruby.ir.interpreter.InterpreterContext;
import org.jruby.ir.targets.JVMVisitor;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.threading.DaemonThreadFactory;
import org.jruby.util.JavaNameMangler;
import org.jruby.util.OneShotClassLoader;
import org.jruby.util.cli.Options;
import org.jruby.util.log.Logger;
import org.jruby.util.log.LoggerFactory;
import org.objectweb.asm.Opcodes;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
public class JITCompiler implements JITCompilerMBean {
private static final Logger LOG = LoggerFactory.getLogger("JITCompiler");
public static final String RUBY_JIT_PREFIX = "rubyjit";
public static final String CLASS_METHOD_DELIMITER = "$$";
public static class JITCounts {
private final AtomicLong compiledCount = new AtomicLong(0);
private final AtomicLong successCount = new AtomicLong(0);
private final AtomicLong failCount = new AtomicLong(0);
private final AtomicLong abandonCount = new AtomicLong(0);
private final AtomicLong compileTime = new AtomicLong(0);
private final AtomicLong averageCompileTime = new AtomicLong(0);
private final AtomicLong codeSize = new AtomicLong(0);
private final AtomicLong averageCodeSize = new AtomicLong(0);
private final AtomicLong largestCodeSize = new AtomicLong(0);
}
private final JITCounts counts = new JITCounts();
private final ExecutorService executor;
private final Ruby runtime;
private final RubyInstanceConfig config;
public JITCompiler(Ruby runtime) {
this.runtime = runtime;
this.config = runtime.getInstanceConfig();
this.executor = new ThreadPoolExecutor(
0, // don't start threads until needed
2, // two max
60, // stop then if no jitting for 60 seconds
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(),
new DaemonThreadFactory("Ruby-" + runtime.getRuntimeNumber() + "-JIT", Thread.MIN_PRIORITY));
}
public long getSuccessCount() {
return counts.successCount.get();
}
public long getCompileCount() {
return counts.compiledCount.get();
}
public long getFailCount() {
return counts.failCount.get();
}
public long getCompileTime() {
return counts.compileTime.get() / 1000;
}
public long getAbandonCount() {
return counts.abandonCount.get();
}
public long getCodeSize() {
return counts.codeSize.get();
}
public long getAverageCodeSize() {
return counts.averageCodeSize.get();
}
public long getAverageCompileTime() {
return counts.averageCompileTime.get() / 1000;
}
public long getLargestCodeSize() {
return counts.largestCodeSize.get();
}
public void tearDown() {
try {
executor.shutdown();
} catch (SecurityException se) {
// ignore, can't shut down executor
}
}
public Runnable getTaskFor(ThreadContext context, Compilable method) {
if (method instanceof MixedModeIRMethod) {
return new JITTask((MixedModeIRMethod) method, method.getClassName(context));
}
return new FullBuildTask(method);
}
public void buildThresholdReached(ThreadContext context, final Compilable method) {
final RubyInstanceConfig config = context.runtime.getInstanceConfig();
// Disable any other jit tasks from entering queue
method.setCallCount(-1);
Runnable jitTask = getTaskFor(context, method);
if (config.getJitBackground() && config.getJitThreshold() > 0) {
try {
executor.submit(jitTask);
} catch (RejectedExecutionException ree) {
// failed to submit, just run it directly
jitTask.run();
}
} else {
// Because are non-asynchonously build if the JIT threshold happens to be 0 we will have no ic yet.
method.ensureInstrsReady();
// just run directly
jitTask.run();
}
}
private static final MethodHandles.Lookup PUBLIC_LOOKUP = MethodHandles.publicLookup().in(Ruby.class);
private class FullBuildTask implements Runnable {
private final Compilable method;
public FullBuildTask(Compilable method) {
this.method = method;
}
public void run() {
try {
method.completeBuild(method.getIRScope().prepareFullBuild());
if (config.isJitLogging()) {
log(method.getImplementationClass(), method.getFile(), method.getLine(), method.getName(), "done building");
}
} catch (Throwable t) {
if (config.isJitLogging()) {
log(method.getImplementationClass(), method.getFile(), method.getLine(), method.getName(),
"Could not build; passes run: " + method.getIRScope().getExecutedPasses(), t.getMessage());
if (config.isJitLoggingVerbose()) {
t.printStackTrace();
}
}
}
}
}
private class JITTask implements Runnable {
private final String className;
private final MixedModeIRMethod method;
private final String methodName;
public JITTask(MixedModeIRMethod method, String className) {
this.method = method;
this.className = className;
this.methodName = method.getName();
}
public void run() {
try {
// Check if the method has been explicitly excluded
if (config.getExcludedMethods().size() > 0) {
String excludeModuleName = className;
if (method.getImplementationClass().getMethodLocation().isSingleton()) {
IRubyObject possibleRealClass = ((MetaClass) method.getImplementationClass()).getAttached();
if (possibleRealClass instanceof RubyModule) {
excludeModuleName = "Meta:" + ((RubyModule) possibleRealClass).getName();
}
}
if ((config.getExcludedMethods().contains(excludeModuleName)
|| config.getExcludedMethods().contains(excludeModuleName + "#" + methodName)
|| config.getExcludedMethods().contains(methodName))) {
method.setCallCount(-1);
if (config.isJitLogging()) {
log(method.getImplementationClass(), method.getFile(), method.getLine(), methodName, "skipping method: " + excludeModuleName + "#" + methodName);
}
return;
}
}
String key = SexpMaker.sha1(method.getIRScope());
JVMVisitor visitor = new JVMVisitor();
JITClassGenerator generator = new JITClassGenerator(className, methodName, key, runtime, method, visitor);
generator.compile();
// FIXME: reinstate active bytecode size check
// At this point we still need to reinstate the bytecode size check, to ensure we're not loading code
// that's so big that JVMs won't even try to compile it. Removed the check because with the new IR JIT
// bytecode counts often include all nested scopes, even if they'd be different methods. We need a new
// mechanism of getting all method sizes.
Class sourceClass = visitor.defineFromBytecode(method.getIRScope(), generator.bytecode(), new OneShotClassLoader(runtime.getJRubyClassLoader()));
if (sourceClass == null) {
// class could not be found nor generated; give up on JIT and bail out
counts.failCount.incrementAndGet();
return;
} else {
generator.updateCounters(counts);
}
// successfully got back a jitted method
long methodCount = counts.successCount.incrementAndGet();
// logEvery n methods based on configuration
if (config.getJitLogEvery() > 0) {
if (methodCount % config.getJitLogEvery() == 0) {
log(method.getImplementationClass(), method.getFile(), method.getLine(), methodName, "live compiled methods: " + methodCount);
}
}
if (config.isJitLogging()) {
log(method.getImplementationClass(), method.getFile(), method.getLine(), className + "." + methodName, "done jitting");
}
Map<Integer, MethodType> signatures = ((IRMethod)method.getIRScope()).getNativeSignatures();
String jittedName = ((IRMethod)method.getIRScope()).getJittedName();
if (signatures.size() == 1) {
// only variable-arity
method.completeBuild(
new CompiledIRMethod(
PUBLIC_LOOKUP.findStatic(sourceClass, jittedName, signatures.get(-1)),
method.getIRScope(),
method.getVisibility(),
method.getImplementationClass(),
method.getIRScope().receivesKeywordArgs()));
} else {
// also specific-arity
for (Map.Entry<Integer, MethodType> entry : signatures.entrySet()) {
if (entry.getKey() == -1) continue; // variable arity handle pushed above
method.completeBuild(
new CompiledIRMethod(
PUBLIC_LOOKUP.findStatic(sourceClass, jittedName, signatures.get(-1)),
PUBLIC_LOOKUP.findStatic(sourceClass, jittedName, entry.getValue()),
entry.getKey(),
method.getIRScope(),
method.getVisibility(),
method.getImplementationClass(),
method.getIRScope().receivesKeywordArgs()));
break;
}
}
} catch (Throwable t) {
if (config.isJitLogging()) {
log(method.getImplementationClass(), method.getFile(), method.getLine(), className + "." + methodName, "Could not compile; passes run: " + method.getIRScope().getExecutedPasses(), t.getMessage());
if (config.isJitLoggingVerbose()) {
t.printStackTrace();
}
}
counts.failCount.incrementAndGet();
}
}
}
public static String getHashForString(String str) {
return getHashForBytes(RubyEncoding.encodeUTF8(str));
}
public static String getHashForBytes(byte[] bytes) {
try {
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
sha1.update(bytes);
byte[] digest = sha1.digest();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < digest.length; i++) {
builder.append(Integer.toString( ( digest[i] & 0xff ) + 0x100, 16).substring( 1 ));
}
return builder.toString().toUpperCase(Locale.ENGLISH);
} catch (NoSuchAlgorithmException nsae) {
throw new RuntimeException(nsae);
}
}
public static class JITClassGenerator {
public JITClassGenerator(String className, String methodName, String key, Ruby ruby, MixedModeIRMethod method, JVMVisitor visitor) {
this.packageName = JITCompiler.RUBY_JIT_PREFIX;
if (RubyInstanceConfig.JAVA_VERSION == Opcodes.V1_7 || Options.COMPILE_INVOKEDYNAMIC.load() == true) {
// Some versions of Java 7 seems to have a bug that leaks definitions across cousin classloaders
// so we force the class name to be unique to this runtime.
// Also, invokedynamic forces us to make jitted bytecode unique to each runtime, since the call sites cache
// at class level rather than at our runtime level. This makes it impossible to share jitted bytecode
// across runtimes.
digestString = key + Math.abs(ruby.hashCode());
} else {
digestString = key;
}
this.className = packageName + "/" + className.replace('.', '/') + CLASS_METHOD_DELIMITER + JavaNameMangler.mangleMethodName(methodName) + "_" + digestString;
this.name = this.className.replaceAll("/", ".");
this.methodName = methodName;
this.method = method;
this.visitor = visitor;
}
@SuppressWarnings("unchecked")
protected void compile() {
if (bytecode != null) return;
// Time the compilation
long start = System.nanoTime();
InterpreterContext ic = method.ensureInstrsReady();
int insnCount = ic.getInstructions().length;
if (insnCount > Options.JIT_MAXSIZE.load()) {
// methods with more than our limit of basic blocks are likely too large to JIT, so bail out
throw new NotCompilableException("Could not compile " + method + "; instruction count " + insnCount + " exceeds threshold of " + Options.JIT_MAXSIZE.load());
}
// This may not be ok since we'll end up running passes specific to JIT
// CON FIXME: Really should clone scope before passes in any case
bytecode = visitor.compileToBytecode(method.getIRScope());
compileTime = System.nanoTime() - start;
}
void updateCounters(JITCounts counts) {
counts.compiledCount.incrementAndGet();
counts.compileTime.addAndGet(compileTime);
counts.codeSize.addAndGet(bytecode.length);
counts.averageCompileTime.set(counts.compileTime.get() / counts.compiledCount.get());
counts.averageCodeSize.set(counts.codeSize.get() / counts.compiledCount.get());
synchronized (counts) {
if (counts.largestCodeSize.get() < bytecode.length) {
counts.largestCodeSize.set(bytecode.length);
}
}
}
public void generate() {
compile();
}
public byte[] bytecode() {
return bytecode;
}
public String name() {
return name;
}
@Override
public String toString() {
return methodName + "() at " + method.getFile() + ":" + method.getLine();
}
private final String packageName;
private final String className;
private final String methodName;
private final String digestString;
private final MixedModeIRMethod method;
private final JVMVisitor visitor;
private byte[] bytecode;
private long compileTime;
private String name;
}
static void log(RubyModule implementationClass, String file, int line, String name, String message, String... reason) {
boolean isBlock = implementationClass == null;
String className = isBlock ? "<block>" : implementationClass.getBaseName();
if (className == null) className = "<anon class>";
name = isBlock ? "" : "." + name;
StringBuilder builder = new StringBuilder(message + ":" + className + name + " at " + file + ":" + line);
if (reason.length > 0) {
builder.append(" because of: \"");
for (int i = 0; i < reason.length; i++) {
builder.append(reason[i]);
}
builder.append('"');
}
LOG.info(builder.toString());
}
}