blob: 9a2cc3107934867920f15e99990508d63ea8a53d [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"
Ian Rogers0571d352011-11-03 19:51:38 -070021#include "leb128.h"
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -070022#include "object.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070023#include "runtime.h"
buzbee67bf8852011-08-17 17:51:35 -070024
buzbeece302932011-10-04 14:32:18 -070025/* Default optimizer/debug setting for the compiler. */
26uint32_t compilerOptimizerDisableFlags = 0 | // Disable specific optimizations
buzbee67bc2362011-10-11 18:08:40 -070027 //(1 << kLoadStoreElimination) |
28 //(1 << kLoadHoisting) |
29 //(1 << kSuppressLoads) |
30 //(1 << kNullCheckElimination) |
buzbeeb7990c72011-10-31 15:29:33 -070031 (1 << kPromoteRegs) |
32 (1 << kTrackLiveTemps) |
buzbeece302932011-10-04 14:32:18 -070033 0;
34
35uint32_t compilerDebugFlags = 0 | // Enable debug/testing modes
buzbeee3de7492011-10-05 13:37:17 -070036 //(1 << kDebugDisplayMissingTargets) |
buzbeece302932011-10-04 14:32:18 -070037 //(1 << kDebugVerbose) |
38 //(1 << kDebugDumpCFG) |
39 //(1 << kDebugSlowFieldPath) |
40 //(1 << kDebugSlowInvokePath) |
41 //(1 << kDebugSlowStringPath) |
42 //(1 << kDebugSlowestFieldPath) |
43 //(1 << kDebugSlowestStringPath) |
44 0;
45
46std::string compilerMethodMatch; // Method name match to apply above flags
47
48bool compilerFlipMatch = false; // Reverses sense of method name match
49
buzbeeed3e9302011-09-23 17:34:19 -070050STATIC inline bool contentIsInsn(const u2* codePtr) {
buzbee67bf8852011-08-17 17:51:35 -070051 u2 instr = *codePtr;
52 Opcode opcode = (Opcode)(instr & 0xff);
53
54 /*
55 * Since the low 8-bit in metadata may look like OP_NOP, we need to check
56 * both the low and whole sub-word to determine whether it is code or data.
57 */
58 return (opcode != OP_NOP || instr == 0);
59}
60
61/*
62 * Parse an instruction, return the length of the instruction
63 */
buzbeeed3e9302011-09-23 17:34:19 -070064STATIC inline int parseInsn(const u2* codePtr, DecodedInstruction* decInsn,
buzbee67bf8852011-08-17 17:51:35 -070065 bool printMe)
66{
67 // Don't parse instruction data
68 if (!contentIsInsn(codePtr)) {
69 return 0;
70 }
71
72 u2 instr = *codePtr;
73 Opcode opcode = dexOpcodeFromCodeUnit(instr);
74
75 dexDecodeInstruction(codePtr, decInsn);
76 if (printMe) {
77 char *decodedString = oatGetDalvikDisassembly(decInsn, NULL);
78 LOG(INFO) << codePtr << ": 0x" << std::hex << (int)opcode <<
79 " " << decodedString;
80 }
81 return dexGetWidthFromOpcode(opcode);
82}
83
84#define UNKNOWN_TARGET 0xffffffff
85
buzbeeed3e9302011-09-23 17:34:19 -070086STATIC inline bool isGoto(MIR* insn)
buzbee67bf8852011-08-17 17:51:35 -070087{
88 switch (insn->dalvikInsn.opcode) {
89 case OP_GOTO:
90 case OP_GOTO_16:
91 case OP_GOTO_32:
92 return true;
93 default:
94 return false;
95 }
96}
97
98/*
99 * Identify unconditional branch instructions
100 */
buzbeeed3e9302011-09-23 17:34:19 -0700101STATIC inline bool isUnconditionalBranch(MIR* insn)
buzbee67bf8852011-08-17 17:51:35 -0700102{
103 switch (insn->dalvikInsn.opcode) {
104 case OP_RETURN_VOID:
105 case OP_RETURN:
106 case OP_RETURN_WIDE:
107 case OP_RETURN_OBJECT:
108 return true;
109 default:
110 return isGoto(insn);
111 }
112}
113
114/* Split an existing block from the specified code offset into two */
buzbeeed3e9302011-09-23 17:34:19 -0700115STATIC BasicBlock *splitBlock(CompilationUnit* cUnit,
buzbee67bf8852011-08-17 17:51:35 -0700116 unsigned int codeOffset,
117 BasicBlock* origBlock)
118{
119 MIR* insn = origBlock->firstMIRInsn;
120 while (insn) {
121 if (insn->offset == codeOffset) break;
122 insn = insn->next;
123 }
124 if (insn == NULL) {
125 LOG(FATAL) << "Break split failed";
126 }
127 BasicBlock *bottomBlock = oatNewBB(kDalvikByteCode,
128 cUnit->numBlocks++);
129 oatInsertGrowableList(&cUnit->blockList, (intptr_t) bottomBlock);
130
131 bottomBlock->startOffset = codeOffset;
132 bottomBlock->firstMIRInsn = insn;
133 bottomBlock->lastMIRInsn = origBlock->lastMIRInsn;
134
135 /* Handle the taken path */
136 bottomBlock->taken = origBlock->taken;
137 if (bottomBlock->taken) {
138 origBlock->taken = NULL;
139 oatClearBit(bottomBlock->taken->predecessors, origBlock->id);
140 oatSetBit(bottomBlock->taken->predecessors, bottomBlock->id);
141 }
142
143 /* Handle the fallthrough path */
144 bottomBlock->needFallThroughBranch = origBlock->needFallThroughBranch;
145 bottomBlock->fallThrough = origBlock->fallThrough;
146 origBlock->fallThrough = bottomBlock;
147 origBlock->needFallThroughBranch = true;
148 oatSetBit(bottomBlock->predecessors, origBlock->id);
149 if (bottomBlock->fallThrough) {
150 oatClearBit(bottomBlock->fallThrough->predecessors,
151 origBlock->id);
152 oatSetBit(bottomBlock->fallThrough->predecessors,
153 bottomBlock->id);
154 }
155
156 /* Handle the successor list */
157 if (origBlock->successorBlockList.blockListType != kNotUsed) {
158 bottomBlock->successorBlockList = origBlock->successorBlockList;
159 origBlock->successorBlockList.blockListType = kNotUsed;
160 GrowableListIterator iterator;
161
162 oatGrowableListIteratorInit(&bottomBlock->successorBlockList.blocks,
163 &iterator);
164 while (true) {
165 SuccessorBlockInfo *successorBlockInfo =
166 (SuccessorBlockInfo *) oatGrowableListIteratorNext(&iterator);
167 if (successorBlockInfo == NULL) break;
168 BasicBlock *bb = successorBlockInfo->block;
169 oatClearBit(bb->predecessors, origBlock->id);
170 oatSetBit(bb->predecessors, bottomBlock->id);
171 }
172 }
173
174 origBlock->lastMIRInsn = insn->prev;
175
176 insn->prev->next = NULL;
177 insn->prev = NULL;
178 return bottomBlock;
179}
180
181/*
182 * Given a code offset, find out the block that starts with it. If the offset
183 * is in the middle of an existing block, split it into two.
184 */
buzbeeed3e9302011-09-23 17:34:19 -0700185STATIC BasicBlock *findBlock(CompilationUnit* cUnit,
buzbee67bf8852011-08-17 17:51:35 -0700186 unsigned int codeOffset,
187 bool split, bool create)
188{
189 GrowableList* blockList = &cUnit->blockList;
190 BasicBlock* bb;
191 unsigned int i;
192
193 for (i = 0; i < blockList->numUsed; i++) {
194 bb = (BasicBlock *) blockList->elemList[i];
195 if (bb->blockType != kDalvikByteCode) continue;
196 if (bb->startOffset == codeOffset) return bb;
197 /* Check if a branch jumps into the middle of an existing block */
198 if ((split == true) && (codeOffset > bb->startOffset) &&
199 (bb->lastMIRInsn != NULL) &&
200 (codeOffset <= bb->lastMIRInsn->offset)) {
201 BasicBlock *newBB = splitBlock(cUnit, codeOffset, bb);
202 return newBB;
203 }
204 }
205 if (create) {
206 bb = oatNewBB(kDalvikByteCode, cUnit->numBlocks++);
207 oatInsertGrowableList(&cUnit->blockList, (intptr_t) bb);
208 bb->startOffset = codeOffset;
209 return bb;
210 }
211 return NULL;
212}
213
214/* Dump the CFG into a DOT graph */
215void oatDumpCFG(CompilationUnit* cUnit, const char* dirPrefix)
216{
buzbee67bf8852011-08-17 17:51:35 -0700217 FILE* file;
buzbeedfd3d702011-08-28 12:56:51 -0700218 std::string name = art::PrettyMethod(cUnit->method);
buzbee67bf8852011-08-17 17:51:35 -0700219 char startOffset[80];
220 sprintf(startOffset, "_%x", cUnit->entryBlock->fallThrough->startOffset);
221 char* fileName = (char *) oatNew(
buzbeec143c552011-08-20 17:38:58 -0700222 strlen(dirPrefix) +
223 name.length() +
224 strlen(".dot") + 1, true);
225 sprintf(fileName, "%s%s%s.dot", dirPrefix, name.c_str(), startOffset);
buzbee67bf8852011-08-17 17:51:35 -0700226
227 /*
228 * Convert the special characters into a filesystem- and shell-friendly
229 * format.
230 */
231 int i;
232 for (i = strlen(dirPrefix); fileName[i]; i++) {
233 if (fileName[i] == '/') {
234 fileName[i] = '_';
235 } else if (fileName[i] == ';') {
236 fileName[i] = '#';
237 } else if (fileName[i] == '$') {
238 fileName[i] = '+';
239 } else if (fileName[i] == '(' || fileName[i] == ')') {
240 fileName[i] = '@';
241 } else if (fileName[i] == '<' || fileName[i] == '>') {
242 fileName[i] = '=';
243 }
244 }
245 file = fopen(fileName, "w");
246 if (file == NULL) {
247 return;
248 }
249 fprintf(file, "digraph G {\n");
250
251 fprintf(file, " rankdir=TB\n");
252
253 int numReachableBlocks = cUnit->numReachableBlocks;
254 int idx;
255 const GrowableList *blockList = &cUnit->blockList;
256
257 for (idx = 0; idx < numReachableBlocks; idx++) {
258 int blockIdx = cUnit->dfsOrder.elemList[idx];
259 BasicBlock *bb = (BasicBlock *) oatGrowableListGetElement(blockList,
260 blockIdx);
261 if (bb == NULL) break;
262 if (bb->blockType == kEntryBlock) {
263 fprintf(file, " entry [shape=Mdiamond];\n");
264 } else if (bb->blockType == kExitBlock) {
265 fprintf(file, " exit [shape=Mdiamond];\n");
266 } else if (bb->blockType == kDalvikByteCode) {
267 fprintf(file, " block%04x [shape=record,label = \"{ \\\n",
268 bb->startOffset);
269 const MIR *mir;
270 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
271 bb->firstMIRInsn ? " | " : " ");
272 for (mir = bb->firstMIRInsn; mir; mir = mir->next) {
273 fprintf(file, " {%04x %s\\l}%s\\\n", mir->offset,
274 mir->ssaRep ?
275 oatFullDisassembler(cUnit, mir) :
276 dexGetOpcodeName(mir->dalvikInsn.opcode),
277 mir->next ? " | " : " ");
278 }
279 fprintf(file, " }\"];\n\n");
280 } else if (bb->blockType == kExceptionHandling) {
281 char blockName[BLOCK_NAME_LEN];
282
283 oatGetBlockName(bb, blockName);
284 fprintf(file, " %s [shape=invhouse];\n", blockName);
285 }
286
287 char blockName1[BLOCK_NAME_LEN], blockName2[BLOCK_NAME_LEN];
288
289 if (bb->taken) {
290 oatGetBlockName(bb, blockName1);
291 oatGetBlockName(bb->taken, blockName2);
292 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
293 blockName1, blockName2);
294 }
295 if (bb->fallThrough) {
296 oatGetBlockName(bb, blockName1);
297 oatGetBlockName(bb->fallThrough, blockName2);
298 fprintf(file, " %s:s -> %s:n\n", blockName1, blockName2);
299 }
300
301 if (bb->successorBlockList.blockListType != kNotUsed) {
302 fprintf(file, " succ%04x [shape=%s,label = \"{ \\\n",
303 bb->startOffset,
304 (bb->successorBlockList.blockListType == kCatch) ?
305 "Mrecord" : "record");
306 GrowableListIterator iterator;
307 oatGrowableListIteratorInit(&bb->successorBlockList.blocks,
308 &iterator);
309 SuccessorBlockInfo *successorBlockInfo =
310 (SuccessorBlockInfo *) oatGrowableListIteratorNext(&iterator);
311
312 int succId = 0;
313 while (true) {
314 if (successorBlockInfo == NULL) break;
315
316 BasicBlock *destBlock = successorBlockInfo->block;
317 SuccessorBlockInfo *nextSuccessorBlockInfo =
318 (SuccessorBlockInfo *) oatGrowableListIteratorNext(&iterator);
319
320 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
321 succId++,
322 successorBlockInfo->key,
323 destBlock->startOffset,
324 (nextSuccessorBlockInfo != NULL) ? " | " : " ");
325
326 successorBlockInfo = nextSuccessorBlockInfo;
327 }
328 fprintf(file, " }\"];\n\n");
329
330 oatGetBlockName(bb, blockName1);
331 fprintf(file, " %s:s -> succ%04x:n [style=dashed]\n",
332 blockName1, bb->startOffset);
333
334 if (bb->successorBlockList.blockListType == kPackedSwitch ||
335 bb->successorBlockList.blockListType == kSparseSwitch) {
336
337 oatGrowableListIteratorInit(&bb->successorBlockList.blocks,
338 &iterator);
339
340 succId = 0;
341 while (true) {
342 SuccessorBlockInfo *successorBlockInfo =
343 (SuccessorBlockInfo *)
344 oatGrowableListIteratorNext(&iterator);
345 if (successorBlockInfo == NULL) break;
346
347 BasicBlock *destBlock = successorBlockInfo->block;
348
349 oatGetBlockName(destBlock, blockName2);
350 fprintf(file, " succ%04x:f%d:e -> %s:n\n",
351 bb->startOffset, succId++,
352 blockName2);
353 }
354 }
355 }
356 fprintf(file, "\n");
357
buzbeece302932011-10-04 14:32:18 -0700358 /* Display the dominator tree */
buzbee67bf8852011-08-17 17:51:35 -0700359 oatGetBlockName(bb, blockName1);
360 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
361 blockName1, blockName1);
362 if (bb->iDom) {
363 oatGetBlockName(bb->iDom, blockName2);
364 fprintf(file, " cfg%s:s -> cfg%s:n\n\n",
365 blockName2, blockName1);
366 }
buzbee67bf8852011-08-17 17:51:35 -0700367 }
368 fprintf(file, "}\n");
369 fclose(file);
370}
371
372/* Verify if all the successor is connected with all the claimed predecessors */
buzbeeed3e9302011-09-23 17:34:19 -0700373STATIC bool verifyPredInfo(CompilationUnit* cUnit, BasicBlock* bb)
buzbee67bf8852011-08-17 17:51:35 -0700374{
375 ArenaBitVectorIterator bvIterator;
376
377 oatBitVectorIteratorInit(bb->predecessors, &bvIterator);
378 while (true) {
379 int blockIdx = oatBitVectorIteratorNext(&bvIterator);
380 if (blockIdx == -1) break;
381 BasicBlock *predBB = (BasicBlock *)
382 oatGrowableListGetElement(&cUnit->blockList, blockIdx);
383 bool found = false;
384 if (predBB->taken == bb) {
385 found = true;
386 } else if (predBB->fallThrough == bb) {
387 found = true;
388 } else if (predBB->successorBlockList.blockListType != kNotUsed) {
389 GrowableListIterator iterator;
390 oatGrowableListIteratorInit(&predBB->successorBlockList.blocks,
391 &iterator);
392 while (true) {
393 SuccessorBlockInfo *successorBlockInfo =
394 (SuccessorBlockInfo *)
395 oatGrowableListIteratorNext(&iterator);
396 if (successorBlockInfo == NULL) break;
397 BasicBlock *succBB = successorBlockInfo->block;
398 if (succBB == bb) {
399 found = true;
400 break;
401 }
402 }
403 }
404 if (found == false) {
405 char blockName1[BLOCK_NAME_LEN], blockName2[BLOCK_NAME_LEN];
406 oatGetBlockName(bb, blockName1);
407 oatGetBlockName(predBB, blockName2);
408 oatDumpCFG(cUnit, "/sdcard/cfg/");
409 LOG(FATAL) << "Successor " << blockName1 << "not found from "
410 << blockName2;
411 }
412 }
413 return true;
414}
415
416/* Identify code range in try blocks and set up the empty catch blocks */
buzbeeed3e9302011-09-23 17:34:19 -0700417STATIC void processTryCatchBlocks(CompilationUnit* cUnit)
buzbee67bf8852011-08-17 17:51:35 -0700418{
buzbeee9a72f62011-09-04 17:59:07 -0700419 const Method* method = cUnit->method;
420 art::ClassLinker* class_linker = art::Runtime::Current()->GetClassLinker();
421 const art::DexFile& dex_file = class_linker->FindDexFile(
422 method->GetDeclaringClass()->GetDexCache());
423 const art::DexFile::CodeItem* code_item =
424 dex_file.GetCodeItem(method->GetCodeItemOffset());
425 int triesSize = code_item->tries_size_;
buzbee67bf8852011-08-17 17:51:35 -0700426 int offset;
427
428 if (triesSize == 0) {
429 return;
430 }
431
buzbee67bf8852011-08-17 17:51:35 -0700432 ArenaBitVector* tryBlockAddr = cUnit->tryBlockAddr;
433
buzbeee9a72f62011-09-04 17:59:07 -0700434 for (int i = 0; i < triesSize; i++) {
435 const art::DexFile::TryItem* pTry =
Ian Rogers0571d352011-11-03 19:51:38 -0700436 art::DexFile::GetTryItems(*code_item, i);
buzbeee9a72f62011-09-04 17:59:07 -0700437 int startOffset = pTry->start_addr_;
438 int endOffset = startOffset + pTry->insn_count_;
buzbee67bf8852011-08-17 17:51:35 -0700439 for (offset = startOffset; offset < endOffset; offset++) {
440 oatSetBit(tryBlockAddr, offset);
441 }
442 }
443
buzbeee9a72f62011-09-04 17:59:07 -0700444 // Iterate over each of the handlers to enqueue the empty Catch blocks
445 const art::byte* handlers_ptr =
Ian Rogers0571d352011-11-03 19:51:38 -0700446 art::DexFile::GetCatchHandlerData(*code_item, 0);
buzbeee9a72f62011-09-04 17:59:07 -0700447 uint32_t handlers_size = art::DecodeUnsignedLeb128(&handlers_ptr);
448 for (uint32_t idx = 0; idx < handlers_size; idx++) {
Ian Rogers0571d352011-11-03 19:51:38 -0700449 art::CatchHandlerIterator iterator(handlers_ptr);
450 for (; iterator.HasNext(); iterator.Next()) {
451 uint32_t address = iterator.GetHandlerAddress();
buzbeee9a72f62011-09-04 17:59:07 -0700452 findBlock(cUnit, address, false /* split */, true /*create*/);
buzbee67bf8852011-08-17 17:51:35 -0700453 }
Ian Rogers0571d352011-11-03 19:51:38 -0700454 handlers_ptr = iterator.EndDataPointer();
buzbee67bf8852011-08-17 17:51:35 -0700455 }
456}
457
458/* Process instructions with the kInstrCanBranch flag */
buzbeeed3e9302011-09-23 17:34:19 -0700459STATIC void processCanBranch(CompilationUnit* cUnit, BasicBlock* curBlock,
buzbee67bf8852011-08-17 17:51:35 -0700460 MIR* insn, int curOffset, int width, int flags,
461 const u2* codePtr, const u2* codeEnd)
462{
463 int target = curOffset;
464 switch (insn->dalvikInsn.opcode) {
465 case OP_GOTO:
466 case OP_GOTO_16:
467 case OP_GOTO_32:
468 target += (int) insn->dalvikInsn.vA;
469 break;
470 case OP_IF_EQ:
471 case OP_IF_NE:
472 case OP_IF_LT:
473 case OP_IF_GE:
474 case OP_IF_GT:
475 case OP_IF_LE:
476 target += (int) insn->dalvikInsn.vC;
477 break;
478 case OP_IF_EQZ:
479 case OP_IF_NEZ:
480 case OP_IF_LTZ:
481 case OP_IF_GEZ:
482 case OP_IF_GTZ:
483 case OP_IF_LEZ:
484 target += (int) insn->dalvikInsn.vB;
485 break;
486 default:
487 LOG(FATAL) << "Unexpected opcode(" << (int)insn->dalvikInsn.opcode
488 << ") with kInstrCanBranch set";
489 }
490 BasicBlock *takenBlock = findBlock(cUnit, target,
491 /* split */
492 true,
493 /* create */
494 true);
495 curBlock->taken = takenBlock;
496 oatSetBit(takenBlock->predecessors, curBlock->id);
497
498 /* Always terminate the current block for conditional branches */
499 if (flags & kInstrCanContinue) {
500 BasicBlock *fallthroughBlock = findBlock(cUnit,
501 curOffset + width,
502 /*
503 * If the method is processed
504 * in sequential order from the
505 * beginning, we don't need to
506 * specify split for continue
507 * blocks. However, this
508 * routine can be called by
509 * compileLoop, which starts
510 * parsing the method from an
511 * arbitrary address in the
512 * method body.
513 */
514 true,
515 /* create */
516 true);
517 curBlock->fallThrough = fallthroughBlock;
518 oatSetBit(fallthroughBlock->predecessors, curBlock->id);
519 } else if (codePtr < codeEnd) {
520 /* Create a fallthrough block for real instructions (incl. OP_NOP) */
521 if (contentIsInsn(codePtr)) {
522 findBlock(cUnit, curOffset + width,
523 /* split */
524 false,
525 /* create */
526 true);
527 }
528 }
529}
530
531/* Process instructions with the kInstrCanSwitch flag */
buzbeeed3e9302011-09-23 17:34:19 -0700532STATIC void processCanSwitch(CompilationUnit* cUnit, BasicBlock* curBlock,
buzbee67bf8852011-08-17 17:51:35 -0700533 MIR* insn, int curOffset, int width, int flags)
534{
535 u2* switchData= (u2 *) (cUnit->insns + curOffset +
536 insn->dalvikInsn.vB);
537 int size;
538 int* keyTable;
539 int* targetTable;
540 int i;
541 int firstKey;
542
543 /*
544 * Packed switch data format:
545 * ushort ident = 0x0100 magic value
546 * ushort size number of entries in the table
547 * int first_key first (and lowest) switch case value
548 * int targets[size] branch targets, relative to switch opcode
549 *
550 * Total size is (4+size*2) 16-bit code units.
551 */
552 if (insn->dalvikInsn.opcode == OP_PACKED_SWITCH) {
buzbeeed3e9302011-09-23 17:34:19 -0700553 DCHECK_EQ(switchData[0], kPackedSwitchSignature);
buzbee67bf8852011-08-17 17:51:35 -0700554 size = switchData[1];
555 firstKey = switchData[2] | (switchData[3] << 16);
556 targetTable = (int *) &switchData[4];
557 keyTable = NULL; // Make the compiler happy
558 /*
559 * Sparse switch data format:
560 * ushort ident = 0x0200 magic value
561 * ushort size number of entries in the table; > 0
562 * int keys[size] keys, sorted low-to-high; 32-bit aligned
563 * int targets[size] branch targets, relative to switch opcode
564 *
565 * Total size is (2+size*4) 16-bit code units.
566 */
567 } else {
buzbeeed3e9302011-09-23 17:34:19 -0700568 DCHECK_EQ(switchData[0], kSparseSwitchSignature);
buzbee67bf8852011-08-17 17:51:35 -0700569 size = switchData[1];
570 keyTable = (int *) &switchData[2];
571 targetTable = (int *) &switchData[2 + size*2];
572 firstKey = 0; // To make the compiler happy
573 }
574
575 if (curBlock->successorBlockList.blockListType != kNotUsed) {
576 LOG(FATAL) << "Successor block list already in use: " <<
577 (int)curBlock->successorBlockList.blockListType;
578 }
579 curBlock->successorBlockList.blockListType =
580 (insn->dalvikInsn.opcode == OP_PACKED_SWITCH) ?
581 kPackedSwitch : kSparseSwitch;
582 oatInitGrowableList(&curBlock->successorBlockList.blocks, size);
583
584 for (i = 0; i < size; i++) {
585 BasicBlock *caseBlock = findBlock(cUnit, curOffset + targetTable[i],
586 /* split */
587 true,
588 /* create */
589 true);
590 SuccessorBlockInfo *successorBlockInfo =
591 (SuccessorBlockInfo *) oatNew(sizeof(SuccessorBlockInfo),
592 false);
593 successorBlockInfo->block = caseBlock;
594 successorBlockInfo->key = (insn->dalvikInsn.opcode == OP_PACKED_SWITCH)?
595 firstKey + i : keyTable[i];
596 oatInsertGrowableList(&curBlock->successorBlockList.blocks,
597 (intptr_t) successorBlockInfo);
598 oatSetBit(caseBlock->predecessors, curBlock->id);
599 }
600
601 /* Fall-through case */
602 BasicBlock* fallthroughBlock = findBlock(cUnit,
603 curOffset + width,
604 /* split */
605 false,
606 /* create */
607 true);
608 curBlock->fallThrough = fallthroughBlock;
609 oatSetBit(fallthroughBlock->predecessors, curBlock->id);
610}
611
612/* Process instructions with the kInstrCanThrow flag */
buzbeeed3e9302011-09-23 17:34:19 -0700613STATIC void processCanThrow(CompilationUnit* cUnit, BasicBlock* curBlock,
buzbee67bf8852011-08-17 17:51:35 -0700614 MIR* insn, int curOffset, int width, int flags,
615 ArenaBitVector* tryBlockAddr, const u2* codePtr,
616 const u2* codeEnd)
617{
buzbeee9a72f62011-09-04 17:59:07 -0700618
buzbee67bf8852011-08-17 17:51:35 -0700619 const Method* method = cUnit->method;
buzbeee9a72f62011-09-04 17:59:07 -0700620 art::ClassLinker* class_linker = art::Runtime::Current()->GetClassLinker();
621 const art::DexFile& dex_file = class_linker->FindDexFile(
622 method->GetDeclaringClass()->GetDexCache());
623 const art::DexFile::CodeItem* code_item =
624 dex_file.GetCodeItem(method->GetCodeItemOffset());
buzbee67bf8852011-08-17 17:51:35 -0700625
626 /* In try block */
627 if (oatIsBitSet(tryBlockAddr, curOffset)) {
Ian Rogers0571d352011-11-03 19:51:38 -0700628 art::CatchHandlerIterator iterator(*code_item, curOffset);
buzbee67bf8852011-08-17 17:51:35 -0700629
buzbee67bf8852011-08-17 17:51:35 -0700630 if (curBlock->successorBlockList.blockListType != kNotUsed) {
631 LOG(FATAL) << "Successor block list already in use: " <<
632 (int)curBlock->successorBlockList.blockListType;
633 }
buzbeee9a72f62011-09-04 17:59:07 -0700634
buzbee67bf8852011-08-17 17:51:35 -0700635 curBlock->successorBlockList.blockListType = kCatch;
636 oatInitGrowableList(&curBlock->successorBlockList.blocks, 2);
637
Ian Rogers0571d352011-11-03 19:51:38 -0700638 for (;iterator.HasNext(); iterator.Next()) {
639 BasicBlock *catchBlock = findBlock(cUnit, iterator.GetHandlerAddress(),
buzbeee9a72f62011-09-04 17:59:07 -0700640 false /* split*/,
641 false /* creat */);
buzbee43a36422011-09-14 14:00:13 -0700642 catchBlock->catchEntry = true;
buzbee67bf8852011-08-17 17:51:35 -0700643 SuccessorBlockInfo *successorBlockInfo =
buzbeee9a72f62011-09-04 17:59:07 -0700644 (SuccessorBlockInfo *) oatNew(sizeof(SuccessorBlockInfo),
645 false);
buzbee67bf8852011-08-17 17:51:35 -0700646 successorBlockInfo->block = catchBlock;
Ian Rogers0571d352011-11-03 19:51:38 -0700647 successorBlockInfo->key = iterator.GetHandlerTypeIndex();
buzbee67bf8852011-08-17 17:51:35 -0700648 oatInsertGrowableList(&curBlock->successorBlockList.blocks,
649 (intptr_t) successorBlockInfo);
650 oatSetBit(catchBlock->predecessors, curBlock->id);
651 }
652 } else {
653 BasicBlock *ehBlock = oatNewBB(kExceptionHandling,
654 cUnit->numBlocks++);
655 curBlock->taken = ehBlock;
656 oatInsertGrowableList(&cUnit->blockList, (intptr_t) ehBlock);
657 ehBlock->startOffset = curOffset;
658 oatSetBit(ehBlock->predecessors, curBlock->id);
659 }
660
661 /*
662 * Force the current block to terminate.
663 *
664 * Data may be present before codeEnd, so we need to parse it to know
665 * whether it is code or data.
666 */
667 if (codePtr < codeEnd) {
668 /* Create a fallthrough block for real instructions (incl. OP_NOP) */
669 if (contentIsInsn(codePtr)) {
670 BasicBlock *fallthroughBlock = findBlock(cUnit,
671 curOffset + width,
672 /* split */
673 false,
674 /* create */
675 true);
676 /*
buzbee510c6052011-10-27 10:47:20 -0700677 * OP_THROW is an unconditional branch. NOTE:
678 * OP_THROW_VERIFICATION_ERROR is also an unconditional
679 * branch, but we shouldn't treat it as such until we have
680 * a dead code elimination pass (which won't be important
681 * until inlining w/ constant propogation is implemented.
buzbee67bf8852011-08-17 17:51:35 -0700682 */
buzbee510c6052011-10-27 10:47:20 -0700683 if (insn->dalvikInsn.opcode != OP_THROW) {
buzbee67bf8852011-08-17 17:51:35 -0700684 curBlock->fallThrough = fallthroughBlock;
685 oatSetBit(fallthroughBlock->predecessors, curBlock->id);
686 }
687 }
688 }
689}
690
691/*
692 * Compile a method.
693 */
Ian Rogers0571d352011-11-03 19:51:38 -0700694CompiledMethod* oatCompileMethod(const Compiler& compiler, bool is_direct,
695 uint32_t method_idx, const art::ClassLoader* class_loader,
696 const art::DexFile& dex_file, art::InstructionSet insnSet)
buzbee67bf8852011-08-17 17:51:35 -0700697{
Ian Rogers0571d352011-11-03 19:51:38 -0700698 art::ClassLinker* linker = art::Runtime::Current()->GetClassLinker();
699 art::DexCache* dex_cache = linker->FindDexCache(dex_file);
700 art::Method* method = linker->ResolveMethod(dex_file, method_idx, dex_cache,
701 class_loader, is_direct);
702 if (method == NULL) {
703 CHECK(Thread::Current()->IsExceptionPending());
704 Thread::Current()->ClearException();
705 LOG(INFO) << "Couldn't resolve " << PrettyMethod(method_idx, dex_file, true)
706 << " for compilation";
707 return NULL;
708 }
Brian Carlstrom16192862011-09-12 17:50:06 -0700709 if (compiler.IsVerbose()) {
710 LOG(INFO) << "Compiling " << PrettyMethod(method) << "...";
711 }
buzbee2a475e72011-09-07 17:19:17 -0700712 oatArenaReset();
Brian Carlstrom94496d32011-08-22 09:22:47 -0700713
buzbeec143c552011-08-20 17:38:58 -0700714 const art::DexFile::CodeItem* code_item =
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700715 dex_file.GetCodeItem(method->GetCodeItemOffset());
buzbeec143c552011-08-20 17:38:58 -0700716 const u2* codePtr = code_item->insns_;
Ian Rogersd81871c2011-10-03 13:57:23 -0700717 const u2* codeEnd = code_item->insns_ + code_item->insns_size_in_code_units_;
buzbee67bf8852011-08-17 17:51:35 -0700718 int numBlocks = 0;
719 unsigned int curOffset = 0;
720
Brian Carlstrom16192862011-09-12 17:50:06 -0700721 oatInit(compiler);
buzbee67bf8852011-08-17 17:51:35 -0700722
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700723 UniquePtr<CompilationUnit> cUnit(new CompilationUnit);
724 memset(cUnit.get(), 0, sizeof(*cUnit));
725 cUnit->compiler = &compiler;
726 cUnit->method = method;
727 cUnit->instructionSet = (OatInstructionSetType)insnSet;
728 cUnit->insns = code_item->insns_;
Ian Rogersd81871c2011-10-03 13:57:23 -0700729 cUnit->insnsSize = code_item->insns_size_in_code_units_;
buzbeece302932011-10-04 14:32:18 -0700730 bool useMatch = compilerMethodMatch.length() != 0;
731 bool match = useMatch && (compilerFlipMatch ^
732 (PrettyMethod(method).find(compilerMethodMatch) != std::string::npos));
733 if (!useMatch || match) {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700734 cUnit->disableOpt = compilerOptimizerDisableFlags;
735 cUnit->enableDebug = compilerDebugFlags;
736 cUnit->printMe = compiler.IsVerbose() || (cUnit->enableDebug & (1 << kDebugVerbose));
buzbeece302932011-10-04 14:32:18 -0700737 }
buzbee67bf8852011-08-17 17:51:35 -0700738
buzbeecefd1872011-09-09 09:59:52 -0700739 /* Assume non-throwing leaf */
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700740 cUnit->attrs = (METHOD_IS_LEAF | METHOD_IS_THROW_FREE);
buzbeecefd1872011-09-09 09:59:52 -0700741
buzbee67bf8852011-08-17 17:51:35 -0700742 /* Initialize the block list */
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700743 oatInitGrowableList(&cUnit->blockList, 40);
buzbee67bf8852011-08-17 17:51:35 -0700744
745 /* Initialize the switchTables list */
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700746 oatInitGrowableList(&cUnit->switchTables, 4);
buzbee67bf8852011-08-17 17:51:35 -0700747
748 /* Intialize the fillArrayData list */
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700749 oatInitGrowableList(&cUnit->fillArrayData, 4);
buzbee67bf8852011-08-17 17:51:35 -0700750
buzbee5ade1d22011-09-09 14:44:52 -0700751 /* Intialize the throwLaunchpads list */
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700752 oatInitGrowableList(&cUnit->throwLaunchpads, 4);
buzbee5ade1d22011-09-09 14:44:52 -0700753
buzbeec1f45042011-09-21 16:03:19 -0700754 /* Intialize the suspendLaunchpads list */
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700755 oatInitGrowableList(&cUnit->suspendLaunchpads, 4);
buzbeec1f45042011-09-21 16:03:19 -0700756
buzbee67bf8852011-08-17 17:51:35 -0700757 /* Allocate the bit-vector to track the beginning of basic blocks */
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700758 ArenaBitVector *tryBlockAddr = oatAllocBitVector(cUnit->insnsSize,
buzbee67bf8852011-08-17 17:51:35 -0700759 true /* expandable */);
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700760 cUnit->tryBlockAddr = tryBlockAddr;
buzbee67bf8852011-08-17 17:51:35 -0700761
762 /* Create the default entry and exit blocks and enter them to the list */
763 BasicBlock *entryBlock = oatNewBB(kEntryBlock, numBlocks++);
764 BasicBlock *exitBlock = oatNewBB(kExitBlock, numBlocks++);
765
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700766 cUnit->entryBlock = entryBlock;
767 cUnit->exitBlock = exitBlock;
buzbee67bf8852011-08-17 17:51:35 -0700768
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700769 oatInsertGrowableList(&cUnit->blockList, (intptr_t) entryBlock);
770 oatInsertGrowableList(&cUnit->blockList, (intptr_t) exitBlock);
buzbee67bf8852011-08-17 17:51:35 -0700771
772 /* Current block to record parsed instructions */
773 BasicBlock *curBlock = oatNewBB(kDalvikByteCode, numBlocks++);
774 curBlock->startOffset = 0;
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700775 oatInsertGrowableList(&cUnit->blockList, (intptr_t) curBlock);
buzbee67bf8852011-08-17 17:51:35 -0700776 entryBlock->fallThrough = curBlock;
777 oatSetBit(curBlock->predecessors, entryBlock->id);
778
779 /*
780 * Store back the number of blocks since new blocks may be created of
781 * accessing cUnit.
782 */
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700783 cUnit->numBlocks = numBlocks;
buzbee67bf8852011-08-17 17:51:35 -0700784
785 /* Identify code range in try blocks and set up the empty catch blocks */
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700786 processTryCatchBlocks(cUnit.get());
buzbee67bf8852011-08-17 17:51:35 -0700787
788 /* Parse all instructions and put them into containing basic blocks */
789 while (codePtr < codeEnd) {
790 MIR *insn = (MIR *) oatNew(sizeof(MIR), true);
791 insn->offset = curOffset;
792 int width = parseInsn(codePtr, &insn->dalvikInsn, false);
793 insn->width = width;
794
795 /* Terminate when the data section is seen */
796 if (width == 0)
797 break;
798
799 oatAppendMIR(curBlock, insn);
800
801 codePtr += width;
802 int flags = dexGetFlagsFromOpcode(insn->dalvikInsn.opcode);
803
804 if (flags & kInstrCanBranch) {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700805 processCanBranch(cUnit.get(), curBlock, insn, curOffset, width, flags,
buzbee67bf8852011-08-17 17:51:35 -0700806 codePtr, codeEnd);
807 } else if (flags & kInstrCanReturn) {
808 curBlock->fallThrough = exitBlock;
809 oatSetBit(exitBlock->predecessors, curBlock->id);
810 /*
811 * Terminate the current block if there are instructions
812 * afterwards.
813 */
814 if (codePtr < codeEnd) {
815 /*
816 * Create a fallthrough block for real instructions
817 * (incl. OP_NOP).
818 */
819 if (contentIsInsn(codePtr)) {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700820 findBlock(cUnit.get(), curOffset + width,
buzbee67bf8852011-08-17 17:51:35 -0700821 /* split */
822 false,
823 /* create */
824 true);
825 }
826 }
827 } else if (flags & kInstrCanThrow) {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700828 processCanThrow(cUnit.get(), curBlock, insn, curOffset, width, flags,
buzbee67bf8852011-08-17 17:51:35 -0700829 tryBlockAddr, codePtr, codeEnd);
830 } else if (flags & kInstrCanSwitch) {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700831 processCanSwitch(cUnit.get(), curBlock, insn, curOffset, width, flags);
buzbee67bf8852011-08-17 17:51:35 -0700832 }
833 curOffset += width;
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700834 BasicBlock *nextBlock = findBlock(cUnit.get(), curOffset,
buzbee67bf8852011-08-17 17:51:35 -0700835 /* split */
836 false,
837 /* create */
838 false);
839 if (nextBlock) {
840 /*
841 * The next instruction could be the target of a previously parsed
842 * forward branch so a block is already created. If the current
843 * instruction is not an unconditional branch, connect them through
844 * the fall-through link.
845 */
buzbeeed3e9302011-09-23 17:34:19 -0700846 DCHECK(curBlock->fallThrough == NULL ||
buzbee67bf8852011-08-17 17:51:35 -0700847 curBlock->fallThrough == nextBlock ||
848 curBlock->fallThrough == exitBlock);
849
850 if ((curBlock->fallThrough == NULL) &&
851 (flags & kInstrCanContinue)) {
852 curBlock->fallThrough = nextBlock;
853 oatSetBit(nextBlock->predecessors, curBlock->id);
854 }
855 curBlock = nextBlock;
856 }
857 }
858
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700859 if (cUnit->printMe) {
860 oatDumpCompilationUnit(cUnit.get());
buzbee67bf8852011-08-17 17:51:35 -0700861 }
862
863 /* Adjust this value accordingly once inlining is performed */
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700864 cUnit->numDalvikRegisters = cUnit->method->NumRegisters();
buzbee67bf8852011-08-17 17:51:35 -0700865
866
867 /* Verify if all blocks are connected as claimed */
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700868 oatDataFlowAnalysisDispatcher(cUnit.get(), verifyPredInfo, kAllNodes, false /* isIterative */);
buzbee67bf8852011-08-17 17:51:35 -0700869
870 /* Perform SSA transformation for the whole method */
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700871 oatMethodSSATransformation(cUnit.get());
buzbee67bf8852011-08-17 17:51:35 -0700872
buzbee43a36422011-09-14 14:00:13 -0700873 /* Perform null check elimination */
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700874 oatMethodNullCheckElimination(cUnit.get());
buzbee43a36422011-09-14 14:00:13 -0700875
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700876 oatInitializeRegAlloc(cUnit.get()); // Needs to happen after SSA naming
buzbee67bf8852011-08-17 17:51:35 -0700877
878 /* Allocate Registers using simple local allocation scheme */
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700879 oatSimpleRegAlloc(cUnit.get());
buzbee67bf8852011-08-17 17:51:35 -0700880
881 /* Convert MIR to LIR, etc. */
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700882 oatMethodMIR2LIR(cUnit.get());
buzbee67bf8852011-08-17 17:51:35 -0700883
884 // Debugging only
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700885 if (cUnit->enableDebug & (1 << kDebugDumpCFG)) {
886 oatDumpCFG(cUnit.get(), "/sdcard/cfg/");
buzbeeec5adf32011-09-11 15:25:43 -0700887 }
buzbee67bf8852011-08-17 17:51:35 -0700888
889 /* Method is not empty */
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700890 if (cUnit->firstLIRInsn) {
buzbee67bf8852011-08-17 17:51:35 -0700891
892 // mark the targets of switch statement case labels
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700893 oatProcessSwitchTables(cUnit.get());
buzbee67bf8852011-08-17 17:51:35 -0700894
895 /* Convert LIR into machine code. */
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700896 oatAssembleLIR(cUnit.get());
buzbee67bf8852011-08-17 17:51:35 -0700897
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700898 if (cUnit->printMe) {
899 oatCodegenDump(cUnit.get());
buzbee67bf8852011-08-17 17:51:35 -0700900 }
901 }
902
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700903 // Combine vmap tables - core regs, then fp regs - into vmapTable
904 std::vector<uint16_t> vmapTable;
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700905 for (size_t i = 0 ; i < cUnit->coreVmapTable.size(); i++) {
906 vmapTable.push_back(cUnit->coreVmapTable[i]);
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700907 }
buzbeec41e5b52011-09-23 12:46:19 -0700908 // Add a marker to take place of lr
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700909 vmapTable.push_back(INVALID_VREG);
buzbeec41e5b52011-09-23 12:46:19 -0700910 // Combine vmap tables - core regs, then fp regs
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700911 for (uint32_t i = 0; i < cUnit->fpVmapTable.size(); i++) {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700912 vmapTable.push_back(cUnit->fpVmapTable[i]);
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700913 }
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700914 DCHECK_EQ(vmapTable.size(),
915 static_cast<uint32_t>(__builtin_popcount(cUnit->coreSpillMask)
916 + __builtin_popcount(cUnit->fpSpillMask)));
917 DCHECK_GE(vmapTable.size(), 1U); // should always at least one INVALID_VREG for lr
918
Ian Rogers0571d352011-11-03 19:51:38 -0700919 CompiledMethod* result = new CompiledMethod(art::kThumb2, cUnit->codeBuffer,
920 cUnit->frameSize, cUnit->coreSpillMask,
921 cUnit->fpSpillMask, cUnit->mappingTable,
922 vmapTable);
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700923
Brian Carlstrom16192862011-09-12 17:50:06 -0700924 if (compiler.IsVerbose()) {
925 LOG(INFO) << "Compiled " << PrettyMethod(method)
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700926 << " (" << (cUnit->codeBuffer.size() * sizeof(cUnit->codeBuffer[0])) << " bytes)";
Brian Carlstrom16192862011-09-12 17:50:06 -0700927 }
buzbee67bf8852011-08-17 17:51:35 -0700928
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700929 return result;
buzbee67bf8852011-08-17 17:51:35 -0700930}
931
Brian Carlstrom16192862011-09-12 17:50:06 -0700932void oatInit(const Compiler& compiler)
buzbee67bf8852011-08-17 17:51:35 -0700933{
buzbee67bf8852011-08-17 17:51:35 -0700934 static bool initialized = false;
935 if (initialized)
936 return;
937 initialized = true;
Brian Carlstrom16192862011-09-12 17:50:06 -0700938 if (compiler.IsVerbose()) {
939 LOG(INFO) << "Initializing compiler";
940 }
buzbee67bf8852011-08-17 17:51:35 -0700941 if (!oatArchInit()) {
942 LOG(FATAL) << "Failed to initialize oat";
943 }
944 if (!oatHeapInit()) {
945 LOG(FATAL) << "Failed to initialize oat heap";
946 }
947}