blob: c4dbf2794d87990d0de1f2cad6e9fb549e6c625c [file] [log] [blame]
Ben Chengba4fc8b2009-06-01 13:00:29 -07001/*
2 * Copyright (C) 2009 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
17#include "Dalvik.h"
Dan Bornsteindf4daaf2010-12-01 14:23:44 -080018#include "libdex/DexOpcodes.h"
Ben Cheng00603072010-10-28 11:13:58 -070019#include "libdex/DexCatch.h"
Ben Chengba4fc8b2009-06-01 13:00:29 -070020#include "interp/Jit.h"
21#include "CompilerInternals.h"
Ben Cheng7a2697d2010-06-07 13:44:23 -070022#include "Dataflow.h"
Ben Chengba4fc8b2009-06-01 13:00:29 -070023
Ben Cheng00603072010-10-28 11:13:58 -070024static inline bool contentIsInsn(const u2 *codePtr) {
25 u2 instr = *codePtr;
26 Opcode opcode = instr & 0xff;
27
28 /*
29 * Since the low 8-bit in metadata may look like OP_NOP, we need to check
30 * both the low and whole sub-word to determine whether it is code or data.
31 */
32 return (opcode != OP_NOP || instr == 0);
33}
34
Ben Chengba4fc8b2009-06-01 13:00:29 -070035/*
36 * Parse an instruction, return the length of the instruction
37 */
38static inline int parseInsn(const u2 *codePtr, DecodedInstruction *decInsn,
39 bool printMe)
40{
Ben Cheng00603072010-10-28 11:13:58 -070041 // Don't parse instruction data
42 if (!contentIsInsn(codePtr)) {
43 return 0;
44 }
45
Ben Chengba4fc8b2009-06-01 13:00:29 -070046 u2 instr = *codePtr;
Dan Bornstein9a1f8162010-12-01 17:02:26 -080047 Opcode opcode = dexOpcodeFromCodeUnit(instr);
Ben Chengba4fc8b2009-06-01 13:00:29 -070048
Dan Bornstein54322392010-11-17 14:16:56 -080049 dexDecodeInstruction(codePtr, decInsn);
Ben Chengba4fc8b2009-06-01 13:00:29 -070050 if (printMe) {
Ben Cheng7a2697d2010-06-07 13:44:23 -070051 char *decodedString = dvmCompilerGetDalvikDisassembly(decInsn, NULL);
Ben Chengccd6c012009-10-15 14:52:45 -070052 LOGD("%p: %#06x %s\n", codePtr, opcode, decodedString);
Ben Chengba4fc8b2009-06-01 13:00:29 -070053 }
Ben Cheng00603072010-10-28 11:13:58 -070054 return dexGetWidthFromOpcode(opcode);
Ben Chengba4fc8b2009-06-01 13:00:29 -070055}
56
Ben Cheng9c147b82009-10-07 16:41:46 -070057#define UNKNOWN_TARGET 0xffffffff
58
Ben Chengba4fc8b2009-06-01 13:00:29 -070059/*
60 * Identify block-ending instructions and collect supplemental information
61 * regarding the following instructions.
62 */
63static inline bool findBlockBoundary(const Method *caller, MIR *insn,
64 unsigned int curOffset,
65 unsigned int *target, bool *isInvoke,
66 const Method **callee)
67{
Dan Bornstein9a1f8162010-12-01 17:02:26 -080068 switch (insn->dalvikInsn.opcode) {
Ben Chengba4fc8b2009-06-01 13:00:29 -070069 /* Target is not compile-time constant */
70 case OP_RETURN_VOID:
71 case OP_RETURN:
72 case OP_RETURN_WIDE:
73 case OP_RETURN_OBJECT:
74 case OP_THROW:
Ben Cheng9c147b82009-10-07 16:41:46 -070075 *target = UNKNOWN_TARGET;
76 break;
Ben Chengba4fc8b2009-06-01 13:00:29 -070077 case OP_INVOKE_VIRTUAL:
78 case OP_INVOKE_VIRTUAL_RANGE:
jeffhao71eee1f2011-01-04 14:18:54 -080079 case OP_INVOKE_VIRTUAL_JUMBO:
Ben Chengba4fc8b2009-06-01 13:00:29 -070080 case OP_INVOKE_INTERFACE:
81 case OP_INVOKE_INTERFACE_RANGE:
jeffhao71eee1f2011-01-04 14:18:54 -080082 case OP_INVOKE_INTERFACE_JUMBO:
Ben Chengba4fc8b2009-06-01 13:00:29 -070083 case OP_INVOKE_VIRTUAL_QUICK:
84 case OP_INVOKE_VIRTUAL_QUICK_RANGE:
85 *isInvoke = true;
86 break;
87 case OP_INVOKE_SUPER:
jeffhao71eee1f2011-01-04 14:18:54 -080088 case OP_INVOKE_SUPER_RANGE:
89 case OP_INVOKE_SUPER_JUMBO: {
Ben Chengba4fc8b2009-06-01 13:00:29 -070090 int mIndex = caller->clazz->pDvmDex->
91 pResMethods[insn->dalvikInsn.vB]->methodIndex;
92 const Method *calleeMethod =
93 caller->clazz->super->vtable[mIndex];
94
Ben Cheng8b258bf2009-06-24 17:27:07 -070095 if (calleeMethod && !dvmIsNativeMethod(calleeMethod)) {
Ben Chengba4fc8b2009-06-01 13:00:29 -070096 *target = (unsigned int) calleeMethod->insns;
97 }
98 *isInvoke = true;
99 *callee = calleeMethod;
100 break;
101 }
102 case OP_INVOKE_STATIC:
jeffhao71eee1f2011-01-04 14:18:54 -0800103 case OP_INVOKE_STATIC_RANGE:
104 case OP_INVOKE_STATIC_JUMBO: {
Ben Chengba4fc8b2009-06-01 13:00:29 -0700105 const Method *calleeMethod =
106 caller->clazz->pDvmDex->pResMethods[insn->dalvikInsn.vB];
107
Ben Cheng8b258bf2009-06-24 17:27:07 -0700108 if (calleeMethod && !dvmIsNativeMethod(calleeMethod)) {
Ben Chengba4fc8b2009-06-01 13:00:29 -0700109 *target = (unsigned int) calleeMethod->insns;
110 }
111 *isInvoke = true;
112 *callee = calleeMethod;
113 break;
114 }
115 case OP_INVOKE_SUPER_QUICK:
116 case OP_INVOKE_SUPER_QUICK_RANGE: {
117 const Method *calleeMethod =
118 caller->clazz->super->vtable[insn->dalvikInsn.vB];
119
Ben Cheng8b258bf2009-06-24 17:27:07 -0700120 if (calleeMethod && !dvmIsNativeMethod(calleeMethod)) {
Ben Chengba4fc8b2009-06-01 13:00:29 -0700121 *target = (unsigned int) calleeMethod->insns;
122 }
123 *isInvoke = true;
124 *callee = calleeMethod;
125 break;
126 }
127 case OP_INVOKE_DIRECT:
jeffhao71eee1f2011-01-04 14:18:54 -0800128 case OP_INVOKE_DIRECT_RANGE:
129 case OP_INVOKE_DIRECT_JUMBO: {
Ben Chengba4fc8b2009-06-01 13:00:29 -0700130 const Method *calleeMethod =
131 caller->clazz->pDvmDex->pResMethods[insn->dalvikInsn.vB];
Ben Cheng8b258bf2009-06-24 17:27:07 -0700132 if (calleeMethod && !dvmIsNativeMethod(calleeMethod)) {
Ben Chengba4fc8b2009-06-01 13:00:29 -0700133 *target = (unsigned int) calleeMethod->insns;
134 }
135 *isInvoke = true;
136 *callee = calleeMethod;
137 break;
138 }
139 case OP_GOTO:
140 case OP_GOTO_16:
141 case OP_GOTO_32:
142 *target = curOffset + (int) insn->dalvikInsn.vA;
143 break;
144
145 case OP_IF_EQ:
146 case OP_IF_NE:
147 case OP_IF_LT:
148 case OP_IF_GE:
149 case OP_IF_GT:
150 case OP_IF_LE:
151 *target = curOffset + (int) insn->dalvikInsn.vC;
152 break;
153
154 case OP_IF_EQZ:
155 case OP_IF_NEZ:
156 case OP_IF_LTZ:
157 case OP_IF_GEZ:
158 case OP_IF_GTZ:
159 case OP_IF_LEZ:
160 *target = curOffset + (int) insn->dalvikInsn.vB;
161 break;
162
163 default:
164 return false;
Ben Cheng9c147b82009-10-07 16:41:46 -0700165 }
166 return true;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700167}
168
Bill Buzbee324b3ac2009-12-04 13:17:36 -0800169static inline bool isGoto(MIR *insn)
170{
Dan Bornstein9a1f8162010-12-01 17:02:26 -0800171 switch (insn->dalvikInsn.opcode) {
Bill Buzbee324b3ac2009-12-04 13:17:36 -0800172 case OP_GOTO:
173 case OP_GOTO_16:
174 case OP_GOTO_32:
175 return true;
176 default:
177 return false;
178 }
179}
180
Ben Chengba4fc8b2009-06-01 13:00:29 -0700181/*
Bill Buzbee324b3ac2009-12-04 13:17:36 -0800182 * Identify unconditional branch instructions
Ben Chengba4fc8b2009-06-01 13:00:29 -0700183 */
184static inline bool isUnconditionalBranch(MIR *insn)
185{
Dan Bornstein9a1f8162010-12-01 17:02:26 -0800186 switch (insn->dalvikInsn.opcode) {
Ben Chengba4fc8b2009-06-01 13:00:29 -0700187 case OP_RETURN_VOID:
188 case OP_RETURN:
189 case OP_RETURN_WIDE:
190 case OP_RETURN_OBJECT:
Ben Chengba4fc8b2009-06-01 13:00:29 -0700191 return true;
192 default:
Bill Buzbee324b3ac2009-12-04 13:17:36 -0800193 return isGoto(insn);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700194 }
195}
196
197/*
Ben Cheng8b258bf2009-06-24 17:27:07 -0700198 * dvmHashTableLookup() callback
199 */
200static int compareMethod(const CompilerMethodStats *m1,
201 const CompilerMethodStats *m2)
202{
203 return (int) m1->method - (int) m2->method;
204}
205
206/*
Ben Cheng7a2697d2010-06-07 13:44:23 -0700207 * Analyze the body of the method to collect high-level information regarding
208 * inlining:
209 * - is empty method?
210 * - is getter/setter?
211 * - can throw exception?
212 *
213 * Currently the inliner only handles getters and setters. When its capability
214 * becomes more sophisticated more information will be retrieved here.
215 */
216static int analyzeInlineTarget(DecodedInstruction *dalvikInsn, int attributes,
217 int offset)
218{
Dan Bornsteine4852762010-12-02 12:45:00 -0800219 int flags = dexGetFlagsFromOpcode(dalvikInsn->opcode);
Dan Bornstein9a1f8162010-12-01 17:02:26 -0800220 int dalvikOpcode = dalvikInsn->opcode;
Ben Cheng7a2697d2010-06-07 13:44:23 -0700221
Dan Bornstein0759f522010-11-30 14:58:53 -0800222 if (flags & kInstrInvoke) {
Ben Cheng7a2697d2010-06-07 13:44:23 -0700223 attributes &= ~METHOD_IS_LEAF;
224 }
225
226 if (!(flags & kInstrCanReturn)) {
Dan Bornstein9a1f8162010-12-01 17:02:26 -0800227 if (!(dvmCompilerDataFlowAttributes[dalvikOpcode] &
Ben Cheng7a2697d2010-06-07 13:44:23 -0700228 DF_IS_GETTER)) {
229 attributes &= ~METHOD_IS_GETTER;
230 }
Dan Bornstein9a1f8162010-12-01 17:02:26 -0800231 if (!(dvmCompilerDataFlowAttributes[dalvikOpcode] &
Ben Cheng7a2697d2010-06-07 13:44:23 -0700232 DF_IS_SETTER)) {
233 attributes &= ~METHOD_IS_SETTER;
234 }
235 }
236
237 /*
238 * The expected instruction sequence is setter will never return value and
239 * getter will also do. Clear the bits if the behavior is discovered
240 * otherwise.
241 */
242 if (flags & kInstrCanReturn) {
Dan Bornstein9a1f8162010-12-01 17:02:26 -0800243 if (dalvikOpcode == OP_RETURN_VOID) {
Ben Cheng7a2697d2010-06-07 13:44:23 -0700244 attributes &= ~METHOD_IS_GETTER;
245 }
246 else {
247 attributes &= ~METHOD_IS_SETTER;
248 }
249 }
250
251 if (flags & kInstrCanThrow) {
252 attributes &= ~METHOD_IS_THROW_FREE;
253 }
254
Dan Bornstein9a1f8162010-12-01 17:02:26 -0800255 if (offset == 0 && dalvikOpcode == OP_RETURN_VOID) {
Ben Cheng7a2697d2010-06-07 13:44:23 -0700256 attributes |= METHOD_IS_EMPTY;
257 }
258
Ben Cheng34dc7962010-08-26 14:56:31 -0700259 /*
260 * Check if this opcode is selected for single stepping.
261 * If so, don't inline the callee as there is no stack frame for the
262 * interpreter to single-step through the instruction.
263 */
Dan Bornstein9a1f8162010-12-01 17:02:26 -0800264 if (SINGLE_STEP_OP(dalvikOpcode)) {
Ben Cheng34dc7962010-08-26 14:56:31 -0700265 attributes &= ~(METHOD_IS_GETTER | METHOD_IS_SETTER);
266 }
267
Ben Cheng7a2697d2010-06-07 13:44:23 -0700268 return attributes;
269}
270
271/*
Ben Cheng8b258bf2009-06-24 17:27:07 -0700272 * Analyze each method whose traces are ever compiled. Collect a variety of
273 * statistics like the ratio of exercised vs overall code and code bloat
Ben Cheng7a2697d2010-06-07 13:44:23 -0700274 * ratios. If isCallee is true, also analyze each instruction in more details
275 * to see if it is suitable for inlining.
Ben Cheng8b258bf2009-06-24 17:27:07 -0700276 */
Ben Cheng7a2697d2010-06-07 13:44:23 -0700277CompilerMethodStats *dvmCompilerAnalyzeMethodBody(const Method *method,
278 bool isCallee)
Ben Cheng8b258bf2009-06-24 17:27:07 -0700279{
280 const DexCode *dexCode = dvmGetMethodCode(method);
281 const u2 *codePtr = dexCode->insns;
282 const u2 *codeEnd = dexCode->insns + dexCode->insnsSize;
283 int insnSize = 0;
284 int hashValue = dvmComputeUtf8Hash(method->name);
285
286 CompilerMethodStats dummyMethodEntry; // For hash table lookup
287 CompilerMethodStats *realMethodEntry; // For hash table storage
288
289 /* For lookup only */
290 dummyMethodEntry.method = method;
Ben Chengcfdeca32011-01-14 11:36:46 -0800291 realMethodEntry = (CompilerMethodStats *)
292 dvmHashTableLookup(gDvmJit.methodStatsTable,
293 hashValue,
294 &dummyMethodEntry,
295 (HashCompareFunc) compareMethod,
296 false);
Ben Cheng8b258bf2009-06-24 17:27:07 -0700297
Ben Cheng7a2697d2010-06-07 13:44:23 -0700298 /* This method has never been analyzed before - create an entry */
299 if (realMethodEntry == NULL) {
300 realMethodEntry =
301 (CompilerMethodStats *) calloc(1, sizeof(CompilerMethodStats));
302 realMethodEntry->method = method;
303
304 dvmHashTableLookup(gDvmJit.methodStatsTable, hashValue,
305 realMethodEntry,
306 (HashCompareFunc) compareMethod,
307 true);
Ben Cheng8b258bf2009-06-24 17:27:07 -0700308 }
309
Ben Cheng7a2697d2010-06-07 13:44:23 -0700310 /* This method is invoked as a callee and has been analyzed - just return */
311 if ((isCallee == true) && (realMethodEntry->attributes & METHOD_IS_CALLEE))
312 return realMethodEntry;
Ben Cheng8b258bf2009-06-24 17:27:07 -0700313
Ben Cheng7a2697d2010-06-07 13:44:23 -0700314 /*
315 * Similarly, return if this method has been compiled before as a hot
316 * method already.
317 */
318 if ((isCallee == false) &&
319 (realMethodEntry->attributes & METHOD_IS_HOT))
320 return realMethodEntry;
321
322 int attributes;
323
324 /* Method hasn't been analyzed for the desired purpose yet */
325 if (isCallee) {
326 /* Aggressively set the attributes until proven otherwise */
327 attributes = METHOD_IS_LEAF | METHOD_IS_THROW_FREE | METHOD_IS_CALLEE |
328 METHOD_IS_GETTER | METHOD_IS_SETTER;
329 } else {
330 attributes = METHOD_IS_HOT;
331 }
Ben Cheng8b258bf2009-06-24 17:27:07 -0700332
333 /* Count the number of instructions */
334 while (codePtr < codeEnd) {
335 DecodedInstruction dalvikInsn;
336 int width = parseInsn(codePtr, &dalvikInsn, false);
337
338 /* Terminate when the data section is seen */
339 if (width == 0)
340 break;
341
Ben Cheng7a2697d2010-06-07 13:44:23 -0700342 if (isCallee) {
343 attributes = analyzeInlineTarget(&dalvikInsn, attributes, insnSize);
344 }
345
Ben Cheng8b258bf2009-06-24 17:27:07 -0700346 insnSize += width;
347 codePtr += width;
348 }
349
Ben Cheng7a2697d2010-06-07 13:44:23 -0700350 /*
351 * Only handle simple getters/setters with one instruction followed by
352 * return
353 */
354 if ((attributes & (METHOD_IS_GETTER | METHOD_IS_SETTER)) &&
355 (insnSize != 3)) {
356 attributes &= ~(METHOD_IS_GETTER | METHOD_IS_SETTER);
357 }
358
Ben Cheng8b258bf2009-06-24 17:27:07 -0700359 realMethodEntry->dalvikSize = insnSize * 2;
Ben Cheng7a2697d2010-06-07 13:44:23 -0700360 realMethodEntry->attributes |= attributes;
361
362#if 0
363 /* Uncomment the following to explore various callee patterns */
364 if (attributes & METHOD_IS_THROW_FREE) {
365 LOGE("%s%s is inlinable%s", method->clazz->descriptor, method->name,
366 (attributes & METHOD_IS_EMPTY) ? " empty" : "");
367 }
368
369 if (attributes & METHOD_IS_LEAF) {
370 LOGE("%s%s is leaf %d%s", method->clazz->descriptor, method->name,
371 insnSize, insnSize < 5 ? " (small)" : "");
372 }
373
374 if (attributes & (METHOD_IS_GETTER | METHOD_IS_SETTER)) {
375 LOGE("%s%s is %s", method->clazz->descriptor, method->name,
376 attributes & METHOD_IS_GETTER ? "getter": "setter");
377 }
378 if (attributes ==
379 (METHOD_IS_LEAF | METHOD_IS_THROW_FREE | METHOD_IS_CALLEE)) {
380 LOGE("%s%s is inlinable non setter/getter", method->clazz->descriptor,
381 method->name);
382 }
383#endif
384
Ben Cheng8b258bf2009-06-24 17:27:07 -0700385 return realMethodEntry;
386}
387
388/*
Ben Cheng33672452010-01-12 14:59:30 -0800389 * Crawl the stack of the thread that requesed compilation to see if any of the
390 * ancestors are on the blacklist.
391 */
Andy McFadden953a0ed2010-09-17 15:48:38 -0700392static bool filterMethodByCallGraph(Thread *thread, const char *curMethodName)
Ben Cheng33672452010-01-12 14:59:30 -0800393{
394 /* Crawl the Dalvik stack frames and compare the method name*/
395 StackSaveArea *ssaPtr = ((StackSaveArea *) thread->curFrame) - 1;
396 while (ssaPtr != ((StackSaveArea *) NULL) - 1) {
397 const Method *method = ssaPtr->method;
398 if (method) {
399 int hashValue = dvmComputeUtf8Hash(method->name);
400 bool found =
401 dvmHashTableLookup(gDvmJit.methodTable, hashValue,
402 (char *) method->name,
403 (HashCompareFunc) strcmp, false) !=
404 NULL;
405 if (found) {
406 LOGD("Method %s (--> %s) found on the JIT %s list",
407 method->name, curMethodName,
408 gDvmJit.includeSelectedMethod ? "white" : "black");
409 return true;
410 }
411
412 }
413 ssaPtr = ((StackSaveArea *) ssaPtr->prevFrame) - 1;
414 };
415 return false;
416}
417
418/*
Ben Chengba4fc8b2009-06-01 13:00:29 -0700419 * Main entry point to start trace compilation. Basic blocks are constructed
420 * first and they will be passed to the codegen routines to convert Dalvik
421 * bytecode into machine code.
422 */
Bill Buzbee716f1202009-07-23 13:22:09 -0700423bool dvmCompileTrace(JitTraceDescription *desc, int numMaxInsts,
Ben Cheng4a419582010-08-04 13:23:09 -0700424 JitTranslationInfo *info, jmp_buf *bailPtr,
425 int optHints)
Ben Chengba4fc8b2009-06-01 13:00:29 -0700426{
427 const DexCode *dexCode = dvmGetMethodCode(desc->method);
428 const JitTraceRun* currRun = &desc->trace[0];
Ben Chengba4fc8b2009-06-01 13:00:29 -0700429 unsigned int curOffset = currRun->frag.startOffset;
430 unsigned int numInsts = currRun->frag.numInsts;
431 const u2 *codePtr = dexCode->insns + curOffset;
Ben Cheng8b258bf2009-06-24 17:27:07 -0700432 int traceSize = 0; // # of half-words
Ben Chengba4fc8b2009-06-01 13:00:29 -0700433 const u2 *startCodePtr = codePtr;
Ben Cheng00603072010-10-28 11:13:58 -0700434 BasicBlock *curBB, *entryCodeBB;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700435 int numBlocks = 0;
436 static int compilationId;
437 CompilationUnit cUnit;
Ben Cheng00603072010-10-28 11:13:58 -0700438 GrowableList *blockList;
Ben Cheng1357e942010-02-10 17:21:39 -0800439#if defined(WITH_JIT_TUNING)
Ben Cheng8b258bf2009-06-24 17:27:07 -0700440 CompilerMethodStats *methodStats;
Ben Cheng1357e942010-02-10 17:21:39 -0800441#endif
Ben Chengba4fc8b2009-06-01 13:00:29 -0700442
Bill Buzbee964a7b02010-01-28 12:54:19 -0800443 /* If we've already compiled this trace, just return success */
Ben Chengcfdeca32011-01-14 11:36:46 -0800444 if (dvmJitGetTraceAddr(startCodePtr) && !info->discardResult) {
Ben Cheng7a2697d2010-06-07 13:44:23 -0700445 /*
446 * Make sure the codeAddress is NULL so that it won't clobber the
447 * existing entry.
448 */
449 info->codeAddress = NULL;
Bill Buzbee964a7b02010-01-28 12:54:19 -0800450 return true;
451 }
452
buzbee18fba342011-01-19 15:31:15 -0800453 /* If the work order is stale, discard it */
454 if (info->cacheVersion != gDvmJit.cacheVersion) {
455 return false;
456 }
457
Ben Chenge9695e52009-06-16 16:11:47 -0700458 compilationId++;
Ben Cheng8b258bf2009-06-24 17:27:07 -0700459 memset(&cUnit, 0, sizeof(CompilationUnit));
460
Ben Cheng1357e942010-02-10 17:21:39 -0800461#if defined(WITH_JIT_TUNING)
Ben Cheng8b258bf2009-06-24 17:27:07 -0700462 /* Locate the entry to store compilation statistics for this method */
Ben Cheng7a2697d2010-06-07 13:44:23 -0700463 methodStats = dvmCompilerAnalyzeMethodBody(desc->method, false);
Ben Cheng1357e942010-02-10 17:21:39 -0800464#endif
Ben Chenge9695e52009-06-16 16:11:47 -0700465
Bill Buzbeefc519dc2010-03-06 23:30:57 -0800466 /* Set the recover buffer pointer */
467 cUnit.bailPtr = bailPtr;
468
Ben Chengba4fc8b2009-06-01 13:00:29 -0700469 /* Initialize the printMe flag */
470 cUnit.printMe = gDvmJit.printMe;
471
Ben Cheng7a2697d2010-06-07 13:44:23 -0700472 /* Setup the method */
473 cUnit.method = desc->method;
474
475 /* Initialize the PC reconstruction list */
476 dvmInitGrowableList(&cUnit.pcReconstructionList, 8);
477
Ben Cheng00603072010-10-28 11:13:58 -0700478 /* Initialize the basic block list */
479 blockList = &cUnit.blockList;
480 dvmInitGrowableList(blockList, 8);
481
Ben Chengba4fc8b2009-06-01 13:00:29 -0700482 /* Identify traces that we don't want to compile */
483 if (gDvmJit.methodTable) {
484 int len = strlen(desc->method->clazz->descriptor) +
485 strlen(desc->method->name) + 1;
Carl Shapirofc75f3e2010-12-07 11:43:38 -0800486 char *fullSignature = (char *)dvmCompilerNew(len, true);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700487 strcpy(fullSignature, desc->method->clazz->descriptor);
488 strcat(fullSignature, desc->method->name);
489
490 int hashValue = dvmComputeUtf8Hash(fullSignature);
491
492 /*
493 * Doing three levels of screening to see whether we want to skip
494 * compiling this method
495 */
496
497 /* First, check the full "class;method" signature */
498 bool methodFound =
499 dvmHashTableLookup(gDvmJit.methodTable, hashValue,
500 fullSignature, (HashCompareFunc) strcmp,
501 false) !=
502 NULL;
503
504 /* Full signature not found - check the enclosing class */
505 if (methodFound == false) {
506 int hashValue = dvmComputeUtf8Hash(desc->method->clazz->descriptor);
507 methodFound =
508 dvmHashTableLookup(gDvmJit.methodTable, hashValue,
509 (char *) desc->method->clazz->descriptor,
510 (HashCompareFunc) strcmp, false) !=
511 NULL;
512 /* Enclosing class not found - check the method name */
513 if (methodFound == false) {
514 int hashValue = dvmComputeUtf8Hash(desc->method->name);
515 methodFound =
516 dvmHashTableLookup(gDvmJit.methodTable, hashValue,
517 (char *) desc->method->name,
518 (HashCompareFunc) strcmp, false) !=
519 NULL;
Ben Cheng33672452010-01-12 14:59:30 -0800520
521 /*
522 * Debug by call-graph is enabled. Check if the debug list
523 * covers any methods on the VM stack.
524 */
525 if (methodFound == false && gDvmJit.checkCallGraph == true) {
526 methodFound =
527 filterMethodByCallGraph(info->requestingThread,
528 desc->method->name);
529 }
Ben Chengba4fc8b2009-06-01 13:00:29 -0700530 }
531 }
532
533 /*
534 * Under the following conditions, the trace will be *conservatively*
535 * compiled by only containing single-step instructions to and from the
536 * interpreter.
537 * 1) If includeSelectedMethod == false, the method matches the full or
538 * partial signature stored in the hash table.
539 *
540 * 2) If includeSelectedMethod == true, the method does not match the
541 * full and partial signature stored in the hash table.
542 */
543 if (gDvmJit.includeSelectedMethod != methodFound) {
544 cUnit.allSingleStep = true;
545 } else {
546 /* Compile the trace as normal */
547
548 /* Print the method we cherry picked */
549 if (gDvmJit.includeSelectedMethod == true) {
550 cUnit.printMe = true;
551 }
552 }
553 }
554
Ben Cheng4238ec22009-08-24 16:32:22 -0700555 /* Allocate the entry block */
Ben Cheng00603072010-10-28 11:13:58 -0700556 curBB = dvmCompilerNewBB(kTraceEntryBlock, numBlocks++);
557 dvmInsertGrowableList(blockList, (intptr_t) curBB);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700558 curBB->startOffset = curOffset;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700559
Ben Cheng00603072010-10-28 11:13:58 -0700560 entryCodeBB = dvmCompilerNewBB(kDalvikByteCode, numBlocks++);
561 dvmInsertGrowableList(blockList, (intptr_t) entryCodeBB);
562 entryCodeBB->startOffset = curOffset;
563 curBB->fallThrough = entryCodeBB;
564 curBB = entryCodeBB;
Ben Cheng4238ec22009-08-24 16:32:22 -0700565
Ben Chengba4fc8b2009-06-01 13:00:29 -0700566 if (cUnit.printMe) {
567 LOGD("--------\nCompiler: Building trace for %s, offset 0x%x\n",
568 desc->method->name, curOffset);
569 }
570
Ben Cheng1efc9c52009-06-08 18:25:27 -0700571 /*
572 * Analyze the trace descriptor and include up to the maximal number
573 * of Dalvik instructions into the IR.
574 */
575 while (1) {
Ben Chengba4fc8b2009-06-01 13:00:29 -0700576 MIR *insn;
577 int width;
Carl Shapirofc75f3e2010-12-07 11:43:38 -0800578 insn = (MIR *)dvmCompilerNew(sizeof(MIR), true);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700579 insn->offset = curOffset;
580 width = parseInsn(codePtr, &insn->dalvikInsn, cUnit.printMe);
Ben Cheng8b258bf2009-06-24 17:27:07 -0700581
582 /* The trace should never incude instruction data */
583 assert(width);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700584 insn->width = width;
585 traceSize += width;
586 dvmCompilerAppendMIR(curBB, insn);
Ben Cheng1efc9c52009-06-08 18:25:27 -0700587 cUnit.numInsts++;
Ben Cheng7a2697d2010-06-07 13:44:23 -0700588
Dan Bornsteine4852762010-12-02 12:45:00 -0800589 int flags = dexGetFlagsFromOpcode(insn->dalvikInsn.opcode);
Ben Cheng7a2697d2010-06-07 13:44:23 -0700590
Dan Bornstein0759f522010-11-30 14:58:53 -0800591 if (flags & kInstrInvoke) {
Ben Chengcfdeca32011-01-14 11:36:46 -0800592 const Method *calleeMethod = (const Method *) currRun[2].meta;
Ben Cheng7a2697d2010-06-07 13:44:23 -0700593 assert(numInsts == 1);
594 CallsiteInfo *callsiteInfo =
Carl Shapirofc75f3e2010-12-07 11:43:38 -0800595 (CallsiteInfo *)dvmCompilerNew(sizeof(CallsiteInfo), true);
596 callsiteInfo->clazz = (ClassObject *)currRun[1].meta;
Ben Chengcfdeca32011-01-14 11:36:46 -0800597 callsiteInfo->method = calleeMethod;
Ben Cheng7a2697d2010-06-07 13:44:23 -0700598 insn->meta.callsiteInfo = callsiteInfo;
599 }
600
Ben Cheng1efc9c52009-06-08 18:25:27 -0700601 /* Instruction limit reached - terminate the trace here */
602 if (cUnit.numInsts >= numMaxInsts) {
603 break;
604 }
605 if (--numInsts == 0) {
Ben Chengba4fc8b2009-06-01 13:00:29 -0700606 if (currRun->frag.runEnd) {
Ben Cheng1efc9c52009-06-08 18:25:27 -0700607 break;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700608 } else {
Ben Cheng7a2697d2010-06-07 13:44:23 -0700609 /* Advance to the next trace description (ie non-meta info) */
610 do {
611 currRun++;
612 } while (!currRun->frag.isCode);
613
614 /* Dummy end-of-run marker seen */
615 if (currRun->frag.numInsts == 0) {
616 break;
617 }
618
Ben Cheng00603072010-10-28 11:13:58 -0700619 curBB = dvmCompilerNewBB(kDalvikByteCode, numBlocks++);
620 dvmInsertGrowableList(blockList, (intptr_t) curBB);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700621 curOffset = currRun->frag.startOffset;
622 numInsts = currRun->frag.numInsts;
623 curBB->startOffset = curOffset;
624 codePtr = dexCode->insns + curOffset;
625 }
626 } else {
627 curOffset += width;
628 codePtr += width;
629 }
630 }
631
Ben Cheng1357e942010-02-10 17:21:39 -0800632#if defined(WITH_JIT_TUNING)
Ben Cheng8b258bf2009-06-24 17:27:07 -0700633 /* Convert # of half-word to bytes */
634 methodStats->compiledDalvikSize += traceSize * 2;
Ben Cheng1357e942010-02-10 17:21:39 -0800635#endif
Ben Cheng8b258bf2009-06-24 17:27:07 -0700636
Ben Chengba4fc8b2009-06-01 13:00:29 -0700637 /*
638 * Now scan basic blocks containing real code to connect the
639 * taken/fallthrough links. Also create chaining cells for code not included
640 * in the trace.
641 */
Ben Cheng00603072010-10-28 11:13:58 -0700642 size_t blockId;
643 for (blockId = 0; blockId < blockList->numUsed; blockId++) {
644 curBB = (BasicBlock *) dvmGrowableListGetElement(blockList, blockId);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700645 MIR *lastInsn = curBB->lastMIRInsn;
buzbee2e152ba2010-12-15 16:32:35 -0800646 BasicBlock *backwardCell;
Ben Cheng4238ec22009-08-24 16:32:22 -0700647 /* Skip empty blocks */
Ben Chengba4fc8b2009-06-01 13:00:29 -0700648 if (lastInsn == NULL) {
Ben Cheng4238ec22009-08-24 16:32:22 -0700649 continue;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700650 }
651 curOffset = lastInsn->offset;
652 unsigned int targetOffset = curOffset;
653 unsigned int fallThroughOffset = curOffset + lastInsn->width;
654 bool isInvoke = false;
655 const Method *callee = NULL;
656
657 findBlockBoundary(desc->method, curBB->lastMIRInsn, curOffset,
658 &targetOffset, &isInvoke, &callee);
659
660 /* Link the taken and fallthrough blocks */
661 BasicBlock *searchBB;
662
Dan Bornsteine4852762010-12-02 12:45:00 -0800663 int flags = dexGetFlagsFromOpcode(lastInsn->dalvikInsn.opcode);
Ben Cheng7a2697d2010-06-07 13:44:23 -0700664
665 if (flags & kInstrInvoke) {
666 cUnit.hasInvoke = true;
667 }
668
Ben Chengba4fc8b2009-06-01 13:00:29 -0700669 /* No backward branch in the trace - start searching the next BB */
Ben Cheng00603072010-10-28 11:13:58 -0700670 size_t searchBlockId;
671 for (searchBlockId = blockId+1; searchBlockId < blockList->numUsed;
672 searchBlockId++) {
673 searchBB = (BasicBlock *) dvmGrowableListGetElement(blockList,
674 searchBlockId);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700675 if (targetOffset == searchBB->startOffset) {
676 curBB->taken = searchBB;
677 }
678 if (fallThroughOffset == searchBB->startOffset) {
679 curBB->fallThrough = searchBB;
Ben Cheng7a2697d2010-06-07 13:44:23 -0700680
681 /*
682 * Fallthrough block of an invoke instruction needs to be
683 * aligned to 4-byte boundary (alignment instruction to be
684 * inserted later.
685 */
686 if (flags & kInstrInvoke) {
687 searchBB->isFallThroughFromInvoke = true;
688 }
Ben Chengba4fc8b2009-06-01 13:00:29 -0700689 }
690 }
691
Ben Cheng1efc9c52009-06-08 18:25:27 -0700692 /*
693 * Some blocks are ended by non-control-flow-change instructions,
694 * currently only due to trace length constraint. In this case we need
695 * to generate an explicit branch at the end of the block to jump to
696 * the chaining cell.
697 */
698 curBB->needFallThroughBranch =
Ben Cheng17f15ce2009-07-27 16:21:52 -0700699 ((flags & (kInstrCanBranch | kInstrCanSwitch | kInstrCanReturn |
Dan Bornstein0759f522010-11-30 14:58:53 -0800700 kInstrInvoke)) == 0);
Ben Cheng17f15ce2009-07-27 16:21:52 -0700701
Ben Cheng4a419582010-08-04 13:23:09 -0700702 /* Only form a loop if JIT_OPT_NO_LOOP is not set */
Ben Cheng4238ec22009-08-24 16:32:22 -0700703 if (curBB->taken == NULL &&
704 curBB->fallThrough == NULL &&
705 flags == (kInstrCanBranch | kInstrCanContinue) &&
Ben Cheng00603072010-10-28 11:13:58 -0700706 fallThroughOffset == entryCodeBB->startOffset &&
Ben Cheng4a419582010-08-04 13:23:09 -0700707 JIT_OPT_NO_LOOP != (optHints & JIT_OPT_NO_LOOP)) {
Ben Cheng0fd31e42009-09-03 14:40:16 -0700708 BasicBlock *loopBranch = curBB;
709 BasicBlock *exitBB;
710 BasicBlock *exitChainingCell;
Ben Cheng4238ec22009-08-24 16:32:22 -0700711
712 if (cUnit.printMe) {
713 LOGD("Natural loop detected!");
714 }
Ben Cheng00603072010-10-28 11:13:58 -0700715 exitBB = dvmCompilerNewBB(kTraceExitBlock, numBlocks++);
716 dvmInsertGrowableList(blockList, (intptr_t) exitBB);
Ben Cheng0fd31e42009-09-03 14:40:16 -0700717 exitBB->startOffset = targetOffset;
Ben Cheng0fd31e42009-09-03 14:40:16 -0700718 exitBB->needFallThroughBranch = true;
Ben Cheng4238ec22009-08-24 16:32:22 -0700719
Ben Cheng0fd31e42009-09-03 14:40:16 -0700720 loopBranch->taken = exitBB;
buzbee2e152ba2010-12-15 16:32:35 -0800721 backwardCell =
Ben Cheng00603072010-10-28 11:13:58 -0700722 dvmCompilerNewBB(kChainingCellBackwardBranch, numBlocks++);
723 dvmInsertGrowableList(blockList, (intptr_t) backwardCell);
724 backwardCell->startOffset = entryCodeBB->startOffset;
Ben Cheng0fd31e42009-09-03 14:40:16 -0700725 loopBranch->fallThrough = backwardCell;
Ben Cheng0fd31e42009-09-03 14:40:16 -0700726
727 /* Create the chaining cell as the fallthrough of the exit block */
Ben Cheng00603072010-10-28 11:13:58 -0700728 exitChainingCell = dvmCompilerNewBB(kChainingCellNormal,
729 numBlocks++);
730 dvmInsertGrowableList(blockList, (intptr_t) exitChainingCell);
Ben Cheng0fd31e42009-09-03 14:40:16 -0700731 exitChainingCell->startOffset = targetOffset;
Ben Cheng0fd31e42009-09-03 14:40:16 -0700732
733 exitBB->fallThrough = exitChainingCell;
734
Ben Cheng4238ec22009-08-24 16:32:22 -0700735 cUnit.hasLoop = true;
736 }
737
Dan Bornstein9a1f8162010-12-01 17:02:26 -0800738 if (lastInsn->dalvikInsn.opcode == OP_PACKED_SWITCH ||
739 lastInsn->dalvikInsn.opcode == OP_SPARSE_SWITCH) {
Ben Cheng6c10a972009-10-29 14:39:18 -0700740 int i;
741 const u2 *switchData = desc->method->insns + lastInsn->offset +
742 lastInsn->dalvikInsn.vB;
743 int size = switchData[1];
744 int maxChains = MIN(size, MAX_CHAINED_SWITCH_CASES);
745
746 /*
747 * Generate the landing pad for cases whose ranks are higher than
748 * MAX_CHAINED_SWITCH_CASES. The code will re-enter the interpreter
749 * through the NoChain point.
750 */
751 if (maxChains != size) {
752 cUnit.switchOverflowPad =
753 desc->method->insns + lastInsn->offset;
754 }
755
756 s4 *targets = (s4 *) (switchData + 2 +
Dan Bornstein9a1f8162010-12-01 17:02:26 -0800757 (lastInsn->dalvikInsn.opcode == OP_PACKED_SWITCH ?
Ben Cheng6c10a972009-10-29 14:39:18 -0700758 2 : size * 2));
759
760 /* One chaining cell for the first MAX_CHAINED_SWITCH_CASES cases */
761 for (i = 0; i < maxChains; i++) {
Ben Cheng00603072010-10-28 11:13:58 -0700762 BasicBlock *caseChain = dvmCompilerNewBB(kChainingCellNormal,
763 numBlocks++);
764 dvmInsertGrowableList(blockList, (intptr_t) caseChain);
Ben Cheng6c10a972009-10-29 14:39:18 -0700765 caseChain->startOffset = lastInsn->offset + targets[i];
Ben Cheng6c10a972009-10-29 14:39:18 -0700766 }
767
768 /* One more chaining cell for the default case */
Ben Cheng00603072010-10-28 11:13:58 -0700769 BasicBlock *caseChain = dvmCompilerNewBB(kChainingCellNormal,
770 numBlocks++);
771 dvmInsertGrowableList(blockList, (intptr_t) caseChain);
Ben Cheng6c10a972009-10-29 14:39:18 -0700772 caseChain->startOffset = lastInsn->offset + lastInsn->width;
Ben Cheng6d576092009-09-01 17:01:58 -0700773 /* Fallthrough block not included in the trace */
Ben Cheng6c10a972009-10-29 14:39:18 -0700774 } else if (!isUnconditionalBranch(lastInsn) &&
775 curBB->fallThrough == NULL) {
Ben Cheng00603072010-10-28 11:13:58 -0700776 BasicBlock *fallThroughBB;
Ben Cheng6d576092009-09-01 17:01:58 -0700777 /*
778 * If the chaining cell is after an invoke or
779 * instruction that cannot change the control flow, request a hot
780 * chaining cell.
781 */
782 if (isInvoke || curBB->needFallThroughBranch) {
Ben Cheng00603072010-10-28 11:13:58 -0700783 fallThroughBB = dvmCompilerNewBB(kChainingCellHot, numBlocks++);
Ben Cheng6d576092009-09-01 17:01:58 -0700784 } else {
Ben Cheng00603072010-10-28 11:13:58 -0700785 fallThroughBB = dvmCompilerNewBB(kChainingCellNormal,
786 numBlocks++);
Ben Cheng6d576092009-09-01 17:01:58 -0700787 }
Ben Cheng00603072010-10-28 11:13:58 -0700788 dvmInsertGrowableList(blockList, (intptr_t) fallThroughBB);
789 fallThroughBB->startOffset = fallThroughOffset;
790 curBB->fallThrough = fallThroughBB;
Ben Cheng6d576092009-09-01 17:01:58 -0700791 }
Ben Chengba4fc8b2009-06-01 13:00:29 -0700792 /* Target block not included in the trace */
Ben Cheng38329f52009-07-07 14:19:20 -0700793 if (curBB->taken == NULL &&
Bill Buzbee324b3ac2009-12-04 13:17:36 -0800794 (isGoto(lastInsn) || isInvoke ||
795 (targetOffset != UNKNOWN_TARGET && targetOffset != curOffset))) {
Ben Cheng7e2c3c72010-12-22 16:40:46 -0800796 BasicBlock *newBB = NULL;
Ben Cheng1efc9c52009-06-08 18:25:27 -0700797 if (isInvoke) {
Ben Cheng38329f52009-07-07 14:19:20 -0700798 /* Monomorphic callee */
799 if (callee) {
Ben Cheng7e2c3c72010-12-22 16:40:46 -0800800 /* JNI call doesn't need a chaining cell */
801 if (!dvmIsNativeMethod(callee)) {
802 newBB = dvmCompilerNewBB(kChainingCellInvokeSingleton,
803 numBlocks++);
804 newBB->startOffset = 0;
805 newBB->containingMethod = callee;
806 }
Ben Cheng38329f52009-07-07 14:19:20 -0700807 /* Will resolve at runtime */
808 } else {
Ben Cheng00603072010-10-28 11:13:58 -0700809 newBB = dvmCompilerNewBB(kChainingCellInvokePredicted,
810 numBlocks++);
Ben Cheng38329f52009-07-07 14:19:20 -0700811 newBB->startOffset = 0;
812 }
Ben Cheng1efc9c52009-06-08 18:25:27 -0700813 /* For unconditional branches, request a hot chaining cell */
814 } else {
Jeff Hao97319a82009-08-12 16:57:15 -0700815#if !defined(WITH_SELF_VERIFICATION)
Dan Bornsteinc2b486f2010-11-12 16:07:16 -0800816 newBB = dvmCompilerNewBB(dexIsGoto(flags) ?
Bill Buzbee1465db52009-09-23 17:17:35 -0700817 kChainingCellHot :
Ben Cheng00603072010-10-28 11:13:58 -0700818 kChainingCellNormal,
819 numBlocks++);
Ben Cheng38329f52009-07-07 14:19:20 -0700820 newBB->startOffset = targetOffset;
Jeff Hao97319a82009-08-12 16:57:15 -0700821#else
822 /* Handle branches that branch back into the block */
823 if (targetOffset >= curBB->firstMIRInsn->offset &&
824 targetOffset <= curBB->lastMIRInsn->offset) {
Ben Cheng00603072010-10-28 11:13:58 -0700825 newBB = dvmCompilerNewBB(kChainingCellBackwardBranch,
826 numBlocks++);
Jeff Hao97319a82009-08-12 16:57:15 -0700827 } else {
Dan Bornsteinc2b486f2010-11-12 16:07:16 -0800828 newBB = dvmCompilerNewBB(dexIsGoto(flags) ?
Bill Buzbee1465db52009-09-23 17:17:35 -0700829 kChainingCellHot :
Ben Cheng00603072010-10-28 11:13:58 -0700830 kChainingCellNormal,
831 numBlocks++);
Jeff Hao97319a82009-08-12 16:57:15 -0700832 }
833 newBB->startOffset = targetOffset;
834#endif
Ben Cheng1efc9c52009-06-08 18:25:27 -0700835 }
Ben Cheng7e2c3c72010-12-22 16:40:46 -0800836 if (newBB) {
837 curBB->taken = newBB;
838 dvmInsertGrowableList(blockList, (intptr_t) newBB);
839 }
Ben Chengba4fc8b2009-06-01 13:00:29 -0700840 }
Ben Chengba4fc8b2009-06-01 13:00:29 -0700841 }
842
843 /* Now create a special block to host PC reconstruction code */
Ben Cheng00603072010-10-28 11:13:58 -0700844 curBB = dvmCompilerNewBB(kPCReconstruction, numBlocks++);
845 dvmInsertGrowableList(blockList, (intptr_t) curBB);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700846
847 /* And one final block that publishes the PC and raise the exception */
Ben Cheng00603072010-10-28 11:13:58 -0700848 curBB = dvmCompilerNewBB(kExceptionHandling, numBlocks++);
849 dvmInsertGrowableList(blockList, (intptr_t) curBB);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700850
851 if (cUnit.printMe) {
Ben Cheng00603072010-10-28 11:13:58 -0700852 char* signature =
853 dexProtoCopyMethodDescriptor(&desc->method->prototype);
Elliott Hughescc6fac82010-07-02 13:38:44 -0700854 LOGD("TRACEINFO (%d): 0x%08x %s%s.%s 0x%x %d of %d, %d blocks",
Ben Chenge9695e52009-06-16 16:11:47 -0700855 compilationId,
Ben Chengba4fc8b2009-06-01 13:00:29 -0700856 (intptr_t) desc->method->insns,
857 desc->method->clazz->descriptor,
858 desc->method->name,
Elliott Hughescc6fac82010-07-02 13:38:44 -0700859 signature,
Ben Chengba4fc8b2009-06-01 13:00:29 -0700860 desc->trace[0].frag.startOffset,
861 traceSize,
862 dexCode->insnsSize,
863 numBlocks);
Elliott Hughescc6fac82010-07-02 13:38:44 -0700864 free(signature);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700865 }
866
Ben Chengba4fc8b2009-06-01 13:00:29 -0700867 cUnit.traceDesc = desc;
868 cUnit.numBlocks = numBlocks;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700869
Ben Cheng7a2697d2010-06-07 13:44:23 -0700870 /* Set the instruction set to use (NOTE: later components may change it) */
871 cUnit.instructionSet = dvmCompilerInstructionSet();
872
873 /* Inline transformation @ the MIR level */
874 if (cUnit.hasInvoke && !(gDvmJit.disableOpt & (1 << kMethodInlining))) {
Ben Chengcfdeca32011-01-14 11:36:46 -0800875 dvmCompilerInlineMIR(&cUnit, info);
Ben Cheng7a2697d2010-06-07 13:44:23 -0700876 }
877
Ben Cheng00603072010-10-28 11:13:58 -0700878 cUnit.numDalvikRegisters = cUnit.method->registersSize;
879
Ben Cheng4238ec22009-08-24 16:32:22 -0700880 /* Preparation for SSA conversion */
881 dvmInitializeSSAConversion(&cUnit);
882
883 if (cUnit.hasLoop) {
Ben Cheng4a419582010-08-04 13:23:09 -0700884 /*
885 * Loop is not optimizable (for example lack of a single induction
886 * variable), punt and recompile the trace with loop optimization
887 * disabled.
888 */
889 bool loopOpt = dvmCompilerLoopOpt(&cUnit);
890 if (loopOpt == false) {
891 if (cUnit.printMe) {
892 LOGD("Loop is not optimizable - retry codegen");
893 }
894 /* Reset the compiler resource pool */
895 dvmCompilerArenaReset();
896 return dvmCompileTrace(desc, cUnit.numInsts, info, bailPtr,
897 optHints | JIT_OPT_NO_LOOP);
898 }
Ben Cheng4238ec22009-08-24 16:32:22 -0700899 }
900 else {
901 dvmCompilerNonLoopAnalysis(&cUnit);
902 }
903
Bill Buzbee1465db52009-09-23 17:17:35 -0700904 dvmCompilerInitializeRegAlloc(&cUnit); // Needs to happen after SSA naming
905
Ben Chengba4fc8b2009-06-01 13:00:29 -0700906 if (cUnit.printMe) {
907 dvmCompilerDumpCompilationUnit(&cUnit);
908 }
909
buzbee23d95d02010-12-14 13:16:43 -0800910 /* Allocate Registers using simple local allocation scheme */
911 dvmCompilerLocalRegAlloc(&cUnit);
Bill Buzbee1465db52009-09-23 17:17:35 -0700912
Ben Chengba4fc8b2009-06-01 13:00:29 -0700913 /* Convert MIR to LIR, etc. */
914 dvmCompilerMIR2LIR(&cUnit);
915
buzbeebff121a2010-08-04 15:25:06 -0700916 /* Convert LIR into machine code. Loop for recoverable retries */
917 do {
918 dvmCompilerAssembleLIR(&cUnit, info);
919 cUnit.assemblerRetries++;
920 if (cUnit.printMe && cUnit.assemblerStatus != kSuccess)
921 LOGD("Assembler abort #%d on %d",cUnit.assemblerRetries,
922 cUnit.assemblerStatus);
923 } while (cUnit.assemblerStatus == kRetryAll);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700924
925 if (cUnit.printMe) {
Ben Chengcfdeca32011-01-14 11:36:46 -0800926 LOGD("Trace Dalvik PC: %p", startCodePtr);
buzbeebff121a2010-08-04 15:25:06 -0700927 dvmCompilerCodegenDump(&cUnit);
Ben Cheng1efc9c52009-06-08 18:25:27 -0700928 LOGD("End %s%s, %d Dalvik instructions",
929 desc->method->clazz->descriptor, desc->method->name,
930 cUnit.numInsts);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700931 }
932
933 /* Reset the compiler resource pool */
934 dvmCompilerArenaReset();
935
buzbeebff121a2010-08-04 15:25:06 -0700936 if (cUnit.assemblerStatus == kRetryHalve) {
937 /* Halve the instruction count and start from the top */
Ben Cheng4a419582010-08-04 13:23:09 -0700938 return dvmCompileTrace(desc, cUnit.numInsts / 2, info, bailPtr,
939 optHints);
Ben Cheng1efc9c52009-06-08 18:25:27 -0700940 }
buzbeebff121a2010-08-04 15:25:06 -0700941
942 assert(cUnit.assemblerStatus == kSuccess);
943#if defined(WITH_JIT_TUNING)
944 methodStats->nativeSize += cUnit.totalSize;
945#endif
Ben Cheng00603072010-10-28 11:13:58 -0700946
buzbeebff121a2010-08-04 15:25:06 -0700947 return info->codeAddress != NULL;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700948}
949
950/*
Ben Cheng7a2697d2010-06-07 13:44:23 -0700951 * Since we are including instructions from possibly a cold method into the
952 * current trace, we need to make sure that all the associated information
953 * with the callee is properly initialized. If not, we punt on this inline
954 * target.
955 *
Ben Cheng34dc7962010-08-26 14:56:31 -0700956 * TODO: volatile instructions will be handled later.
Ben Cheng7a2697d2010-06-07 13:44:23 -0700957 */
958bool dvmCompilerCanIncludeThisInstruction(const Method *method,
959 const DecodedInstruction *insn)
960{
Dan Bornstein9a1f8162010-12-01 17:02:26 -0800961 switch (insn->opcode) {
Ben Cheng7a2697d2010-06-07 13:44:23 -0700962 case OP_NEW_INSTANCE:
jeffhao71eee1f2011-01-04 14:18:54 -0800963 case OP_NEW_INSTANCE_JUMBO:
964 case OP_CHECK_CAST:
965 case OP_CHECK_CAST_JUMBO: {
Carl Shapirofc75f3e2010-12-07 11:43:38 -0800966 ClassObject *classPtr = (ClassObject *)(void*)
Ben Cheng7a2697d2010-06-07 13:44:23 -0700967 (method->clazz->pDvmDex->pResClasses[insn->vB]);
968
969 /* Class hasn't been initialized yet */
970 if (classPtr == NULL) {
971 return false;
972 }
973 return true;
974 }
Ben Cheng7a2697d2010-06-07 13:44:23 -0700975 case OP_SGET:
jeffhao71eee1f2011-01-04 14:18:54 -0800976 case OP_SGET_JUMBO:
Ben Cheng7a2697d2010-06-07 13:44:23 -0700977 case OP_SGET_WIDE:
jeffhao71eee1f2011-01-04 14:18:54 -0800978 case OP_SGET_WIDE_JUMBO:
979 case OP_SGET_OBJECT:
980 case OP_SGET_OBJECT_JUMBO:
981 case OP_SGET_BOOLEAN:
982 case OP_SGET_BOOLEAN_JUMBO:
983 case OP_SGET_BYTE:
984 case OP_SGET_BYTE_JUMBO:
985 case OP_SGET_CHAR:
986 case OP_SGET_CHAR_JUMBO:
987 case OP_SGET_SHORT:
988 case OP_SGET_SHORT_JUMBO:
Ben Cheng7a2697d2010-06-07 13:44:23 -0700989 case OP_SPUT:
jeffhao71eee1f2011-01-04 14:18:54 -0800990 case OP_SPUT_JUMBO:
991 case OP_SPUT_WIDE:
992 case OP_SPUT_WIDE_JUMBO:
993 case OP_SPUT_OBJECT:
994 case OP_SPUT_OBJECT_JUMBO:
995 case OP_SPUT_BOOLEAN:
996 case OP_SPUT_BOOLEAN_JUMBO:
997 case OP_SPUT_BYTE:
998 case OP_SPUT_BYTE_JUMBO:
999 case OP_SPUT_CHAR:
1000 case OP_SPUT_CHAR_JUMBO:
1001 case OP_SPUT_SHORT:
1002 case OP_SPUT_SHORT_JUMBO: {
Ben Cheng7a2697d2010-06-07 13:44:23 -07001003 void *fieldPtr = (void*)
1004 (method->clazz->pDvmDex->pResFields[insn->vB]);
1005
1006 if (fieldPtr == NULL) {
1007 return false;
1008 }
1009 return true;
1010 }
1011 case OP_INVOKE_SUPER:
jeffhao71eee1f2011-01-04 14:18:54 -08001012 case OP_INVOKE_SUPER_RANGE:
1013 case OP_INVOKE_SUPER_JUMBO: {
Ben Cheng7a2697d2010-06-07 13:44:23 -07001014 int mIndex = method->clazz->pDvmDex->
1015 pResMethods[insn->vB]->methodIndex;
1016 const Method *calleeMethod = method->clazz->super->vtable[mIndex];
1017 if (calleeMethod == NULL) {
1018 return false;
1019 }
1020 return true;
1021 }
1022 case OP_INVOKE_SUPER_QUICK:
1023 case OP_INVOKE_SUPER_QUICK_RANGE: {
1024 const Method *calleeMethod = method->clazz->super->vtable[insn->vB];
1025 if (calleeMethod == NULL) {
1026 return false;
1027 }
1028 return true;
1029 }
1030 case OP_INVOKE_STATIC:
1031 case OP_INVOKE_STATIC_RANGE:
jeffhao71eee1f2011-01-04 14:18:54 -08001032 case OP_INVOKE_STATIC_JUMBO:
Ben Cheng7a2697d2010-06-07 13:44:23 -07001033 case OP_INVOKE_DIRECT:
jeffhao71eee1f2011-01-04 14:18:54 -08001034 case OP_INVOKE_DIRECT_RANGE:
1035 case OP_INVOKE_DIRECT_JUMBO: {
Ben Cheng7a2697d2010-06-07 13:44:23 -07001036 const Method *calleeMethod =
1037 method->clazz->pDvmDex->pResMethods[insn->vB];
1038 if (calleeMethod == NULL) {
1039 return false;
1040 }
1041 return true;
1042 }
jeffhao71eee1f2011-01-04 14:18:54 -08001043 case OP_CONST_CLASS:
1044 case OP_CONST_CLASS_JUMBO: {
Ben Cheng7a2697d2010-06-07 13:44:23 -07001045 void *classPtr = (void*)
1046 (method->clazz->pDvmDex->pResClasses[insn->vB]);
1047
1048 if (classPtr == NULL) {
1049 return false;
1050 }
1051 return true;
1052 }
1053 case OP_CONST_STRING_JUMBO:
1054 case OP_CONST_STRING: {
1055 void *strPtr = (void*)
1056 (method->clazz->pDvmDex->pResStrings[insn->vB]);
1057
1058 if (strPtr == NULL) {
1059 return false;
1060 }
1061 return true;
1062 }
1063 default:
1064 return true;
1065 }
1066}
1067
Ben Cheng00603072010-10-28 11:13:58 -07001068/* Split an existing block from the specified code offset into two */
1069static BasicBlock *splitBlock(CompilationUnit *cUnit,
1070 unsigned int codeOffset,
1071 BasicBlock *origBlock)
1072{
1073 MIR *insn = origBlock->firstMIRInsn;
1074 while (insn) {
1075 if (insn->offset == codeOffset) break;
1076 insn = insn->next;
1077 }
1078 if (insn == NULL) {
1079 LOGE("Break split failed");
1080 dvmAbort();
1081 }
1082 BasicBlock *bottomBlock = dvmCompilerNewBB(kDalvikByteCode,
1083 cUnit->numBlocks++);
1084 dvmInsertGrowableList(&cUnit->blockList, (intptr_t) bottomBlock);
1085
1086 bottomBlock->startOffset = codeOffset;
1087 bottomBlock->firstMIRInsn = insn;
1088 bottomBlock->lastMIRInsn = origBlock->lastMIRInsn;
1089
Ben Cheng00603072010-10-28 11:13:58 -07001090 /* Handle the taken path */
1091 bottomBlock->taken = origBlock->taken;
1092 if (bottomBlock->taken) {
1093 origBlock->taken = NULL;
1094 dvmCompilerClearBit(bottomBlock->taken->predecessors, origBlock->id);
1095 dvmCompilerSetBit(bottomBlock->taken->predecessors, bottomBlock->id);
1096 }
1097
1098 /* Handle the fallthrough path */
1099 bottomBlock->fallThrough = origBlock->fallThrough;
1100 origBlock->fallThrough = bottomBlock;
1101 dvmCompilerSetBit(bottomBlock->predecessors, origBlock->id);
1102 if (bottomBlock->fallThrough) {
1103 dvmCompilerClearBit(bottomBlock->fallThrough->predecessors,
1104 origBlock->id);
1105 dvmCompilerSetBit(bottomBlock->fallThrough->predecessors,
1106 bottomBlock->id);
1107 }
1108
1109 /* Handle the successor list */
1110 if (origBlock->successorBlockList.blockListType != kNotUsed) {
1111 bottomBlock->successorBlockList = origBlock->successorBlockList;
1112 origBlock->successorBlockList.blockListType = kNotUsed;
1113 GrowableListIterator iterator;
1114
1115 dvmGrowableListIteratorInit(&bottomBlock->successorBlockList.blocks,
1116 &iterator);
1117 while (true) {
Ben Cheng7a02cb12010-12-15 14:18:31 -08001118 SuccessorBlockInfo *successorBlockInfo =
1119 (SuccessorBlockInfo *) dvmGrowableListIteratorNext(&iterator);
1120 if (successorBlockInfo == NULL) break;
1121 BasicBlock *bb = successorBlockInfo->block;
Ben Cheng00603072010-10-28 11:13:58 -07001122 dvmCompilerClearBit(bb->predecessors, origBlock->id);
1123 dvmCompilerSetBit(bb->predecessors, bottomBlock->id);
1124 }
1125 }
1126
1127 origBlock->lastMIRInsn = insn->prev;
Ben Cheng00603072010-10-28 11:13:58 -07001128
1129 insn->prev->next = NULL;
1130 insn->prev = NULL;
1131 return bottomBlock;
1132}
1133
1134/*
1135 * Given a code offset, find out the block that starts with it. If the offset
1136 * is in the middle of an existing block, split it into two.
1137 */
1138static BasicBlock *findBlock(CompilationUnit *cUnit,
1139 unsigned int codeOffset,
1140 bool split, bool create)
1141{
1142 GrowableList *blockList = &cUnit->blockList;
1143 BasicBlock *bb;
1144 unsigned int i;
1145
1146 for (i = 0; i < blockList->numUsed; i++) {
1147 bb = (BasicBlock *) blockList->elemList[i];
1148 if (bb->blockType != kDalvikByteCode) continue;
1149 if (bb->startOffset == codeOffset) return bb;
1150 /* Check if a branch jumps into the middle of an existing block */
1151 if ((split == true) && (codeOffset > bb->startOffset) &&
1152 (bb->lastMIRInsn != NULL) &&
1153 (codeOffset <= bb->lastMIRInsn->offset)) {
1154 BasicBlock *newBB = splitBlock(cUnit, codeOffset, bb);
1155 return newBB;
1156 }
1157 }
1158 if (create) {
1159 bb = dvmCompilerNewBB(kDalvikByteCode, cUnit->numBlocks++);
1160 dvmInsertGrowableList(&cUnit->blockList, (intptr_t) bb);
1161 bb->startOffset = codeOffset;
1162 return bb;
1163 }
1164 return NULL;
1165}
1166
1167/* Dump the CFG into a DOT graph */
1168void dumpCFG(CompilationUnit *cUnit, const char *dirPrefix)
1169{
1170 const Method *method = cUnit->method;
1171 FILE *file;
1172 char* signature = dexProtoCopyMethodDescriptor(&method->prototype);
1173 char *fileName = (char *) dvmCompilerNew(
1174 strlen(dirPrefix) +
1175 strlen(method->clazz->descriptor) +
1176 strlen(method->name) +
1177 strlen(signature) +
1178 strlen(".dot") + 1, true);
1179 sprintf(fileName, "%s%s%s%s.dot", dirPrefix,
1180 method->clazz->descriptor, method->name, signature);
1181 free(signature);
1182
1183 /*
1184 * Convert the special characters into a filesystem- and shell-friendly
1185 * format.
1186 */
1187 int i;
1188 for (i = strlen(dirPrefix); fileName[i]; i++) {
1189 if (fileName[i] == '/') {
1190 fileName[i] = '_';
1191 } else if (fileName[i] == ';') {
1192 fileName[i] = '#';
1193 } else if (fileName[i] == '$') {
1194 fileName[i] = '+';
1195 } else if (fileName[i] == '(' || fileName[i] == ')') {
1196 fileName[i] = '@';
1197 } else if (fileName[i] == '<' || fileName[i] == '>') {
1198 fileName[i] = '=';
1199 }
1200 }
1201 file = fopen(fileName, "w");
1202 if (file == NULL) {
1203 return;
1204 }
1205 fprintf(file, "digraph G {\n");
1206
1207 fprintf(file, " rankdir=TB\n");
1208
1209 int numReachableBlocks = cUnit->numReachableBlocks;
1210 int idx;
1211 const GrowableList *blockList = &cUnit->blockList;
1212
1213 for (idx = 0; idx < numReachableBlocks; idx++) {
1214 int blockIdx = cUnit->dfsOrder.elemList[idx];
1215 BasicBlock *bb = (BasicBlock *) dvmGrowableListGetElement(blockList,
1216 blockIdx);
1217 if (bb == NULL) break;
1218 if (bb->blockType == kMethodEntryBlock) {
1219 fprintf(file, " entry [shape=Mdiamond];\n");
1220 } else if (bb->blockType == kMethodExitBlock) {
1221 fprintf(file, " exit [shape=Mdiamond];\n");
1222 } else if (bb->blockType == kDalvikByteCode) {
Ben Cheng7a02cb12010-12-15 14:18:31 -08001223 fprintf(file, " block%04x [shape=record,label = \"{ \\\n",
1224 bb->startOffset);
Ben Cheng00603072010-10-28 11:13:58 -07001225 const MIR *mir;
1226 for (mir = bb->firstMIRInsn; mir; mir = mir->next) {
1227 fprintf(file, " {%04x %s\\l}%s\\\n", mir->offset,
1228 dvmCompilerFullDisassembler(cUnit, mir),
1229 mir->next ? " | " : " ");
1230 }
1231 fprintf(file, " }\"];\n\n");
1232 } else if (bb->blockType == kExceptionHandling) {
1233 char blockName[BLOCK_NAME_LEN];
1234
1235 dvmGetBlockName(bb, blockName);
1236 fprintf(file, " %s [shape=invhouse];\n", blockName);
1237 }
1238
1239 char blockName1[BLOCK_NAME_LEN], blockName2[BLOCK_NAME_LEN];
1240
1241 if (bb->taken) {
1242 dvmGetBlockName(bb, blockName1);
1243 dvmGetBlockName(bb->taken, blockName2);
1244 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
1245 blockName1, blockName2);
1246 }
1247 if (bb->fallThrough) {
1248 dvmGetBlockName(bb, blockName1);
1249 dvmGetBlockName(bb->fallThrough, blockName2);
1250 fprintf(file, " %s:s -> %s:n\n", blockName1, blockName2);
1251 }
1252
1253 if (bb->successorBlockList.blockListType != kNotUsed) {
1254 fprintf(file, " succ%04x [shape=%s,label = \"{ \\\n",
1255 bb->startOffset,
1256 (bb->successorBlockList.blockListType == kCatch) ?
1257 "Mrecord" : "record");
1258 GrowableListIterator iterator;
1259 dvmGrowableListIteratorInit(&bb->successorBlockList.blocks,
1260 &iterator);
Ben Cheng7a02cb12010-12-15 14:18:31 -08001261 SuccessorBlockInfo *successorBlockInfo =
1262 (SuccessorBlockInfo *) dvmGrowableListIteratorNext(&iterator);
Ben Cheng00603072010-10-28 11:13:58 -07001263
1264 int succId = 0;
1265 while (true) {
Ben Cheng7a02cb12010-12-15 14:18:31 -08001266 if (successorBlockInfo == NULL) break;
1267
1268 BasicBlock *destBlock = successorBlockInfo->block;
1269 SuccessorBlockInfo *nextSuccessorBlockInfo =
1270 (SuccessorBlockInfo *) dvmGrowableListIteratorNext(&iterator);
1271
1272 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
Ben Cheng00603072010-10-28 11:13:58 -07001273 succId++,
Ben Cheng7a02cb12010-12-15 14:18:31 -08001274 successorBlockInfo->key,
Ben Cheng00603072010-10-28 11:13:58 -07001275 destBlock->startOffset,
Ben Cheng7a02cb12010-12-15 14:18:31 -08001276 (nextSuccessorBlockInfo != NULL) ? " | " : " ");
1277
1278 successorBlockInfo = nextSuccessorBlockInfo;
Ben Cheng00603072010-10-28 11:13:58 -07001279 }
1280 fprintf(file, " }\"];\n\n");
1281
1282 dvmGetBlockName(bb, blockName1);
1283 fprintf(file, " %s:s -> succ%04x:n [style=dashed]\n",
1284 blockName1, bb->startOffset);
1285
1286 if (bb->successorBlockList.blockListType == kPackedSwitch ||
1287 bb->successorBlockList.blockListType == kSparseSwitch) {
1288
1289 dvmGrowableListIteratorInit(&bb->successorBlockList.blocks,
1290 &iterator);
1291
1292 succId = 0;
1293 while (true) {
Ben Cheng7a02cb12010-12-15 14:18:31 -08001294 SuccessorBlockInfo *successorBlockInfo =
1295 (SuccessorBlockInfo *)
1296 dvmGrowableListIteratorNext(&iterator);
1297 if (successorBlockInfo == NULL) break;
1298
1299 BasicBlock *destBlock = successorBlockInfo->block;
Ben Cheng00603072010-10-28 11:13:58 -07001300
1301 dvmGetBlockName(destBlock, blockName2);
1302 fprintf(file, " succ%04x:f%d:e -> %s:n\n",
1303 bb->startOffset, succId++,
1304 blockName2);
1305 }
1306 }
1307 }
1308 fprintf(file, "\n");
1309
1310 /*
1311 * If we need to debug the dominator tree, uncomment the following code
1312 */
1313#if 0
1314 dvmGetBlockName(bb, blockName1);
1315 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
1316 blockName1, blockName1);
1317 if (bb->iDom) {
1318 dvmGetBlockName(bb->iDom, blockName2);
1319 fprintf(file, " cfg%s:s -> cfg%s:n\n\n",
1320 blockName2, blockName1);
1321 }
1322#endif
1323 }
1324 fprintf(file, "}\n");
1325 fclose(file);
1326}
1327
1328/* Verify if all the successor is connected with all the claimed predecessors */
1329static bool verifyPredInfo(CompilationUnit *cUnit, BasicBlock *bb)
1330{
1331 BitVectorIterator bvIterator;
1332
1333 dvmBitVectorIteratorInit(bb->predecessors, &bvIterator);
1334 while (true) {
1335 int blockIdx = dvmBitVectorIteratorNext(&bvIterator);
1336 if (blockIdx == -1) break;
1337 BasicBlock *predBB = (BasicBlock *)
1338 dvmGrowableListGetElement(&cUnit->blockList, blockIdx);
1339 bool found = false;
1340 if (predBB->taken == bb) {
1341 found = true;
1342 } else if (predBB->fallThrough == bb) {
1343 found = true;
1344 } else if (predBB->successorBlockList.blockListType != kNotUsed) {
1345 GrowableListIterator iterator;
1346 dvmGrowableListIteratorInit(&predBB->successorBlockList.blocks,
1347 &iterator);
1348 while (true) {
Ben Cheng7a02cb12010-12-15 14:18:31 -08001349 SuccessorBlockInfo *successorBlockInfo =
1350 (SuccessorBlockInfo *)
1351 dvmGrowableListIteratorNext(&iterator);
1352 if (successorBlockInfo == NULL) break;
1353 BasicBlock *succBB = successorBlockInfo->block;
Ben Cheng00603072010-10-28 11:13:58 -07001354 if (succBB == bb) {
1355 found = true;
1356 break;
1357 }
1358 }
1359 }
1360 if (found == false) {
1361 char blockName1[BLOCK_NAME_LEN], blockName2[BLOCK_NAME_LEN];
1362 dvmGetBlockName(bb, blockName1);
1363 dvmGetBlockName(predBB, blockName2);
1364 dumpCFG(cUnit, "/data/tombstones/");
1365 LOGE("Successor %s not found from %s",
1366 blockName1, blockName2);
1367 dvmAbort();
1368 }
1369 }
1370 return true;
1371}
1372
1373/* Identify code range in try blocks and set up the empty catch blocks */
1374static void processTryCatchBlocks(CompilationUnit *cUnit)
1375{
1376 const Method *meth = cUnit->method;
1377 const DexCode *pCode = dvmGetMethodCode(meth);
1378 int triesSize = pCode->triesSize;
1379 int i;
1380 int offset;
1381
1382 if (triesSize == 0) {
1383 return;
1384 }
1385
1386 const DexTry *pTries = dexGetTries(pCode);
1387 BitVector *tryBlockAddr = cUnit->tryBlockAddr;
1388
1389 /* Mark all the insn offsets in Try blocks */
1390 for (i = 0; i < triesSize; i++) {
1391 const DexTry* pTry = &pTries[i];
1392 /* all in 16-bit units */
1393 int startOffset = pTry->startAddr;
1394 int endOffset = startOffset + pTry->insnCount;
1395
1396 for (offset = startOffset; offset < endOffset; offset++) {
1397 dvmCompilerSetBit(tryBlockAddr, offset);
1398 }
1399 }
1400
1401 /* Iterate over each of the handlers to enqueue the empty Catch blocks */
1402 offset = dexGetFirstHandlerOffset(pCode);
1403 int handlersSize = dexGetHandlersSize(pCode);
1404
1405 for (i = 0; i < handlersSize; i++) {
1406 DexCatchIterator iterator;
1407 dexCatchIteratorInit(&iterator, pCode, offset);
1408
1409 for (;;) {
1410 DexCatchHandler* handler = dexCatchIteratorNext(&iterator);
1411
1412 if (handler == NULL) {
1413 break;
1414 }
1415
Ben Cheng7a02cb12010-12-15 14:18:31 -08001416 /*
1417 * Create dummy catch blocks first. Since these are created before
1418 * other blocks are processed, "split" is specified as false.
1419 */
1420 findBlock(cUnit, handler->address,
1421 /* split */
1422 false,
1423 /* create */
1424 true);
Ben Cheng00603072010-10-28 11:13:58 -07001425 }
1426
1427 offset = dexCatchIteratorGetEndOffset(&iterator, pCode);
1428 }
1429}
1430
1431/* Process instructions with the kInstrCanBranch flag */
1432static void processCanBranch(CompilationUnit *cUnit, BasicBlock *curBlock,
1433 MIR *insn, int curOffset, int width, int flags,
1434 const u2* codePtr, const u2* codeEnd)
1435{
1436 int target = curOffset;
1437 switch (insn->dalvikInsn.opcode) {
1438 case OP_GOTO:
1439 case OP_GOTO_16:
1440 case OP_GOTO_32:
1441 target += (int) insn->dalvikInsn.vA;
1442 break;
1443 case OP_IF_EQ:
1444 case OP_IF_NE:
1445 case OP_IF_LT:
1446 case OP_IF_GE:
1447 case OP_IF_GT:
1448 case OP_IF_LE:
1449 target += (int) insn->dalvikInsn.vC;
1450 break;
1451 case OP_IF_EQZ:
1452 case OP_IF_NEZ:
1453 case OP_IF_LTZ:
1454 case OP_IF_GEZ:
1455 case OP_IF_GTZ:
1456 case OP_IF_LEZ:
1457 target += (int) insn->dalvikInsn.vB;
1458 break;
1459 default:
1460 LOGE("Unexpected opcode(%d) with kInstrCanBranch set",
1461 insn->dalvikInsn.opcode);
1462 dvmAbort();
1463 }
1464 BasicBlock *takenBlock = findBlock(cUnit, target,
1465 /* split */
1466 true,
1467 /* create */
1468 true);
1469 curBlock->taken = takenBlock;
1470 dvmCompilerSetBit(takenBlock->predecessors, curBlock->id);
1471
1472 /* Always terminate the current block for conditional branches */
1473 if (flags & kInstrCanContinue) {
1474 BasicBlock *fallthroughBlock = findBlock(cUnit,
1475 curOffset + width,
1476 /* split */
1477 false,
1478 /* create */
1479 true);
1480 curBlock->fallThrough = fallthroughBlock;
1481 dvmCompilerSetBit(fallthroughBlock->predecessors, curBlock->id);
1482 } else if (codePtr < codeEnd) {
1483 /* Create a fallthrough block for real instructions (incl. OP_NOP) */
1484 if (contentIsInsn(codePtr)) {
1485 findBlock(cUnit, curOffset + width,
1486 /* split */
1487 false,
1488 /* create */
1489 true);
1490 }
1491 }
1492}
1493
1494/* Process instructions with the kInstrCanSwitch flag */
1495static void processCanSwitch(CompilationUnit *cUnit, BasicBlock *curBlock,
1496 MIR *insn, int curOffset, int width, int flags)
1497{
1498 u2 *switchData= (u2 *) (cUnit->method->insns + curOffset +
1499 insn->dalvikInsn.vB);
1500 int size;
Ben Cheng7a02cb12010-12-15 14:18:31 -08001501 int *keyTable;
Ben Cheng00603072010-10-28 11:13:58 -07001502 int *targetTable;
1503 int i;
Ben Cheng7a02cb12010-12-15 14:18:31 -08001504 int firstKey;
Ben Cheng00603072010-10-28 11:13:58 -07001505
1506 /*
1507 * Packed switch data format:
1508 * ushort ident = 0x0100 magic value
1509 * ushort size number of entries in the table
1510 * int first_key first (and lowest) switch case value
1511 * int targets[size] branch targets, relative to switch opcode
1512 *
1513 * Total size is (4+size*2) 16-bit code units.
1514 */
1515 if (insn->dalvikInsn.opcode == OP_PACKED_SWITCH) {
1516 assert(switchData[0] == kPackedSwitchSignature);
1517 size = switchData[1];
Ben Cheng7a02cb12010-12-15 14:18:31 -08001518 firstKey = switchData[2] | (switchData[3] << 16);
Ben Cheng00603072010-10-28 11:13:58 -07001519 targetTable = (int *) &switchData[4];
Ben Cheng7a02cb12010-12-15 14:18:31 -08001520 keyTable = NULL; // Make the compiler happy
Ben Cheng00603072010-10-28 11:13:58 -07001521 /*
1522 * Sparse switch data format:
1523 * ushort ident = 0x0200 magic value
1524 * ushort size number of entries in the table; > 0
1525 * int keys[size] keys, sorted low-to-high; 32-bit aligned
1526 * int targets[size] branch targets, relative to switch opcode
1527 *
1528 * Total size is (2+size*4) 16-bit code units.
1529 */
1530 } else {
1531 assert(switchData[0] == kSparseSwitchSignature);
1532 size = switchData[1];
Ben Cheng7a02cb12010-12-15 14:18:31 -08001533 keyTable = (int *) &switchData[2];
Ben Cheng00603072010-10-28 11:13:58 -07001534 targetTable = (int *) &switchData[2 + size*2];
Ben Cheng7a02cb12010-12-15 14:18:31 -08001535 firstKey = 0; // To make the compiler happy
Ben Cheng00603072010-10-28 11:13:58 -07001536 }
1537
1538 if (curBlock->successorBlockList.blockListType != kNotUsed) {
1539 LOGE("Successor block list already in use: %d",
1540 curBlock->successorBlockList.blockListType);
1541 dvmAbort();
1542 }
1543 curBlock->successorBlockList.blockListType =
1544 (insn->dalvikInsn.opcode == OP_PACKED_SWITCH) ?
1545 kPackedSwitch : kSparseSwitch;
1546 dvmInitGrowableList(&curBlock->successorBlockList.blocks, size);
1547
1548 for (i = 0; i < size; i++) {
1549 BasicBlock *caseBlock = findBlock(cUnit, curOffset + targetTable[i],
1550 /* split */
1551 true,
1552 /* create */
1553 true);
Ben Cheng7a02cb12010-12-15 14:18:31 -08001554 SuccessorBlockInfo *successorBlockInfo =
1555 (SuccessorBlockInfo *) dvmCompilerNew(sizeof(SuccessorBlockInfo),
1556 false);
1557 successorBlockInfo->block = caseBlock;
1558 successorBlockInfo->key = (insn->dalvikInsn.opcode == OP_PACKED_SWITCH)?
1559 firstKey + i : keyTable[i];
Ben Cheng00603072010-10-28 11:13:58 -07001560 dvmInsertGrowableList(&curBlock->successorBlockList.blocks,
Ben Cheng7a02cb12010-12-15 14:18:31 -08001561 (intptr_t) successorBlockInfo);
Ben Cheng00603072010-10-28 11:13:58 -07001562 dvmCompilerSetBit(caseBlock->predecessors, curBlock->id);
1563 }
1564
1565 /* Fall-through case */
1566 BasicBlock *fallthroughBlock = findBlock(cUnit,
1567 curOffset + width,
1568 /* split */
1569 false,
1570 /* create */
1571 true);
1572 curBlock->fallThrough = fallthroughBlock;
1573 dvmCompilerSetBit(fallthroughBlock->predecessors, curBlock->id);
1574}
1575
1576/* Process instructions with the kInstrCanThrow flag */
1577static void processCanThrow(CompilationUnit *cUnit, BasicBlock *curBlock,
1578 MIR *insn, int curOffset, int width, int flags,
1579 BitVector *tryBlockAddr, const u2 *codePtr,
1580 const u2* codeEnd)
1581{
1582 const Method *method = cUnit->method;
1583 const DexCode *dexCode = dvmGetMethodCode(method);
1584
Ben Cheng00603072010-10-28 11:13:58 -07001585 /* In try block */
1586 if (dvmIsBitSet(tryBlockAddr, curOffset)) {
1587 DexCatchIterator iterator;
1588
1589 if (!dexFindCatchHandler(&iterator, dexCode, curOffset)) {
1590 LOGE("Catch block not found in dexfile for insn %x in %s",
1591 curOffset, method->name);
1592 dvmAbort();
1593
1594 }
1595 if (curBlock->successorBlockList.blockListType != kNotUsed) {
1596 LOGE("Successor block list already in use: %d",
1597 curBlock->successorBlockList.blockListType);
1598 dvmAbort();
1599 }
1600 curBlock->successorBlockList.blockListType = kCatch;
1601 dvmInitGrowableList(&curBlock->successorBlockList.blocks, 2);
1602
1603 for (;;) {
1604 DexCatchHandler* handler = dexCatchIteratorNext(&iterator);
1605
1606 if (handler == NULL) {
1607 break;
1608 }
1609
1610 BasicBlock *catchBlock = findBlock(cUnit, handler->address,
1611 /* split */
1612 false,
1613 /* create */
1614 false);
1615
Ben Cheng7a02cb12010-12-15 14:18:31 -08001616 SuccessorBlockInfo *successorBlockInfo =
1617 (SuccessorBlockInfo *) dvmCompilerNew(sizeof(SuccessorBlockInfo),
1618 false);
1619 successorBlockInfo->block = catchBlock;
1620 successorBlockInfo->key = handler->typeIdx;
Ben Cheng00603072010-10-28 11:13:58 -07001621 dvmInsertGrowableList(&curBlock->successorBlockList.blocks,
Ben Cheng7a02cb12010-12-15 14:18:31 -08001622 (intptr_t) successorBlockInfo);
Ben Cheng00603072010-10-28 11:13:58 -07001623 dvmCompilerSetBit(catchBlock->predecessors, curBlock->id);
1624 }
1625 } else {
1626 BasicBlock *ehBlock = dvmCompilerNewBB(kExceptionHandling,
1627 cUnit->numBlocks++);
1628 curBlock->taken = ehBlock;
1629 dvmInsertGrowableList(&cUnit->blockList, (intptr_t) ehBlock);
1630 ehBlock->startOffset = curOffset;
1631 dvmCompilerSetBit(ehBlock->predecessors, curBlock->id);
1632 }
1633
1634 /*
1635 * Force the current block to terminate.
1636 *
1637 * Data may be present before codeEnd, so we need to parse it to know
1638 * whether it is code or data.
1639 */
1640 if (codePtr < codeEnd) {
1641 /* Create a fallthrough block for real instructions (incl. OP_NOP) */
1642 if (contentIsInsn(codePtr)) {
1643 BasicBlock *fallthroughBlock = findBlock(cUnit,
1644 curOffset + width,
1645 /* split */
1646 false,
1647 /* create */
1648 true);
1649 /*
1650 * OP_THROW and OP_THROW_VERIFICATION_ERROR are unconditional
1651 * branches.
1652 */
1653 if (insn->dalvikInsn.opcode != OP_THROW_VERIFICATION_ERROR &&
1654 insn->dalvikInsn.opcode != OP_THROW) {
1655 curBlock->fallThrough = fallthroughBlock;
1656 dvmCompilerSetBit(fallthroughBlock->predecessors, curBlock->id);
1657 }
1658 }
1659 }
1660}
1661
Ben Cheng7a2697d2010-06-07 13:44:23 -07001662/*
Ben Chengba4fc8b2009-06-01 13:00:29 -07001663 * Similar to dvmCompileTrace, but the entity processed here is the whole
1664 * method.
1665 *
1666 * TODO: implementation will be revisited when the trace builder can provide
1667 * whole-method traces.
1668 */
Ben Chengcfdeca32011-01-14 11:36:46 -08001669bool dvmCompileMethod(const Method *method, JitTranslationInfo *info)
Ben Chengba4fc8b2009-06-01 13:00:29 -07001670{
Ben Cheng00603072010-10-28 11:13:58 -07001671 CompilationUnit cUnit;
Ben Chengba4fc8b2009-06-01 13:00:29 -07001672 const DexCode *dexCode = dvmGetMethodCode(method);
1673 const u2 *codePtr = dexCode->insns;
1674 const u2 *codeEnd = dexCode->insns + dexCode->insnsSize;
Ben Cheng00603072010-10-28 11:13:58 -07001675 int numBlocks = 0;
Ben Chengba4fc8b2009-06-01 13:00:29 -07001676 unsigned int curOffset = 0;
1677
Ben Chengcfdeca32011-01-14 11:36:46 -08001678 /* Method already compiled */
1679 if (dvmJitGetMethodAddr(codePtr)) {
1680 info->codeAddress = NULL;
1681 return false;
1682 }
1683
Ben Cheng00603072010-10-28 11:13:58 -07001684 memset(&cUnit, 0, sizeof(cUnit));
1685 cUnit.method = method;
Ben Cheng7a2697d2010-06-07 13:44:23 -07001686
Ben Chengcfdeca32011-01-14 11:36:46 -08001687 cUnit.methodJitMode = true;
1688
Ben Cheng00603072010-10-28 11:13:58 -07001689 /* Initialize the block list */
1690 dvmInitGrowableList(&cUnit.blockList, 4);
Ben Chengba4fc8b2009-06-01 13:00:29 -07001691
Ben Chengcfdeca32011-01-14 11:36:46 -08001692 /*
1693 * FIXME - PC reconstruction list won't be needed after the codegen routines
1694 * are enhanced to true method mode.
1695 */
1696 /* Initialize the PC reconstruction list */
1697 dvmInitGrowableList(&cUnit.pcReconstructionList, 8);
1698
Ben Chengba4fc8b2009-06-01 13:00:29 -07001699 /* Allocate the bit-vector to track the beginning of basic blocks */
Ben Cheng00603072010-10-28 11:13:58 -07001700 BitVector *tryBlockAddr = dvmCompilerAllocBitVector(dexCode->insnsSize,
1701 true /* expandable */);
1702 cUnit.tryBlockAddr = tryBlockAddr;
Ben Chengba4fc8b2009-06-01 13:00:29 -07001703
Ben Cheng00603072010-10-28 11:13:58 -07001704 /* Create the default entry and exit blocks and enter them to the list */
1705 BasicBlock *entryBlock = dvmCompilerNewBB(kMethodEntryBlock, numBlocks++);
1706 BasicBlock *exitBlock = dvmCompilerNewBB(kMethodExitBlock, numBlocks++);
1707
1708 cUnit.entryBlock = entryBlock;
1709 cUnit.exitBlock = exitBlock;
1710
1711 dvmInsertGrowableList(&cUnit.blockList, (intptr_t) entryBlock);
1712 dvmInsertGrowableList(&cUnit.blockList, (intptr_t) exitBlock);
1713
1714 /* Current block to record parsed instructions */
1715 BasicBlock *curBlock = dvmCompilerNewBB(kDalvikByteCode, numBlocks++);
1716 curBlock->startOffset = 0;
1717 dvmInsertGrowableList(&cUnit.blockList, (intptr_t) curBlock);
1718 entryBlock->fallThrough = curBlock;
1719 dvmCompilerSetBit(curBlock->predecessors, entryBlock->id);
Ben Cheng7a2697d2010-06-07 13:44:23 -07001720
Ben Chengba4fc8b2009-06-01 13:00:29 -07001721 /*
Ben Cheng00603072010-10-28 11:13:58 -07001722 * Store back the number of blocks since new blocks may be created of
1723 * accessing cUnit.
Ben Chengba4fc8b2009-06-01 13:00:29 -07001724 */
Ben Cheng00603072010-10-28 11:13:58 -07001725 cUnit.numBlocks = numBlocks;
1726
1727 /* Identify code range in try blocks and set up the empty catch blocks */
1728 processTryCatchBlocks(&cUnit);
1729
1730 /* Parse all instructions and put them into containing basic blocks */
Ben Chengba4fc8b2009-06-01 13:00:29 -07001731 while (codePtr < codeEnd) {
Ben Cheng00603072010-10-28 11:13:58 -07001732 MIR *insn = (MIR *) dvmCompilerNew(sizeof(MIR), true);
Ben Chengba4fc8b2009-06-01 13:00:29 -07001733 insn->offset = curOffset;
1734 int width = parseInsn(codePtr, &insn->dalvikInsn, false);
Ben Chengba4fc8b2009-06-01 13:00:29 -07001735 insn->width = width;
1736
Ben Cheng8b258bf2009-06-24 17:27:07 -07001737 /* Terminate when the data section is seen */
1738 if (width == 0)
1739 break;
Ben Cheng7a2697d2010-06-07 13:44:23 -07001740
Ben Cheng00603072010-10-28 11:13:58 -07001741 dvmCompilerAppendMIR(curBlock, insn);
Ben Chengba4fc8b2009-06-01 13:00:29 -07001742
1743 codePtr += width;
Ben Cheng00603072010-10-28 11:13:58 -07001744 int flags = dexGetFlagsFromOpcode(insn->dalvikInsn.opcode);
1745
1746 if (flags & kInstrCanBranch) {
1747 processCanBranch(&cUnit, curBlock, insn, curOffset, width, flags,
1748 codePtr, codeEnd);
1749 } else if (flags & kInstrCanReturn) {
1750 curBlock->fallThrough = exitBlock;
1751 dvmCompilerSetBit(exitBlock->predecessors, curBlock->id);
1752 /*
1753 * Terminate the current block if there are instructions
1754 * afterwards.
1755 */
1756 if (codePtr < codeEnd) {
1757 /*
1758 * Create a fallthrough block for real instructions
1759 * (incl. OP_NOP).
1760 */
1761 if (contentIsInsn(codePtr)) {
1762 findBlock(&cUnit, curOffset + width,
1763 /* split */
1764 false,
1765 /* create */
1766 true);
1767 }
1768 }
1769 } else if (flags & kInstrCanThrow) {
1770 processCanThrow(&cUnit, curBlock, insn, curOffset, width, flags,
1771 tryBlockAddr, codePtr, codeEnd);
1772 } else if (flags & kInstrCanSwitch) {
1773 processCanSwitch(&cUnit, curBlock, insn, curOffset, width, flags);
1774 }
Ben Chengba4fc8b2009-06-01 13:00:29 -07001775 curOffset += width;
Ben Cheng00603072010-10-28 11:13:58 -07001776 BasicBlock *nextBlock = findBlock(&cUnit, curOffset,
1777 /* split */
1778 false,
1779 /* create */
1780 false);
1781 if (nextBlock) {
1782 /*
1783 * The next instruction could be the target of a previously parsed
1784 * forward branch so a block is already created. If the current
1785 * instruction is not an unconditional branch, connect them through
1786 * the fall-through link.
1787 */
1788 assert(curBlock->fallThrough == NULL ||
1789 curBlock->fallThrough == nextBlock ||
1790 curBlock->fallThrough == exitBlock);
Ben Chengba4fc8b2009-06-01 13:00:29 -07001791
Ben Cheng00603072010-10-28 11:13:58 -07001792 if ((curBlock->fallThrough == NULL) &&
1793 !dexIsGoto(flags) &&
1794 !(flags & kInstrCanReturn)) {
1795 curBlock->fallThrough = nextBlock;
1796 dvmCompilerSetBit(nextBlock->predecessors, curBlock->id);
Ben Chengba4fc8b2009-06-01 13:00:29 -07001797 }
Ben Cheng00603072010-10-28 11:13:58 -07001798 curBlock = nextBlock;
Ben Chengba4fc8b2009-06-01 13:00:29 -07001799 }
1800 }
1801
Ben Chengcfdeca32011-01-14 11:36:46 -08001802 if (cUnit.printMe) {
1803 dvmCompilerDumpCompilationUnit(&cUnit);
1804 }
1805
Ben Cheng00603072010-10-28 11:13:58 -07001806 /* Adjust this value accordingly once inlining is performed */
1807 cUnit.numDalvikRegisters = cUnit.method->registersSize;
Ben Chengba4fc8b2009-06-01 13:00:29 -07001808
Ben Cheng00603072010-10-28 11:13:58 -07001809 /* Verify if all blocks are connected as claimed */
1810 /* FIXME - to be disabled in the future */
1811 dvmCompilerDataFlowAnalysisDispatcher(&cUnit, verifyPredInfo,
1812 kAllNodes,
1813 false /* isIterative */);
Ben Chengba4fc8b2009-06-01 13:00:29 -07001814
Ben Chengba4fc8b2009-06-01 13:00:29 -07001815
Ben Cheng00603072010-10-28 11:13:58 -07001816 /* Perform SSA transformation for the whole method */
1817 dvmCompilerMethodSSATransformation(&cUnit);
Ben Chengba4fc8b2009-06-01 13:00:29 -07001818
Ben Chengcfdeca32011-01-14 11:36:46 -08001819 dvmCompilerInitializeRegAlloc(&cUnit); // Needs to happen after SSA naming
Ben Chengba4fc8b2009-06-01 13:00:29 -07001820
Ben Chengcfdeca32011-01-14 11:36:46 -08001821 /* Allocate Registers using simple local allocation scheme */
1822 dvmCompilerLocalRegAlloc(&cUnit);
1823
1824 /* Convert MIR to LIR, etc. */
1825 dvmCompilerMethodMIR2LIR(&cUnit);
1826
1827 // Debugging only
1828 //dumpCFG(&cUnit, "/data/tombstones/");
1829
1830 /* Method is not empty */
1831 if (cUnit.firstLIRInsn) {
1832 /* Convert LIR into machine code. Loop for recoverable retries */
1833 do {
1834 dvmCompilerAssembleLIR(&cUnit, info);
1835 cUnit.assemblerRetries++;
1836 if (cUnit.printMe && cUnit.assemblerStatus != kSuccess)
1837 LOGD("Assembler abort #%d on %d",cUnit.assemblerRetries,
1838 cUnit.assemblerStatus);
1839 } while (cUnit.assemblerStatus == kRetryAll);
1840
1841 if (cUnit.printMe) {
1842 dvmCompilerCodegenDump(&cUnit);
1843 }
1844
1845 if (info->codeAddress) {
1846 dvmJitSetCodeAddr(dexCode->insns, info->codeAddress,
1847 info->instructionSet, true, 0);
1848 /*
1849 * Clear the codeAddress for the enclosing trace to reuse the info
1850 */
1851 info->codeAddress = NULL;
1852 }
1853 }
Ben Chengba4fc8b2009-06-01 13:00:29 -07001854
Ben Cheng00603072010-10-28 11:13:58 -07001855 return false;
Ben Chengba4fc8b2009-06-01 13:00:29 -07001856}