blob: 2abefe10b0a625f7822814bdd97c87c447e13190 [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{
buzbeee9a72f62011-09-04 17:59:07 -0700397 const Method* method = cUnit->method;
398 art::ClassLinker* class_linker = art::Runtime::Current()->GetClassLinker();
399 const art::DexFile& dex_file = class_linker->FindDexFile(
400 method->GetDeclaringClass()->GetDexCache());
401 const art::DexFile::CodeItem* code_item =
402 dex_file.GetCodeItem(method->GetCodeItemOffset());
403 int triesSize = code_item->tries_size_;
buzbee67bf8852011-08-17 17:51:35 -0700404 int offset;
405
406 if (triesSize == 0) {
407 return;
408 }
409
buzbee67bf8852011-08-17 17:51:35 -0700410 ArenaBitVector* tryBlockAddr = cUnit->tryBlockAddr;
411
buzbeee9a72f62011-09-04 17:59:07 -0700412 for (int i = 0; i < triesSize; i++) {
413 const art::DexFile::TryItem* pTry =
414 art::DexFile::dexGetTryItems(*code_item, i);
415 int startOffset = pTry->start_addr_;
416 int endOffset = startOffset + pTry->insn_count_;
buzbee67bf8852011-08-17 17:51:35 -0700417 for (offset = startOffset; offset < endOffset; offset++) {
418 oatSetBit(tryBlockAddr, offset);
419 }
420 }
421
buzbeee9a72f62011-09-04 17:59:07 -0700422 // Iterate over each of the handlers to enqueue the empty Catch blocks
423 const art::byte* handlers_ptr =
424 art::DexFile::dexGetCatchHandlerData(*code_item, 0);
425 uint32_t handlers_size = art::DecodeUnsignedLeb128(&handlers_ptr);
426 for (uint32_t idx = 0; idx < handlers_size; idx++) {
427 art::DexFile::CatchHandlerIterator iterator(handlers_ptr);
buzbee67bf8852011-08-17 17:51:35 -0700428
buzbeee9a72f62011-09-04 17:59:07 -0700429 for (; !iterator.HasNext(); iterator.Next()) {
430 uint32_t address = iterator.Get().address_;
431 findBlock(cUnit, address, false /* split */, true /*create*/);
buzbee67bf8852011-08-17 17:51:35 -0700432 }
buzbeee9a72f62011-09-04 17:59:07 -0700433 handlers_ptr = iterator.GetData();
buzbee67bf8852011-08-17 17:51:35 -0700434 }
435}
436
437/* Process instructions with the kInstrCanBranch flag */
438static void processCanBranch(CompilationUnit* cUnit, BasicBlock* curBlock,
439 MIR* insn, int curOffset, int width, int flags,
440 const u2* codePtr, const u2* codeEnd)
441{
442 int target = curOffset;
443 switch (insn->dalvikInsn.opcode) {
444 case OP_GOTO:
445 case OP_GOTO_16:
446 case OP_GOTO_32:
447 target += (int) insn->dalvikInsn.vA;
448 break;
449 case OP_IF_EQ:
450 case OP_IF_NE:
451 case OP_IF_LT:
452 case OP_IF_GE:
453 case OP_IF_GT:
454 case OP_IF_LE:
455 target += (int) insn->dalvikInsn.vC;
456 break;
457 case OP_IF_EQZ:
458 case OP_IF_NEZ:
459 case OP_IF_LTZ:
460 case OP_IF_GEZ:
461 case OP_IF_GTZ:
462 case OP_IF_LEZ:
463 target += (int) insn->dalvikInsn.vB;
464 break;
465 default:
466 LOG(FATAL) << "Unexpected opcode(" << (int)insn->dalvikInsn.opcode
467 << ") with kInstrCanBranch set";
468 }
469 BasicBlock *takenBlock = findBlock(cUnit, target,
470 /* split */
471 true,
472 /* create */
473 true);
474 curBlock->taken = takenBlock;
475 oatSetBit(takenBlock->predecessors, curBlock->id);
476
477 /* Always terminate the current block for conditional branches */
478 if (flags & kInstrCanContinue) {
479 BasicBlock *fallthroughBlock = findBlock(cUnit,
480 curOffset + width,
481 /*
482 * If the method is processed
483 * in sequential order from the
484 * beginning, we don't need to
485 * specify split for continue
486 * blocks. However, this
487 * routine can be called by
488 * compileLoop, which starts
489 * parsing the method from an
490 * arbitrary address in the
491 * method body.
492 */
493 true,
494 /* create */
495 true);
496 curBlock->fallThrough = fallthroughBlock;
497 oatSetBit(fallthroughBlock->predecessors, curBlock->id);
498 } else if (codePtr < codeEnd) {
499 /* Create a fallthrough block for real instructions (incl. OP_NOP) */
500 if (contentIsInsn(codePtr)) {
501 findBlock(cUnit, curOffset + width,
502 /* split */
503 false,
504 /* create */
505 true);
506 }
507 }
508}
509
510/* Process instructions with the kInstrCanSwitch flag */
511static void processCanSwitch(CompilationUnit* cUnit, BasicBlock* curBlock,
512 MIR* insn, int curOffset, int width, int flags)
513{
514 u2* switchData= (u2 *) (cUnit->insns + curOffset +
515 insn->dalvikInsn.vB);
516 int size;
517 int* keyTable;
518 int* targetTable;
519 int i;
520 int firstKey;
521
522 /*
523 * Packed switch data format:
524 * ushort ident = 0x0100 magic value
525 * ushort size number of entries in the table
526 * int first_key first (and lowest) switch case value
527 * int targets[size] branch targets, relative to switch opcode
528 *
529 * Total size is (4+size*2) 16-bit code units.
530 */
531 if (insn->dalvikInsn.opcode == OP_PACKED_SWITCH) {
532 assert(switchData[0] == kPackedSwitchSignature);
533 size = switchData[1];
534 firstKey = switchData[2] | (switchData[3] << 16);
535 targetTable = (int *) &switchData[4];
536 keyTable = NULL; // Make the compiler happy
537 /*
538 * Sparse switch data format:
539 * ushort ident = 0x0200 magic value
540 * ushort size number of entries in the table; > 0
541 * int keys[size] keys, sorted low-to-high; 32-bit aligned
542 * int targets[size] branch targets, relative to switch opcode
543 *
544 * Total size is (2+size*4) 16-bit code units.
545 */
546 } else {
547 assert(switchData[0] == kSparseSwitchSignature);
548 size = switchData[1];
549 keyTable = (int *) &switchData[2];
550 targetTable = (int *) &switchData[2 + size*2];
551 firstKey = 0; // To make the compiler happy
552 }
553
554 if (curBlock->successorBlockList.blockListType != kNotUsed) {
555 LOG(FATAL) << "Successor block list already in use: " <<
556 (int)curBlock->successorBlockList.blockListType;
557 }
558 curBlock->successorBlockList.blockListType =
559 (insn->dalvikInsn.opcode == OP_PACKED_SWITCH) ?
560 kPackedSwitch : kSparseSwitch;
561 oatInitGrowableList(&curBlock->successorBlockList.blocks, size);
562
563 for (i = 0; i < size; i++) {
564 BasicBlock *caseBlock = findBlock(cUnit, curOffset + targetTable[i],
565 /* split */
566 true,
567 /* create */
568 true);
569 SuccessorBlockInfo *successorBlockInfo =
570 (SuccessorBlockInfo *) oatNew(sizeof(SuccessorBlockInfo),
571 false);
572 successorBlockInfo->block = caseBlock;
573 successorBlockInfo->key = (insn->dalvikInsn.opcode == OP_PACKED_SWITCH)?
574 firstKey + i : keyTable[i];
575 oatInsertGrowableList(&curBlock->successorBlockList.blocks,
576 (intptr_t) successorBlockInfo);
577 oatSetBit(caseBlock->predecessors, curBlock->id);
578 }
579
580 /* Fall-through case */
581 BasicBlock* fallthroughBlock = findBlock(cUnit,
582 curOffset + width,
583 /* split */
584 false,
585 /* create */
586 true);
587 curBlock->fallThrough = fallthroughBlock;
588 oatSetBit(fallthroughBlock->predecessors, curBlock->id);
589}
590
591/* Process instructions with the kInstrCanThrow flag */
592static void processCanThrow(CompilationUnit* cUnit, BasicBlock* curBlock,
593 MIR* insn, int curOffset, int width, int flags,
594 ArenaBitVector* tryBlockAddr, const u2* codePtr,
595 const u2* codeEnd)
596{
buzbeee9a72f62011-09-04 17:59:07 -0700597
buzbee67bf8852011-08-17 17:51:35 -0700598 const Method* method = cUnit->method;
buzbeee9a72f62011-09-04 17:59:07 -0700599 art::ClassLinker* class_linker = art::Runtime::Current()->GetClassLinker();
600 const art::DexFile& dex_file = class_linker->FindDexFile(
601 method->GetDeclaringClass()->GetDexCache());
602 const art::DexFile::CodeItem* code_item =
603 dex_file.GetCodeItem(method->GetCodeItemOffset());
buzbee67bf8852011-08-17 17:51:35 -0700604
605 /* In try block */
606 if (oatIsBitSet(tryBlockAddr, curOffset)) {
buzbeee9a72f62011-09-04 17:59:07 -0700607 art::DexFile::CatchHandlerIterator iterator =
608 art::DexFile::dexFindCatchHandler(*code_item, curOffset);
buzbee67bf8852011-08-17 17:51:35 -0700609
buzbee67bf8852011-08-17 17:51:35 -0700610 if (curBlock->successorBlockList.blockListType != kNotUsed) {
611 LOG(FATAL) << "Successor block list already in use: " <<
612 (int)curBlock->successorBlockList.blockListType;
613 }
buzbeee9a72f62011-09-04 17:59:07 -0700614
buzbee67bf8852011-08-17 17:51:35 -0700615 curBlock->successorBlockList.blockListType = kCatch;
616 oatInitGrowableList(&curBlock->successorBlockList.blocks, 2);
617
buzbeee9a72f62011-09-04 17:59:07 -0700618 for (;!iterator.HasNext(); iterator.Next()) {
619 BasicBlock *catchBlock = findBlock(cUnit, iterator.Get().address_,
620 false /* split*/,
621 false /* creat */);
buzbee67bf8852011-08-17 17:51:35 -0700622 SuccessorBlockInfo *successorBlockInfo =
buzbeee9a72f62011-09-04 17:59:07 -0700623 (SuccessorBlockInfo *) oatNew(sizeof(SuccessorBlockInfo),
624 false);
buzbee67bf8852011-08-17 17:51:35 -0700625 successorBlockInfo->block = catchBlock;
buzbeee9a72f62011-09-04 17:59:07 -0700626 successorBlockInfo->key = iterator.Get().type_idx_;
buzbee67bf8852011-08-17 17:51:35 -0700627 oatInsertGrowableList(&curBlock->successorBlockList.blocks,
628 (intptr_t) successorBlockInfo);
629 oatSetBit(catchBlock->predecessors, curBlock->id);
630 }
631 } else {
632 BasicBlock *ehBlock = oatNewBB(kExceptionHandling,
633 cUnit->numBlocks++);
634 curBlock->taken = ehBlock;
635 oatInsertGrowableList(&cUnit->blockList, (intptr_t) ehBlock);
636 ehBlock->startOffset = curOffset;
637 oatSetBit(ehBlock->predecessors, curBlock->id);
638 }
639
640 /*
641 * Force the current block to terminate.
642 *
643 * Data may be present before codeEnd, so we need to parse it to know
644 * whether it is code or data.
645 */
646 if (codePtr < codeEnd) {
647 /* Create a fallthrough block for real instructions (incl. OP_NOP) */
648 if (contentIsInsn(codePtr)) {
649 BasicBlock *fallthroughBlock = findBlock(cUnit,
650 curOffset + width,
651 /* split */
652 false,
653 /* create */
654 true);
655 /*
656 * OP_THROW and OP_THROW_VERIFICATION_ERROR are unconditional
657 * branches.
658 */
659 if (insn->dalvikInsn.opcode != OP_THROW_VERIFICATION_ERROR &&
660 insn->dalvikInsn.opcode != OP_THROW) {
661 curBlock->fallThrough = fallthroughBlock;
662 oatSetBit(fallthroughBlock->predecessors, curBlock->id);
663 }
664 }
665 }
666}
667
668/*
669 * Compile a method.
670 */
buzbeec143c552011-08-20 17:38:58 -0700671bool oatCompileMethod(Method* method, art::InstructionSet insnSet)
buzbee67bf8852011-08-17 17:51:35 -0700672{
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700673 LOG(INFO) << "Compiling " << PrettyMethod(method) << "...";
buzbee2a475e72011-09-07 17:19:17 -0700674 oatArenaReset();
Brian Carlstrom94496d32011-08-22 09:22:47 -0700675
buzbee67bf8852011-08-17 17:51:35 -0700676 CompilationUnit cUnit;
buzbeec143c552011-08-20 17:38:58 -0700677 art::ClassLinker* class_linker = art::Runtime::Current()->GetClassLinker();
678 const art::DexFile& dex_file = class_linker->FindDexFile(
679 method->GetDeclaringClass()->GetDexCache());
680 const art::DexFile::CodeItem* code_item =
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700681 dex_file.GetCodeItem(method->GetCodeItemOffset());
buzbeec143c552011-08-20 17:38:58 -0700682 const u2* codePtr = code_item->insns_;
683 const u2* codeEnd = code_item->insns_ + code_item->insns_size_;
buzbee67bf8852011-08-17 17:51:35 -0700684 int numBlocks = 0;
685 unsigned int curOffset = 0;
686
687#if 1
688 // FIXME - temp 'till properly integrated
689 oatInit();
690#endif
691
692 memset(&cUnit, 0, sizeof(cUnit));
693 cUnit.method = method;
buzbeec143c552011-08-20 17:38:58 -0700694 cUnit.instructionSet = (OatInstructionSetType)insnSet;
695 cUnit.insns = code_item->insns_;
696 cUnit.insnsSize = code_item->insns_size_;
buzbee67bf8852011-08-17 17:51:35 -0700697#if 1
buzbee3ea4ec52011-08-22 17:37:19 -0700698 // TODO: Use command-line argument passing mechanism
buzbeee9a72f62011-09-04 17:59:07 -0700699 cUnit.printMe = false;
700 cUnit.printMeVerbose = false;
buzbee3ea4ec52011-08-22 17:37:19 -0700701 cUnit.disableOpt = 0 |
702 (1 << kLoadStoreElimination) |
703 (1 << kLoadHoisting) |
704 (1 << kTrackLiveTemps) |
705 (1 << kSuppressLoads) |
706 (1 << kPromoteRegs) |
707 0;
buzbee67bf8852011-08-17 17:51:35 -0700708#endif
709
710 /* Initialize the block list */
711 oatInitGrowableList(&cUnit.blockList, 40);
712
713 /* Initialize the switchTables list */
714 oatInitGrowableList(&cUnit.switchTables, 4);
715
716 /* Intialize the fillArrayData list */
717 oatInitGrowableList(&cUnit.fillArrayData, 4);
718
719 /* Allocate the bit-vector to track the beginning of basic blocks */
720 ArenaBitVector *tryBlockAddr = oatAllocBitVector(cUnit.insnsSize,
721 true /* expandable */);
722 cUnit.tryBlockAddr = tryBlockAddr;
723
724 /* Create the default entry and exit blocks and enter them to the list */
725 BasicBlock *entryBlock = oatNewBB(kEntryBlock, numBlocks++);
726 BasicBlock *exitBlock = oatNewBB(kExitBlock, numBlocks++);
727
728 cUnit.entryBlock = entryBlock;
729 cUnit.exitBlock = exitBlock;
730
731 oatInsertGrowableList(&cUnit.blockList, (intptr_t) entryBlock);
732 oatInsertGrowableList(&cUnit.blockList, (intptr_t) exitBlock);
733
734 /* Current block to record parsed instructions */
735 BasicBlock *curBlock = oatNewBB(kDalvikByteCode, numBlocks++);
736 curBlock->startOffset = 0;
737 oatInsertGrowableList(&cUnit.blockList, (intptr_t) curBlock);
738 entryBlock->fallThrough = curBlock;
739 oatSetBit(curBlock->predecessors, entryBlock->id);
740
741 /*
742 * Store back the number of blocks since new blocks may be created of
743 * accessing cUnit.
744 */
745 cUnit.numBlocks = numBlocks;
746
747 /* Identify code range in try blocks and set up the empty catch blocks */
748 processTryCatchBlocks(&cUnit);
749
750 /* Parse all instructions and put them into containing basic blocks */
751 while (codePtr < codeEnd) {
752 MIR *insn = (MIR *) oatNew(sizeof(MIR), true);
753 insn->offset = curOffset;
754 int width = parseInsn(codePtr, &insn->dalvikInsn, false);
755 insn->width = width;
756
757 /* Terminate when the data section is seen */
758 if (width == 0)
759 break;
760
761 oatAppendMIR(curBlock, insn);
762
763 codePtr += width;
764 int flags = dexGetFlagsFromOpcode(insn->dalvikInsn.opcode);
765
766 if (flags & kInstrCanBranch) {
767 processCanBranch(&cUnit, curBlock, insn, curOffset, width, flags,
768 codePtr, codeEnd);
769 } else if (flags & kInstrCanReturn) {
770 curBlock->fallThrough = exitBlock;
771 oatSetBit(exitBlock->predecessors, curBlock->id);
772 /*
773 * Terminate the current block if there are instructions
774 * afterwards.
775 */
776 if (codePtr < codeEnd) {
777 /*
778 * Create a fallthrough block for real instructions
779 * (incl. OP_NOP).
780 */
781 if (contentIsInsn(codePtr)) {
782 findBlock(&cUnit, curOffset + width,
783 /* split */
784 false,
785 /* create */
786 true);
787 }
788 }
789 } else if (flags & kInstrCanThrow) {
790 processCanThrow(&cUnit, curBlock, insn, curOffset, width, flags,
791 tryBlockAddr, codePtr, codeEnd);
792 } else if (flags & kInstrCanSwitch) {
793 processCanSwitch(&cUnit, curBlock, insn, curOffset, width, flags);
794 }
795 curOffset += width;
796 BasicBlock *nextBlock = findBlock(&cUnit, curOffset,
797 /* split */
798 false,
799 /* create */
800 false);
801 if (nextBlock) {
802 /*
803 * The next instruction could be the target of a previously parsed
804 * forward branch so a block is already created. If the current
805 * instruction is not an unconditional branch, connect them through
806 * the fall-through link.
807 */
808 assert(curBlock->fallThrough == NULL ||
809 curBlock->fallThrough == nextBlock ||
810 curBlock->fallThrough == exitBlock);
811
812 if ((curBlock->fallThrough == NULL) &&
813 (flags & kInstrCanContinue)) {
814 curBlock->fallThrough = nextBlock;
815 oatSetBit(nextBlock->predecessors, curBlock->id);
816 }
817 curBlock = nextBlock;
818 }
819 }
820
821 if (cUnit.printMe) {
822 oatDumpCompilationUnit(&cUnit);
823 }
824
825 /* Adjust this value accordingly once inlining is performed */
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700826 cUnit.numDalvikRegisters = cUnit.method->NumRegisters();
buzbee67bf8852011-08-17 17:51:35 -0700827
828
829 /* Verify if all blocks are connected as claimed */
830 oatDataFlowAnalysisDispatcher(&cUnit, verifyPredInfo,
831 kAllNodes,
832 false /* isIterative */);
833
834
835
836 /* Perform SSA transformation for the whole method */
837 oatMethodSSATransformation(&cUnit);
838
839 oatInitializeRegAlloc(&cUnit); // Needs to happen after SSA naming
840
841 /* Allocate Registers using simple local allocation scheme */
842 oatSimpleRegAlloc(&cUnit);
843
844 /* Convert MIR to LIR, etc. */
845 oatMethodMIR2LIR(&cUnit);
846
847 // Debugging only
848 //oatDumpCFG(&cUnit, "/sdcard/cfg/");
849
850 /* Method is not empty */
851 if (cUnit.firstLIRInsn) {
852
853 // mark the targets of switch statement case labels
854 oatProcessSwitchTables(&cUnit);
855
856 /* Convert LIR into machine code. */
857 oatAssembleLIR(&cUnit);
858
859 if (cUnit.printMe) {
860 oatCodegenDump(&cUnit);
861 }
862 }
863
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700864 art::ByteArray* managed_code = art::ByteArray::Alloc(cUnit.codeBuffer.size() * 2);
865 memcpy(managed_code->GetData(),
866 reinterpret_cast<const int8_t*>(&cUnit.codeBuffer[0]),
867 managed_code->GetLength());
868 method->SetCode(managed_code, art::kThumb2);
Shih-wei Liaod11af152011-08-23 16:02:11 -0700869 method->SetFrameSizeInBytes(cUnit.frameSize);
buzbeec143c552011-08-20 17:38:58 -0700870 method->SetCoreSpillMask(cUnit.coreSpillMask);
871 method->SetFpSpillMask(cUnit.fpSpillMask);
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700872 LOG(INFO) << "Compiled " << PrettyMethod(method)
873 << " code at " << reinterpret_cast<void*>(managed_code->GetData())
874 << " (" << managed_code->GetLength() << " bytes)";
buzbeec143c552011-08-20 17:38:58 -0700875 // TODO: Transmit mapping table to caller
buzbee67bf8852011-08-17 17:51:35 -0700876
877#if 0
878 oatDumpCFG(&cUnit, "/sdcard/cfg/");
879#endif
880
Brian Carlstrombffb1552011-08-25 12:23:53 -0700881 return true;
buzbee67bf8852011-08-17 17:51:35 -0700882}
883
884void oatInit(void)
885{
886#if 1
887 // FIXME - temp hack 'till properly integrated
888 static bool initialized = false;
889 if (initialized)
890 return;
891 initialized = true;
892 LOG(INFO) << "Initializing compiler";
893#endif
894 if (!oatArchInit()) {
895 LOG(FATAL) << "Failed to initialize oat";
896 }
897 if (!oatHeapInit()) {
898 LOG(FATAL) << "Failed to initialize oat heap";
899 }
900}