blob: 34a7736d6a096a2275beb1843d9b14d89339eaed [file] [log] [blame]
Ben Chengba4fc8b2009-06-01 13:00:29 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#ifdef WITH_JIT
17
18/*
19 * Target independent portion of Android's Jit
20 */
21
22#include "Dalvik.h"
23#include "Jit.h"
24
25
26#include "dexdump/OpCodeNames.h"
27#include <unistd.h>
28#include <pthread.h>
29#include <sys/time.h>
30#include <signal.h>
31#include "compiler/Compiler.h"
Bill Buzbee6e963e12009-06-17 16:56:19 -070032#include "compiler/CompilerUtility.h"
33#include "compiler/CompilerIR.h"
Ben Chengba4fc8b2009-06-01 13:00:29 -070034#include <errno.h>
35
Jeff Hao97319a82009-08-12 16:57:15 -070036#if defined(WITH_SELF_VERIFICATION)
37/* Allocate space for per-thread ShadowSpace data structures */
38void* dvmSelfVerificationShadowSpaceAlloc(Thread* self)
39{
40 self->shadowSpace = (ShadowSpace*) calloc(1, sizeof(ShadowSpace));
41 if (self->shadowSpace == NULL)
42 return NULL;
43
44 self->shadowSpace->registerSpaceSize = REG_SPACE;
45 self->shadowSpace->registerSpace =
46 (int*) calloc(self->shadowSpace->registerSpaceSize, sizeof(int));
47
48 return self->shadowSpace->registerSpace;
49}
50
51/* Free per-thread ShadowSpace data structures */
52void dvmSelfVerificationShadowSpaceFree(Thread* self)
53{
54 free(self->shadowSpace->registerSpace);
55 free(self->shadowSpace);
56}
57
58/*
59 * Save out PC, FP, InterpState, and registers to shadow space.
60 * Return a pointer to the shadow space for JIT to use.
61 */
62void* dvmSelfVerificationSaveState(const u2* pc, const void* fp,
Bill Buzbee9a8c75a2009-11-08 14:31:20 -080063 InterpState* interpState, int targetTrace)
Jeff Hao97319a82009-08-12 16:57:15 -070064{
65 Thread *self = dvmThreadSelf();
66 ShadowSpace *shadowSpace = self->shadowSpace;
Jeff Hao97319a82009-08-12 16:57:15 -070067 int preBytes = interpState->method->outsSize*4 + sizeof(StackSaveArea);
68 int postBytes = interpState->method->registersSize*4;
69
70 //LOGD("### selfVerificationSaveState(%d) pc: 0x%x fp: 0x%x",
71 // self->threadId, (int)pc, (int)fp);
72
73 if (shadowSpace->selfVerificationState != kSVSIdle) {
74 LOGD("~~~ Save: INCORRECT PREVIOUS STATE(%d): %d",
75 self->threadId, shadowSpace->selfVerificationState);
76 LOGD("********** SHADOW STATE DUMP **********");
Ben Chengccd6c012009-10-15 14:52:45 -070077 LOGD("PC: 0x%x FP: 0x%x", (int)pc, (int)fp);
Jeff Hao97319a82009-08-12 16:57:15 -070078 }
79 shadowSpace->selfVerificationState = kSVSStart;
80
81 // Dynamically grow shadow register space if necessary
82 while (preBytes + postBytes > shadowSpace->registerSpaceSize) {
83 shadowSpace->registerSpaceSize *= 2;
84 free(shadowSpace->registerSpace);
85 shadowSpace->registerSpace =
86 (int*) calloc(shadowSpace->registerSpaceSize, sizeof(int));
87 }
88
89 // Remember original state
90 shadowSpace->startPC = pc;
91 shadowSpace->fp = fp;
Ben Chengccd6c012009-10-15 14:52:45 -070092 shadowSpace->glue = interpState;
93 /*
94 * Store the original method here in case the trace ends with a
95 * return/invoke, the last method.
96 */
97 shadowSpace->method = interpState->method;
Jeff Hao97319a82009-08-12 16:57:15 -070098 shadowSpace->shadowFP = shadowSpace->registerSpace +
99 shadowSpace->registerSpaceSize - postBytes/4;
100
101 // Create a copy of the InterpState
Ben Chengccd6c012009-10-15 14:52:45 -0700102 //shadowSpace->interpState = *interpState;
103 memcpy(&(shadowSpace->interpState), interpState, sizeof(InterpState));
Jeff Hao97319a82009-08-12 16:57:15 -0700104 shadowSpace->interpState.fp = shadowSpace->shadowFP;
105 shadowSpace->interpState.interpStackEnd = (u1*)shadowSpace->registerSpace;
106
107 // Create a copy of the stack
108 memcpy(((char*)shadowSpace->shadowFP)-preBytes, ((char*)fp)-preBytes,
109 preBytes+postBytes);
110
111 // Setup the shadowed heap space
112 shadowSpace->heapSpaceTail = shadowSpace->heapSpace;
113
114 // Reset trace length
115 shadowSpace->traceLength = 0;
116
117 return shadowSpace;
118}
119
120/*
121 * Save ending PC, FP and compiled code exit point to shadow space.
122 * Return a pointer to the shadow space for JIT to restore state.
123 */
124void* dvmSelfVerificationRestoreState(const u2* pc, const void* fp,
125 SelfVerificationState exitPoint)
126{
127 Thread *self = dvmThreadSelf();
128 ShadowSpace *shadowSpace = self->shadowSpace;
129 shadowSpace->endPC = pc;
130 shadowSpace->endShadowFP = fp;
131
132 //LOGD("### selfVerificationRestoreState(%d) pc: 0x%x fp: 0x%x endPC: 0x%x",
133 // self->threadId, (int)shadowSpace->startPC, (int)shadowSpace->fp,
134 // (int)pc);
135
136 if (shadowSpace->selfVerificationState != kSVSStart) {
137 LOGD("~~~ Restore: INCORRECT PREVIOUS STATE(%d): %d",
138 self->threadId, shadowSpace->selfVerificationState);
139 LOGD("********** SHADOW STATE DUMP **********");
Ben Chengccd6c012009-10-15 14:52:45 -0700140 LOGD("Dalvik PC: 0x%x endPC: 0x%x", (int)shadowSpace->startPC,
Jeff Hao97319a82009-08-12 16:57:15 -0700141 (int)shadowSpace->endPC);
Ben Chengccd6c012009-10-15 14:52:45 -0700142 LOGD("Interp FP: 0x%x", (int)shadowSpace->fp);
143 LOGD("Shadow FP: 0x%x endFP: 0x%x", (int)shadowSpace->shadowFP,
Jeff Hao97319a82009-08-12 16:57:15 -0700144 (int)shadowSpace->endShadowFP);
145 }
146
147 // Special case when punting after a single instruction
148 if (exitPoint == kSVSPunt && pc == shadowSpace->startPC) {
149 shadowSpace->selfVerificationState = kSVSIdle;
150 } else {
151 shadowSpace->selfVerificationState = exitPoint;
152 }
153
154 return shadowSpace;
155}
156
157/* Print contents of virtual registers */
Ben Chengccd6c012009-10-15 14:52:45 -0700158static void selfVerificationPrintRegisters(int* addr, int* addrRef,
159 int numWords)
Jeff Hao97319a82009-08-12 16:57:15 -0700160{
161 int i;
162 for (i = 0; i < numWords; i++) {
Ben Chengccd6c012009-10-15 14:52:45 -0700163 LOGD("(v%d) 0x%8x%s", i, addr[i], addr[i] != addrRef[i] ? " X" : "");
Jeff Hao97319a82009-08-12 16:57:15 -0700164 }
165}
166
167/* Print values maintained in shadowSpace */
168static void selfVerificationDumpState(const u2* pc, Thread* self)
169{
170 ShadowSpace* shadowSpace = self->shadowSpace;
171 StackSaveArea* stackSave = SAVEAREA_FROM_FP(self->curFrame);
172 int frameBytes = (int) shadowSpace->registerSpace +
173 shadowSpace->registerSpaceSize*4 -
174 (int) shadowSpace->shadowFP;
175 int localRegs = 0;
176 int frameBytes2 = 0;
177 if (self->curFrame < shadowSpace->fp) {
178 localRegs = (stackSave->method->registersSize -
179 stackSave->method->insSize)*4;
180 frameBytes2 = (int) shadowSpace->fp - (int) self->curFrame - localRegs;
181 }
182 LOGD("********** SHADOW STATE DUMP **********");
Ben Chengccd6c012009-10-15 14:52:45 -0700183 LOGD("CurrentPC: 0x%x, Offset: 0x%04x", (int)pc,
Jeff Hao97319a82009-08-12 16:57:15 -0700184 (int)(pc - stackSave->method->insns));
Ben Chengccd6c012009-10-15 14:52:45 -0700185 LOGD("Class: %s", shadowSpace->method->clazz->descriptor);
186 LOGD("Method: %s", shadowSpace->method->name);
187 LOGD("Dalvik PC: 0x%x endPC: 0x%x", (int)shadowSpace->startPC,
Jeff Hao97319a82009-08-12 16:57:15 -0700188 (int)shadowSpace->endPC);
Ben Chengccd6c012009-10-15 14:52:45 -0700189 LOGD("Interp FP: 0x%x endFP: 0x%x", (int)shadowSpace->fp,
Jeff Hao97319a82009-08-12 16:57:15 -0700190 (int)self->curFrame);
Ben Chengccd6c012009-10-15 14:52:45 -0700191 LOGD("Shadow FP: 0x%x endFP: 0x%x", (int)shadowSpace->shadowFP,
Jeff Hao97319a82009-08-12 16:57:15 -0700192 (int)shadowSpace->endShadowFP);
Ben Chengccd6c012009-10-15 14:52:45 -0700193 LOGD("Frame1 Bytes: %d Frame2 Local: %d Bytes: %d", frameBytes,
Jeff Hao97319a82009-08-12 16:57:15 -0700194 localRegs, frameBytes2);
Ben Chengccd6c012009-10-15 14:52:45 -0700195 LOGD("Trace length: %d State: %d", shadowSpace->traceLength,
Jeff Hao97319a82009-08-12 16:57:15 -0700196 shadowSpace->selfVerificationState);
197}
198
199/* Print decoded instructions in the current trace */
200static void selfVerificationDumpTrace(const u2* pc, Thread* self)
201{
202 ShadowSpace* shadowSpace = self->shadowSpace;
203 StackSaveArea* stackSave = SAVEAREA_FROM_FP(self->curFrame);
Ben Chengbcdc1de2009-08-21 16:18:46 -0700204 int i, addr, offset;
205 DecodedInstruction *decInsn;
Jeff Hao97319a82009-08-12 16:57:15 -0700206
207 LOGD("********** SHADOW TRACE DUMP **********");
208 for (i = 0; i < shadowSpace->traceLength; i++) {
Ben Chengbcdc1de2009-08-21 16:18:46 -0700209 addr = shadowSpace->trace[i].addr;
210 offset = (int)((u2*)addr - stackSave->method->insns);
211 decInsn = &(shadowSpace->trace[i].decInsn);
212 /* Not properly decoding instruction, some registers may be garbage */
Ben Chengccd6c012009-10-15 14:52:45 -0700213 LOGD("0x%x: (0x%04x) %s", addr, offset, getOpcodeName(decInsn->opCode));
Jeff Hao97319a82009-08-12 16:57:15 -0700214 }
215}
216
Ben Chengbcdc1de2009-08-21 16:18:46 -0700217/* Code is forced into this spin loop when a divergence is detected */
Ben Chengccd6c012009-10-15 14:52:45 -0700218static void selfVerificationSpinLoop(ShadowSpace *shadowSpace)
Ben Chengbcdc1de2009-08-21 16:18:46 -0700219{
Ben Chengccd6c012009-10-15 14:52:45 -0700220 const u2 *startPC = shadowSpace->startPC;
221 JitTraceDescription* desc = dvmCopyTraceDescriptor(startPC);
222 if (desc) {
223 dvmCompilerWorkEnqueue(startPC, kWorkOrderTraceDebug, desc);
224 }
Ben Chengbcdc1de2009-08-21 16:18:46 -0700225 gDvmJit.selfVerificationSpin = true;
226 while(gDvmJit.selfVerificationSpin) sleep(10);
227}
228
Jeff Hao97319a82009-08-12 16:57:15 -0700229/* Manage self verification while in the debug interpreter */
230static bool selfVerificationDebugInterp(const u2* pc, Thread* self)
231{
232 ShadowSpace *shadowSpace = self->shadowSpace;
Jeff Hao97319a82009-08-12 16:57:15 -0700233 SelfVerificationState state = shadowSpace->selfVerificationState;
Ben Chengbcdc1de2009-08-21 16:18:46 -0700234
235 DecodedInstruction decInsn;
236 dexDecodeInstruction(gDvm.instrFormat, pc, &decInsn);
237
Jeff Hao97319a82009-08-12 16:57:15 -0700238 //LOGD("### DbgIntp(%d): PC: 0x%x endPC: 0x%x state: %d len: %d %s",
239 // self->threadId, (int)pc, (int)shadowSpace->endPC, state,
Ben Chengbcdc1de2009-08-21 16:18:46 -0700240 // shadowSpace->traceLength, getOpcodeName(decInsn.opCode));
Jeff Hao97319a82009-08-12 16:57:15 -0700241
242 if (state == kSVSIdle || state == kSVSStart) {
243 LOGD("~~~ DbgIntrp: INCORRECT PREVIOUS STATE(%d): %d",
244 self->threadId, state);
245 selfVerificationDumpState(pc, self);
246 selfVerificationDumpTrace(pc, self);
247 }
248
249 /* Skip endPC once when trace has a backward branch */
250 if ((state == kSVSBackwardBranch && pc == shadowSpace->endPC) ||
251 state != kSVSBackwardBranch) {
252 shadowSpace->selfVerificationState = kSVSDebugInterp;
253 }
254
255 /* Check that the current pc is the end of the trace */
256 if ((state == kSVSSingleStep || state == kSVSDebugInterp) &&
257 pc == shadowSpace->endPC) {
258
259 shadowSpace->selfVerificationState = kSVSIdle;
260
261 /* Check register space */
262 int frameBytes = (int) shadowSpace->registerSpace +
263 shadowSpace->registerSpaceSize*4 -
264 (int) shadowSpace->shadowFP;
265 if (memcmp(shadowSpace->fp, shadowSpace->shadowFP, frameBytes)) {
Ben Chengccd6c012009-10-15 14:52:45 -0700266 LOGD("~~~ DbgIntp(%d): REGISTERS DIVERGENCE!", self->threadId);
Jeff Hao97319a82009-08-12 16:57:15 -0700267 selfVerificationDumpState(pc, self);
268 selfVerificationDumpTrace(pc, self);
269 LOGD("*** Interp Registers: addr: 0x%x bytes: %d",
270 (int)shadowSpace->fp, frameBytes);
Ben Chengccd6c012009-10-15 14:52:45 -0700271 selfVerificationPrintRegisters((int*)shadowSpace->fp,
272 (int*)shadowSpace->shadowFP,
273 frameBytes/4);
Jeff Hao97319a82009-08-12 16:57:15 -0700274 LOGD("*** Shadow Registers: addr: 0x%x bytes: %d",
275 (int)shadowSpace->shadowFP, frameBytes);
276 selfVerificationPrintRegisters((int*)shadowSpace->shadowFP,
Ben Chengccd6c012009-10-15 14:52:45 -0700277 (int*)shadowSpace->fp,
278 frameBytes/4);
279 selfVerificationSpinLoop(shadowSpace);
Jeff Hao97319a82009-08-12 16:57:15 -0700280 }
281 /* Check new frame if it exists (invokes only) */
282 if (self->curFrame < shadowSpace->fp) {
283 StackSaveArea* stackSave = SAVEAREA_FROM_FP(self->curFrame);
284 int localRegs = (stackSave->method->registersSize -
285 stackSave->method->insSize)*4;
286 int frameBytes2 = (int) shadowSpace->fp -
287 (int) self->curFrame - localRegs;
288 if (memcmp(((char*)self->curFrame)+localRegs,
289 ((char*)shadowSpace->endShadowFP)+localRegs, frameBytes2)) {
Ben Chengccd6c012009-10-15 14:52:45 -0700290 LOGD("~~~ DbgIntp(%d): REGISTERS (FRAME2) DIVERGENCE!",
Jeff Hao97319a82009-08-12 16:57:15 -0700291 self->threadId);
292 selfVerificationDumpState(pc, self);
293 selfVerificationDumpTrace(pc, self);
294 LOGD("*** Interp Registers: addr: 0x%x l: %d bytes: %d",
295 (int)self->curFrame, localRegs, frameBytes2);
296 selfVerificationPrintRegisters((int*)self->curFrame,
Ben Chengccd6c012009-10-15 14:52:45 -0700297 (int*)shadowSpace->endShadowFP,
298 (frameBytes2+localRegs)/4);
Jeff Hao97319a82009-08-12 16:57:15 -0700299 LOGD("*** Shadow Registers: addr: 0x%x l: %d bytes: %d",
300 (int)shadowSpace->endShadowFP, localRegs, frameBytes2);
301 selfVerificationPrintRegisters((int*)shadowSpace->endShadowFP,
Ben Chengccd6c012009-10-15 14:52:45 -0700302 (int*)self->curFrame,
303 (frameBytes2+localRegs)/4);
304 selfVerificationSpinLoop(shadowSpace);
Jeff Hao97319a82009-08-12 16:57:15 -0700305 }
306 }
307
308 /* Check memory space */
Ben Chengbcdc1de2009-08-21 16:18:46 -0700309 bool memDiff = false;
Jeff Hao97319a82009-08-12 16:57:15 -0700310 ShadowHeap* heapSpacePtr;
311 for (heapSpacePtr = shadowSpace->heapSpace;
312 heapSpacePtr != shadowSpace->heapSpaceTail; heapSpacePtr++) {
Ben Chengbcdc1de2009-08-21 16:18:46 -0700313 int memData = *((unsigned int*) heapSpacePtr->addr);
314 if (heapSpacePtr->data != memData) {
Ben Chengccd6c012009-10-15 14:52:45 -0700315 LOGD("~~~ DbgIntp(%d): MEMORY DIVERGENCE!", self->threadId);
316 LOGD("Addr: 0x%x Intrp Data: 0x%x Jit Data: 0x%x",
Ben Chengbcdc1de2009-08-21 16:18:46 -0700317 heapSpacePtr->addr, memData, heapSpacePtr->data);
Jeff Hao97319a82009-08-12 16:57:15 -0700318 selfVerificationDumpState(pc, self);
319 selfVerificationDumpTrace(pc, self);
Ben Chengbcdc1de2009-08-21 16:18:46 -0700320 memDiff = true;
Jeff Hao97319a82009-08-12 16:57:15 -0700321 }
322 }
Ben Chengccd6c012009-10-15 14:52:45 -0700323 if (memDiff) selfVerificationSpinLoop(shadowSpace);
Jeff Hao97319a82009-08-12 16:57:15 -0700324 return true;
325
326 /* If end not been reached, make sure max length not exceeded */
327 } else if (shadowSpace->traceLength >= JIT_MAX_TRACE_LEN) {
328 LOGD("~~~ DbgIntp(%d): CONTROL DIVERGENCE!", self->threadId);
Ben Chengccd6c012009-10-15 14:52:45 -0700329 LOGD("startPC: 0x%x endPC: 0x%x currPC: 0x%x",
Jeff Hao97319a82009-08-12 16:57:15 -0700330 (int)shadowSpace->startPC, (int)shadowSpace->endPC, (int)pc);
331 selfVerificationDumpState(pc, self);
332 selfVerificationDumpTrace(pc, self);
Ben Chengccd6c012009-10-15 14:52:45 -0700333 selfVerificationSpinLoop(shadowSpace);
Jeff Hao97319a82009-08-12 16:57:15 -0700334
335 return true;
336 }
Ben Chengbcdc1de2009-08-21 16:18:46 -0700337 /* Log the instruction address and decoded instruction for debug */
Jeff Hao97319a82009-08-12 16:57:15 -0700338 shadowSpace->trace[shadowSpace->traceLength].addr = (int)pc;
Ben Chengbcdc1de2009-08-21 16:18:46 -0700339 shadowSpace->trace[shadowSpace->traceLength].decInsn = decInsn;
Jeff Hao97319a82009-08-12 16:57:15 -0700340 shadowSpace->traceLength++;
341
342 return false;
343}
344#endif
345
Ben Chengba4fc8b2009-06-01 13:00:29 -0700346int dvmJitStartup(void)
347{
348 unsigned int i;
349 bool res = true; /* Assume success */
350
Bill Buzbee964a7b02010-01-28 12:54:19 -0800351 // Create the compiler thread, which will complete initialization
352 if (gDvm.executionMode == kExecutionModeJit) {
353 res = dvmCompilerStartup();
Ben Chengba4fc8b2009-06-01 13:00:29 -0700354 }
355 return res;
356}
357
358/*
359 * If one of our fixed tables or the translation buffer fills up,
360 * call this routine to avoid wasting cycles on future translation requests.
361 */
362void dvmJitStopTranslationRequests()
363{
364 /*
365 * Note 1: This won't necessarily stop all translation requests, and
366 * operates on a delayed mechanism. Running threads look to the copy
367 * of this value in their private InterpState structures and won't see
368 * this change until it is refreshed (which happens on interpreter
369 * entry).
370 * Note 2: This is a one-shot memory leak on this table. Because this is a
371 * permanent off switch for Jit profiling, it is a one-time leak of 1K
372 * bytes, and no further attempt will be made to re-allocate it. Can't
373 * free it because some thread may be holding a reference.
374 */
Bill Buzbeeb1d80442009-12-17 14:55:21 -0800375 gDvmJit.pProfTable = NULL;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700376}
377
378#if defined(EXIT_STATS)
379/* Convenience function to increment counter from assembly code */
Ben Cheng6c10a972009-10-29 14:39:18 -0700380void dvmBumpNoChain(int from)
Ben Chengba4fc8b2009-06-01 13:00:29 -0700381{
Ben Cheng6c10a972009-10-29 14:39:18 -0700382 gDvmJit.noChainExit[from]++;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700383}
384
385/* Convenience function to increment counter from assembly code */
386void dvmBumpNormal()
387{
Ben Cheng6c10a972009-10-29 14:39:18 -0700388 gDvmJit.normalExit++;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700389}
390
391/* Convenience function to increment counter from assembly code */
392void dvmBumpPunt(int from)
393{
Ben Cheng6c10a972009-10-29 14:39:18 -0700394 gDvmJit.puntExit++;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700395}
396#endif
397
398/* Dumps debugging & tuning stats to the log */
399void dvmJitStats()
400{
401 int i;
402 int hit;
403 int not_hit;
404 int chains;
Bill Buzbee9a8c75a2009-11-08 14:31:20 -0800405 int stubs;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700406 if (gDvmJit.pJitEntryTable) {
Bill Buzbee9a8c75a2009-11-08 14:31:20 -0800407 for (i=0, stubs=chains=hit=not_hit=0;
Bill Buzbee27176222009-06-09 09:20:16 -0700408 i < (int) gDvmJit.jitTableSize;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700409 i++) {
Bill Buzbee9a8c75a2009-11-08 14:31:20 -0800410 if (gDvmJit.pJitEntryTable[i].dPC != 0) {
Ben Chengba4fc8b2009-06-01 13:00:29 -0700411 hit++;
Bill Buzbee9a8c75a2009-11-08 14:31:20 -0800412 if (gDvmJit.pJitEntryTable[i].codeAddress ==
413 gDvmJit.interpretTemplate)
414 stubs++;
415 } else
Ben Chengba4fc8b2009-06-01 13:00:29 -0700416 not_hit++;
Bill Buzbee716f1202009-07-23 13:22:09 -0700417 if (gDvmJit.pJitEntryTable[i].u.info.chain != gDvmJit.jitTableSize)
Ben Chengba4fc8b2009-06-01 13:00:29 -0700418 chains++;
419 }
420 LOGD(
421 "JIT: %d traces, %d slots, %d chains, %d maxQ, %d thresh, %s",
422 hit, not_hit + hit, chains, gDvmJit.compilerMaxQueued,
423 gDvmJit.threshold, gDvmJit.blockingMode ? "Blocking" : "Non-blocking");
424#if defined(EXIT_STATS)
425 LOGD(
Ben Cheng6c10a972009-10-29 14:39:18 -0700426 "JIT: Lookups: %d hits, %d misses; %d normal, %d punt",
Ben Chengba4fc8b2009-06-01 13:00:29 -0700427 gDvmJit.addrLookupsFound, gDvmJit.addrLookupsNotFound,
Ben Cheng6c10a972009-10-29 14:39:18 -0700428 gDvmJit.normalExit, gDvmJit.puntExit);
429 LOGD(
430 "JIT: noChainExit: %d IC miss, %d interp callsite, %d switch overflow",
431 gDvmJit.noChainExit[kInlineCacheMiss],
432 gDvmJit.noChainExit[kCallsiteInterpreted],
433 gDvmJit.noChainExit[kSwitchOverflow]);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700434#endif
Bill Buzbee9a8c75a2009-11-08 14:31:20 -0800435 LOGD("JIT: %d Translation chains, %d interp stubs",
436 gDvmJit.translationChains, stubs);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700437#if defined(INVOKE_STATS)
Ben Cheng38329f52009-07-07 14:19:20 -0700438 LOGD("JIT: Invoke: %d chainable, %d pred. chain, %d native, "
439 "%d return",
440 gDvmJit.invokeChain, gDvmJit.invokePredictedChain,
441 gDvmJit.invokeNative, gDvmJit.returnOp);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700442#endif
Ben Chenge80cd942009-07-17 15:54:23 -0700443 if (gDvmJit.profile) {
Bill Buzbee716f1202009-07-23 13:22:09 -0700444 dvmCompilerSortAndPrintTraceProfiles();
Bill Buzbee6e963e12009-06-17 16:56:19 -0700445 }
Ben Chengba4fc8b2009-06-01 13:00:29 -0700446 }
447}
448
Bill Buzbee716f1202009-07-23 13:22:09 -0700449
Ben Chengba4fc8b2009-06-01 13:00:29 -0700450/*
451 * Final JIT shutdown. Only do this once, and do not attempt to restart
452 * the JIT later.
453 */
454void dvmJitShutdown(void)
455{
456 /* Shutdown the compiler thread */
Bill Buzbee1465db52009-09-23 17:17:35 -0700457
Ben Chengba4fc8b2009-06-01 13:00:29 -0700458 dvmCompilerShutdown();
459
460 dvmCompilerDumpStats();
461
462 dvmDestroyMutex(&gDvmJit.tableLock);
463
464 if (gDvmJit.pJitEntryTable) {
465 free(gDvmJit.pJitEntryTable);
466 gDvmJit.pJitEntryTable = NULL;
467 }
468
469 if (gDvmJit.pProfTable) {
470 free(gDvmJit.pProfTable);
471 gDvmJit.pProfTable = NULL;
472 }
473}
474
Bill Buzbeed7269912009-11-10 14:31:32 -0800475void setTraceConstruction(JitEntry *slot, bool value)
476{
477
478 JitEntryInfoUnion oldValue;
479 JitEntryInfoUnion newValue;
480 do {
481 oldValue = slot->u;
482 newValue = oldValue;
483 newValue.info.traceConstruction = value;
484 } while (!ATOMIC_CMP_SWAP( &slot->u.infoWord,
485 oldValue.infoWord, newValue.infoWord));
486}
487
488void resetTracehead(InterpState* interpState, JitEntry *slot)
489{
490 slot->codeAddress = gDvmJit.interpretTemplate;
491 setTraceConstruction(slot, false);
492}
493
494/* Clean up any pending trace builds */
495void dvmJitAbortTraceSelect(InterpState* interpState)
496{
497 if (interpState->jitState == kJitTSelect)
498 interpState->jitState = kJitTSelectAbort;
499}
500
Bill Buzbeef9f33282009-11-22 12:45:30 -0800501#if defined(WITH_SELF_VERIFICATION)
502static bool selfVerificationPuntOps(DecodedInstruction *decInsn)
503{
504 OpCode op = decInsn->opCode;
505 int flags = dexGetInstrFlags(gDvm.instrFlags, op);
506 return (op == OP_MONITOR_ENTER || op == OP_MONITOR_EXIT ||
507 op == OP_NEW_INSTANCE || op == OP_NEW_ARRAY ||
508 op == OP_CHECK_CAST || op == OP_MOVE_EXCEPTION ||
509 (flags & kInstrInvoke));
510}
511#endif
512
Ben Chengba4fc8b2009-06-01 13:00:29 -0700513/*
Bill Buzbee964a7b02010-01-28 12:54:19 -0800514 * Find an entry in the JitTable, creating if necessary.
515 * Returns null if table is full.
516 */
517static JitEntry *lookupAndAdd(const u2* dPC, bool callerLocked)
518{
519 u4 chainEndMarker = gDvmJit.jitTableSize;
520 u4 idx = dvmJitHash(dPC);
521
522 /* Walk the bucket chain to find an exact match for our PC */
523 while ((gDvmJit.pJitEntryTable[idx].u.info.chain != chainEndMarker) &&
524 (gDvmJit.pJitEntryTable[idx].dPC != dPC)) {
525 idx = gDvmJit.pJitEntryTable[idx].u.info.chain;
526 }
527
528 if (gDvmJit.pJitEntryTable[idx].dPC != dPC) {
529 /*
530 * No match. Aquire jitTableLock and find the last
531 * slot in the chain. Possibly continue the chain walk in case
532 * some other thread allocated the slot we were looking
533 * at previuosly (perhaps even the dPC we're trying to enter).
534 */
535 if (!callerLocked)
536 dvmLockMutex(&gDvmJit.tableLock);
537 /*
538 * At this point, if .dPC is NULL, then the slot we're
539 * looking at is the target slot from the primary hash
540 * (the simple, and common case). Otherwise we're going
541 * to have to find a free slot and chain it.
542 */
543 MEM_BARRIER(); /* Make sure we reload [].dPC after lock */
544 if (gDvmJit.pJitEntryTable[idx].dPC != NULL) {
545 u4 prev;
546 while (gDvmJit.pJitEntryTable[idx].u.info.chain != chainEndMarker) {
547 if (gDvmJit.pJitEntryTable[idx].dPC == dPC) {
548 /* Another thread got there first for this dPC */
549 if (!callerLocked)
550 dvmUnlockMutex(&gDvmJit.tableLock);
551 return &gDvmJit.pJitEntryTable[idx];
552 }
553 idx = gDvmJit.pJitEntryTable[idx].u.info.chain;
554 }
555 /* Here, idx should be pointing to the last cell of an
556 * active chain whose last member contains a valid dPC */
557 assert(gDvmJit.pJitEntryTable[idx].dPC != NULL);
558 /* Linear walk to find a free cell and add it to the end */
559 prev = idx;
560 while (true) {
561 idx++;
562 if (idx == chainEndMarker)
563 idx = 0; /* Wraparound */
564 if ((gDvmJit.pJitEntryTable[idx].dPC == NULL) ||
565 (idx == prev))
566 break;
567 }
568 if (idx != prev) {
569 JitEntryInfoUnion oldValue;
570 JitEntryInfoUnion newValue;
571 /*
572 * Although we hold the lock so that noone else will
573 * be trying to update a chain field, the other fields
574 * packed into the word may be in use by other threads.
575 */
576 do {
577 oldValue = gDvmJit.pJitEntryTable[prev].u;
578 newValue = oldValue;
579 newValue.info.chain = idx;
580 } while (!ATOMIC_CMP_SWAP(
581 &gDvmJit.pJitEntryTable[prev].u.infoWord,
582 oldValue.infoWord, newValue.infoWord));
583 }
584 }
585 if (gDvmJit.pJitEntryTable[idx].dPC == NULL) {
586 /*
587 * Initialize codeAddress and allocate the slot. Must
588 * happen in this order (since dPC is set, the entry is live.
589 */
590 gDvmJit.pJitEntryTable[idx].dPC = dPC;
591 gDvmJit.jitTableEntriesUsed++;
592 } else {
593 /* Table is full */
594 idx = chainEndMarker;
595 }
596 if (!callerLocked)
597 dvmUnlockMutex(&gDvmJit.tableLock);
598 }
599 return (idx == chainEndMarker) ? NULL : &gDvmJit.pJitEntryTable[idx];
600}
601/*
Ben Chengba4fc8b2009-06-01 13:00:29 -0700602 * Adds to the current trace request one instruction at a time, just
603 * before that instruction is interpreted. This is the primary trace
604 * selection function. NOTE: return instruction are handled a little
605 * differently. In general, instructions are "proposed" to be added
606 * to the current trace prior to interpretation. If the interpreter
607 * then successfully completes the instruction, is will be considered
608 * part of the request. This allows us to examine machine state prior
609 * to interpretation, and also abort the trace request if the instruction
610 * throws or does something unexpected. However, return instructions
611 * will cause an immediate end to the translation request - which will
612 * be passed to the compiler before the return completes. This is done
613 * in response to special handling of returns by the interpreter (and
614 * because returns cannot throw in a way that causes problems for the
615 * translated code.
616 */
Ben Chengba4fc8b2009-06-01 13:00:29 -0700617int dvmCheckJit(const u2* pc, Thread* self, InterpState* interpState)
618{
619 int flags,i,len;
620 int switchInterp = false;
621 int debugOrProfile = (gDvm.debuggerActive || self->suspendCount
622#if defined(WITH_PROFILER)
623 || gDvm.activeProfilers
624#endif
625 );
Bill Buzbeed7269912009-11-10 14:31:32 -0800626
Ben Cheng79d173c2009-09-29 16:12:51 -0700627 /* Prepare to handle last PC and stage the current PC */
628 const u2 *lastPC = interpState->lastPC;
629 interpState->lastPC = pc;
630
Bill Buzbeef9f33282009-11-22 12:45:30 -0800631#if defined(WITH_SELF_VERIFICATION)
632 /*
633 * We can't allow some instructions to be executed twice, and so they
634 * must not appear in any translations. End the trace before they
635 * are inlcluded.
636 */
637 if (lastPC && interpState->jitState == kJitTSelect) {
638 DecodedInstruction decInsn;
639 dexDecodeInstruction(gDvm.instrFormat, lastPC, &decInsn);
640 if (selfVerificationPuntOps(&decInsn)) {
641 interpState->jitState = kJitTSelectEnd;
642 }
643 }
644#endif
645
Ben Chengba4fc8b2009-06-01 13:00:29 -0700646 switch (interpState->jitState) {
647 char* nopStr;
648 int target;
649 int offset;
650 DecodedInstruction decInsn;
651 case kJitTSelect:
Ben Chengdc84bb22009-10-02 12:58:52 -0700652 /* First instruction - just remember the PC and exit */
653 if (lastPC == NULL) break;
Ben Cheng79d173c2009-09-29 16:12:51 -0700654 /* Grow the trace around the last PC if jitState is kJitTSelect */
655 dexDecodeInstruction(gDvm.instrFormat, lastPC, &decInsn);
Ben Cheng6c10a972009-10-29 14:39:18 -0700656
657 /*
658 * Treat {PACKED,SPARSE}_SWITCH as trace-ending instructions due
659 * to the amount of space it takes to generate the chaining
660 * cells.
661 */
662 if (interpState->totalTraceLen != 0 &&
663 (decInsn.opCode == OP_PACKED_SWITCH ||
664 decInsn.opCode == OP_SPARSE_SWITCH)) {
665 interpState->jitState = kJitTSelectEnd;
666 break;
667 }
668
Bill Buzbeef9f33282009-11-22 12:45:30 -0800669
Ben Chengba4fc8b2009-06-01 13:00:29 -0700670#if defined(SHOW_TRACE)
671 LOGD("TraceGen: adding %s",getOpcodeName(decInsn.opCode));
672#endif
673 flags = dexGetInstrFlags(gDvm.instrFlags, decInsn.opCode);
Ben Cheng79d173c2009-09-29 16:12:51 -0700674 len = dexGetInstrOrTableWidthAbs(gDvm.instrWidth, lastPC);
675 offset = lastPC - interpState->method->insns;
676 assert((unsigned) offset <
677 dvmGetMethodInsnsSize(interpState->method));
678 if (lastPC != interpState->currRunHead + interpState->currRunLen) {
Bill Buzbee50a6bf22009-07-08 13:08:04 -0700679 int currTraceRun;
680 /* We need to start a new trace run */
681 currTraceRun = ++interpState->currTraceRun;
682 interpState->currRunLen = 0;
Ben Cheng79d173c2009-09-29 16:12:51 -0700683 interpState->currRunHead = (u2*)lastPC;
Bill Buzbee50a6bf22009-07-08 13:08:04 -0700684 interpState->trace[currTraceRun].frag.startOffset = offset;
685 interpState->trace[currTraceRun].frag.numInsts = 0;
686 interpState->trace[currTraceRun].frag.runEnd = false;
687 interpState->trace[currTraceRun].frag.hint = kJitHintNone;
688 }
689 interpState->trace[interpState->currTraceRun].frag.numInsts++;
690 interpState->totalTraceLen++;
691 interpState->currRunLen += len;
Ben Cheng79d173c2009-09-29 16:12:51 -0700692
693 /* Will probably never hit this with the current trace buildier */
694 if (interpState->currTraceRun == (MAX_JIT_RUN_LEN - 1)) {
695 interpState->jitState = kJitTSelectEnd;
696 }
697
Bill Buzbee50a6bf22009-07-08 13:08:04 -0700698 if ( ((flags & kInstrUnconditional) == 0) &&
Bill Buzbeef4ce16f2009-07-28 13:28:25 -0700699 /* don't end trace on INVOKE_DIRECT_EMPTY */
700 (decInsn.opCode != OP_INVOKE_DIRECT_EMPTY) &&
Bill Buzbee50a6bf22009-07-08 13:08:04 -0700701 ((flags & (kInstrCanBranch |
702 kInstrCanSwitch |
703 kInstrCanReturn |
704 kInstrInvoke)) != 0)) {
705 interpState->jitState = kJitTSelectEnd;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700706#if defined(SHOW_TRACE)
Bill Buzbee50a6bf22009-07-08 13:08:04 -0700707 LOGD("TraceGen: ending on %s, basic block end",
708 getOpcodeName(decInsn.opCode));
Ben Chengba4fc8b2009-06-01 13:00:29 -0700709#endif
Bill Buzbee50a6bf22009-07-08 13:08:04 -0700710 }
Bill Buzbee2ce8a6c2009-12-03 15:09:32 -0800711 /* Break on throw or self-loop */
Bill Buzbee324b3ac2009-12-04 13:17:36 -0800712 if ((decInsn.opCode == OP_THROW) || (lastPC == pc)){
Bill Buzbee50a6bf22009-07-08 13:08:04 -0700713 interpState->jitState = kJitTSelectEnd;
714 }
715 if (interpState->totalTraceLen >= JIT_MAX_TRACE_LEN) {
716 interpState->jitState = kJitTSelectEnd;
717 }
718 if (debugOrProfile) {
719 interpState->jitState = kJitTSelectAbort;
720 switchInterp = !debugOrProfile;
721 break;
722 }
723 if ((flags & kInstrCanReturn) != kInstrCanReturn) {
724 break;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700725 }
726 /* NOTE: intentional fallthrough for returns */
727 case kJitTSelectEnd:
728 {
729 if (interpState->totalTraceLen == 0) {
Bill Buzbeed7269912009-11-10 14:31:32 -0800730 /* Bad trace - mark as untranslatable */
731 dvmJitAbortTraceSelect(interpState);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700732 switchInterp = !debugOrProfile;
733 break;
734 }
735 JitTraceDescription* desc =
736 (JitTraceDescription*)malloc(sizeof(JitTraceDescription) +
737 sizeof(JitTraceRun) * (interpState->currTraceRun+1));
738 if (desc == NULL) {
739 LOGE("Out of memory in trace selection");
740 dvmJitStopTranslationRequests();
741 interpState->jitState = kJitTSelectAbort;
Bill Buzbeed7269912009-11-10 14:31:32 -0800742 dvmJitAbortTraceSelect(interpState);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700743 switchInterp = !debugOrProfile;
744 break;
745 }
746 interpState->trace[interpState->currTraceRun].frag.runEnd =
747 true;
748 interpState->jitState = kJitNormal;
749 desc->method = interpState->method;
750 memcpy((char*)&(desc->trace[0]),
751 (char*)&(interpState->trace[0]),
752 sizeof(JitTraceRun) * (interpState->currTraceRun+1));
753#if defined(SHOW_TRACE)
754 LOGD("TraceGen: trace done, adding to queue");
755#endif
Bill Buzbee964a7b02010-01-28 12:54:19 -0800756 if (dvmCompilerWorkEnqueue(
757 interpState->currTraceHead,kWorkOrderTrace,desc)) {
758 /* Work order successfully enqueued */
759 if (gDvmJit.blockingMode) {
760 dvmCompilerDrainQueue();
761 }
Ben Chengba4fc8b2009-06-01 13:00:29 -0700762 }
Bill Buzbee964a7b02010-01-28 12:54:19 -0800763 /*
764 * Reset "trace in progress" flag whether or not we
765 * successfully entered a work order.
766 */
767 setTraceConstruction(
768 lookupAndAdd(interpState->currTraceHead, false), false);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700769 switchInterp = !debugOrProfile;
770 }
771 break;
772 case kJitSingleStep:
773 interpState->jitState = kJitSingleStepEnd;
774 break;
775 case kJitSingleStepEnd:
776 interpState->entryPoint = kInterpEntryResume;
777 switchInterp = !debugOrProfile;
778 break;
779 case kJitTSelectAbort:
780#if defined(SHOW_TRACE)
781 LOGD("TraceGen: trace abort");
782#endif
Bill Buzbeed7269912009-11-10 14:31:32 -0800783 dvmJitAbortTraceSelect(interpState);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700784 interpState->jitState = kJitNormal;
785 switchInterp = !debugOrProfile;
786 break;
787 case kJitNormal:
Ben Cheng38329f52009-07-07 14:19:20 -0700788 switchInterp = !debugOrProfile;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700789 break;
Jeff Hao97319a82009-08-12 16:57:15 -0700790#if defined(WITH_SELF_VERIFICATION)
791 case kJitSelfVerification:
792 if (selfVerificationDebugInterp(pc, self)) {
793 interpState->jitState = kJitNormal;
794 switchInterp = !debugOrProfile;
795 }
796 break;
797#endif
Ben Chenged79ff02009-10-13 13:26:40 -0700798 /* If JIT is off stay out of interpreter selections */
799 case kJitOff:
800 break;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700801 default:
Ben Cheng9c147b82009-10-07 16:41:46 -0700802 if (!debugOrProfile) {
803 LOGE("Unexpected JIT state: %d", interpState->jitState);
804 dvmAbort();
805 }
806 break;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700807 }
808 return switchInterp;
809}
810
Ben Chengccd6c012009-10-15 14:52:45 -0700811JitEntry *dvmFindJitEntry(const u2* pc)
Ben Chengba4fc8b2009-06-01 13:00:29 -0700812{
813 int idx = dvmJitHash(pc);
814
815 /* Expect a high hit rate on 1st shot */
816 if (gDvmJit.pJitEntryTable[idx].dPC == pc)
817 return &gDvmJit.pJitEntryTable[idx];
818 else {
Bill Buzbee27176222009-06-09 09:20:16 -0700819 int chainEndMarker = gDvmJit.jitTableSize;
Bill Buzbee716f1202009-07-23 13:22:09 -0700820 while (gDvmJit.pJitEntryTable[idx].u.info.chain != chainEndMarker) {
821 idx = gDvmJit.pJitEntryTable[idx].u.info.chain;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700822 if (gDvmJit.pJitEntryTable[idx].dPC == pc)
823 return &gDvmJit.pJitEntryTable[idx];
824 }
825 }
826 return NULL;
827}
828
Bill Buzbee27176222009-06-09 09:20:16 -0700829/*
Ben Chengba4fc8b2009-06-01 13:00:29 -0700830 * If a translated code address exists for the davik byte code
831 * pointer return it. This routine needs to be fast.
832 */
833void* dvmJitGetCodeAddr(const u2* dPC)
834{
835 int idx = dvmJitHash(dPC);
Ben Cheng33672452010-01-12 14:59:30 -0800836 const u2* npc = gDvmJit.pJitEntryTable[idx].dPC;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700837
Bill Buzbee9797a232010-01-12 12:20:13 -0800838 if (npc != NULL) {
839 if (npc == dPC) {
Ben Chengba4fc8b2009-06-01 13:00:29 -0700840#if defined(EXIT_STATS)
Bill Buzbee9797a232010-01-12 12:20:13 -0800841 gDvmJit.addrLookupsFound++;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700842#endif
Bill Buzbee9797a232010-01-12 12:20:13 -0800843 return gDvm.sumThreadSuspendCount ? NULL :
844 gDvmJit.pJitEntryTable[idx].codeAddress;
845 } else {
846 int chainEndMarker = gDvmJit.jitTableSize;
847 while (gDvmJit.pJitEntryTable[idx].u.info.chain != chainEndMarker) {
848 idx = gDvmJit.pJitEntryTable[idx].u.info.chain;
849 if (gDvmJit.pJitEntryTable[idx].dPC == dPC) {
Ben Chengba4fc8b2009-06-01 13:00:29 -0700850#if defined(EXIT_STATS)
Bill Buzbee9797a232010-01-12 12:20:13 -0800851 gDvmJit.addrLookupsFound++;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700852#endif
Bill Buzbee9797a232010-01-12 12:20:13 -0800853 return gDvm.sumThreadSuspendCount ? NULL :
854 gDvmJit.pJitEntryTable[idx].codeAddress;
855 }
Ben Chengba4fc8b2009-06-01 13:00:29 -0700856 }
857 }
858 }
859#if defined(EXIT_STATS)
860 gDvmJit.addrLookupsNotFound++;
861#endif
862 return NULL;
863}
864
865/*
866 * Register the translated code pointer into the JitTable.
Bill Buzbee9a8c75a2009-11-08 14:31:20 -0800867 * NOTE: Once a codeAddress field transitions from initial state to
Ben Chengba4fc8b2009-06-01 13:00:29 -0700868 * JIT'd code, it must not be altered without first halting all
Bill Buzbee716f1202009-07-23 13:22:09 -0700869 * threads. This routine should only be called by the compiler
870 * thread.
Ben Chengba4fc8b2009-06-01 13:00:29 -0700871 */
Bill Buzbee716f1202009-07-23 13:22:09 -0700872void dvmJitSetCodeAddr(const u2* dPC, void *nPC, JitInstructionSetType set) {
873 JitEntryInfoUnion oldValue;
874 JitEntryInfoUnion newValue;
Bill Buzbee964a7b02010-01-28 12:54:19 -0800875 JitEntry *jitEntry = lookupAndAdd(dPC, false);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700876 assert(jitEntry);
Bill Buzbee716f1202009-07-23 13:22:09 -0700877 /* Note: order of update is important */
878 do {
879 oldValue = jitEntry->u;
880 newValue = oldValue;
881 newValue.info.instructionSet = set;
882 } while (!ATOMIC_CMP_SWAP(
883 &jitEntry->u.infoWord,
884 oldValue.infoWord, newValue.infoWord));
885 jitEntry->codeAddress = nPC;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700886}
887
888/*
889 * Determine if valid trace-bulding request is active. Return true
890 * if we need to abort and switch back to the fast interpreter, false
891 * otherwise. NOTE: may be called even when trace selection is not being
892 * requested
893 */
Ben Chengba4fc8b2009-06-01 13:00:29 -0700894bool dvmJitCheckTraceRequest(Thread* self, InterpState* interpState)
895{
Bill Buzbee48f18242009-06-19 16:02:27 -0700896 bool res = false; /* Assume success */
897 int i;
Bill Buzbee9a8c75a2009-11-08 14:31:20 -0800898 /*
899 * If previous trace-building attempt failed, force it's head to be
900 * interpret-only.
901 */
Ben Chengba4fc8b2009-06-01 13:00:29 -0700902 if (gDvmJit.pJitEntryTable != NULL) {
Bill Buzbee48f18242009-06-19 16:02:27 -0700903 /* Two-level filtering scheme */
904 for (i=0; i< JIT_TRACE_THRESH_FILTER_SIZE; i++) {
905 if (interpState->pc == interpState->threshFilter[i]) {
906 break;
907 }
908 }
909 if (i == JIT_TRACE_THRESH_FILTER_SIZE) {
910 /*
911 * Use random replacement policy - otherwise we could miss a large
912 * loop that contains more traces than the size of our filter array.
913 */
914 i = rand() % JIT_TRACE_THRESH_FILTER_SIZE;
915 interpState->threshFilter[i] = interpState->pc;
916 res = true;
917 }
Bill Buzbeed7269912009-11-10 14:31:32 -0800918
Bill Buzbeef9f33282009-11-22 12:45:30 -0800919 /* If stress mode (threshold <= 6), always translate */
920 res &= (gDvmJit.threshold > 6);
Bill Buzbeed7269912009-11-10 14:31:32 -0800921
Ben Chengba4fc8b2009-06-01 13:00:29 -0700922 /*
923 * If the compiler is backlogged, or if a debugger or profiler is
924 * active, cancel any JIT actions
925 */
Bill Buzbee9a8c75a2009-11-08 14:31:20 -0800926 if (res || (gDvmJit.compilerQueueLength >= gDvmJit.compilerHighWater)
927 || gDvm.debuggerActive || self->suspendCount
Ben Chengba4fc8b2009-06-01 13:00:29 -0700928#if defined(WITH_PROFILER)
929 || gDvm.activeProfilers
930#endif
931 ) {
932 if (interpState->jitState != kJitOff) {
933 interpState->jitState = kJitNormal;
934 }
Ben Chengba4fc8b2009-06-01 13:00:29 -0700935 } else if (interpState->jitState == kJitTSelectRequest) {
Bill Buzbee964a7b02010-01-28 12:54:19 -0800936 JitEntry *slot = lookupAndAdd(interpState->pc, false);
Bill Buzbee716f1202009-07-23 13:22:09 -0700937 if (slot == NULL) {
Ben Chengba4fc8b2009-06-01 13:00:29 -0700938 /*
Bill Buzbee716f1202009-07-23 13:22:09 -0700939 * Table is full. This should have been
940 * detected by the compiler thread and the table
941 * resized before we run into it here. Assume bad things
942 * are afoot and disable profiling.
Ben Chengba4fc8b2009-06-01 13:00:29 -0700943 */
944 interpState->jitState = kJitTSelectAbort;
Bill Buzbee716f1202009-07-23 13:22:09 -0700945 LOGD("JIT: JitTable full, disabling profiling");
946 dvmJitStopTranslationRequests();
Bill Buzbeed7269912009-11-10 14:31:32 -0800947 } else if (slot->u.info.traceConstruction) {
948 /*
Ben Cheng60c24f42010-01-04 12:29:56 -0800949 * Trace request already in progress, but most likely it
Bill Buzbeed7269912009-11-10 14:31:32 -0800950 * aborted without cleaning up. Assume the worst and
951 * mark trace head as untranslatable. If we're wrong,
952 * the compiler thread will correct the entry when the
953 * translation is completed. The downside here is that
954 * some existing translation may chain to the interpret-only
955 * template instead of the real translation during this
956 * window. Performance, but not correctness, issue.
957 */
958 interpState->jitState = kJitTSelectAbort;
959 resetTracehead(interpState, slot);
960 } else if (slot->codeAddress) {
961 /* Nothing to do here - just return */
Bill Buzbee716f1202009-07-23 13:22:09 -0700962 interpState->jitState = kJitTSelectAbort;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700963 } else {
Bill Buzbeed7269912009-11-10 14:31:32 -0800964 /*
965 * Mark request. Note, we are not guaranteed exclusivity
966 * here. A window exists for another thread to be
967 * attempting to build this same trace. Rather than
968 * bear the cost of locking, we'll just allow that to
969 * happen. The compiler thread, if it chooses, can
970 * discard redundant requests.
971 */
972 setTraceConstruction(slot, true);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700973 }
974 }
975 switch (interpState->jitState) {
976 case kJitTSelectRequest:
977 interpState->jitState = kJitTSelect;
978 interpState->currTraceHead = interpState->pc;
979 interpState->currTraceRun = 0;
980 interpState->totalTraceLen = 0;
981 interpState->currRunHead = interpState->pc;
982 interpState->currRunLen = 0;
983 interpState->trace[0].frag.startOffset =
984 interpState->pc - interpState->method->insns;
985 interpState->trace[0].frag.numInsts = 0;
986 interpState->trace[0].frag.runEnd = false;
987 interpState->trace[0].frag.hint = kJitHintNone;
Ben Cheng79d173c2009-09-29 16:12:51 -0700988 interpState->lastPC = 0;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700989 break;
990 case kJitTSelect:
991 case kJitTSelectAbort:
992 res = true;
993 case kJitSingleStep:
994 case kJitSingleStepEnd:
995 case kJitOff:
996 case kJitNormal:
Jeff Hao97319a82009-08-12 16:57:15 -0700997#if defined(WITH_SELF_VERIFICATION)
998 case kJitSelfVerification:
999#endif
Ben Chengba4fc8b2009-06-01 13:00:29 -07001000 break;
1001 default:
Ben Cheng9c147b82009-10-07 16:41:46 -07001002 LOGE("Unexpected JIT state: %d", interpState->jitState);
Ben Chengba4fc8b2009-06-01 13:00:29 -07001003 dvmAbort();
1004 }
1005 }
1006 return res;
1007}
1008
Bill Buzbee27176222009-06-09 09:20:16 -07001009/*
1010 * Resizes the JitTable. Must be a power of 2, and returns true on failure.
Bill Buzbee964a7b02010-01-28 12:54:19 -08001011 * Stops all threads, and thus is a heavyweight operation. May only be called
1012 * by the compiler thread.
Bill Buzbee27176222009-06-09 09:20:16 -07001013 */
1014bool dvmJitResizeJitTable( unsigned int size )
1015{
Bill Buzbee716f1202009-07-23 13:22:09 -07001016 JitEntry *pNewTable;
1017 JitEntry *pOldTable;
Bill Buzbee964a7b02010-01-28 12:54:19 -08001018 JitEntry tempEntry;
Bill Buzbee27176222009-06-09 09:20:16 -07001019 u4 newMask;
Bill Buzbee716f1202009-07-23 13:22:09 -07001020 unsigned int oldSize;
Bill Buzbee27176222009-06-09 09:20:16 -07001021 unsigned int i;
1022
Ben Cheng3f02aa42009-08-14 13:52:09 -07001023 assert(gDvmJit.pJitEntryTable != NULL);
Bill Buzbee27176222009-06-09 09:20:16 -07001024 assert(size && !(size & (size - 1))); /* Is power of 2? */
1025
1026 LOGD("Jit: resizing JitTable from %d to %d", gDvmJit.jitTableSize, size);
1027
1028 newMask = size - 1;
1029
1030 if (size <= gDvmJit.jitTableSize) {
1031 return true;
1032 }
1033
Bill Buzbee964a7b02010-01-28 12:54:19 -08001034 /* Make sure requested size is compatible with chain field width */
1035 tempEntry.u.info.chain = size;
1036 if (tempEntry.u.info.chain != size) {
1037 LOGD("Jit: JitTable request of %d too big", size);
1038 return true;
1039 }
1040
Bill Buzbee716f1202009-07-23 13:22:09 -07001041 pNewTable = (JitEntry*)calloc(size, sizeof(*pNewTable));
Bill Buzbee27176222009-06-09 09:20:16 -07001042 if (pNewTable == NULL) {
1043 return true;
1044 }
1045 for (i=0; i< size; i++) {
Bill Buzbee716f1202009-07-23 13:22:09 -07001046 pNewTable[i].u.info.chain = size; /* Initialize chain termination */
Bill Buzbee27176222009-06-09 09:20:16 -07001047 }
1048
1049 /* Stop all other interpreting/jit'ng threads */
Ben Chenga8e64a72009-10-20 13:01:36 -07001050 dvmSuspendAllThreads(SUSPEND_FOR_TBL_RESIZE);
Bill Buzbee27176222009-06-09 09:20:16 -07001051
Bill Buzbee716f1202009-07-23 13:22:09 -07001052 pOldTable = gDvmJit.pJitEntryTable;
1053 oldSize = gDvmJit.jitTableSize;
Bill Buzbee27176222009-06-09 09:20:16 -07001054
1055 dvmLockMutex(&gDvmJit.tableLock);
Bill Buzbee27176222009-06-09 09:20:16 -07001056 gDvmJit.pJitEntryTable = pNewTable;
1057 gDvmJit.jitTableSize = size;
1058 gDvmJit.jitTableMask = size - 1;
Bill Buzbee716f1202009-07-23 13:22:09 -07001059 gDvmJit.jitTableEntriesUsed = 0;
Bill Buzbee27176222009-06-09 09:20:16 -07001060
Bill Buzbee716f1202009-07-23 13:22:09 -07001061 for (i=0; i < oldSize; i++) {
1062 if (pOldTable[i].dPC) {
1063 JitEntry *p;
1064 u2 chain;
Bill Buzbee964a7b02010-01-28 12:54:19 -08001065 p = lookupAndAdd(pOldTable[i].dPC, true /* holds tableLock*/ );
1066 p->codeAddress = pOldTable[i].codeAddress;
Bill Buzbee716f1202009-07-23 13:22:09 -07001067 /* We need to preserve the new chain field, but copy the rest */
Bill Buzbee716f1202009-07-23 13:22:09 -07001068 chain = p->u.info.chain;
1069 p->u = pOldTable[i].u;
1070 p->u.info.chain = chain;
Bill Buzbee716f1202009-07-23 13:22:09 -07001071 }
1072 }
Bill Buzbee964a7b02010-01-28 12:54:19 -08001073 dvmUnlockMutex(&gDvmJit.tableLock);
Bill Buzbee716f1202009-07-23 13:22:09 -07001074
1075 free(pOldTable);
1076
Bill Buzbee27176222009-06-09 09:20:16 -07001077 /* Restart the world */
Ben Chenga8e64a72009-10-20 13:01:36 -07001078 dvmResumeAllThreads(SUSPEND_FOR_TBL_RESIZE);
Bill Buzbee27176222009-06-09 09:20:16 -07001079
1080 return false;
1081}
1082
Bill Buzbee50a6bf22009-07-08 13:08:04 -07001083/*
Ben Cheng60c24f42010-01-04 12:29:56 -08001084 * Reset the JitTable to the initial clean state.
1085 */
1086void dvmJitResetTable(void)
1087{
1088 JitEntry *jitEntry = gDvmJit.pJitEntryTable;
1089 unsigned int size = gDvmJit.jitTableSize;
1090 unsigned int i;
1091
1092 dvmLockMutex(&gDvmJit.tableLock);
1093 memset((void *) jitEntry, 0, sizeof(JitEntry) * size);
1094 for (i=0; i< size; i++) {
1095 jitEntry[i].u.info.chain = size; /* Initialize chain termination */
1096 }
1097 gDvmJit.jitTableEntriesUsed = 0;
1098 dvmUnlockMutex(&gDvmJit.tableLock);
1099}
1100
1101/*
Bill Buzbee50a6bf22009-07-08 13:08:04 -07001102 * Float/double conversion requires clamping to min and max of integer form. If
1103 * target doesn't support this normally, use these.
1104 */
1105s8 dvmJitd2l(double d)
1106{
Bill Buzbee9727c3d2009-08-01 11:32:36 -07001107 static const double kMaxLong = (double)(s8)0x7fffffffffffffffULL;
1108 static const double kMinLong = (double)(s8)0x8000000000000000ULL;
Bill Buzbee50a6bf22009-07-08 13:08:04 -07001109 if (d >= kMaxLong)
Bill Buzbee9727c3d2009-08-01 11:32:36 -07001110 return (s8)0x7fffffffffffffffULL;
Bill Buzbee50a6bf22009-07-08 13:08:04 -07001111 else if (d <= kMinLong)
Bill Buzbee9727c3d2009-08-01 11:32:36 -07001112 return (s8)0x8000000000000000ULL;
Bill Buzbee50a6bf22009-07-08 13:08:04 -07001113 else if (d != d) // NaN case
1114 return 0;
1115 else
1116 return (s8)d;
1117}
1118
1119s8 dvmJitf2l(float f)
1120{
Bill Buzbee9727c3d2009-08-01 11:32:36 -07001121 static const float kMaxLong = (float)(s8)0x7fffffffffffffffULL;
1122 static const float kMinLong = (float)(s8)0x8000000000000000ULL;
Bill Buzbee50a6bf22009-07-08 13:08:04 -07001123 if (f >= kMaxLong)
Bill Buzbee9727c3d2009-08-01 11:32:36 -07001124 return (s8)0x7fffffffffffffffULL;
Bill Buzbee50a6bf22009-07-08 13:08:04 -07001125 else if (f <= kMinLong)
Bill Buzbee9727c3d2009-08-01 11:32:36 -07001126 return (s8)0x8000000000000000ULL;
Bill Buzbee50a6bf22009-07-08 13:08:04 -07001127 else if (f != f) // NaN case
1128 return 0;
1129 else
1130 return (s8)f;
1131}
1132
Bill Buzbee27176222009-06-09 09:20:16 -07001133
Ben Chengba4fc8b2009-06-01 13:00:29 -07001134#endif /* WITH_JIT */