blob: 64d701eb7dc3a9b08969374f7cc1ecdef2c0d752 [file] [log] [blame]
buzbee67bf8852011-08-17 17:51:35 -07001/*
2 * Copyright (C) 2011 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"
18#include "CompilerInternals.h"
19#include "Dataflow.h"
buzbeec143c552011-08-20 17:38:58 -070020#include "constants.h"
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -070021#include "object.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070022#include "runtime.h"
buzbee67bf8852011-08-17 17:51:35 -070023
24static inline bool contentIsInsn(const u2* codePtr) {
25 u2 instr = *codePtr;
26 Opcode 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
35/*
36 * Parse an instruction, return the length of the instruction
37 */
38static inline int parseInsn(const u2* codePtr, DecodedInstruction* decInsn,
39 bool printMe)
40{
41 // Don't parse instruction data
42 if (!contentIsInsn(codePtr)) {
43 return 0;
44 }
45
46 u2 instr = *codePtr;
47 Opcode opcode = dexOpcodeFromCodeUnit(instr);
48
49 dexDecodeInstruction(codePtr, decInsn);
50 if (printMe) {
51 char *decodedString = oatGetDalvikDisassembly(decInsn, NULL);
52 LOG(INFO) << codePtr << ": 0x" << std::hex << (int)opcode <<
53 " " << decodedString;
54 }
55 return dexGetWidthFromOpcode(opcode);
56}
57
58#define UNKNOWN_TARGET 0xffffffff
59
60static inline bool isGoto(MIR* insn)
61{
62 switch (insn->dalvikInsn.opcode) {
63 case OP_GOTO:
64 case OP_GOTO_16:
65 case OP_GOTO_32:
66 return true;
67 default:
68 return false;
69 }
70}
71
72/*
73 * Identify unconditional branch instructions
74 */
75static inline bool isUnconditionalBranch(MIR* insn)
76{
77 switch (insn->dalvikInsn.opcode) {
78 case OP_RETURN_VOID:
79 case OP_RETURN:
80 case OP_RETURN_WIDE:
81 case OP_RETURN_OBJECT:
82 return true;
83 default:
84 return isGoto(insn);
85 }
86}
87
88/* Split an existing block from the specified code offset into two */
89static BasicBlock *splitBlock(CompilationUnit* cUnit,
90 unsigned int codeOffset,
91 BasicBlock* origBlock)
92{
93 MIR* insn = origBlock->firstMIRInsn;
94 while (insn) {
95 if (insn->offset == codeOffset) break;
96 insn = insn->next;
97 }
98 if (insn == NULL) {
99 LOG(FATAL) << "Break split failed";
100 }
101 BasicBlock *bottomBlock = oatNewBB(kDalvikByteCode,
102 cUnit->numBlocks++);
103 oatInsertGrowableList(&cUnit->blockList, (intptr_t) bottomBlock);
104
105 bottomBlock->startOffset = codeOffset;
106 bottomBlock->firstMIRInsn = insn;
107 bottomBlock->lastMIRInsn = origBlock->lastMIRInsn;
108
109 /* Handle the taken path */
110 bottomBlock->taken = origBlock->taken;
111 if (bottomBlock->taken) {
112 origBlock->taken = NULL;
113 oatClearBit(bottomBlock->taken->predecessors, origBlock->id);
114 oatSetBit(bottomBlock->taken->predecessors, bottomBlock->id);
115 }
116
117 /* Handle the fallthrough path */
118 bottomBlock->needFallThroughBranch = origBlock->needFallThroughBranch;
119 bottomBlock->fallThrough = origBlock->fallThrough;
120 origBlock->fallThrough = bottomBlock;
121 origBlock->needFallThroughBranch = true;
122 oatSetBit(bottomBlock->predecessors, origBlock->id);
123 if (bottomBlock->fallThrough) {
124 oatClearBit(bottomBlock->fallThrough->predecessors,
125 origBlock->id);
126 oatSetBit(bottomBlock->fallThrough->predecessors,
127 bottomBlock->id);
128 }
129
130 /* Handle the successor list */
131 if (origBlock->successorBlockList.blockListType != kNotUsed) {
132 bottomBlock->successorBlockList = origBlock->successorBlockList;
133 origBlock->successorBlockList.blockListType = kNotUsed;
134 GrowableListIterator iterator;
135
136 oatGrowableListIteratorInit(&bottomBlock->successorBlockList.blocks,
137 &iterator);
138 while (true) {
139 SuccessorBlockInfo *successorBlockInfo =
140 (SuccessorBlockInfo *) oatGrowableListIteratorNext(&iterator);
141 if (successorBlockInfo == NULL) break;
142 BasicBlock *bb = successorBlockInfo->block;
143 oatClearBit(bb->predecessors, origBlock->id);
144 oatSetBit(bb->predecessors, bottomBlock->id);
145 }
146 }
147
148 origBlock->lastMIRInsn = insn->prev;
149
150 insn->prev->next = NULL;
151 insn->prev = NULL;
152 return bottomBlock;
153}
154
155/*
156 * Given a code offset, find out the block that starts with it. If the offset
157 * is in the middle of an existing block, split it into two.
158 */
159static BasicBlock *findBlock(CompilationUnit* cUnit,
160 unsigned int codeOffset,
161 bool split, bool create)
162{
163 GrowableList* blockList = &cUnit->blockList;
164 BasicBlock* bb;
165 unsigned int i;
166
167 for (i = 0; i < blockList->numUsed; i++) {
168 bb = (BasicBlock *) blockList->elemList[i];
169 if (bb->blockType != kDalvikByteCode) continue;
170 if (bb->startOffset == codeOffset) return bb;
171 /* Check if a branch jumps into the middle of an existing block */
172 if ((split == true) && (codeOffset > bb->startOffset) &&
173 (bb->lastMIRInsn != NULL) &&
174 (codeOffset <= bb->lastMIRInsn->offset)) {
175 BasicBlock *newBB = splitBlock(cUnit, codeOffset, bb);
176 return newBB;
177 }
178 }
179 if (create) {
180 bb = oatNewBB(kDalvikByteCode, cUnit->numBlocks++);
181 oatInsertGrowableList(&cUnit->blockList, (intptr_t) bb);
182 bb->startOffset = codeOffset;
183 return bb;
184 }
185 return NULL;
186}
187
188/* Dump the CFG into a DOT graph */
189void oatDumpCFG(CompilationUnit* cUnit, const char* dirPrefix)
190{
buzbee67bf8852011-08-17 17:51:35 -0700191 FILE* file;
buzbeedfd3d702011-08-28 12:56:51 -0700192 std::string name = art::PrettyMethod(cUnit->method);
buzbee67bf8852011-08-17 17:51:35 -0700193 char startOffset[80];
194 sprintf(startOffset, "_%x", cUnit->entryBlock->fallThrough->startOffset);
195 char* fileName = (char *) oatNew(
buzbeec143c552011-08-20 17:38:58 -0700196 strlen(dirPrefix) +
197 name.length() +
198 strlen(".dot") + 1, true);
199 sprintf(fileName, "%s%s%s.dot", dirPrefix, name.c_str(), startOffset);
buzbee67bf8852011-08-17 17:51:35 -0700200
201 /*
202 * Convert the special characters into a filesystem- and shell-friendly
203 * format.
204 */
205 int i;
206 for (i = strlen(dirPrefix); fileName[i]; i++) {
207 if (fileName[i] == '/') {
208 fileName[i] = '_';
209 } else if (fileName[i] == ';') {
210 fileName[i] = '#';
211 } else if (fileName[i] == '$') {
212 fileName[i] = '+';
213 } else if (fileName[i] == '(' || fileName[i] == ')') {
214 fileName[i] = '@';
215 } else if (fileName[i] == '<' || fileName[i] == '>') {
216 fileName[i] = '=';
217 }
218 }
219 file = fopen(fileName, "w");
220 if (file == NULL) {
221 return;
222 }
223 fprintf(file, "digraph G {\n");
224
225 fprintf(file, " rankdir=TB\n");
226
227 int numReachableBlocks = cUnit->numReachableBlocks;
228 int idx;
229 const GrowableList *blockList = &cUnit->blockList;
230
231 for (idx = 0; idx < numReachableBlocks; idx++) {
232 int blockIdx = cUnit->dfsOrder.elemList[idx];
233 BasicBlock *bb = (BasicBlock *) oatGrowableListGetElement(blockList,
234 blockIdx);
235 if (bb == NULL) break;
236 if (bb->blockType == kEntryBlock) {
237 fprintf(file, " entry [shape=Mdiamond];\n");
238 } else if (bb->blockType == kExitBlock) {
239 fprintf(file, " exit [shape=Mdiamond];\n");
240 } else if (bb->blockType == kDalvikByteCode) {
241 fprintf(file, " block%04x [shape=record,label = \"{ \\\n",
242 bb->startOffset);
243 const MIR *mir;
244 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
245 bb->firstMIRInsn ? " | " : " ");
246 for (mir = bb->firstMIRInsn; mir; mir = mir->next) {
247 fprintf(file, " {%04x %s\\l}%s\\\n", mir->offset,
248 mir->ssaRep ?
249 oatFullDisassembler(cUnit, mir) :
250 dexGetOpcodeName(mir->dalvikInsn.opcode),
251 mir->next ? " | " : " ");
252 }
253 fprintf(file, " }\"];\n\n");
254 } else if (bb->blockType == kExceptionHandling) {
255 char blockName[BLOCK_NAME_LEN];
256
257 oatGetBlockName(bb, blockName);
258 fprintf(file, " %s [shape=invhouse];\n", blockName);
259 }
260
261 char blockName1[BLOCK_NAME_LEN], blockName2[BLOCK_NAME_LEN];
262
263 if (bb->taken) {
264 oatGetBlockName(bb, blockName1);
265 oatGetBlockName(bb->taken, blockName2);
266 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
267 blockName1, blockName2);
268 }
269 if (bb->fallThrough) {
270 oatGetBlockName(bb, blockName1);
271 oatGetBlockName(bb->fallThrough, blockName2);
272 fprintf(file, " %s:s -> %s:n\n", blockName1, blockName2);
273 }
274
275 if (bb->successorBlockList.blockListType != kNotUsed) {
276 fprintf(file, " succ%04x [shape=%s,label = \"{ \\\n",
277 bb->startOffset,
278 (bb->successorBlockList.blockListType == kCatch) ?
279 "Mrecord" : "record");
280 GrowableListIterator iterator;
281 oatGrowableListIteratorInit(&bb->successorBlockList.blocks,
282 &iterator);
283 SuccessorBlockInfo *successorBlockInfo =
284 (SuccessorBlockInfo *) oatGrowableListIteratorNext(&iterator);
285
286 int succId = 0;
287 while (true) {
288 if (successorBlockInfo == NULL) break;
289
290 BasicBlock *destBlock = successorBlockInfo->block;
291 SuccessorBlockInfo *nextSuccessorBlockInfo =
292 (SuccessorBlockInfo *) oatGrowableListIteratorNext(&iterator);
293
294 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
295 succId++,
296 successorBlockInfo->key,
297 destBlock->startOffset,
298 (nextSuccessorBlockInfo != NULL) ? " | " : " ");
299
300 successorBlockInfo = nextSuccessorBlockInfo;
301 }
302 fprintf(file, " }\"];\n\n");
303
304 oatGetBlockName(bb, blockName1);
305 fprintf(file, " %s:s -> succ%04x:n [style=dashed]\n",
306 blockName1, bb->startOffset);
307
308 if (bb->successorBlockList.blockListType == kPackedSwitch ||
309 bb->successorBlockList.blockListType == kSparseSwitch) {
310
311 oatGrowableListIteratorInit(&bb->successorBlockList.blocks,
312 &iterator);
313
314 succId = 0;
315 while (true) {
316 SuccessorBlockInfo *successorBlockInfo =
317 (SuccessorBlockInfo *)
318 oatGrowableListIteratorNext(&iterator);
319 if (successorBlockInfo == NULL) break;
320
321 BasicBlock *destBlock = successorBlockInfo->block;
322
323 oatGetBlockName(destBlock, blockName2);
324 fprintf(file, " succ%04x:f%d:e -> %s:n\n",
325 bb->startOffset, succId++,
326 blockName2);
327 }
328 }
329 }
330 fprintf(file, "\n");
331
332 /*
333 * If we need to debug the dominator tree, uncomment the following code
334 */
335#if 1
336 oatGetBlockName(bb, blockName1);
337 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
338 blockName1, blockName1);
339 if (bb->iDom) {
340 oatGetBlockName(bb->iDom, blockName2);
341 fprintf(file, " cfg%s:s -> cfg%s:n\n\n",
342 blockName2, blockName1);
343 }
344#endif
345 }
346 fprintf(file, "}\n");
347 fclose(file);
348}
349
350/* Verify if all the successor is connected with all the claimed predecessors */
351static bool verifyPredInfo(CompilationUnit* cUnit, BasicBlock* bb)
352{
353 ArenaBitVectorIterator bvIterator;
354
355 oatBitVectorIteratorInit(bb->predecessors, &bvIterator);
356 while (true) {
357 int blockIdx = oatBitVectorIteratorNext(&bvIterator);
358 if (blockIdx == -1) break;
359 BasicBlock *predBB = (BasicBlock *)
360 oatGrowableListGetElement(&cUnit->blockList, blockIdx);
361 bool found = false;
362 if (predBB->taken == bb) {
363 found = true;
364 } else if (predBB->fallThrough == bb) {
365 found = true;
366 } else if (predBB->successorBlockList.blockListType != kNotUsed) {
367 GrowableListIterator iterator;
368 oatGrowableListIteratorInit(&predBB->successorBlockList.blocks,
369 &iterator);
370 while (true) {
371 SuccessorBlockInfo *successorBlockInfo =
372 (SuccessorBlockInfo *)
373 oatGrowableListIteratorNext(&iterator);
374 if (successorBlockInfo == NULL) break;
375 BasicBlock *succBB = successorBlockInfo->block;
376 if (succBB == bb) {
377 found = true;
378 break;
379 }
380 }
381 }
382 if (found == false) {
383 char blockName1[BLOCK_NAME_LEN], blockName2[BLOCK_NAME_LEN];
384 oatGetBlockName(bb, blockName1);
385 oatGetBlockName(predBB, blockName2);
386 oatDumpCFG(cUnit, "/sdcard/cfg/");
387 LOG(FATAL) << "Successor " << blockName1 << "not found from "
388 << blockName2;
389 }
390 }
391 return true;
392}
393
394/* Identify code range in try blocks and set up the empty catch blocks */
395static void processTryCatchBlocks(CompilationUnit* cUnit)
396{
buzbeec143c552011-08-20 17:38:58 -0700397
398 UNIMPLEMENTED(WARNING) << "Need to finish processTryCatchBlocks()";
399#if 0
buzbee67bf8852011-08-17 17:51:35 -0700400 const Method* meth = cUnit->method;
401 const DexCode *pCode = dvmGetMethodCode(meth);
402 int triesSize = pCode->triesSize;
403 int i;
404 int offset;
405
406 if (triesSize == 0) {
407 return;
408 }
409
410 const DexTry* pTries = dexGetTries(pCode);
411 ArenaBitVector* tryBlockAddr = cUnit->tryBlockAddr;
412
413 /* Mark all the insn offsets in Try blocks */
414 for (i = 0; i < triesSize; i++) {
415 const DexTry* pTry = &pTries[i];
416 /* all in 16-bit units */
417 int startOffset = pTry->startAddr;
418 int endOffset = startOffset + pTry->insnCount;
419
420 for (offset = startOffset; offset < endOffset; offset++) {
421 oatSetBit(tryBlockAddr, offset);
422 }
423 }
424
425 /* Iterate over each of the handlers to enqueue the empty Catch blocks */
426 offset = dexGetFirstHandlerOffset(pCode);
427 int handlersSize = dexGetHandlersSize(pCode);
428
429 for (i = 0; i < handlersSize; i++) {
430 DexCatchIterator iterator;
431 dexCatchIteratorInit(&iterator, pCode, offset);
432
433 for (;;) {
434 DexCatchHandler* handler = dexCatchIteratorNext(&iterator);
435
436 if (handler == NULL) {
437 break;
438 }
439
440 /*
441 * Create dummy catch blocks first. Since these are created before
442 * other blocks are processed, "split" is specified as false.
443 */
444 findBlock(cUnit, handler->address,
445 /* split */
446 false,
447 /* create */
448 true);
449 }
450
451 offset = dexCatchIteratorGetEndOffset(&iterator, pCode);
452 }
buzbeec143c552011-08-20 17:38:58 -0700453#endif
buzbee67bf8852011-08-17 17:51:35 -0700454}
455
456/* Process instructions with the kInstrCanBranch flag */
457static void processCanBranch(CompilationUnit* cUnit, BasicBlock* curBlock,
458 MIR* insn, int curOffset, int width, int flags,
459 const u2* codePtr, const u2* codeEnd)
460{
461 int target = curOffset;
462 switch (insn->dalvikInsn.opcode) {
463 case OP_GOTO:
464 case OP_GOTO_16:
465 case OP_GOTO_32:
466 target += (int) insn->dalvikInsn.vA;
467 break;
468 case OP_IF_EQ:
469 case OP_IF_NE:
470 case OP_IF_LT:
471 case OP_IF_GE:
472 case OP_IF_GT:
473 case OP_IF_LE:
474 target += (int) insn->dalvikInsn.vC;
475 break;
476 case OP_IF_EQZ:
477 case OP_IF_NEZ:
478 case OP_IF_LTZ:
479 case OP_IF_GEZ:
480 case OP_IF_GTZ:
481 case OP_IF_LEZ:
482 target += (int) insn->dalvikInsn.vB;
483 break;
484 default:
485 LOG(FATAL) << "Unexpected opcode(" << (int)insn->dalvikInsn.opcode
486 << ") with kInstrCanBranch set";
487 }
488 BasicBlock *takenBlock = findBlock(cUnit, target,
489 /* split */
490 true,
491 /* create */
492 true);
493 curBlock->taken = takenBlock;
494 oatSetBit(takenBlock->predecessors, curBlock->id);
495
496 /* Always terminate the current block for conditional branches */
497 if (flags & kInstrCanContinue) {
498 BasicBlock *fallthroughBlock = findBlock(cUnit,
499 curOffset + width,
500 /*
501 * If the method is processed
502 * in sequential order from the
503 * beginning, we don't need to
504 * specify split for continue
505 * blocks. However, this
506 * routine can be called by
507 * compileLoop, which starts
508 * parsing the method from an
509 * arbitrary address in the
510 * method body.
511 */
512 true,
513 /* create */
514 true);
515 curBlock->fallThrough = fallthroughBlock;
516 oatSetBit(fallthroughBlock->predecessors, curBlock->id);
517 } else if (codePtr < codeEnd) {
518 /* Create a fallthrough block for real instructions (incl. OP_NOP) */
519 if (contentIsInsn(codePtr)) {
520 findBlock(cUnit, curOffset + width,
521 /* split */
522 false,
523 /* create */
524 true);
525 }
526 }
527}
528
529/* Process instructions with the kInstrCanSwitch flag */
530static void processCanSwitch(CompilationUnit* cUnit, BasicBlock* curBlock,
531 MIR* insn, int curOffset, int width, int flags)
532{
533 u2* switchData= (u2 *) (cUnit->insns + curOffset +
534 insn->dalvikInsn.vB);
535 int size;
536 int* keyTable;
537 int* targetTable;
538 int i;
539 int firstKey;
540
541 /*
542 * Packed switch data format:
543 * ushort ident = 0x0100 magic value
544 * ushort size number of entries in the table
545 * int first_key first (and lowest) switch case value
546 * int targets[size] branch targets, relative to switch opcode
547 *
548 * Total size is (4+size*2) 16-bit code units.
549 */
550 if (insn->dalvikInsn.opcode == OP_PACKED_SWITCH) {
551 assert(switchData[0] == kPackedSwitchSignature);
552 size = switchData[1];
553 firstKey = switchData[2] | (switchData[3] << 16);
554 targetTable = (int *) &switchData[4];
555 keyTable = NULL; // Make the compiler happy
556 /*
557 * Sparse switch data format:
558 * ushort ident = 0x0200 magic value
559 * ushort size number of entries in the table; > 0
560 * int keys[size] keys, sorted low-to-high; 32-bit aligned
561 * int targets[size] branch targets, relative to switch opcode
562 *
563 * Total size is (2+size*4) 16-bit code units.
564 */
565 } else {
566 assert(switchData[0] == kSparseSwitchSignature);
567 size = switchData[1];
568 keyTable = (int *) &switchData[2];
569 targetTable = (int *) &switchData[2 + size*2];
570 firstKey = 0; // To make the compiler happy
571 }
572
573 if (curBlock->successorBlockList.blockListType != kNotUsed) {
574 LOG(FATAL) << "Successor block list already in use: " <<
575 (int)curBlock->successorBlockList.blockListType;
576 }
577 curBlock->successorBlockList.blockListType =
578 (insn->dalvikInsn.opcode == OP_PACKED_SWITCH) ?
579 kPackedSwitch : kSparseSwitch;
580 oatInitGrowableList(&curBlock->successorBlockList.blocks, size);
581
582 for (i = 0; i < size; i++) {
583 BasicBlock *caseBlock = findBlock(cUnit, curOffset + targetTable[i],
584 /* split */
585 true,
586 /* create */
587 true);
588 SuccessorBlockInfo *successorBlockInfo =
589 (SuccessorBlockInfo *) oatNew(sizeof(SuccessorBlockInfo),
590 false);
591 successorBlockInfo->block = caseBlock;
592 successorBlockInfo->key = (insn->dalvikInsn.opcode == OP_PACKED_SWITCH)?
593 firstKey + i : keyTable[i];
594 oatInsertGrowableList(&curBlock->successorBlockList.blocks,
595 (intptr_t) successorBlockInfo);
596 oatSetBit(caseBlock->predecessors, curBlock->id);
597 }
598
599 /* Fall-through case */
600 BasicBlock* fallthroughBlock = findBlock(cUnit,
601 curOffset + width,
602 /* split */
603 false,
604 /* create */
605 true);
606 curBlock->fallThrough = fallthroughBlock;
607 oatSetBit(fallthroughBlock->predecessors, curBlock->id);
608}
609
610/* Process instructions with the kInstrCanThrow flag */
611static void processCanThrow(CompilationUnit* cUnit, BasicBlock* curBlock,
612 MIR* insn, int curOffset, int width, int flags,
613 ArenaBitVector* tryBlockAddr, const u2* codePtr,
614 const u2* codeEnd)
615{
buzbeec143c552011-08-20 17:38:58 -0700616 UNIMPLEMENTED(WARNING) << "Need to complete processCanThrow";
617#if 0
buzbee67bf8852011-08-17 17:51:35 -0700618 const Method* method = cUnit->method;
619 const DexCode* dexCode = dvmGetMethodCode(method);
620
621 /* In try block */
622 if (oatIsBitSet(tryBlockAddr, curOffset)) {
623 DexCatchIterator iterator;
624
625 if (!dexFindCatchHandler(&iterator, dexCode, curOffset)) {
626 LOG(FATAL) << "Catch block not found in dexfile for insn " <<
627 curOffset << " in " << method->name;
628
629 }
630 if (curBlock->successorBlockList.blockListType != kNotUsed) {
631 LOG(FATAL) << "Successor block list already in use: " <<
632 (int)curBlock->successorBlockList.blockListType;
633 }
634 curBlock->successorBlockList.blockListType = kCatch;
635 oatInitGrowableList(&curBlock->successorBlockList.blocks, 2);
636
637 for (;;) {
638 DexCatchHandler* handler = dexCatchIteratorNext(&iterator);
639
640 if (handler == NULL) {
641 break;
642 }
643
644 BasicBlock *catchBlock = findBlock(cUnit, handler->address,
645 /* split */
646 false,
647 /* create */
648 false);
649
650 SuccessorBlockInfo *successorBlockInfo =
651 (SuccessorBlockInfo *) oatNew(sizeof(SuccessorBlockInfo),
652 false);
653 successorBlockInfo->block = catchBlock;
654 successorBlockInfo->key = handler->typeIdx;
655 oatInsertGrowableList(&curBlock->successorBlockList.blocks,
656 (intptr_t) successorBlockInfo);
657 oatSetBit(catchBlock->predecessors, curBlock->id);
658 }
659 } else {
660 BasicBlock *ehBlock = oatNewBB(kExceptionHandling,
661 cUnit->numBlocks++);
662 curBlock->taken = ehBlock;
663 oatInsertGrowableList(&cUnit->blockList, (intptr_t) ehBlock);
664 ehBlock->startOffset = curOffset;
665 oatSetBit(ehBlock->predecessors, curBlock->id);
666 }
667
668 /*
669 * Force the current block to terminate.
670 *
671 * Data may be present before codeEnd, so we need to parse it to know
672 * whether it is code or data.
673 */
674 if (codePtr < codeEnd) {
675 /* Create a fallthrough block for real instructions (incl. OP_NOP) */
676 if (contentIsInsn(codePtr)) {
677 BasicBlock *fallthroughBlock = findBlock(cUnit,
678 curOffset + width,
679 /* split */
680 false,
681 /* create */
682 true);
683 /*
684 * OP_THROW and OP_THROW_VERIFICATION_ERROR are unconditional
685 * branches.
686 */
687 if (insn->dalvikInsn.opcode != OP_THROW_VERIFICATION_ERROR &&
688 insn->dalvikInsn.opcode != OP_THROW) {
689 curBlock->fallThrough = fallthroughBlock;
690 oatSetBit(fallthroughBlock->predecessors, curBlock->id);
691 }
692 }
693 }
buzbeec143c552011-08-20 17:38:58 -0700694#endif
buzbee67bf8852011-08-17 17:51:35 -0700695}
696
697/*
698 * Compile a method.
699 */
buzbeec143c552011-08-20 17:38:58 -0700700bool oatCompileMethod(Method* method, art::InstructionSet insnSet)
buzbee67bf8852011-08-17 17:51:35 -0700701{
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700702 LOG(INFO) << "Compiling " << PrettyMethod(method) << "...";
Brian Carlstrom94496d32011-08-22 09:22:47 -0700703
buzbee67bf8852011-08-17 17:51:35 -0700704 CompilationUnit cUnit;
buzbeec143c552011-08-20 17:38:58 -0700705 art::ClassLinker* class_linker = art::Runtime::Current()->GetClassLinker();
706 const art::DexFile& dex_file = class_linker->FindDexFile(
707 method->GetDeclaringClass()->GetDexCache());
708 const art::DexFile::CodeItem* code_item =
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700709 dex_file.GetCodeItem(method->GetCodeItemOffset());
buzbeec143c552011-08-20 17:38:58 -0700710 const u2* codePtr = code_item->insns_;
711 const u2* codeEnd = code_item->insns_ + code_item->insns_size_;
buzbee67bf8852011-08-17 17:51:35 -0700712 int numBlocks = 0;
713 unsigned int curOffset = 0;
714
715#if 1
716 // FIXME - temp 'till properly integrated
717 oatInit();
718#endif
719
720 memset(&cUnit, 0, sizeof(cUnit));
721 cUnit.method = method;
buzbeec143c552011-08-20 17:38:58 -0700722 cUnit.instructionSet = (OatInstructionSetType)insnSet;
723 cUnit.insns = code_item->insns_;
724 cUnit.insnsSize = code_item->insns_size_;
buzbee67bf8852011-08-17 17:51:35 -0700725#if 1
buzbee3ea4ec52011-08-22 17:37:19 -0700726 // TODO: Use command-line argument passing mechanism
buzbee67bf8852011-08-17 17:51:35 -0700727 cUnit.printMe = true;
728 cUnit.printMeVerbose = true;
buzbee3ea4ec52011-08-22 17:37:19 -0700729 cUnit.disableOpt = 0 |
730 (1 << kLoadStoreElimination) |
731 (1 << kLoadHoisting) |
732 (1 << kTrackLiveTemps) |
733 (1 << kSuppressLoads) |
734 (1 << kPromoteRegs) |
735 0;
buzbee67bf8852011-08-17 17:51:35 -0700736#endif
737
738 /* Initialize the block list */
739 oatInitGrowableList(&cUnit.blockList, 40);
740
741 /* Initialize the switchTables list */
742 oatInitGrowableList(&cUnit.switchTables, 4);
743
744 /* Intialize the fillArrayData list */
745 oatInitGrowableList(&cUnit.fillArrayData, 4);
746
747 /* Allocate the bit-vector to track the beginning of basic blocks */
748 ArenaBitVector *tryBlockAddr = oatAllocBitVector(cUnit.insnsSize,
749 true /* expandable */);
750 cUnit.tryBlockAddr = tryBlockAddr;
751
752 /* Create the default entry and exit blocks and enter them to the list */
753 BasicBlock *entryBlock = oatNewBB(kEntryBlock, numBlocks++);
754 BasicBlock *exitBlock = oatNewBB(kExitBlock, numBlocks++);
755
756 cUnit.entryBlock = entryBlock;
757 cUnit.exitBlock = exitBlock;
758
759 oatInsertGrowableList(&cUnit.blockList, (intptr_t) entryBlock);
760 oatInsertGrowableList(&cUnit.blockList, (intptr_t) exitBlock);
761
762 /* Current block to record parsed instructions */
763 BasicBlock *curBlock = oatNewBB(kDalvikByteCode, numBlocks++);
764 curBlock->startOffset = 0;
765 oatInsertGrowableList(&cUnit.blockList, (intptr_t) curBlock);
766 entryBlock->fallThrough = curBlock;
767 oatSetBit(curBlock->predecessors, entryBlock->id);
768
769 /*
770 * Store back the number of blocks since new blocks may be created of
771 * accessing cUnit.
772 */
773 cUnit.numBlocks = numBlocks;
774
775 /* Identify code range in try blocks and set up the empty catch blocks */
776 processTryCatchBlocks(&cUnit);
777
778 /* Parse all instructions and put them into containing basic blocks */
779 while (codePtr < codeEnd) {
780 MIR *insn = (MIR *) oatNew(sizeof(MIR), true);
781 insn->offset = curOffset;
782 int width = parseInsn(codePtr, &insn->dalvikInsn, false);
783 insn->width = width;
784
785 /* Terminate when the data section is seen */
786 if (width == 0)
787 break;
788
789 oatAppendMIR(curBlock, insn);
790
791 codePtr += width;
792 int flags = dexGetFlagsFromOpcode(insn->dalvikInsn.opcode);
793
794 if (flags & kInstrCanBranch) {
795 processCanBranch(&cUnit, curBlock, insn, curOffset, width, flags,
796 codePtr, codeEnd);
797 } else if (flags & kInstrCanReturn) {
798 curBlock->fallThrough = exitBlock;
799 oatSetBit(exitBlock->predecessors, curBlock->id);
800 /*
801 * Terminate the current block if there are instructions
802 * afterwards.
803 */
804 if (codePtr < codeEnd) {
805 /*
806 * Create a fallthrough block for real instructions
807 * (incl. OP_NOP).
808 */
809 if (contentIsInsn(codePtr)) {
810 findBlock(&cUnit, curOffset + width,
811 /* split */
812 false,
813 /* create */
814 true);
815 }
816 }
817 } else if (flags & kInstrCanThrow) {
818 processCanThrow(&cUnit, curBlock, insn, curOffset, width, flags,
819 tryBlockAddr, codePtr, codeEnd);
820 } else if (flags & kInstrCanSwitch) {
821 processCanSwitch(&cUnit, curBlock, insn, curOffset, width, flags);
822 }
823 curOffset += width;
824 BasicBlock *nextBlock = findBlock(&cUnit, curOffset,
825 /* split */
826 false,
827 /* create */
828 false);
829 if (nextBlock) {
830 /*
831 * The next instruction could be the target of a previously parsed
832 * forward branch so a block is already created. If the current
833 * instruction is not an unconditional branch, connect them through
834 * the fall-through link.
835 */
836 assert(curBlock->fallThrough == NULL ||
837 curBlock->fallThrough == nextBlock ||
838 curBlock->fallThrough == exitBlock);
839
840 if ((curBlock->fallThrough == NULL) &&
841 (flags & kInstrCanContinue)) {
842 curBlock->fallThrough = nextBlock;
843 oatSetBit(nextBlock->predecessors, curBlock->id);
844 }
845 curBlock = nextBlock;
846 }
847 }
848
849 if (cUnit.printMe) {
850 oatDumpCompilationUnit(&cUnit);
851 }
852
853 /* Adjust this value accordingly once inlining is performed */
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700854 cUnit.numDalvikRegisters = cUnit.method->NumRegisters();
buzbee67bf8852011-08-17 17:51:35 -0700855
856
857 /* Verify if all blocks are connected as claimed */
858 oatDataFlowAnalysisDispatcher(&cUnit, verifyPredInfo,
859 kAllNodes,
860 false /* isIterative */);
861
862
863
864 /* Perform SSA transformation for the whole method */
865 oatMethodSSATransformation(&cUnit);
866
867 oatInitializeRegAlloc(&cUnit); // Needs to happen after SSA naming
868
869 /* Allocate Registers using simple local allocation scheme */
870 oatSimpleRegAlloc(&cUnit);
871
872 /* Convert MIR to LIR, etc. */
873 oatMethodMIR2LIR(&cUnit);
874
875 // Debugging only
876 //oatDumpCFG(&cUnit, "/sdcard/cfg/");
877
878 /* Method is not empty */
879 if (cUnit.firstLIRInsn) {
880
881 // mark the targets of switch statement case labels
882 oatProcessSwitchTables(&cUnit);
883
884 /* Convert LIR into machine code. */
885 oatAssembleLIR(&cUnit);
886
887 if (cUnit.printMe) {
888 oatCodegenDump(&cUnit);
889 }
890 }
891
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700892 art::ByteArray* managed_code = art::ByteArray::Alloc(cUnit.codeBuffer.size() * 2);
893 memcpy(managed_code->GetData(),
894 reinterpret_cast<const int8_t*>(&cUnit.codeBuffer[0]),
895 managed_code->GetLength());
896 method->SetCode(managed_code, art::kThumb2);
Shih-wei Liaod11af152011-08-23 16:02:11 -0700897 method->SetFrameSizeInBytes(cUnit.frameSize);
buzbeec143c552011-08-20 17:38:58 -0700898 method->SetCoreSpillMask(cUnit.coreSpillMask);
899 method->SetFpSpillMask(cUnit.fpSpillMask);
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700900 LOG(INFO) << "Compiled " << PrettyMethod(method)
901 << " code at " << reinterpret_cast<void*>(managed_code->GetData())
902 << " (" << managed_code->GetLength() << " bytes)";
buzbeec143c552011-08-20 17:38:58 -0700903 // TODO: Transmit mapping table to caller
buzbee67bf8852011-08-17 17:51:35 -0700904
905#if 0
906 oatDumpCFG(&cUnit, "/sdcard/cfg/");
907#endif
908
Brian Carlstrombffb1552011-08-25 12:23:53 -0700909 return true;
buzbee67bf8852011-08-17 17:51:35 -0700910}
911
912void oatInit(void)
913{
914#if 1
915 // FIXME - temp hack 'till properly integrated
916 static bool initialized = false;
917 if (initialized)
918 return;
919 initialized = true;
920 LOG(INFO) << "Initializing compiler";
921#endif
922 if (!oatArchInit()) {
923 LOG(FATAL) << "Failed to initialize oat";
924 }
925 if (!oatHeapInit()) {
926 LOG(FATAL) << "Failed to initialize oat heap";
927 }
928}