Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/openj9
Path: blob/master/runtime/compiler/control/rossa.cpp
6000 views
1
/*******************************************************************************
2
* Copyright (c) 2000, 2022 IBM Corp. and others
3
*
4
* This program and the accompanying materials are made available under
5
* the terms of the Eclipse Public License 2.0 which accompanies this
6
* distribution and is available at https://www.eclipse.org/legal/epl-2.0/
7
* or the Apache License, Version 2.0 which accompanies this distribution and
8
* is available at https://www.apache.org/licenses/LICENSE-2.0.
9
*
10
* This Source Code may also be made available under the following
11
* Secondary Licenses when the conditions for such availability set
12
* forth in the Eclipse Public License, v. 2.0 are satisfied: GNU
13
* General Public License, version 2 with the GNU Classpath
14
* Exception [1] and GNU General Public License, version 2 with the
15
* OpenJDK Assembly Exception [2].
16
*
17
* [1] https://www.gnu.org/software/classpath/license.html
18
* [2] http://openjdk.java.net/legal/assembly-exception.html
19
*
20
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
21
*******************************************************************************/
22
23
#include <stdio.h>
24
#include <stdlib.h>
25
#include <string.h>
26
27
#ifdef WINDOWS
28
// Undefine the winsockapi because winsock2 defines it. Removes warnings.
29
#if defined(_WINSOCKAPI_) && !defined(_WINSOCK2API_)
30
#undef _WINSOCKAPI_
31
#endif
32
#include <winsock2.h>
33
#include <process.h>
34
#else
35
#include <sys/types.h>
36
#include <sys/socket.h>
37
#include <netinet/in.h>
38
#include <netdb.h>
39
#include <unistd.h>
40
#include <pthread.h>
41
#ifdef J9ZOS390
42
#include <arpa/inet.h>
43
#endif
44
#endif
45
#ifdef J9ZTPF
46
#include <tpf/c_eb0eb.h>
47
#include <tpf/sysapi.h>
48
#include <tpf/tpfapi.h>
49
#include <tpf/c_cinfc.h>
50
#endif
51
52
#include "env/annotations/AnnotationBase.hpp"
53
54
#define J9_EXTERNAL_TO_VM
55
#include "codegen/PrivateLinkage.hpp"
56
#include "control/CompilationRuntime.hpp"
57
#include "control/CompilationThread.hpp"
58
#include "control/JitDump.hpp"
59
#include "control/Recompilation.hpp"
60
#include "control/RecompilationInfo.hpp"
61
#include "runtime/ArtifactManager.hpp"
62
#include "runtime/CodeCache.hpp"
63
#include "runtime/CodeCacheManager.hpp"
64
#include "runtime/CodeCacheReclamation.h"
65
#include "runtime/codertinit.hpp"
66
#include "runtime/IProfiler.hpp"
67
#include "runtime/HWProfiler.hpp"
68
#include "runtime/RelocationRuntime.hpp"
69
#include "env/PersistentInfo.hpp"
70
#include "env/ClassLoaderTable.hpp"
71
#include "env/J2IThunk.hpp"
72
#include "env/PersistentCHTable.hpp"
73
#include "env/CompilerEnv.hpp"
74
#include "env/jittypes.h"
75
#include "env/ClassTableCriticalSection.hpp"
76
#include "env/VerboseLog.hpp"
77
78
#include "ilgen/IlGeneratorMethodDetails_inlines.hpp"
79
80
/* Hardware Profiling */
81
#if defined(TR_HOST_S390) && defined(BUILD_Z_RUNTIME_INSTRUMENTATION)
82
#include "z/runtime/ZHWProfiler.hpp"
83
#elif defined(TR_HOST_POWER)
84
#include "p/runtime/PPCHWProfiler.hpp"
85
#endif
86
87
#include "control/rossa.h"
88
#include "control/OptimizationPlan.hpp"
89
#include "control/CompilationController.hpp"
90
#include "runtime/IProfiler.hpp"
91
92
#define _UTE_STATIC_
93
#include "env/ut_j9jit.h"
94
95
#include "jitprotos.h"
96
#if defined(J9VM_OPT_SHARED_CLASSES)
97
#include "j9jitnls.h"
98
#endif
99
#include "env/J9SharedCache.hpp"
100
101
#ifdef J9VM_OPT_JAVA_CRYPTO_ACCELERATION
102
#include "runtime/Crypto.hpp"
103
#endif
104
105
#include "infra/Monitor.hpp"
106
107
#include "j9.h"
108
#include "j9cfg.h"
109
#include "vmaccess.h"
110
#include "jvminit.h"
111
#include "j9port.h"
112
#include "env/exports.h"
113
#if defined(J9VM_OPT_JITSERVER)
114
#include "env/JITServerPersistentCHTable.hpp"
115
#include "net/CommunicationStream.hpp"
116
#include "net/ClientStream.hpp"
117
#include "net/LoadSSLLibs.hpp"
118
#include "runtime/JITClientSession.hpp"
119
#include "runtime/JITServerAOTCache.hpp"
120
#include "runtime/JITServerAOTDeserializer.hpp"
121
#include "runtime/JITServerIProfiler.hpp"
122
#include "runtime/JITServerSharedROMClassCache.hpp"
123
#include "runtime/JITServerStatisticsThread.hpp"
124
#include "runtime/Listener.hpp"
125
#endif /* defined(J9VM_OPT_JITSERVER) */
126
127
extern "C" int32_t encodeCount(int32_t count);
128
129
extern "C" {
130
struct J9RASdumpContext;
131
}
132
133
#if defined(TR_TARGET_X86) && defined(TR_HOST_32BIT)
134
extern TR_X86CPUIDBuffer *queryX86TargetCPUID(void * javaVM);
135
#endif
136
137
extern void setupCodeCacheParameters(int32_t *, OMR::CodeCacheCodeGenCallbacks *callBacks, int32_t *numHelpers, int32_t *CCPreLoadedCodeSize);
138
extern "C" void stopInterpreterProfiling(J9JITConfig *jitConfig);
139
extern "C" void restartInterpreterProfiling();
140
141
#ifdef J9VM_JIT_RUNTIME_INSTRUMENTATION
142
// extern until these functions are added to oti/jitprotos.h
143
extern "C" UDATA initializeJITRuntimeInstrumentation(J9JavaVM *vm);
144
#endif
145
146
extern void *ppcPicTrampInit(TR_FrontEnd *, TR::PersistentInfo *);
147
extern TR_Debug *createDebugObject(TR::Compilation *);
148
149
150
bool isQuickstart = false;
151
152
#define TRANSLATE_METHODHANDLE_TAKES_FLAGS
153
154
TR::Monitor *vpMonitor = 0;
155
156
157
char *compilationErrorNames[]={
158
"compilationOK", // 0
159
"compilationFailure", // 1
160
"compilationRestrictionILNodes", // 2
161
"compilationRestrictionRecDepth", // 3
162
"compilationRestrictedMethod", // 4
163
"compilationExcessiveComplexity", // 5
164
"compilationNotNeeded", // 6
165
"compilationSuspended", // 7
166
"compilationExcessiveSize", // 8
167
"compilationInterrupted", // 9
168
"compilationMetaDataFailure", //10
169
"compilationInProgress", //11
170
"compilationCHTableCommitFailure",//12
171
"compilationMaxCallerIndexExceeded",//13
172
"compilationKilledByClassReplacement",//14
173
"compilationHeapLimitExceeded", //15
174
"compilationNeededAtHigherLevel", //16
175
"compilationAotValidateFieldFailure", //17
176
"compilationAotStaticFieldReloFailure", //18
177
"compilationAotClassReloFailure", //19
178
"compilationAotThunkReloFailure", //20
179
"compilationAotTrampolineReloFailure", //21
180
"compilationAotPicTrampolineReloFailure", //22
181
"compilationAotCacheFullReloFailure", //23
182
"compilationAotUnknownReloTypeFailure", //24
183
"compilationCodeReservationFailure", //25
184
"compilationAotHasInvokehandle", //26
185
"compilationTrampolineFailure", //27
186
"compilationRecoverableTrampolineFailure", // 28
187
"compilationIlGenFailure", // 29
188
"compilationIllegalCodeCacheSwitch", // 30
189
"compilationNullSubstituteCodeCache", // 31
190
"compilationCodeMemoryExhausted", // 32
191
"compilationGCRPatchFailure", // 33
192
"compilationAotValidateMethodExitFailure", // 34
193
"compilationAotValidateMethodEnterFailure", // 35
194
"compilationAotArrayClassReloFailure", // 36
195
"compilationLambdaEnforceScorching", // 37
196
"compilationInternalPointerExceedLimit", // 38
197
"compilationAotRelocationInterrupted", // 39
198
"compilationAotClassChainPersistenceFailure", // 40
199
"compilationLowPhysicalMemory", // 41
200
"compilationDataCacheError", // 42
201
"compilationCodeCacheError", // 43
202
"compilationRecoverableCodeCacheError", // 44
203
"compilationAotHasInvokeVarHandle", //45
204
"compilationAotValidateStringCompressionFailure", // 46
205
"compilationFSDHasInvokeHandle", //47
206
"compilationVirtualAddressExhaustion", //48
207
"compilationEnforceProfiling", //49
208
"compilationSymbolValidationManagerFailure", //50
209
"compilationAOTNoSupportForAOTFailure", //51
210
"compilationAOTValidateTMFailure", //52
211
"compilationILGenUnsupportedValueTypeOperationFailure", //53
212
"compilationAOTRelocationRecordGenerationFailure", //54
213
"compilationAotPatchedCPConstant", //55
214
"compilationAotHasInvokeSpecialInterface", //56
215
"compilationAotValidateExceptionHookFailure", //57
216
"compilationAotBlockFrequencyReloFailure", //58
217
"compilationAotRecompQueuedFlagReloFailure", //59
218
"compilationAOTValidateOSRFailure", //60
219
#if defined(J9VM_OPT_JITSERVER)
220
"compilationStreamFailure", // compilationFirstJITServerFailure = 61
221
"compilationStreamLostMessage", // 62
222
"compilationStreamMessageTypeMismatch", // 63
223
"compilationStreamVersionIncompatible", // 64
224
"compilationStreamInterrupted", // 65
225
"aotCacheDeserializationFailure", // 66
226
#endif /* defined(J9VM_OPT_JITSERVER) */
227
"compilationMaxError",
228
};
229
230
int32_t aggressiveOption = 0;
231
232
233
// Tells the sampler thread whether it is being interrupted to resume it or to
234
// shut it down.
235
//
236
volatile bool shutdownSamplerThread = false; // only set once
237
238
239
extern "C" void *compileMethodHandleThunk(j9object_t methodHandle, j9object_t arg, J9VMThread *vmThread, U_32 flags);
240
extern "C" J9NameAndSignature newInstancePrototypeNameAndSig;
241
242
extern "C" void getOutOfIdleStates(TR::CompilationInfo::TR_SamplerStates expectedState, TR::CompilationInfo *compInfo, const char* reason);
243
244
245
extern "C" IDATA
246
launchGPU(J9VMThread *vmThread, jobject invokeObject,
247
J9Method *method, int deviceId,
248
I_32 gridDimX, I_32 gridDimY, I_32 gridDimZ,
249
I_32 blockDimX, I_32 blockDimY, I_32 blockDimZ,
250
void **args);
251
252
extern "C" void promoteGPUCompile(J9VMThread *vmThread);
253
254
extern "C" int32_t setUpHooks(J9JavaVM * javaVM, J9JITConfig * jitConfig, TR_FrontEnd * vm);
255
extern "C" int32_t startJITServer(J9JITConfig *jitConfig);
256
extern "C" int32_t waitJITServerTermination(J9JITConfig *jitConfig);
257
258
char *AOTcgDiagOn="1";
259
260
261
262
// -----------------------------------------------------------------------------
263
// Method translation
264
// -----------------------------------------------------------------------------
265
266
extern "C" IDATA j9jit_testarossa(struct J9JITConfig * jitConfig, J9VMThread * vmThread, J9Method * method, void * oldStartPC)
267
{
268
return j9jit_testarossa_err(jitConfig, vmThread, method, oldStartPC, NULL);
269
}
270
271
272
extern "C" IDATA
273
j9jit_testarossa_err(
274
struct J9JITConfig *jitConfig,
275
J9VMThread *vmThread,
276
J9Method *method,
277
void *oldStartPC,
278
TR_CompilationErrorCode *compErrCode)
279
{
280
// The method is called by the interpreter when a method's invocation count has reached zero.
281
// Rather than just compiling blindly, pass the controller an event, and let it decide what to do.
282
//
283
bool queued = false;
284
TR_YesNoMaybe async = TR_maybe;
285
TR_MethodEvent event;
286
if (oldStartPC)
287
{
288
// any recompilation attempt using fixUpMethodCode would go here
289
J9::PrivateLinkage::LinkageInfo *linkageInfo = J9::PrivateLinkage::LinkageInfo::get(oldStartPC);
290
TR_PersistentJittedBodyInfo* jbi = TR::Recompilation::getJittedBodyInfoFromPC(oldStartPC);
291
292
if (!jbi)
293
{
294
return 0;
295
}
296
297
TR_PersistentMethodInfo *pmi = jbi->getMethodInfo();
298
299
if (pmi && pmi->hasBeenReplaced()) // HCR
300
{
301
// Obsolete method bodies are invalid.
302
//
303
TR::Recompilation::fixUpMethodCode(oldStartPC);
304
jbi->setIsInvalidated();
305
}
306
307
if (jbi->getIsInvalidated())
308
{
309
event._eventType = TR_MethodEvent::MethodBodyInvalidated;
310
async = TR_no;
311
}
312
else
313
{
314
// Async compilation is disabled or recompilations triggered from jitted code
315
//
316
// Check if the method has already been scheduled for compilation and return
317
// abruptly if so. This will reduce contention on the optimizationPlanMonitor
318
// when a profiled compilation is followed by a very slow recompilation
319
// (until the recompilation is over, the java threads will try to trigger
320
// recompilations again and again. See defect 193193)
321
//
322
if (linkageInfo->isBeingCompiled())
323
{
324
TR_J9VMBase *fe = TR_J9VMBase::get(jitConfig, vmThread);
325
if (fe->isAsyncCompilation())
326
return 0; // early return because the method is queued for compilation
327
}
328
// If PersistentJittedBody contains the profile Info and has BlockFrequencyInfo, it will set the
329
// isQueuedForRecompilation field which can be used by the jitted code at runtime to skip the profiling
330
// code if it has made request to recompile this method.
331
if (jbi->getProfileInfo() != NULL && jbi->getProfileInfo()->getBlockFrequencyInfo() != NULL)
332
jbi->getProfileInfo()->getBlockFrequencyInfo()->setIsQueuedForRecompilation();
333
334
event._eventType = TR_MethodEvent::OtherRecompilationTrigger;
335
}
336
}
337
else
338
{
339
event._eventType = TR_MethodEvent::InterpreterCounterTripped;
340
// Experimental code: user may want to artificially delay the compilation
341
// of methods to gather more IProfiler info
342
TR::CompilationInfo * compInfo = getCompilationInfo(jitConfig);
343
if (TR::Options::_compilationDelayTime > 0)
344
{
345
if (!TR::CompilationInfo::isJNINative(method))
346
{
347
if (compInfo->getPersistentInfo()->getElapsedTime() < 1000 * TR::Options::_compilationDelayTime)
348
{
349
// Add 2 to the invocationCount
350
int32_t count = TR::CompilationInfo::getInvocationCount(method);
351
if (count >= 0)
352
{
353
TR::CompilationInfo::setInvocationCount(method, 2);
354
return 0;
355
}
356
}
357
}
358
}
359
#if defined(J9VM_OPT_JITSERVER)
360
// Do not allow local compilations in JITServer server mode
361
if (compInfo->getPersistentInfo()->getRemoteCompilationMode() == JITServer::SERVER)
362
return 0;
363
#endif
364
}
365
366
event._j9method = method;
367
event._oldStartPC = oldStartPC;
368
event._vmThread = vmThread;
369
event._classNeedingThunk = 0;
370
bool newPlanCreated;
371
IDATA result = 0;
372
TR_OptimizationPlan *plan = TR::CompilationController::getCompilationStrategy()->processEvent(&event, &newPlanCreated);
373
374
// if the controller decides to compile this method, trigger the compilation
375
if (plan)
376
{
377
TR::CompilationInfo * compInfo = getCompilationInfo(jitConfig);
378
379
// Check to see if we need to wake up the sampling thread should it be in DEEPIDLE state
380
if (compInfo->getSamplerState() == TR::CompilationInfo::SAMPLER_DEEPIDLE &&
381
compInfo->_intervalStats._numFirstTimeCompilationsInInterval >= 1)
382
getOutOfIdleStates(TR::CompilationInfo::SAMPLER_DEEPIDLE, compInfo, "comp req");
383
else if (compInfo->getSamplerState() == TR::CompilationInfo::SAMPLER_IDLE &&
384
compInfo->_intervalStats._numFirstTimeCompilationsInInterval >= TR::Options::_numFirstTimeCompilationsToExitIdleMode)
385
getOutOfIdleStates(TR::CompilationInfo::SAMPLER_IDLE, compInfo, "comp req");
386
387
{ // scope for details
388
TR::IlGeneratorMethodDetails details(method);
389
result = (IDATA)compInfo->compileMethod(vmThread, details, oldStartPC, async, compErrCode, &queued, plan);
390
}
391
392
if (!queued && newPlanCreated)
393
TR_OptimizationPlan::freeOptimizationPlan(plan);
394
}
395
else // OOM; Very rare case
396
{
397
// Invalidation requests MUST not be ignored even if OOM
398
if (event._eventType == TR_MethodEvent::MethodBodyInvalidated)
399
{
400
// Allocate a plan on the stack and force a synchronous compilation
401
// so that we wait until the compilation finishes
402
TR_OptimizationPlan plan;
403
plan.init(noOpt); // use the cheapest compilation; It's unlikely the compilation will
404
// succeed because we are running low on native memory
405
plan.setIsStackAllocated(); // mark that this plan is not dynamically allocated
406
TR::CompilationInfo * compInfo = getCompilationInfo(jitConfig);
407
408
{ // scope for details
409
TR::IlGeneratorMethodDetails details(method);
410
result = (IDATA)compInfo->compileMethod(vmThread, details, oldStartPC, async, compErrCode, &queued, &plan);
411
}
412
413
// We should probably prevent any future non-essential compilation
414
compInfo->getPersistentInfo()->setDisableFurtherCompilation(true);
415
if (TR::Options::getCmdLineOptions()->getVerboseOption(TR_VerbosePerformance))
416
{
417
TR_VerboseLog::writeLineLocked(TR_Vlog_PERF,"t=%6u Disable further compilation due to OOM while creating an optimization plan", (uint32_t)compInfo->getPersistentInfo()->getElapsedTime());
418
}
419
}
420
}
421
return result;
422
}
423
424
extern "C" IDATA
425
retranslateWithPreparationForMethodRedefinition(
426
struct J9JITConfig *jitConfig,
427
J9VMThread *vmThread,
428
J9Method *method,
429
void *oldStartPC)
430
{
431
return retranslateWithPreparation(jitConfig, vmThread, method, oldStartPC, TR_PersistentMethodInfo::RecompDueToInlinedMethodRedefinition);
432
}
433
434
extern "C" IDATA
435
retranslateWithPreparation(
436
struct J9JITConfig *jitConfig,
437
J9VMThread *vmThread,
438
J9Method *method,
439
void *oldStartPC,
440
UDATA reason)
441
{
442
if (!TR::CompilationInfo::get()->asynchronousCompilation() && !J9::PrivateLinkage::LinkageInfo::get(oldStartPC)->recompilationAttempted())
443
{
444
TR::Recompilation::fixUpMethodCode(oldStartPC);
445
}
446
447
TR_PersistentJittedBodyInfo* jbi = TR::Recompilation::getJittedBodyInfoFromPC(oldStartPC);
448
if (jbi)
449
{
450
TR_PersistentMethodInfo *pmi = jbi->getMethodInfo();
451
if (pmi)
452
pmi->setReasonForRecompilation(reason);
453
}
454
return j9jit_testarossa(jitConfig, vmThread, method, oldStartPC);
455
}
456
457
458
extern "C" void *
459
old_translateMethodHandle(J9VMThread *currentThread, j9object_t methodHandle)
460
{
461
void *result = compileMethodHandleThunk(methodHandle, NULL, currentThread, 0);
462
if (result)
463
{
464
static char *returnNullFromTranslateMethodHandle = feGetEnv("TR_returnNullFromTranslateMethodHandle");
465
if (returnNullFromTranslateMethodHandle)
466
result = NULL;
467
}
468
469
return result;
470
}
471
472
473
extern "C" void *
474
translateMethodHandle(J9VMThread *currentThread, j9object_t methodHandle, j9object_t arg, U_32 flags)
475
{
476
void *result = compileMethodHandleThunk(methodHandle, arg, currentThread, flags);
477
if (result)
478
{
479
static char *returnNullFromTranslateMethodHandle = feGetEnv("TR_returnNullFromTranslateMethodHandle");
480
if (returnNullFromTranslateMethodHandle)
481
result = NULL;
482
}
483
484
return result;
485
}
486
487
488
// -----------------------------------------------------------------------------
489
// NewInstanceImpl Thunks
490
// -----------------------------------------------------------------------------
491
492
extern "C" J9Method *
493
getNewInstancePrototype(J9VMThread * context)
494
{
495
J9Method *newInstanceProto = 0;
496
J9InternalVMFunctions *intFunc = context->javaVM->internalVMFunctions;
497
498
J9Class * jlClass = intFunc->internalFindKnownClass(context, J9VMCONSTANTPOOL_JAVALANGCLASS, J9_FINDKNOWNCLASS_FLAG_EXISTING_ONLY);
499
if (jlClass)
500
{
501
newInstanceProto = (J9Method *) intFunc->javaLookupMethod(
502
context,
503
jlClass,
504
(J9ROMNameAndSignature *) &newInstancePrototypeNameAndSig,
505
0,
506
J9_LOOK_DIRECT_NAS | J9_LOOK_VIRTUAL | J9_LOOK_NO_JAVA);
507
}
508
509
return newInstanceProto;
510
}
511
512
513
extern "C" UDATA
514
j9jit_createNewInstanceThunk_err(
515
struct J9JITConfig *jitConfig,
516
J9VMThread *vmThread,
517
J9Class *classNeedingThunk,
518
TR_CompilationErrorCode *compErrCode)
519
{
520
TR::CompilationInfo * compInfo = getCompilationInfo(jitConfig);
521
J9Method *method = getNewInstancePrototype(vmThread);
522
if (!method)
523
{
524
*compErrCode = compilationFailure;
525
return 0;
526
}
527
528
#if defined(J9VM_OPT_JITSERVER)
529
// Do not allow local compilations in JITServer server mode
530
if (compInfo->getPersistentInfo()->getRemoteCompilationMode() == JITServer::SERVER)
531
return 0;
532
#endif
533
534
bool queued = false;
535
536
TR_MethodEvent event;
537
event._eventType = TR_MethodEvent::NewInstanceImpl;
538
event._j9method = method;
539
event._oldStartPC = 0;
540
event._vmThread = vmThread;
541
bool newPlanCreated;
542
TR_OptimizationPlan *plan = TR::CompilationController::getCompilationStrategy()->processEvent(&event, &newPlanCreated);
543
UDATA result = 0;
544
if (plan)
545
{
546
// if the controller decides to compile this method, trigger the compilation and wait here
547
548
{ // scope for details
549
J9::NewInstanceThunkDetails details(method, classNeedingThunk);
550
result = (UDATA)compInfo->compileMethod(vmThread, details, 0, TR_maybe, compErrCode, &queued, plan);
551
}
552
553
if (!queued && newPlanCreated)
554
TR_OptimizationPlan::freeOptimizationPlan(plan);
555
}
556
557
return result;
558
}
559
560
561
extern "C" UDATA
562
j9jit_createNewInstanceThunk(struct J9JITConfig * jitConfig, J9VMThread * vmThread, J9Class * classNeedingThunk)
563
{
564
return j9jit_createNewInstanceThunk_err(jitConfig, vmThread, classNeedingThunk, NULL);
565
}
566
567
568
// -----------------------------------------------------------------------------
569
// JIT shutdown
570
// -----------------------------------------------------------------------------
571
572
extern "C" void
573
stopSamplingThread(J9JITConfig * jitConfig)
574
{
575
// Was the samplerThread even created?
576
if (jitConfig->samplerThread)
577
{
578
// TODO: add a trace point in this routine
579
//Trc_JIT_stopSamplingThread_Entry();
580
TR::CompilationInfo *compInfo = getCompilationInfo(jitConfig);
581
j9thread_monitor_enter(jitConfig->samplerMonitor);
582
// In most cases the state of the sampling thread should be SAMPLE_THR_INITIALIZED
583
// However, if an early error happens, stage 15 might not be run (this is where we initialize
584
// the thread) and so the thread could be in ATTACHED_STATE
585
TR_ASSERT(compInfo->getSamplingThreadLifetimeState() == TR::CompilationInfo::SAMPLE_THR_INITIALIZED ||
586
compInfo->getSamplingThreadLifetimeState() == TR::CompilationInfo::SAMPLE_THR_ATTACHED,
587
"sampling thread must be initialized or at least attached if we try to stop it");
588
// inform samplerThread to exit its loop
589
shutdownSamplerThread = true;
590
compInfo->setSamplingThreadLifetimeState(TR::CompilationInfo::SAMPLE_THR_STOPPING);
591
// interrupt possible nap time for the samplerThread
592
j9thread_interrupt(jitConfig->samplerThread);
593
// Wait for samplerThread to exit
594
while (compInfo->getSamplingThreadLifetimeState() != TR::CompilationInfo::SAMPLE_THR_DESTROYED)
595
j9thread_monitor_wait(jitConfig->samplerMonitor);
596
// At this point samplingThread has gone away
597
compInfo->setSamplerThread(NULL);
598
jitConfig->samplerThread = 0; // just in case we enter this routine again
599
j9thread_monitor_exit(jitConfig->samplerMonitor);
600
// sampleMonitor is no longer needed
601
j9thread_monitor_destroy(jitConfig->samplerMonitor);
602
jitConfig->samplerMonitor = 0;
603
//Trc_JIT_stopSamplingThread_Exit();
604
}
605
}
606
607
608
extern "C" void
609
freeJITConfig(J9JITConfig * jitConfig)
610
{
611
// This method must be called only when we are sure that there are no other java threads running
612
if (jitConfig)
613
{
614
// Do all JIT compiler present freeing.
615
//
616
J9JavaVM * javaVM = jitConfig->javaVM;
617
PORT_ACCESS_FROM_JAVAVM(javaVM);
618
619
// stopSamplingThread(jitConfig); // done during JitShutdown below
620
621
jitConfig->runtimeFlags &= ~J9JIT_JIT_ATTACHED;
622
623
// If the jitConfig will be freed,
624
// there is no chance to do all te JIT cleanup.
625
// Do the JIT cleanup now, even if we tried it before
626
//
627
JitShutdown(jitConfig);
628
629
// free the compilation info before freeing the frontend without thread info (jitConfig->compilationInfo)
630
// which is done on codert_OnUnload
631
TR::CompilationInfo::freeCompilationInfo(jitConfig);
632
633
// Tell the runtime to unload.
634
//
635
codert_OnUnload(javaVM);
636
}
637
}
638
639
640
// exclusive shutdown. This normally occurs when System.exit() is called by
641
// the usercode. The VM needs to notify the compilation thread before going
642
// exclusive - otherwise we end up with a deadlock scenario upon exit
643
//
644
extern "C" void
645
jitExclusiveVMShutdownPending(J9VMThread * vmThread)
646
{
647
#ifndef SMALL_APPTHREAD
648
J9JavaVM *javaVM = vmThread->javaVM;
649
#if defined(J9VM_OPT_JITSERVER)
650
TR::CompilationInfo * compInfo = getCompilationInfo(javaVM->jitConfig);
651
if (compInfo->getPersistentInfo()->getRemoteCompilationMode() == JITServer::SERVER)
652
{
653
TR_Listener *listener = ((TR_JitPrivateConfig*)(javaVM->jitConfig->privateConfig))->listener;
654
if (listener)
655
{
656
listener->stop();
657
}
658
}
659
#endif /* defined(J9VM_OPT_JITSERVER) */
660
661
getCompilationInfo(javaVM->jitConfig)->stopCompilationThreads();
662
#endif
663
}
664
665
// Code cache callbacks to be used by the VM
666
//
667
extern "C" U_8*
668
getCodeCacheWarmAlloc(void *codeCache)
669
{
670
TR::CodeCache * cc = static_cast<TR::CodeCache*>(codeCache);
671
return cc->getWarmCodeAlloc();
672
}
673
674
extern "C" U_8*
675
getCodeCacheColdAlloc(void *codeCache)
676
{
677
TR::CodeCache * cc = static_cast<TR::CodeCache*>(codeCache);
678
return cc->getColdCodeAlloc();
679
}
680
681
682
// -----------------------------------------------------------------------------
683
// JIT control
684
// -----------------------------------------------------------------------------
685
686
// Temporarily disable the jit so that no more methods are compiled
687
extern "C" void
688
disableJit(J9JITConfig * jitConfig)
689
{
690
TR::CompilationInfo * compInfo = getCompilationInfo(jitConfig);
691
J9JavaVM * vm = jitConfig->javaVM;
692
if (compInfo && compInfo->getNumCompThreadsActive() > 0)
693
{
694
// Suspend compilation.
695
// This will also flush any methods waiting for compilation
696
//
697
compInfo->suspendCompilationThread();
698
// Generate a trace point
699
Trc_JIT_DisableJIT(vm->internalVMFunctions->currentVMThread(vm));
700
701
// Turn off interpreter profiling
702
//
703
#if defined(J9VM_INTERP_PROFILING_BYTECODES)
704
stopInterpreterProfiling(jitConfig);
705
#endif
706
j9thread_monitor_enter(vm->vmThreadListMutex);
707
// Set the sampling frequency to a high value - this will send the sampling
708
// thread to sleep for a long time. If the jit is enabled later we will have
709
// to interrupt the sampling thread to get it going again.
710
//
711
TR::CompilationInfo::TR_SamplerStates samplerState = compInfo->getSamplerState();
712
if (samplerState != TR::CompilationInfo::SAMPLER_NOT_INITIALIZED && //jitConfig->samplerThread && // Must have a sampler thread
713
samplerState != TR::CompilationInfo::SAMPLER_SUSPENDED && // Nothing to do if sampler is already suspended
714
samplerState != TR::CompilationInfo::SAMPLER_STOPPED)
715
{
716
TR::PersistentInfo *persistentInfo = compInfo->getPersistentInfo();
717
compInfo->setSamplerState(TR::CompilationInfo::SAMPLER_SUSPENDED);
718
jitConfig->samplingFrequency = MAX_SAMPLING_FREQUENCY;
719
persistentInfo->setLastTimeSamplerThreadWasSuspended(persistentInfo->getElapsedTime());
720
if (TR::Options::getVerboseOption(TR_VerbosePerformance))
721
{
722
TR_VerboseLog::writeLineLocked(TR_Vlog_PERF,"t=%u\tSampling thread suspended and changed frequency to %d ms",
723
persistentInfo->getElapsedTime(), jitConfig->samplingFrequency);
724
}
725
}
726
// TODO: what are the implications of remaining in an appropriate JIT state?
727
// Should we change the state to STEADY just to be on the safe side?
728
// What if this happens during startup? We will kill the startup time?
729
730
//set the countDelta
731
J9VMThread * currentThread = vm->mainThread;
732
do
733
{
734
currentThread->jitCountDelta = 0;
735
} while ((currentThread = currentThread->linkNext) != vm->mainThread);
736
737
j9thread_monitor_exit(vm->vmThreadListMutex);
738
}
739
}
740
741
742
// Re-enable the jit after it has been disabled.
743
extern "C" void
744
enableJit(J9JITConfig * jitConfig)
745
{
746
TR::CompilationInfo * compInfo = getCompilationInfo(jitConfig);
747
J9JavaVM * vm = jitConfig->javaVM;
748
if (compInfo && compInfo->getNumCompThreadsActive() == 0)
749
{
750
// Re-enable interpreter profiling if needed
751
//
752
#if defined(J9VM_INTERP_PROFILING_BYTECODES)
753
restartInterpreterProfiling();
754
#endif
755
// Resume compilation.
756
//
757
compInfo->resumeCompilationThread();
758
// Generate a trace point
759
Trc_JIT_EnableJIT(vm->internalVMFunctions->currentVMThread(vm));
760
761
j9thread_monitor_enter(vm->vmThreadListMutex);
762
763
// Set the sampling frequency back to its proper value and kick the
764
// sampler thread back into life.
765
//
766
TR::CompilationInfo::TR_SamplerStates samplerState = compInfo->getSamplerState();
767
if (samplerState == TR::CompilationInfo::SAMPLER_SUSPENDED) // Nothing to do if sampler is not suspended
768
{
769
TR::PersistentInfo *persistentInfo = compInfo->getPersistentInfo();
770
compInfo->setSamplerState(TR::CompilationInfo::SAMPLER_DEFAULT);
771
jitConfig->samplingFrequency = TR::Options::getCmdLineOptions()->getSamplingFrequency();
772
// this wake up call counts as a tick, so mark that we have seen ticks active
773
// so that we need to wait another 5 seconds to enter idle
774
persistentInfo->setLastTimeThreadsWereActive(persistentInfo->getElapsedTime());
775
j9thread_interrupt(jitConfig->samplerThread); // interrupt the sampler to look at its new state
776
if (TR::Options::getVerboseOption(TR_VerbosePerformance))
777
{
778
TR_VerboseLog::writeLineLocked(TR_Vlog_SAMPLING,"t=%u\tSampling thread interrupted and changed frequency to %d ms",
779
persistentInfo->getElapsedTime(), jitConfig->samplingFrequency);
780
}
781
}
782
783
// Set the countDelta
784
J9VMThread * currentThread = vm->mainThread;
785
do
786
{
787
currentThread->jitCountDelta = 2;
788
} while ((currentThread = currentThread->linkNext) != vm->mainThread);
789
790
j9thread_monitor_exit(vm->vmThreadListMutex);
791
792
}
793
} // enableJit
794
795
796
// -----------------------------------------------------------------------------
797
// Programmatic compile interface
798
// -----------------------------------------------------------------------------
799
800
extern "C" I_32
801
command(J9VMThread * vmThread, const char * cmdString)
802
{
803
TR::CompilationInfo * compInfo = TR::CompilationInfo::get();
804
805
if (strncmp(cmdString, "beginningOfStartup", 18) == 0)
806
{
807
TR::Options::getCmdLineOptions()->setOption(TR_AssumeStartupPhaseUntilToldNotTo); // let the JIT know it should wait for endOfStartup hint
808
if (compInfo)
809
{
810
TR::PersistentInfo *persistentInfo = compInfo->getPersistentInfo();
811
// If we trust the application completely, then set CLP right away
812
// Otherwise, let JIT heuristics decide at next decision point
813
if (TR::Options::getCmdLineOptions()->getOption(TR_UseStrictStartupHints))
814
persistentInfo->setClassLoadingPhase(true); // Enter CLP right away
815
if (TR::Options::isAnyVerboseOptionSet(TR_VerboseCLP, TR_VerbosePerformance))
816
{
817
TR_VerboseLog::writeLineLocked(TR_Vlog_INFO,"Compiler.command(beginningOfStartup)");
818
}
819
}
820
return 0;
821
}
822
if (strncmp(cmdString, "endOfStartup", 12) == 0)
823
{
824
if (TR::Options::getCmdLineOptions()->getOption(TR_AssumeStartupPhaseUntilToldNotTo)) // refuse to do anything if JIT option was not specified
825
{
826
if (compInfo)
827
{
828
TR::PersistentInfo *persistentInfo = compInfo->getPersistentInfo();
829
persistentInfo->setExternalStartupEndedSignal(true);
830
// If we trust the application completely, then set CLP right away
831
// Otherwise, let JIT heuristics decide at next decision point
832
if (TR::Options::getCmdLineOptions()->getOption(TR_UseStrictStartupHints))
833
persistentInfo->setClassLoadingPhase(false);
834
if (TR::Options::isAnyVerboseOptionSet(TR_VerboseCLP, TR_VerbosePerformance))
835
{
836
TR_VerboseLog::writeLineLocked(TR_Vlog_INFO,"Compiler.command(endOfStartup)");
837
}
838
}
839
}
840
return 0;
841
}
842
843
return 0;
844
}
845
846
static IDATA
847
internalCompileClass(J9VMThread * vmThread, J9Class * clazz)
848
{
849
J9JavaVM * javaVM = vmThread->javaVM;
850
J9JITConfig * jitConfg = javaVM->jitConfig;
851
TR::CompilationInfo * compInfo = getCompilationInfo(jitConfig);
852
TR_J9VMBase *fe = TR_J9VMBase::get(jitConfg, NULL);
853
854
// To prevent class unloading we need VM access
855
bool threadHadNoVMAccess = (!(vmThread->publicFlags & J9_PUBLIC_FLAGS_VM_ACCESS));
856
if (threadHadNoVMAccess)
857
acquireVMAccess(vmThread);
858
859
J9Method * newInstanceThunk = getNewInstancePrototype(vmThread);
860
861
J9ROMMethod * romMethod = (J9ROMMethod *) J9ROMCLASS_ROMMETHODS(clazz->romClass);
862
J9Method * ramMethods = (J9Method *) (clazz->ramMethods);
863
for (uint32_t m = 0; m < clazz->romClass->romMethodCount; m++)
864
{
865
J9Method * method = &ramMethods[m];
866
if (!(romMethod->modifiers & (J9AccNative | J9AccAbstract))
867
&& method != newInstanceThunk
868
&& !TR::CompilationInfo::isCompiled(method)
869
&& !fe->isThunkArchetype(method))
870
{
871
bool queued = false;
872
TR_MethodEvent event;
873
event._eventType = TR_MethodEvent::InterpreterCounterTripped;
874
event._j9method = method;
875
event._oldStartPC = 0;
876
event._vmThread = vmThread;
877
event._classNeedingThunk = 0;
878
bool newPlanCreated;
879
TR_OptimizationPlan *plan = TR::CompilationController::getCompilationStrategy()->processEvent(&event, &newPlanCreated);
880
if (plan)
881
{
882
plan->setIsExplicitCompilation(true);
883
// If the controller decides to compile this method, trigger the compilation and wait here
884
885
{ // scope for details
886
TR::IlGeneratorMethodDetails details(method);
887
compInfo->compileMethod(vmThread, details, 0, TR_no, NULL, &queued, plan);
888
}
889
890
if (!queued && newPlanCreated)
891
TR_OptimizationPlan::freeOptimizationPlan(plan);
892
}
893
else // No memory to create an optimizationPlan
894
{
895
// There is no point to try to compile other methods if we cannot
896
// create an optimization plan. Bail out
897
break;
898
}
899
}
900
romMethod = nextROMMethod(romMethod);
901
}
902
903
if (threadHadNoVMAccess)
904
releaseVMAccess(vmThread);
905
906
return 1;
907
}
908
909
910
extern "C" IDATA
911
compileClass(J9VMThread * vmThread, jclass clazzParm)
912
{
913
J9JavaVM * javaVM = vmThread->javaVM;
914
J9Class * clazz;
915
IDATA rc;
916
917
acquireVMAccess(vmThread);
918
clazz = J9VM_J9CLASS_FROM_JCLASS(vmThread, clazzParm);
919
rc = internalCompileClass(vmThread, clazz);
920
releaseVMAccess(vmThread);
921
922
return rc;
923
}
924
925
926
extern "C" IDATA
927
compileClasses(J9VMThread * vmThread, const char * pattern)
928
{
929
IDATA foundClassToCompile = 0;
930
J9JavaVM * javaVM = vmThread->javaVM;
931
J9JITConfig * jitConfig = javaVM->jitConfig;
932
TR_FrontEnd * vm = TR_J9VMBase::get(jitConfig, vmThread);
933
TR::CompilationInfo * compInfo = TR::CompilationInfo::get(jitConfig);
934
if (!compInfo)
935
return foundClassToCompile;
936
PORT_ACCESS_FROM_JAVAVM(javaVM);
937
J9ClassWalkState classWalkState;
938
939
#define PATTERN_BUFFER_LENGTH 256
940
char patternBuffer[PATTERN_BUFFER_LENGTH];
941
char * patternString = patternBuffer;
942
int32_t patternLength = strlen(pattern);
943
bool freePatternString = false;
944
945
if (patternLength >= PATTERN_BUFFER_LENGTH)
946
{
947
patternString = (char*)j9mem_allocate_memory(patternLength + 1, J9MEM_CATEGORY_JIT);
948
if (!patternString)
949
return false;
950
freePatternString = true;
951
}
952
#undef PATTERN_BUFFER_LENGTH
953
954
memcpy(patternString, (char *)pattern, patternLength + 1);
955
956
/* Slashify the className */
957
for (int32_t i = 0; i < patternLength; ++i)
958
if (patternString[i] == '.')
959
patternString[i] = '/';
960
961
bool threadHadNoVMAccess = (!(vmThread->publicFlags & J9_PUBLIC_FLAGS_VM_ACCESS));
962
if (threadHadNoVMAccess)
963
acquireVMAccess(vmThread);
964
965
J9Class * clazz = javaVM->internalVMFunctions->allLiveClassesStartDo(&classWalkState, javaVM, NULL);
966
TR_LinkHead0<TR_ClassHolder> *classList = compInfo->getListOfClassesToCompile();
967
bool classListWasEmpty = classList ? false : true;
968
969
bool abortFlag = false;
970
while (clazz && !abortFlag)
971
{
972
if (!J9ROMCLASS_IS_PRIMITIVE_OR_ARRAY(clazz->romClass))
973
{
974
J9UTF8 * clazzUTRF8 = J9ROMCLASS_CLASSNAME(clazz->romClass);
975
976
// j9tty_printf(PORTLIB, "Class %.*s\n", J9UTF8_LENGTH(clazz), J9UTF8_DATA(clazz));
977
978
#define CLASSNAME_BUFFER_LENGTH 1000
979
char classNameBuffer[CLASSNAME_BUFFER_LENGTH];
980
char * classNameString = classNameBuffer;
981
bool freeClassNameString = false;
982
if (J9UTF8_LENGTH(clazzUTRF8) >= CLASSNAME_BUFFER_LENGTH)
983
{
984
classNameString = (char*)j9mem_allocate_memory((J9UTF8_LENGTH(clazzUTRF8)+1)*sizeof(char), J9MEM_CATEGORY_JIT);
985
if (!classNameString)
986
{
987
clazz = javaVM->internalVMFunctions->allLiveClassesNextDo(&classWalkState);
988
continue;
989
}
990
freeClassNameString = true;
991
}
992
#undef CLASSNAME_BUFFER_LENGTH
993
994
strncpy(classNameString, (char*)J9UTF8_DATA(clazzUTRF8), J9UTF8_LENGTH(clazzUTRF8));
995
996
if (strstr(classNameString, patternString))
997
{
998
TR_ClassHolder * c = NULL;
999
if (!classListWasEmpty) // If the list was not empty we must search for duplicates
1000
{
1001
for (c = classList->getFirst(); c; c = c->getNext())
1002
if (c->getClass() == clazz)
1003
break; // duplicate found
1004
}
1005
1006
if (!c) // no duplicate found
1007
{
1008
TR_ClassHolder *ch = new (PERSISTENT_NEW) TR_ClassHolder(clazz);
1009
if (ch)
1010
{
1011
classList->add(ch);
1012
foundClassToCompile = 1;
1013
}
1014
else
1015
{
1016
// cleanup after yourself
1017
abortFlag = true; // If we cannot allocate a small piece of persistent memory we must bail out
1018
}
1019
}
1020
}
1021
1022
if (freeClassNameString)
1023
j9mem_free_memory(classNameString);
1024
} // end if
1025
1026
clazz = javaVM->internalVMFunctions->allLiveClassesNextDo(&classWalkState);
1027
}
1028
1029
javaVM->internalVMFunctions->allLiveClassesEndDo(&classWalkState);
1030
1031
if (freePatternString)
1032
j9mem_free_memory(patternString);
1033
1034
// now compile all classes from the list
1035
TR_ClassHolder * trj9class;
1036
do {
1037
{
1038
TR::ClassTableCriticalSection compileClasses(vm);
1039
trj9class = classList->pop();
1040
}
1041
1042
if (trj9class)
1043
{
1044
// compile all methods from this class
1045
if (!abortFlag)
1046
internalCompileClass(vmThread, trj9class->getClass());
1047
// free the persistent memory
1048
TR_Memory::jitPersistentFree(trj9class);
1049
}
1050
} while (trj9class);
1051
1052
if (threadHadNoVMAccess)
1053
releaseVMAccess(vmThread);
1054
return foundClassToCompile;
1055
}
1056
1057
1058
// -----------------------------------------------------------------------------
1059
// JIT initialization
1060
// -----------------------------------------------------------------------------
1061
1062
TR_PersistentMemory * initializePersistentMemory(J9JITConfig * jitConfig);
1063
1064
extern "C" jint
1065
onLoadInternal(
1066
J9JavaVM *javaVM,
1067
J9JITConfig *jitConfig,
1068
char *xjitCommandLine,
1069
char *xaotCommandLine,
1070
UDATA flagsParm,
1071
void *reserved0,
1072
I_32 xnojit)
1073
{
1074
PORT_ACCESS_FROM_JAVAVM(javaVM);
1075
1076
jitConfig->javaVM = javaVM;
1077
jitConfig->jitLevelName = TR_BUILD_NAME;
1078
1079
TR::CodeCache *firstCodeCache;
1080
1081
/* Allocate the code and data cache lists */
1082
if (!(jitConfig->codeCacheList))
1083
{
1084
if ((jitConfig->codeCacheList = javaVM->internalVMFunctions->allocateMemorySegmentList(javaVM, 3, J9MEM_CATEGORY_JIT)) == NULL)
1085
return -1;
1086
}
1087
if (!(jitConfig->dataCacheList))
1088
{
1089
if ((jitConfig->dataCacheList = javaVM->internalVMFunctions->allocateMemorySegmentList(javaVM, 3, J9MEM_CATEGORY_JIT)) == NULL)
1090
return -1;
1091
}
1092
1093
// Callbacks for code cache allocation pointers
1094
jitConfig->codeCacheWarmAlloc = getCodeCacheWarmAlloc;
1095
jitConfig->codeCacheColdAlloc = getCodeCacheColdAlloc;
1096
1097
/* Allocate the privateConfig structure. Note that the AOTRT DLL does not allocate this structure */
1098
jitConfig->privateConfig = j9mem_allocate_memory(sizeof(TR_JitPrivateConfig), J9MEM_CATEGORY_JIT);
1099
if (jitConfig->privateConfig == NULL) // Memory Allocation Failure.
1100
return -1;
1101
1102
memset(jitConfig->privateConfig, 0, sizeof(TR_JitPrivateConfig));
1103
static_cast<TR_JitPrivateConfig *>(jitConfig->privateConfig)->aotValidHeader = TR_maybe;
1104
uintptr_t initialFlags = flagsParm;
1105
1106
// Force use of register maps
1107
//
1108
// todo: this has to be a runtime test for x-compilation
1109
//
1110
initialFlags |= J9JIT_CG_REGISTER_MAPS;
1111
1112
initialFlags |= J9JIT_GROW_CACHES;
1113
1114
jitConfig->runtimeFlags |= initialFlags; // assumes default of bestAvail if nothing set from cmdline
1115
1116
jitConfig->j9jit_printf = j9jit_printf;
1117
((TR_JitPrivateConfig*)jitConfig->privateConfig)->j9jitrt_printf = j9jitrt_printf;
1118
((TR_JitPrivateConfig*)jitConfig->privateConfig)->j9jitrt_lock_log = j9jitrt_lock_log;
1119
((TR_JitPrivateConfig*)jitConfig->privateConfig)->j9jitrt_unlock_log = j9jitrt_unlock_log;
1120
1121
// set up the entryPoints for compiling and for support of the
1122
// java.lang.Compiler class.
1123
jitConfig->entryPoint = j9jit_testarossa;
1124
jitConfig->retranslateWithPreparation = retranslateWithPreparation;
1125
jitConfig->retranslateWithPreparationForMethodRedefinition = retranslateWithPreparationForMethodRedefinition;
1126
jitConfig->entryPointForNewInstance = j9jit_createNewInstanceThunk;
1127
#if defined(TRANSLATE_METHODHANDLE_TAKES_FLAGS)
1128
jitConfig->translateMethodHandle = translateMethodHandle;
1129
#else
1130
jitConfig->translateMethodHandle = old_translateMethodHandle;
1131
#endif
1132
jitConfig->disableJit = disableJit;
1133
jitConfig->enableJit = enableJit;
1134
jitConfig->compileClass = compileClass;
1135
jitConfig->compileClasses = compileClasses;
1136
#ifdef ENABLE_GPU
1137
jitConfig->launchGPU = launchGPU;
1138
#endif
1139
jitConfig->promoteGPUCompile = promoteGPUCompile;
1140
jitConfig->command = command;
1141
jitConfig->bcSizeLimit = 0xFFFF;
1142
1143
#ifdef J9VM_OPT_JAVA_CRYPTO_ACCELERATION
1144
//Add support for AES methods.
1145
jitConfig->isAESSupportedByHardware = isAESSupportedByHardware;
1146
jitConfig->expandAESKeyInHardware = expandAESKeyInHardware;
1147
jitConfig->doAESInHardware = doAESInHardware;
1148
1149
//Add support for SHA methods.
1150
jitConfig->getCryptoHardwareFeatures = getCryptoHardwareFeatures;
1151
jitConfig->doSha256InHardware = doSha256InHardware;
1152
jitConfig->doSha512InHardware = doSha512InHardware;
1153
#endif
1154
1155
//set up our vlog Manager
1156
TR_VerboseLog::initialize(jitConfig);
1157
initializePersistentMemory(jitConfig);
1158
1159
// set up entry point for starting JITServer
1160
#if defined(J9VM_OPT_JITSERVER)
1161
jitConfig->startJITServer = startJITServer;
1162
jitConfig->waitJITServerTermination = waitJITServerTermination;
1163
#endif /* J9VM_OPT_JITSERVER */
1164
1165
TR_PersistentMemory * persistentMemory = (TR_PersistentMemory *)jitConfig->scratchSegment;
1166
if (persistentMemory == NULL)
1167
return -1;
1168
1169
// JITServer: persistentCHTable used to be inited here, but we have to move it after JITServer commandline opts
1170
// setting it to null here to catch anything that assumes it's set between here and the new init code.
1171
persistentMemory->getPersistentInfo()->setPersistentCHTable(NULL);
1172
1173
if (!TR::CompilationInfo::createCompilationInfo(jitConfig))
1174
return -1;
1175
1176
if (!TR_J9VMBase::createGlobalFrontEnd(jitConfig, TR::CompilationInfo::get()))
1177
return -1;
1178
1179
TR_J9VMBase * feWithoutThread(TR_J9VMBase::get(jitConfig, NULL));
1180
if (!feWithoutThread)
1181
return -1;
1182
1183
/*aotmcc-move it here from below !!!! this is after the jitConfig->runtimeFlags=AOT is set*/
1184
/*also jitConfig->javaVM = javaVM has to be set for the case we run j9.exe -Xnoaot ....*/
1185
J9VMThread *curThread = javaVM->internalVMFunctions->currentVMThread(javaVM);
1186
TR_J9VMBase * fe = TR_J9VMBase::get(jitConfig, curThread);
1187
1188
int32_t numCodeCachesToCreateAtStartup = 1;
1189
1190
#if defined(J9ZOS390) && !defined(TR_TARGET_64BIT)
1191
// zOS 31-bit
1192
J9JavaVM * vm = javaVM; //macro FIND_AND_CONSUME_ARG refers to javaVM as vm
1193
if (isQuickstart)
1194
{
1195
jitConfig->codeCacheKB = 1024;
1196
jitConfig->dataCacheKB = 1024;
1197
}
1198
else
1199
{
1200
jitConfig->codeCacheKB = 2048;
1201
jitConfig->dataCacheKB = 2048;
1202
}
1203
#else
1204
#if (defined(TR_HOST_POWER) || defined(TR_HOST_S390) || (defined(TR_HOST_X86) && defined(TR_HOST_64BIT)))
1205
jitConfig->codeCacheKB = 2048;
1206
jitConfig->dataCacheKB = 2048;
1207
1208
//zOS will set the code cache to create at startup after options are enabled below
1209
#if !defined(J9ZOS390)
1210
if (!isQuickstart) // for -Xquickstart start with one code cache
1211
numCodeCachesToCreateAtStartup = 4;
1212
#endif
1213
#else
1214
jitConfig->codeCacheKB = 2048; // WAS-throughput guided change
1215
//jitConfig->codeCacheKB = J9_JIT_CODE_CACHE_SIZE / 1024; // bytes -> k
1216
jitConfig->dataCacheKB = 512; // bytes -> k
1217
#endif
1218
#endif
1219
1220
1221
#if defined(J9VM_OPT_JITSERVER)
1222
if (javaVM->internalVMFunctions->isJITServerEnabled(javaVM))
1223
{
1224
// Use smaller caches on the server because
1225
// just one method's data is going to be stored there at a time
1226
jitConfig->codeCacheKB = 1024;
1227
jitConfig->dataCacheKB = 1024;
1228
}
1229
#endif
1230
1231
if (fe->isAOT_DEPRECATED_DO_NOT_USE())
1232
{
1233
jitConfig->codeCacheTotalKB = 128 * 1024; // default limit on amount of code that can be generated (128MB)
1234
jitConfig->dataCacheTotalKB = 64 * 1024; // default limit on amount of meta-data that can be generated (64MB)
1235
}
1236
else
1237
{
1238
#if defined(TR_TARGET_64BIT)
1239
jitConfig->codeCacheTotalKB = 256 * 1024;
1240
jitConfig->dataCacheTotalKB = 384 * 1024;
1241
#else
1242
jitConfig->codeCacheTotalKB = 64 * 1024;
1243
jitConfig->dataCacheTotalKB = 192 * 1024;
1244
#endif
1245
1246
#if defined(J9ZTPF)
1247
/*
1248
* The z/TPF OS does not have the ability to reserve memory. It allocates whatever it
1249
* is asked to allocate. Allocate the code cache based on a percentage (20%) of memory
1250
* the process is allowed to have; cap the maximum using the default 256m and use a 1m floor.
1251
* MAXXMMES is specified as the number of 1MB frames.
1252
* Use the default 2048 KB data cache. The default values for z/TPF can be
1253
* overridden via the command line interface.
1254
*/
1255
const uint16_t ZTPF_CODE_CACHE_DIVISOR = 5;
1256
1257
/* Retrieve the maximum number of 1MB frames that a z/TPF process can have and */
1258
/* then take 20% of that value to use for the code cache size. */
1259
const uint16_t physMemory = *(static_cast<uint16_t*>(cinfc_fast(CINFC_CMMMMES)) + 4) / ZTPF_CODE_CACHE_DIVISOR;
1260
1261
/* Provide a 1MB floor and 256MB ceiling for the code cache size */
1262
if (physMemory <= 1)
1263
{
1264
jitConfig->codeCacheKB = 1024;
1265
jitConfig->codeCacheTotalKB = 1024;
1266
}
1267
else if (physMemory < 256)
1268
{
1269
jitConfig->codeCacheKB = 2048;
1270
jitConfig->codeCacheTotalKB = physMemory * 1024;
1271
}
1272
else
1273
{
1274
jitConfig->codeCacheKB = 2048;
1275
jitConfig->codeCacheTotalKB = 256 * 1024;
1276
}
1277
1278
jitConfig->dataCacheKB = 2048;
1279
jitConfig->dataCacheTotalKB = 384 * 1024;
1280
#endif
1281
}
1282
1283
TR::Options::setScratchSpaceLimit(DEFAULT_SCRATCH_SPACE_LIMIT_KB * 1024);
1284
TR::Options::setScratchSpaceLowerBound(DEFAULT_SCRATCH_SPACE_LOWER_BOUND_KB * 1024);
1285
1286
jitConfig->samplingFrequency = TR::Options::getSamplingFrequency();
1287
1288
#if defined(DEBUG)
1289
static char * breakOnLoad = feGetEnv("TR_BreakOnLoad");
1290
if (breakOnLoad)
1291
TR::Compiler->debug.breakPoint();
1292
#endif
1293
1294
// Parse the command line options
1295
//
1296
if (xaotCommandLine)
1297
{
1298
char *endAOTOptions = TR::Options::processOptionsAOT(xaotCommandLine, jitConfig, feWithoutThread);
1299
if (*endAOTOptions)
1300
{
1301
// Generate AOT error message only if error occurs in -Xaot processing
1302
if (0 != (TR::Options::_processOptionsStatus & TR_AOTProcessErrorAOTOpts))
1303
{
1304
scan_failed(PORTLIB, "AOT", endAOTOptions);
1305
printf("<AOT: fatal error, invalid command line>\n");
1306
#ifdef DEBUG
1307
printf(" for help use -Xaot:help\n\n");
1308
#endif
1309
}
1310
return -1;
1311
}
1312
}
1313
1314
char *endJITOptions = TR::Options::processOptionsJIT(xjitCommandLine, jitConfig, feWithoutThread);
1315
1316
if (*endJITOptions)
1317
{
1318
// Generate JIT error message only if error occurs in -Xjit processing
1319
if (0 != (TR::Options::_processOptionsStatus & TR_JITProcessErrorJITOpts))
1320
{
1321
scan_failed(PORTLIB, "JIT", endJITOptions);
1322
printf("<JIT: fatal error, invalid command line>\n");
1323
#ifdef DEBUG
1324
printf(" for help use -Xjit:help\n\n");
1325
#endif
1326
}
1327
return -1;
1328
}
1329
1330
// Now that the options have been processed we can initialize the RuntimeAssumptionTables
1331
// If we cannot allocate various runtime assumption hash tables, fail the JVM
1332
1333
fe->initializeSystemProperties();
1334
1335
// Allocate trampolines for z/OS 64-bit
1336
#if defined(J9ZOS390)
1337
if (TR::Options::getCmdLineOptions()->getOption(TR_EnableRMODE64) && !isQuickstart)
1338
numCodeCachesToCreateAtStartup = 4;
1339
#endif
1340
1341
1342
#if defined(J9VM_OPT_JITSERVER)
1343
if (persistentMemory->getPersistentInfo()->getRemoteCompilationMode() != JITServer::SERVER)
1344
#endif
1345
{
1346
if (!persistentMemory->getPersistentInfo()->getRuntimeAssumptionTable()->init())
1347
return -1;
1348
}
1349
1350
TR_PersistentClassLoaderTable *loaderTable = new (PERSISTENT_NEW) TR_PersistentClassLoaderTable(persistentMemory);
1351
if (loaderTable == NULL)
1352
return -1;
1353
persistentMemory->getPersistentInfo()->setPersistentClassLoaderTable(loaderTable);
1354
1355
jitConfig->iprofilerBufferSize = TR::Options::_iprofilerBufferSize; //1024;
1356
1357
javaVM->minimumSuperclassArraySize = TR::Options::_minimumSuperclassArraySize;
1358
1359
if (!jitConfig->tracingHook && TR::Options::requiresDebugObject())
1360
{
1361
jitConfig->tracingHook = (void*) (TR_CreateDebug_t)createDebugObject;
1362
}
1363
1364
if (!jitConfig->tracingHook)
1365
TR::Options::suppressLogFileBecauseDebugObjectNotCreated();
1366
1367
TR_AOTStats *aotStats = (TR_AOTStats *)j9mem_allocate_memory(sizeof(TR_AOTStats), J9MEM_CATEGORY_JIT);
1368
memset(aotStats, 0, sizeof(TR_AOTStats));
1369
((TR_JitPrivateConfig*)jitConfig->privateConfig)->aotStats = aotStats;
1370
1371
TR::CodeCacheManager *codeCacheManager = (TR::CodeCacheManager *) j9mem_allocate_memory(sizeof(TR::CodeCacheManager), J9MEM_CATEGORY_JIT);
1372
if (codeCacheManager == NULL)
1373
return -1;
1374
memset(codeCacheManager, 0, sizeof(TR::CodeCacheManager));
1375
1376
// must initialize manager using the global (not thread specific) fe because current thread isn't guaranteed to live longer than the manager
1377
new (codeCacheManager) TR::CodeCacheManager(feWithoutThread, TR::Compiler->rawAllocator);
1378
1379
TR::CodeCacheConfig &codeCacheConfig = codeCacheManager->codeCacheConfig();
1380
1381
// Do not allow code caches smaller than 128KB
1382
if (jitConfig->codeCacheKB < 128)
1383
jitConfig->codeCacheKB = 128;
1384
if (!fe->isAOT_DEPRECATED_DO_NOT_USE())
1385
{
1386
if (jitConfig->codeCacheKB > 32768)
1387
jitConfig->codeCacheKB = 32768;
1388
}
1389
1390
if (jitConfig->codeCacheKB > jitConfig->codeCacheTotalKB)
1391
{
1392
/* Handle case where user has set codeCacheTotalKB smaller than codeCacheKB (e.g. -Xjit:codeTotal=256) by setting codeCacheKB = codeCacheTotalKB */
1393
jitConfig->codeCacheKB = jitConfig->codeCacheTotalKB;
1394
}
1395
1396
if (jitConfig->dataCacheKB > jitConfig->dataCacheTotalKB)
1397
{
1398
/* Handle case where user has set dataCacheTotalKB smaller than dataCacheKB (e.g. -Xjit:dataTotal=256) by setting dataCacheKB = dataCacheTotalKB */
1399
jitConfig->dataCacheKB = jitConfig->dataCacheTotalKB;
1400
}
1401
1402
I_32 maxNumberOfCodeCaches = jitConfig->codeCacheTotalKB / jitConfig->codeCacheKB;
1403
if (fe->isAOT_DEPRECATED_DO_NOT_USE())
1404
maxNumberOfCodeCaches = 1;
1405
1406
// setupCodeCacheParameters must stay before TR::CodeCacheManager::initialize() because it needs trampolineCodeSize
1407
setupCodeCacheParameters(&codeCacheConfig._trampolineCodeSize, &codeCacheConfig._mccCallbacks, &codeCacheConfig._numOfRuntimeHelpers, &codeCacheConfig._CCPreLoadedCodeSize);
1408
1409
if (!TR_TranslationArtifactManager::initializeGlobalArtifactManager(jitConfig->translationArtifacts, jitConfig->javaVM))
1410
return -1;
1411
1412
codeCacheConfig._allowedToGrowCache = (javaVM->jitConfig->runtimeFlags & J9JIT_GROW_CACHES) != 0;
1413
codeCacheConfig._lowCodeCacheThreshold = TR::Options::_lowCodeCacheThreshold;
1414
codeCacheConfig._verboseCodeCache = TR::Options::getCmdLineOptions()->getVerboseOption(TR_VerboseCodeCache);
1415
codeCacheConfig._verbosePerformance = TR::Options::getCmdLineOptions()->getVerboseOption(TR_VerbosePerformance);
1416
codeCacheConfig._verboseReclamation = TR::Options::getCmdLineOptions()->getVerboseOption(TR_VerboseCodeCacheReclamation);
1417
codeCacheConfig._doSanityChecks = TR::Options::getCmdLineOptions()->getOption(TR_CodeCacheSanityCheck);
1418
codeCacheConfig._codeCacheTotalKB = jitConfig->codeCacheTotalKB;
1419
codeCacheConfig._codeCacheKB = jitConfig->codeCacheKB;
1420
codeCacheConfig._codeCachePadKB = jitConfig->codeCachePadKB;
1421
codeCacheConfig._codeCacheAlignment = jitConfig->codeCacheAlignment;
1422
codeCacheConfig._codeCacheFreeBlockRecylingEnabled = !TR::Options::getCmdLineOptions()->getOption(TR_DisableFreeCodeCacheBlockRecycling);
1423
codeCacheConfig._largeCodePageSize = jitConfig->largeCodePageSize;
1424
codeCacheConfig._largeCodePageFlags = jitConfig->largeCodePageFlags;
1425
codeCacheConfig._maxNumberOfCodeCaches = maxNumberOfCodeCaches;
1426
codeCacheConfig._canChangeNumCodeCaches = (TR::Options::getCmdLineOptions()->getNumCodeCachesToCreateAtStartup() <= 0);
1427
1428
UDATA totalCacheBytes = codeCacheConfig._codeCacheTotalKB << 10;
1429
codeCacheConfig._highCodeCacheOccupancyThresholdInBytes = TR::Options::_highCodeCacheOccupancyPercentage * (totalCacheBytes / 100);
1430
1431
static char * segmentCarving = feGetEnv("TR_CodeCacheConsolidation");
1432
bool useConsolidatedCodeCache = segmentCarving != NULL ||
1433
TR::Options::getCmdLineOptions()->getOption(TR_EnableCodeCacheConsolidation);
1434
1435
if (TR::Options::getCmdLineOptions()->getNumCodeCachesToCreateAtStartup() > 0) // user has specified option
1436
numCodeCachesToCreateAtStartup = TR::Options::getCmdLineOptions()->getNumCodeCachesToCreateAtStartup();
1437
// We cannot create at startup more code caches than the maximum
1438
if (numCodeCachesToCreateAtStartup > maxNumberOfCodeCaches)
1439
numCodeCachesToCreateAtStartup = maxNumberOfCodeCaches;
1440
1441
firstCodeCache = codeCacheManager->initialize(useConsolidatedCodeCache, numCodeCachesToCreateAtStartup);
1442
1443
// large code page size may have been updated by initialize(), so copy back to jitConfig
1444
jitConfig->largeCodePageSize = (UDATA) codeCacheConfig.largeCodePageSize();
1445
1446
if (firstCodeCache == NULL)
1447
return -1;
1448
jitConfig->codeCache = firstCodeCache->j9segment();
1449
((TR_JitPrivateConfig *) jitConfig->privateConfig)->codeCacheManager = codeCacheManager; // for kca's benefit
1450
1451
if (fe->isAOT_DEPRECATED_DO_NOT_USE())
1452
{
1453
jitConfig->codeCache->heapAlloc = firstCodeCache->getCodeTop();
1454
#if defined(TR_TARGET_X86) && defined(TR_HOST_32BIT)
1455
javaVM->jitConfig = (J9JITConfig *)jitConfig;
1456
queryX86TargetCPUID(javaVM);
1457
#endif
1458
}
1459
1460
if (!fe->isAOT_DEPRECATED_DO_NOT_USE())
1461
{
1462
J9VMThread *currentVMThread = javaVM->internalVMFunctions->currentVMThread(javaVM);
1463
1464
if (currentVMThread)
1465
{
1466
currentVMThread->maxProfilingCount = (UDATA)encodeCount(TR::Options::_maxIprofilingCountInStartupMode);
1467
}
1468
1469
#if defined(TR_TARGET_S390)
1470
// allocate 4K
1471
jitConfig->pseudoTOC = j9mem_allocate_memory(4096, J9MEM_CATEGORY_JIT);
1472
if (!jitConfig->pseudoTOC)
1473
return -1;
1474
1475
if (currentVMThread)
1476
currentVMThread->codertTOC = (void *)jitConfig->pseudoTOC;
1477
#endif
1478
1479
}
1480
1481
/* allocate the data cache */
1482
if (jitConfig->dataCacheKB < 1)
1483
{
1484
printf("<JIT: fatal error, data cache size must be at least 1 Kb>\n");
1485
return -1;
1486
}
1487
if (!TR_DataCacheManager::initialize(jitConfig))
1488
{
1489
printf("{JIT: fatal error, failed to allocate %" OMR_PRIuPTR " Kb data cache}\n", jitConfig->dataCacheKB);
1490
return -1;
1491
}
1492
1493
jitConfig->thunkLookUpNameAndSig = &j9ThunkLookupNameAndSig;
1494
1495
TR::CompilationInfo * compInfo = TR::CompilationInfo::get();
1496
1497
// Now that we have all options (and before starting the compilation thread) we
1498
// should initialize the compilationController
1499
//
1500
TR::CompilationController::init(compInfo);
1501
1502
if (!TR::CompilationController::useController()) // test if initialization succeeded
1503
return -1;
1504
1505
// Create the CpuUtilization object after options processing
1506
{
1507
PORT_ACCESS_FROM_JAVAVM(jitConfig->javaVM);
1508
CpuUtilization* cpuUtil = new (PERSISTENT_NEW) CpuUtilization(jitConfig);
1509
compInfo->setCpuUtil(cpuUtil);
1510
}
1511
1512
// disable CPU utilization monitoring if told to do so on command line
1513
if (TR::Options::getCmdLineOptions()->getOption(TR_DisableCPUUtilization))
1514
compInfo->getCpuUtil()->disable();
1515
else
1516
compInfo->getCpuUtil()->updateCpuUtil(jitConfig);
1517
1518
// Need to let VM know that we will be using a machines vector facility (so it can save/restore preserved regs),
1519
// early in JIT startup to prevent subtle FP bugs
1520
#ifdef TR_TARGET_S390
1521
if (TR::Compiler->target.cpu.supportsFeature(OMR_FEATURE_S390_VECTOR_FACILITY) && !TR::Options::getCmdLineOptions()->getOption(TR_DisableSIMD))
1522
{
1523
javaVM->extendedRuntimeFlags |= J9_EXTENDED_RUNTIME_USE_VECTOR_REGISTERS;
1524
}
1525
#elif defined(TR_TARGET_POWER) && defined(TR_TARGET_64BIT)
1526
if(TR::Compiler->target.cpu.isAtLeast(OMR_PROCESSOR_PPC_P8) && TR::Compiler->target.cpu.supportsFeature(OMR_FEATURE_PPC_HAS_VSX) && !TR::Options::getCmdLineOptions()->getOption(TR_DisableSIMD))
1527
{
1528
javaVM->extendedRuntimeFlags |= J9_EXTENDED_RUNTIME_USE_VECTOR_REGISTERS;
1529
}
1530
#endif
1531
1532
// Address the case where the number of compilation threads is higher than the
1533
// maximum number of code caches
1534
if (TR::Options::_numUsableCompilationThreads > maxNumberOfCodeCaches)
1535
{
1536
#if defined(J9VM_OPT_JITSERVER)
1537
if (persistentMemory->getPersistentInfo()->getRemoteCompilationMode() == JITServer::SERVER)
1538
{
1539
fprintf(stderr,
1540
"Requested number of compilation threads is larger than the maximum number of code caches: %d > %d.\n"
1541
"Use the -Xcodecachetotal option to increase the maximum total size of the code cache.",
1542
TR::Options::_numUsableCompilationThreads, maxNumberOfCodeCaches
1543
);
1544
return -1;
1545
}
1546
#endif /* defined(J9VM_OPT_JITSERVER) */
1547
TR::Options::_numUsableCompilationThreads = maxNumberOfCodeCaches;
1548
}
1549
1550
compInfo->updateNumUsableCompThreads(TR::Options::_numUsableCompilationThreads);
1551
1552
if (!compInfo->allocateCompilationThreads(TR::Options::_numUsableCompilationThreads))
1553
{
1554
fprintf(stderr, "onLoadInternal: Failed to set up %d compilation threads\n", TR::Options::_numUsableCompilationThreads);
1555
return -1;
1556
}
1557
1558
// create regular compilation threads
1559
int32_t highestThreadID = 0;
1560
for (; highestThreadID < TR::Options::_numUsableCompilationThreads; highestThreadID++)
1561
{
1562
if (compInfo->startCompilationThread(-1, highestThreadID, /* isDiagnosticThread */ false) != 0)
1563
{
1564
// Failed to start compilation thread.
1565
Trc_JIT_startCompThreadFailed(curThread);
1566
return -1;
1567
}
1568
}
1569
1570
// If more than one diagnostic compilation thread is created, MAX_DIAGNOSTIC_COMP_THREADS needs to be updated
1571
// create diagnostic compilation thread
1572
if (compInfo->startCompilationThread(-1, highestThreadID, /* isDiagnosticThread */ true) != 0)
1573
{
1574
// Failed to start compilation thread.
1575
Trc_JIT_startCompThreadFailed(curThread);
1576
highestThreadID++;
1577
return -1;
1578
}
1579
1580
// Create the monitor used for log handling in presence of multiple compilation threads
1581
// TODO: postpone this when we know that a log is actually used
1582
if (!compInfo->createLogMonitor())
1583
{
1584
fprintf(stderr, "cannot create log monitor\n");
1585
return -1;
1586
}
1587
1588
if (!fe->isAOT_DEPRECATED_DO_NOT_USE() && !(jitConfig->runtimeFlags & J9JIT_TOSS_CODE))
1589
{
1590
javaVM->runtimeFlags |= J9_RUNTIME_JIT_ACTIVE;
1591
jitConfig->jitExclusiveVMShutdownPending = jitExclusiveVMShutdownPending;
1592
}
1593
1594
// initialize the IProfiler
1595
1596
if (!TR::Options::getCmdLineOptions()->getOption(TR_DisableInterpreterProfiling))
1597
{
1598
#if defined(J9VM_OPT_JITSERVER)
1599
if (persistentMemory->getPersistentInfo()->getRemoteCompilationMode() == JITServer::SERVER)
1600
{
1601
((TR_JitPrivateConfig*)(jitConfig->privateConfig))->iProfiler = JITServerIProfiler::allocate(jitConfig);
1602
}
1603
else if (persistentMemory->getPersistentInfo()->getRemoteCompilationMode() == JITServer::CLIENT)
1604
{
1605
((TR_JitPrivateConfig*)(jitConfig->privateConfig))->iProfiler = JITClientIProfiler::allocate(jitConfig);
1606
}
1607
else
1608
#endif
1609
{
1610
((TR_JitPrivateConfig*)(jitConfig->privateConfig))->iProfiler = TR_IProfiler::allocate(jitConfig);
1611
}
1612
if (!(((TR_JitPrivateConfig*)(jitConfig->privateConfig))->iProfiler))
1613
{
1614
// Warn that IProfiler was not allocated
1615
TR::Options::getCmdLineOptions()->setOption(TR_DisableInterpreterProfiling);
1616
// Warn that Interpreter Profiling was disabled
1617
}
1618
}
1619
else
1620
{
1621
((TR_JitPrivateConfig*)(jitConfig->privateConfig))->iProfiler = NULL;
1622
}
1623
1624
if (!TR::Options::getCmdLineOptions()->getOption(TR_DisableJProfilerThread))
1625
{
1626
((TR_JitPrivateConfig*)(jitConfig->privateConfig))->jProfiler = TR_JProfilerThread::allocate();
1627
if (!(((TR_JitPrivateConfig*)(jitConfig->privateConfig))->jProfiler))
1628
{
1629
TR::Options::getCmdLineOptions()->setOption(TR_DisableJProfilerThread);
1630
}
1631
}
1632
else
1633
{
1634
((TR_JitPrivateConfig*)(jitConfig->privateConfig))->jProfiler = NULL;
1635
}
1636
1637
vpMonitor = TR::Monitor::create("ValueProfilingMutex");
1638
1639
// initialize the HWProfiler
1640
UDATA riInitializeFailed = 1;
1641
if (TR::Options::_hwProfilerEnabled == TR_yes)
1642
{
1643
#if defined(TR_HOST_S390) && defined(BUILD_Z_RUNTIME_INSTRUMENTATION)
1644
if (TR::Compiler->target.cpu.supportsFeature(OMR_FEATURE_S390_RI))
1645
((TR_JitPrivateConfig*)(jitConfig->privateConfig))->hwProfiler = TR_ZHWProfiler::allocate(jitConfig);
1646
#elif defined(TR_HOST_POWER)
1647
#if !defined(J9OS_I5)
1648
/* We disable it on current releases. May enable in future. */
1649
((TR_JitPrivateConfig*)(jitConfig->privateConfig))->hwProfiler = TR::Compiler->target.cpu.isAtLeast(OMR_PROCESSOR_PPC_P8) ? TR_PPCHWProfiler::allocate(jitConfig) : NULL;
1650
#else
1651
((TR_JitPrivateConfig*)(jitConfig->privateConfig))->hwProfiler = NULL;
1652
#endif /* !defined(J9OS_I5) */
1653
#endif
1654
1655
//Initialize VM support for RI.
1656
#ifdef J9VM_JIT_RUNTIME_INSTRUMENTATION
1657
if (NULL != ((TR_JitPrivateConfig*)(jitConfig->privateConfig))->hwProfiler)
1658
riInitializeFailed = initializeJITRuntimeInstrumentation(javaVM);
1659
#endif
1660
}
1661
else
1662
{
1663
((TR_JitPrivateConfig*)(jitConfig->privateConfig))->hwProfiler = NULL;
1664
}
1665
1666
if (riInitializeFailed || ((TR_JitPrivateConfig*)(jitConfig->privateConfig))->hwProfiler == NULL)
1667
{
1668
// This will also internally call setRuntimeInstrumentationRecompilationEnabled(false)
1669
persistentMemory->getPersistentInfo()->setRuntimeInstrumentationEnabled(false);
1670
}
1671
else
1672
{
1673
persistentMemory->getPersistentInfo()->setRuntimeInstrumentationEnabled(true);
1674
1675
if (TR::Options::getCmdLineOptions()->getOption(TR_EnableHardwareProfileRecompilation) &&
1676
!(TR::Options::getCmdLineOptions()->getFixedOptLevel() == -1 &&
1677
TR::Options::getCmdLineOptions()->getOption(TR_InhibitRecompilation)))
1678
persistentMemory->getPersistentInfo()->setRuntimeInstrumentationRecompilationEnabled(true);
1679
}
1680
1681
#if defined(J9VM_OPT_JITSERVER)
1682
// server-side CH table is initialized per-client
1683
if (persistentMemory->getPersistentInfo()->getRemoteCompilationMode() != JITServer::SERVER)
1684
#endif
1685
{
1686
TR_PersistentCHTable *chtable;
1687
#if defined(J9VM_OPT_JITSERVER)
1688
if (persistentMemory->getPersistentInfo()->getRemoteCompilationMode() == JITServer::CLIENT)
1689
{
1690
chtable = new (PERSISTENT_NEW) JITClientPersistentCHTable(persistentMemory);
1691
}
1692
else
1693
#endif
1694
{
1695
chtable = new (PERSISTENT_NEW) TR_PersistentCHTable(persistentMemory);
1696
}
1697
if (chtable == NULL)
1698
return -1;
1699
persistentMemory->getPersistentInfo()->setPersistentCHTable(chtable);
1700
}
1701
1702
#if defined(J9VM_OPT_JITSERVER)
1703
if (JITServer::CommunicationStream::useSSL())
1704
{
1705
if (!JITServer::loadLibsslAndFindSymbols())
1706
return -1;
1707
}
1708
else
1709
{
1710
bool shareROMClasses = TR::Options::_shareROMClasses &&
1711
(compInfo->getPersistentInfo()->getRemoteCompilationMode() == JITServer::SERVER);
1712
bool useAOTCache = compInfo->getPersistentInfo()->getJITServerUseAOTCache();
1713
1714
// ROMClass sharing and AOT cache use a hash implementation from SSL.
1715
// Disable them (with an error message to vlog) if we can't load the library.
1716
if ((shareROMClasses || useAOTCache) && !JITServer::loadLibsslAndFindSymbols())
1717
{
1718
TR::Options::_shareROMClasses = false;
1719
compInfo->getPersistentInfo()->setJITServerUseAOTCache(false);
1720
1721
if (TR::Options::getVerboseOption(TR_VerboseJITServer))
1722
{
1723
if (shareROMClasses)
1724
TR_VerboseLog::writeLineLocked(TR_Vlog_JITServer,
1725
"ERROR: Failed to load SSL library, disabling ROMClass sharing");
1726
if (useAOTCache)
1727
TR_VerboseLog::writeLineLocked(TR_Vlog_JITServer,
1728
"ERROR: Failed to load SSL library, disabling AOT cache");
1729
}
1730
}
1731
}
1732
1733
if (compInfo->getPersistentInfo()->getRemoteCompilationMode() == JITServer::SERVER)
1734
{
1735
JITServer::CommunicationStream::initConfigurationFlags();
1736
1737
// Allocate the hashtable that holds information about clients
1738
compInfo->setClientSessionHT(ClientSessionHT::allocate());
1739
1740
((TR_JitPrivateConfig*)(jitConfig->privateConfig))->listener = TR_Listener::allocate();
1741
if (!((TR_JitPrivateConfig*)(jitConfig->privateConfig))->listener)
1742
{
1743
// warn that Listener was not allocated
1744
j9tty_printf(PORTLIB, "JITServer Listener not allocated, abort.\n");
1745
return -1;
1746
}
1747
if (jitConfig->samplingFrequency != 0)
1748
{
1749
((TR_JitPrivateConfig*)(jitConfig->privateConfig))->statisticsThreadObject = JITServerStatisticsThread::allocate();
1750
if (!((TR_JitPrivateConfig*)(jitConfig->privateConfig))->statisticsThreadObject)
1751
{
1752
// warn that Statistics Thread was not allocated
1753
j9tty_printf(PORTLIB, "JITServer Statistics thread not allocated, abort.\n");
1754
return -1;
1755
}
1756
}
1757
else
1758
{
1759
((TR_JitPrivateConfig*)(jitConfig->privateConfig))->statisticsThreadObject = NULL;
1760
}
1761
1762
//NOTE: This must be done only after the SSL library has been successfully loaded
1763
if (TR::Options::_shareROMClasses)
1764
{
1765
size_t numPartitions = std::max(1, TR::Options::_sharedROMClassCacheNumPartitions);
1766
auto cache = new (PERSISTENT_NEW) JITServerSharedROMClassCache(numPartitions);
1767
if (!cache)
1768
return -1;
1769
compInfo->setJITServerSharedROMClassCache(cache);
1770
}
1771
1772
//NOTE: This must be done only after the SSL library has been successfully loaded
1773
if (compInfo->getPersistentInfo()->getJITServerUseAOTCache())
1774
{
1775
auto aotCacheMap = new (PERSISTENT_NEW) JITServerAOTCacheMap();
1776
if (!aotCacheMap)
1777
return -1;
1778
compInfo->setJITServerAOTCacheMap(aotCacheMap);
1779
}
1780
}
1781
else if (compInfo->getPersistentInfo()->getRemoteCompilationMode() == JITServer::CLIENT)
1782
{
1783
compInfo->setUnloadedClassesTempList(new (PERSISTENT_NEW) PersistentVector<TR_OpaqueClassBlock*>(
1784
PersistentVector<TR_OpaqueClassBlock*>::allocator_type(TR::Compiler->persistentAllocator())));
1785
1786
compInfo->setIllegalFinalFieldModificationList(new (PERSISTENT_NEW) PersistentVector<TR_OpaqueClassBlock*>(
1787
PersistentVector<TR_OpaqueClassBlock*>::allocator_type(TR::Compiler->persistentAllocator())));
1788
1789
compInfo->setNewlyExtendedClasses(new (PERSISTENT_NEW) PersistentUnorderedMap<TR_OpaqueClassBlock*, uint8_t>(
1790
PersistentUnorderedMap<TR_OpaqueClassBlock*, uint8_t>::allocator_type(TR::Compiler->persistentAllocator())));
1791
1792
// Try to initialize SSL
1793
if (JITServer::ClientStream::static_init(compInfo->getPersistentInfo()) != 0)
1794
return -1;
1795
1796
JITServer::CommunicationStream::initConfigurationFlags();
1797
}
1798
#endif // J9VM_OPT_JITSERVER
1799
1800
#if defined(TR_HOST_S390)
1801
if (TR::Compiler->om.readBarrierType() != gc_modron_readbar_none)
1802
{
1803
// TODO (Guarded Storage): With the change to prevent lower trees, there's
1804
// an outstanding DLT issue where a LLGFSG is generated when loading the
1805
// DLT block from the J9VMThread instead of a LG. Disabling DLT until that
1806
// issue is fixed.
1807
TR::Options::getCmdLineOptions()->setOption(TR_DisableDynamicLoopTransfer);
1808
}
1809
#endif
1810
1811
jitConfig->runJitdump = runJitdump;
1812
1813
jitConfig->printAOTHeaderProcessorFeatures = printAOTHeaderProcessorFeatures;
1814
1815
if (!TR::Compiler->target.cpu.isI386())
1816
{
1817
TR_J2IThunkTable *ieThunkTable = new (PERSISTENT_NEW) TR_J2IThunkTable(persistentMemory, "InvokeExactJ2IThunkTable");
1818
if (ieThunkTable == NULL)
1819
return -1;
1820
persistentMemory->getPersistentInfo()->setInvokeExactJ2IThunkTable(ieThunkTable);
1821
}
1822
return 0;
1823
}
1824
1825
1826
extern "C" int32_t
1827
aboutToBootstrap(J9JavaVM * javaVM, J9JITConfig * jitConfig)
1828
{
1829
char isSMP;
1830
PORT_ACCESS_FROM_JAVAVM(javaVM);
1831
bool isSharedAOT = false;
1832
1833
if (!jitConfig)
1834
return -1;
1835
1836
#if defined(J9VM_INTERP_AOT_COMPILE_SUPPORT) && defined(J9VM_OPT_SHARED_CLASSES) && (defined(TR_HOST_X86) || defined(TR_HOST_POWER) || defined(TR_HOST_S390) || defined(TR_HOST_ARM) || defined(TR_HOST_ARM64))
1837
isSharedAOT = TR::Options::sharedClassCache();
1838
#endif /* J9VM_INTERP_AOT_COMPILE_SUPPORT && J9VM_OPT_SHARED_CLASSES && TR_HOST_X86 && TR_HOST_S390 */
1839
1840
#if defined(J9VM_OPT_SHARED_CLASSES)
1841
// must be called before latePostProcess
1842
if (isSharedAOT)
1843
{
1844
TR::CompilationInfo * compInfo = getCompilationInfo(jitConfig);
1845
J9SharedClassJavacoreDataDescriptor *javacoreDataPtr = compInfo->getAddrOfJavacoreData();
1846
1847
TR_ASSERT(javaVM->sharedClassConfig, "sharedClassConfig must exist");
1848
if (javaVM->sharedClassConfig->getJavacoreData)
1849
{
1850
memset(javacoreDataPtr, 0, sizeof(J9SharedClassJavacoreDataDescriptor));
1851
if (javaVM->sharedClassConfig->getJavacoreData(javaVM, javacoreDataPtr))
1852
{
1853
if (javacoreDataPtr->numAOTMethods > TR::Options::_aotWarmSCCThreshold)
1854
compInfo->setIsWarmSCC(TR_yes);
1855
else
1856
compInfo->setIsWarmSCC(TR_no);
1857
}
1858
}
1859
1860
if (TR::Options::getAOTCmdLineOptions()->getOption(TR_DisablePersistIProfile) ||
1861
TR::Options::getJITCmdLineOptions()->getOption(TR_DisablePersistIProfile))
1862
{
1863
javaVM->sharedClassConfig->runtimeFlags &= ~J9SHR_RUNTIMEFLAG_ENABLE_JITDATA;
1864
}
1865
else if ((javaVM->sharedClassConfig->runtimeFlags & J9SHR_RUNTIMEFLAG_ENABLE_JITDATA) == 0)
1866
{
1867
printf("\n ** sc disabled **\n");
1868
1869
TR::Options::getAOTCmdLineOptions()->setOption(TR_DisablePersistIProfile);
1870
}
1871
}
1872
#endif
1873
1874
char * endOptionsAOT = TR::Options::latePostProcessAOT(jitConfig);
1875
if ((intptr_t)endOptionsAOT == 1)
1876
return 1;
1877
1878
if (endOptionsAOT)
1879
{
1880
scan_failed(PORTLIB, "AOT", endOptionsAOT);
1881
printf("<JIT: fatal error, invalid command line>\n");
1882
#ifdef DEBUG
1883
printf(" for help use -Xaot:help\n\n");
1884
#endif
1885
return -1;
1886
}
1887
1888
char * endOptions = TR::Options::latePostProcessJIT(jitConfig);
1889
if ((intptr_t)endOptions == 1)
1890
return 1;
1891
1892
if (endOptions)
1893
{
1894
scan_failed(PORTLIB, "JIT", endOptions);
1895
printf("<JIT: fatal error, invalid command line>\n");
1896
#ifdef DEBUG
1897
printf(" for help use -Xjit:help\n\n");
1898
#endif
1899
return -1;
1900
}
1901
1902
if (!TR::Options::getCmdLineOptions()->allowRecompilation() || !TR::Options::getAOTCmdLineOptions()->allowRecompilation())
1903
{
1904
TR::Options::getCmdLineOptions()->setOption(TR_DisableCHOpts);
1905
TR::Options::getAOTCmdLineOptions()->setOption(TR_DisableCHOpts);
1906
}
1907
1908
// Get local var names if available (ie. classfile was compiled with -g).
1909
// We just check getDebug() for lack of a reliable way to check whether there are any methods being logged.
1910
//
1911
// Do this after all option processing because we don't want the option
1912
// processing to think the user has requested a local variable table. That
1913
// makes it drop into FSD mode.
1914
//
1915
if (TR::Options::getDebug())
1916
javaVM->requiredDebugAttributes |= J9VM_DEBUG_ATTRIBUTE_LOCAL_VARIABLE_TABLE;
1917
1918
J9VMThread *curThread = javaVM->internalVMFunctions->currentVMThread(javaVM);
1919
TR_J9VMBase *vm = TR_J9VMBase::get(jitConfig, curThread);
1920
TR::CompilationInfo * compInfo = TR::CompilationInfo::get(jitConfig);
1921
1922
/* Initialize helpers */
1923
codert_init_helpers_and_targets(jitConfig, TR::Compiler->target.isSMP());
1924
1925
if (vm->isAOT_DEPRECATED_DO_NOT_USE() || (jitConfig->runtimeFlags & J9JIT_TOSS_CODE))
1926
return 0;
1927
1928
TR::PersistentInfo *persistentInfo = compInfo->getPersistentInfo();
1929
#if defined(J9VM_OPT_JITSERVER)
1930
if (persistentInfo->getRemoteCompilationMode() != JITServer::SERVER)
1931
#endif /* defined(J9VM_OPT_JITSERVER) */
1932
{
1933
/* jit specific helpers */
1934
initializeJitRuntimeHelperTable(TR::Compiler->target.isSMP());
1935
}
1936
1937
#if defined(TR_TARGET_POWER)
1938
if (TR::Compiler->target.cpu.isPower())
1939
{
1940
void *tocBase = ppcPicTrampInit(vm, persistentInfo);
1941
if (tocBase == reinterpret_cast<void *>(0x1))
1942
{
1943
printf("<JIT: Cannot allocate TableOfConstants\n");
1944
return -1; // fail the JVM
1945
}
1946
1947
#if defined(TR_TARGET_64BIT) && defined(TR_HOST_POWER)
1948
jitConfig->pseudoTOC = tocBase;
1949
#endif
1950
}
1951
#endif
1952
1953
1954
#if defined(J9VM_OPT_SHARED_CLASSES)
1955
if (isSharedAOT)
1956
{
1957
bool validateSCC = true;
1958
1959
#if defined(J9VM_OPT_JITSERVER)
1960
if (persistentInfo->getRemoteCompilationMode() == JITServer::SERVER)
1961
validateSCC = false;
1962
#endif /* defined(J9VM_OPT_JITSERVER) */
1963
1964
if (validateSCC)
1965
{
1966
/* If AOT Shared Classes is turned ON, perform compatibility checks for AOT Shared Classes
1967
*
1968
* This check has to be done after latePostProcessJIT so that all the necessary JIT options
1969
* can be set
1970
*/
1971
TR_J9VMBase *fe = TR_J9VMBase::get(jitConfig, curThread);
1972
if (!compInfo->reloRuntime()->validateAOTHeader(fe, curThread))
1973
{
1974
TR_ASSERT_FATAL(static_cast<TR_JitPrivateConfig *>(jitConfig->privateConfig)->aotValidHeader != TR_yes,
1975
"aotValidHeader is TR_yes after failing to validate AOT header\n");
1976
1977
/* If this is the second run, then failing to validate AOT header will cause aotValidHeader
1978
* to be TR_no, in which case the SCC is not valid for use. However, if this is the first
1979
* run, then aotValidHeader will be TR_maybe; try to store the AOT Header in this case.
1980
*/
1981
if (static_cast<TR_JitPrivateConfig *>(jitConfig->privateConfig)->aotValidHeader == TR_no
1982
|| !compInfo->reloRuntime()->storeAOTHeader(fe, curThread))
1983
{
1984
static_cast<TR_JitPrivateConfig *>(jitConfig->privateConfig)->aotValidHeader = TR_no;
1985
TR::Options::getAOTCmdLineOptions()->setOption(TR_NoLoadAOT);
1986
TR::Options::getAOTCmdLineOptions()->setOption(TR_NoStoreAOT);
1987
TR::Options::setSharedClassCache(false);
1988
TR_J9SharedCache::setSharedCacheDisabledReason(TR_J9SharedCache::AOT_DISABLED);
1989
}
1990
}
1991
else
1992
{
1993
TR::Compiler->relocatableTarget.cpu = TR::CPU::customize(compInfo->reloRuntime()->getProcessorDescriptionFromSCC(curThread));
1994
jitConfig->relocatableTargetProcessor = TR::Compiler->relocatableTarget.cpu.getProcessorDescription();
1995
}
1996
}
1997
1998
if (TR::Options::getAOTCmdLineOptions()->getOption(TR_NoStoreAOT))
1999
{
2000
javaVM->sharedClassConfig->runtimeFlags &= ~J9SHR_RUNTIMEFLAG_ENABLE_AOT;
2001
TR_J9SharedCache::setSharedCacheDisabledReason(TR_J9SharedCache::AOT_DISABLED);
2002
#if defined(J9VM_OPT_JITSERVER)
2003
if (persistentInfo->getRemoteCompilationMode() == JITServer::SERVER)
2004
{
2005
fprintf(stderr, "Error: -Xaot:nostore option is not compatible with JITServer mode.");
2006
return -1;
2007
}
2008
#endif /* defined(J9VM_OPT_JITSERVER) */
2009
}
2010
else if ((javaVM->sharedClassConfig->runtimeFlags & J9SHR_RUNTIMEFLAG_ENABLE_AOT) == 0)
2011
{
2012
TR::Options::getAOTCmdLineOptions()->setOption(TR_NoStoreAOT);
2013
TR_J9SharedCache::setSharedCacheDisabledReason(TR_J9SharedCache::AOT_DISABLED);
2014
#if defined(J9VM_OPT_JITSERVER)
2015
if (persistentInfo->getRemoteCompilationMode() == JITServer::SERVER)
2016
{
2017
fprintf(stderr, "Error: -Xnoaot option must not be specified for JITServer.");
2018
return -1;
2019
}
2020
#endif /* defined(J9VM_OPT_JITSERVER) */
2021
}
2022
}
2023
#endif /* defined(J9VM_OPT_SHARED_CLASSES) */
2024
2025
#if defined(J9VM_OPT_JITSERVER)
2026
// Create AOT deserializer at the client if using JITServer with AOT cache
2027
if ((persistentInfo->getRemoteCompilationMode() == JITServer::CLIENT) && persistentInfo->getJITServerUseAOTCache())
2028
{
2029
if (TR::Options::sharedClassCache())
2030
{
2031
auto deserializer = new (PERSISTENT_NEW) JITServerAOTDeserializer(persistentInfo->getPersistentClassLoaderTable());
2032
if (!deserializer)
2033
return -1;
2034
compInfo->setJITServerAOTDeserializer(deserializer);
2035
}
2036
else
2037
{
2038
fprintf(stderr, "Disabling JITServer AOT cache since AOT compilation is disabled\n");
2039
persistentInfo->setJITServerUseAOTCache(false);
2040
}
2041
}
2042
#endif /* defined(J9VM_OPT_JITSERVER) */
2043
2044
#if defined(J9VM_OPT_CRIU_SUPPORT)
2045
/* If the JVM is in CRIU mode and checkpointing is allowed, then the JIT should be
2046
* limited to the same processor features as those used in Portable AOT mode. This
2047
* is because, the restore run may not be on the same machine as the one that created
2048
* the snapshot; thus the JIT code must be portable.
2049
*/
2050
if (javaVM->internalVMFunctions->isCheckpointAllowed(curThread))
2051
{
2052
TR::Compiler->target.cpu = TR::CPU::detectRelocatable(TR::Compiler->omrPortLib);
2053
jitConfig->targetProcessor = TR::Compiler->target.cpu.getProcessorDescription();
2054
}
2055
#endif /* defined(J9VM_OPT_CRIU_SUPPORT) */
2056
2057
#if defined(TR_TARGET_S390)
2058
uintptr_t * tocBase = (uintptr_t *)jitConfig->pseudoTOC;
2059
2060
// Initialize the helper function table (0 to TR_S390numRuntimeHelpers-2)
2061
for (int32_t idx=1; idx<TR_S390numRuntimeHelpers; idx++)
2062
tocBase[idx-1] = (uintptr_t)runtimeHelperValue((TR_RuntimeHelper)idx);
2063
#endif
2064
2065
TR::CodeCacheManager::instance()->lateInitialization();
2066
2067
/* Do not set up the following hooks if we are in testmode */
2068
if (!(jitConfig->runtimeFlags & J9JIT_TOSS_CODE))
2069
{
2070
if (setUpHooks(javaVM, jitConfig, vm))
2071
return -1;
2072
}
2073
2074
// For RI enabled we may want to start as off and only enable when there is
2075
// compilation pressure
2076
if (persistentInfo->isRuntimeInstrumentationEnabled() &&
2077
TR::Options::getCmdLineOptions()->getOption(TR_UseRIOnlyForLargeQSZ))
2078
{
2079
TR_HWProfiler *hwProfiler = compInfo->getHWProfiler();
2080
hwProfiler->turnBufferProcessingOffTemporarily();
2081
}
2082
2083
UT_MODULE_LOADED(J9_UTINTERFACE_FROM_VM(javaVM));
2084
Trc_JIT_VMInitStages_Event1(curThread);
2085
Trc_JIT_portableSharedCache_enabled_or_disabled(curThread, J9_ARE_ANY_BITS_SET(javaVM->extendedRuntimeFlags2, J9_EXTENDED_RUNTIME2_ENABLE_PORTABLE_SHARED_CACHE) ? 1 : 0);
2086
return 0;
2087
}
2088
2089
2090
// -----------------------------------------------------------------------------
2091
// GPU
2092
// -----------------------------------------------------------------------------
2093
2094
#ifdef ENABLE_GPU
2095
extern I_32 jitCallGPU(J9VMThread *vmThread, J9Method *method,
2096
char * programSource, jobject invokeObject, int deviceId,
2097
I_32 gridDimX, I_32 gridDimY, I_32 gridDimZ,
2098
I_32 blockDimX, I_32 blockDimY, I_32 blockDimZ,
2099
I_32 argCount, void **args);
2100
2101
IDATA launchGPU(J9VMThread *vmThread, jobject invokeObject,
2102
J9Method *method, int deviceId,
2103
I_32 gridDimX, I_32 gridDimY, I_32 gridDimZ,
2104
I_32 blockDimX, I_32 blockDimY, I_32 blockDimZ,
2105
void **args)
2106
{
2107
TR::CompilationInfo * compInfo = getCompilationInfo(jitConfig);
2108
bool queued = false;
2109
TR_MethodEvent event;
2110
I_32 result = 0;
2111
event._eventType = TR_MethodEvent::InterpreterCounterTripped;
2112
event._j9method = method;
2113
event._oldStartPC = 0;
2114
event._vmThread = vmThread;
2115
event._classNeedingThunk = 0;
2116
bool newPlanCreated;
2117
TR_OptimizationPlan *plan = TR::CompilationController::getCompilationStrategy()->processEvent(&event, &newPlanCreated);
2118
if (plan)
2119
{
2120
plan->setIsExplicitCompilation(true);
2121
2122
plan->setIsGPUCompilation(true);
2123
plan->setGPUBlockDimX(blockDimX);
2124
plan->setGPUParms(args);
2125
if (!args)
2126
plan->setIsGPUParallelStream(true);
2127
2128
static char *GPUCompileCPUCode = feGetEnv("TR_GPUCompileCPUCode");
2129
if (GPUCompileCPUCode)
2130
plan->setIsGPUCompileCPUCode(true);
2131
2132
// If the controller decides to compile this method, trigger the compilation and wait here
2133
2134
{ // scope for details
2135
TR::IlGeneratorMethodDetails details(method);
2136
2137
clock_t start = clock();
2138
if(!compInfo->isCompiled(method) || GPUCompileCPUCode)
2139
compInfo->compileMethod(vmThread, details, 0, TR_no, NULL, &queued, plan);
2140
clock_t end = clock();
2141
printf ("\tJitted Java Kernel %6.3f msec\n", (double)(end-start)*1000/CLOCKS_PER_SEC);
2142
2143
result = plan->getGPUResult();
2144
2145
if (result == 0)
2146
{
2147
J9ROMMethod *romMethod = J9_ROM_METHOD_FROM_RAM_METHOD(method);
2148
I_32 argCount = J9_ARG_COUNT_FROM_ROM_METHOD(romMethod) - 1; // for this (this is not passed to GPU)
2149
2150
if (GPUCompileCPUCode)
2151
{
2152
typedef I_32 (*gpuCodePtr)(J9VMThread *vmThread, J9Method *method,
2153
char * programSource, jobject invokeObject, int deviceId,
2154
I_32 gridDimX, I_32 gridDimY, I_32 gridDimZ,
2155
I_32 blockDimX, I_32 blockDimY, I_32 blockDimZ,
2156
I_32 argCount, void **args);
2157
2158
printf ("In launchGPU: %p %p %p %p %d %d %d %d %d %d %d %d %p\n",
2159
vmThread, method, plan->getGPUIR(), invokeObject, deviceId,
2160
gridDimX, gridDimY, gridDimZ,
2161
blockDimX, blockDimY, blockDimZ,
2162
argCount, args);
2163
2164
2165
gpuCodePtr gpuCode = (gpuCodePtr)TR::CompilationInfo::getJ9MethodExtra(method);
2166
2167
if ((int64_t)gpuCode != 0x1)
2168
result = gpuCode(vmThread, method, plan->getGPUIR(), invokeObject, deviceId,
2169
gridDimX, gridDimY, gridDimZ,
2170
blockDimX, blockDimY, blockDimZ,
2171
argCount, args);
2172
}
2173
else
2174
{
2175
result = jitCallGPU(vmThread, method, plan->getGPUIR(), invokeObject, deviceId,
2176
gridDimX, gridDimY, gridDimZ,
2177
blockDimX, blockDimY, blockDimZ,
2178
argCount, args);
2179
}
2180
2181
printf ("launchGPU result = %d\n", result);
2182
fflush(NULL);
2183
}
2184
}
2185
2186
if (!queued && newPlanCreated)
2187
TR_OptimizationPlan::freeOptimizationPlan(plan);
2188
}
2189
2190
return result;
2191
}
2192
2193
2194
static UDATA forEachIterator(J9VMThread *vmThread, J9StackWalkState *walkState)
2195
{
2196
// stop iterating if the walk state is null
2197
if (!walkState)
2198
{
2199
return J9_STACKWALK_STOP_ITERATING;
2200
}
2201
2202
J9Method *j9method = walkState->method;
2203
J9ROMMethod *romMethod = J9_ROM_METHOD_FROM_RAM_METHOD(j9method);
2204
2205
J9JITConfig* jitConfig = vmThread->javaVM->jitConfig;
2206
TR::CompilationInfo *compInfo = TR::CompilationInfo::get(jitConfig);
2207
2208
compInfo->acquireCompMonitor(vmThread);
2209
2210
intptr_t count = TR::CompilationInfo::getJ9MethodExtra(j9method) >> 1;
2211
2212
if (!(romMethod->modifiers & J9AccNative) && // Never change the extra field of a native method
2213
!(walkState->jitInfo) && // If the frame has jit metadata, it was already compiled
2214
!(TR::CompilationInfo::isCompiled(j9method)) && //If isCompiled is true it was already compiled
2215
!(TR::CompilationInfo::getJ9MethodVMExtra(j9method) == J9_JIT_QUEUED_FOR_COMPILATION) && //No change needed if already queued
2216
(count > 0)) // No change needed if count is already 0
2217
{
2218
TR::CompilationInfo::setInitialInvocationCountUnsynchronized(j9method,0); //set count to 0
2219
}
2220
2221
compInfo->releaseCompMonitor(vmThread);
2222
2223
return J9_STACKWALK_STOP_ITERATING;
2224
}
2225
#endif
2226
2227
2228
void promoteGPUCompile(J9VMThread *vmThread)
2229
{
2230
#ifdef ENABLE_GPU
2231
if (TR::Options::getCmdLineOptions()->getEnableGPU(TR_EnableGPU))
2232
{
2233
J9StackWalkState walkState;
2234
2235
walkState.walkThread = vmThread;
2236
walkState.skipCount = 3; //method to compile is 3 up from the forEach
2237
2238
walkState.flags = J9_STACKWALK_VISIBLE_ONLY |
2239
J9_STACKWALK_INCLUDE_NATIVES |
2240
J9_STACKWALK_ITERATE_FRAMES;
2241
walkState.frameWalkFunction = forEachIterator;
2242
2243
vmThread->javaVM->walkStackFrames(vmThread, &walkState);
2244
}
2245
#endif
2246
}
2247
2248