blob: 4aa0ac89e9bcdcad9f039239f171c015c049b979 [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"
Ian Rogers0571d352011-11-03 19:51:38 -070020#include "leb128.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
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080024namespace art {
25
buzbee692be802012-08-29 15:52:59 -070026#if defined(ART_USE_QUICK_COMPILER)
27QuickCompiler::QuickCompiler(art::Compiler* compiler)
28 : compiler_(compiler) {
29 // Create context, module, intrinsic helper & ir builder
30 llvm_context_.reset(new llvm::LLVMContext());
31 llvm_module_.reset(new llvm::Module("art", *llvm_context_));
32 llvm::StructType::create(*llvm_context_, "JavaObject");
33 llvm::StructType::create(*llvm_context_, "Method");
34 llvm::StructType::create(*llvm_context_, "Thread");
35 intrinsic_helper_.reset( new greenland::IntrinsicHelper(*llvm_context_, *llvm_module_));
36 ir_builder_.reset(new greenland::IRBuilder(*llvm_context_, *llvm_module_, *intrinsic_helper_));
37}
38
39QuickCompiler::~QuickCompiler() {
40}
41
42extern "C" void ArtInitQuickCompilerContext(art::Compiler& compiler) {
43 CHECK(compiler.GetCompilerContext() == NULL);
44 QuickCompiler* quickCompiler = new QuickCompiler(&compiler);
45 compiler.SetCompilerContext(quickCompiler);
46}
47
48extern "C" void ArtUnInitQuickCompilerContext(art::Compiler& compiler) {
49 delete reinterpret_cast<QuickCompiler*>(compiler.GetCompilerContext());
50 compiler.SetCompilerContext(NULL);
51}
52#endif
53
buzbeece302932011-10-04 14:32:18 -070054/* Default optimizer/debug setting for the compiler. */
Elliott Hughese52e49b2012-04-02 16:05:44 -070055static uint32_t kCompilerOptimizerDisableFlags = 0 | // Disable specific optimizations
Bill Buzbeea114add2012-05-03 15:00:40 -070056 //(1 << kLoadStoreElimination) |
57 //(1 << kLoadHoisting) |
58 //(1 << kSuppressLoads) |
59 //(1 << kNullCheckElimination) |
60 //(1 << kPromoteRegs) |
61 //(1 << kTrackLiveTemps) |
62 //(1 << kSkipLargeMethodOptimization) |
63 //(1 << kSafeOptimizations) |
64 //(1 << kBBOpt) |
65 //(1 << kMatch) |
66 //(1 << kPromoteCompilerTemps) |
67 0;
buzbeece302932011-10-04 14:32:18 -070068
Elliott Hughese52e49b2012-04-02 16:05:44 -070069static uint32_t kCompilerDebugFlags = 0 | // Enable debug/testing modes
Bill Buzbeea114add2012-05-03 15:00:40 -070070 //(1 << kDebugDisplayMissingTargets) |
71 //(1 << kDebugVerbose) |
72 //(1 << kDebugDumpCFG) |
73 //(1 << kDebugSlowFieldPath) |
74 //(1 << kDebugSlowInvokePath) |
75 //(1 << kDebugSlowStringPath) |
76 //(1 << kDebugSlowestFieldPath) |
77 //(1 << kDebugSlowestStringPath) |
78 //(1 << kDebugExerciseResolveMethod) |
79 //(1 << kDebugVerifyDataflow) |
80 //(1 << kDebugShowMemoryUsage) |
81 //(1 << kDebugShowNops) |
82 //(1 << kDebugCountOpcodes) |
buzbeed1643e42012-09-05 14:06:51 -070083 //(1 << kDebugDumpCheckStats) |
buzbeead8f15e2012-06-18 14:49:45 -070084#if defined(ART_USE_QUICK_COMPILER)
85 //(1 << kDebugDumpBitcodeFile) |
Bill Buzbeec9f40dd2012-08-15 11:35:25 -070086 //(1 << kDebugVerifyBitcode) |
buzbeead8f15e2012-06-18 14:49:45 -070087#endif
Bill Buzbeea114add2012-05-03 15:00:40 -070088 0;
buzbeece302932011-10-04 14:32:18 -070089
buzbee31a4a6f2012-02-28 15:36:15 -080090inline bool contentIsInsn(const u2* codePtr) {
Bill Buzbeea114add2012-05-03 15:00:40 -070091 u2 instr = *codePtr;
92 Instruction::Code opcode = (Instruction::Code)(instr & 0xff);
buzbee67bf8852011-08-17 17:51:35 -070093
Bill Buzbeea114add2012-05-03 15:00:40 -070094 /*
95 * Since the low 8-bit in metadata may look like NOP, we need to check
96 * both the low and whole sub-word to determine whether it is code or data.
97 */
98 return (opcode != Instruction::NOP || instr == 0);
buzbee67bf8852011-08-17 17:51:35 -070099}
100
101/*
102 * Parse an instruction, return the length of the instruction
103 */
buzbee31a4a6f2012-02-28 15:36:15 -0800104inline int parseInsn(CompilationUnit* cUnit, const u2* codePtr,
Bill Buzbeea114add2012-05-03 15:00:40 -0700105 DecodedInstruction* decoded_instruction, bool printMe)
buzbee67bf8852011-08-17 17:51:35 -0700106{
Elliott Hughesadb8c672012-03-06 16:49:32 -0800107 // Don't parse instruction data
108 if (!contentIsInsn(codePtr)) {
109 return 0;
110 }
buzbee67bf8852011-08-17 17:51:35 -0700111
Elliott Hughesadb8c672012-03-06 16:49:32 -0800112 const Instruction* instruction = Instruction::At(codePtr);
113 *decoded_instruction = DecodedInstruction(instruction);
buzbee67bf8852011-08-17 17:51:35 -0700114
Elliott Hughesadb8c672012-03-06 16:49:32 -0800115 if (printMe) {
Bill Buzbeea114add2012-05-03 15:00:40 -0700116 char* decodedString = oatGetDalvikDisassembly(cUnit, *decoded_instruction,
117 NULL);
118 LOG(INFO) << codePtr << ": 0x"
119 << std::hex << static_cast<int>(decoded_instruction->opcode)
Elliott Hughesadb8c672012-03-06 16:49:32 -0800120 << " " << decodedString;
121 }
122 return instruction->SizeInCodeUnits();
buzbee67bf8852011-08-17 17:51:35 -0700123}
124
125#define UNKNOWN_TARGET 0xffffffff
126
Elliott Hughesadb8c672012-03-06 16:49:32 -0800127inline bool isGoto(MIR* insn) {
128 switch (insn->dalvikInsn.opcode) {
129 case Instruction::GOTO:
130 case Instruction::GOTO_16:
131 case Instruction::GOTO_32:
132 return true;
133 default:
134 return false;
Bill Buzbeea114add2012-05-03 15:00:40 -0700135 }
buzbee67bf8852011-08-17 17:51:35 -0700136}
137
138/*
139 * Identify unconditional branch instructions
140 */
Elliott Hughesadb8c672012-03-06 16:49:32 -0800141inline bool isUnconditionalBranch(MIR* insn) {
142 switch (insn->dalvikInsn.opcode) {
143 case Instruction::RETURN_VOID:
144 case Instruction::RETURN:
145 case Instruction::RETURN_WIDE:
146 case Instruction::RETURN_OBJECT:
147 return true;
Bill Buzbeea114add2012-05-03 15:00:40 -0700148 default:
149 return isGoto(insn);
Elliott Hughesadb8c672012-03-06 16:49:32 -0800150 }
buzbee67bf8852011-08-17 17:51:35 -0700151}
152
153/* Split an existing block from the specified code offset into two */
buzbee31a4a6f2012-02-28 15:36:15 -0800154BasicBlock *splitBlock(CompilationUnit* cUnit, unsigned int codeOffset,
Bill Buzbeea114add2012-05-03 15:00:40 -0700155 BasicBlock* origBlock, BasicBlock** immedPredBlockP)
buzbee67bf8852011-08-17 17:51:35 -0700156{
Bill Buzbeea114add2012-05-03 15:00:40 -0700157 MIR* insn = origBlock->firstMIRInsn;
158 while (insn) {
159 if (insn->offset == codeOffset) break;
160 insn = insn->next;
161 }
162 if (insn == NULL) {
163 LOG(FATAL) << "Break split failed";
164 }
165 BasicBlock *bottomBlock = oatNewBB(cUnit, kDalvikByteCode,
166 cUnit->numBlocks++);
167 oatInsertGrowableList(cUnit, &cUnit->blockList, (intptr_t) bottomBlock);
buzbee67bf8852011-08-17 17:51:35 -0700168
Bill Buzbeea114add2012-05-03 15:00:40 -0700169 bottomBlock->startOffset = codeOffset;
170 bottomBlock->firstMIRInsn = insn;
171 bottomBlock->lastMIRInsn = origBlock->lastMIRInsn;
buzbee67bf8852011-08-17 17:51:35 -0700172
Bill Buzbeea114add2012-05-03 15:00:40 -0700173 /* Add it to the quick lookup cache */
174 cUnit->blockMap.Put(bottomBlock->startOffset, bottomBlock);
buzbee5b537102012-01-17 17:33:47 -0800175
Bill Buzbeea114add2012-05-03 15:00:40 -0700176 /* Handle the taken path */
177 bottomBlock->taken = origBlock->taken;
178 if (bottomBlock->taken) {
179 origBlock->taken = NULL;
180 oatDeleteGrowableList(bottomBlock->taken->predecessors,
buzbeeba938cb2012-02-03 14:47:55 -0800181 (intptr_t)origBlock);
Bill Buzbeea114add2012-05-03 15:00:40 -0700182 oatInsertGrowableList(cUnit, bottomBlock->taken->predecessors,
183 (intptr_t)bottomBlock);
184 }
185
186 /* Handle the fallthrough path */
Bill Buzbeea114add2012-05-03 15:00:40 -0700187 bottomBlock->fallThrough = origBlock->fallThrough;
188 origBlock->fallThrough = bottomBlock;
Bill Buzbeea114add2012-05-03 15:00:40 -0700189 oatInsertGrowableList(cUnit, bottomBlock->predecessors,
190 (intptr_t)origBlock);
191 if (bottomBlock->fallThrough) {
192 oatDeleteGrowableList(bottomBlock->fallThrough->predecessors,
193 (intptr_t)origBlock);
194 oatInsertGrowableList(cUnit, bottomBlock->fallThrough->predecessors,
195 (intptr_t)bottomBlock);
196 }
197
198 /* Handle the successor list */
199 if (origBlock->successorBlockList.blockListType != kNotUsed) {
200 bottomBlock->successorBlockList = origBlock->successorBlockList;
201 origBlock->successorBlockList.blockListType = kNotUsed;
202 GrowableListIterator iterator;
203
204 oatGrowableListIteratorInit(&bottomBlock->successorBlockList.blocks,
205 &iterator);
206 while (true) {
207 SuccessorBlockInfo *successorBlockInfo =
208 (SuccessorBlockInfo *) oatGrowableListIteratorNext(&iterator);
209 if (successorBlockInfo == NULL) break;
210 BasicBlock *bb = successorBlockInfo->block;
211 oatDeleteGrowableList(bb->predecessors, (intptr_t)origBlock);
212 oatInsertGrowableList(cUnit, bb->predecessors, (intptr_t)bottomBlock);
buzbee67bf8852011-08-17 17:51:35 -0700213 }
Bill Buzbeea114add2012-05-03 15:00:40 -0700214 }
buzbee67bf8852011-08-17 17:51:35 -0700215
Bill Buzbeea114add2012-05-03 15:00:40 -0700216 origBlock->lastMIRInsn = insn->prev;
buzbee67bf8852011-08-17 17:51:35 -0700217
Bill Buzbeea114add2012-05-03 15:00:40 -0700218 insn->prev->next = NULL;
219 insn->prev = NULL;
220 /*
221 * Update the immediate predecessor block pointer so that outgoing edges
222 * can be applied to the proper block.
223 */
224 if (immedPredBlockP) {
225 DCHECK_EQ(*immedPredBlockP, origBlock);
226 *immedPredBlockP = bottomBlock;
227 }
228 return bottomBlock;
buzbee67bf8852011-08-17 17:51:35 -0700229}
230
231/*
232 * Given a code offset, find out the block that starts with it. If the offset
buzbee9ab05de2012-01-18 15:43:48 -0800233 * is in the middle of an existing block, split it into two. If immedPredBlockP
234 * is not non-null and is the block being split, update *immedPredBlockP to
235 * point to the bottom block so that outgoing edges can be set up properly
236 * (by the caller)
buzbee5b537102012-01-17 17:33:47 -0800237 * Utilizes a map for fast lookup of the typical cases.
buzbee67bf8852011-08-17 17:51:35 -0700238 */
buzbee31a4a6f2012-02-28 15:36:15 -0800239BasicBlock *findBlock(CompilationUnit* cUnit, unsigned int codeOffset,
240 bool split, bool create, BasicBlock** immedPredBlockP)
buzbee67bf8852011-08-17 17:51:35 -0700241{
Bill Buzbeea114add2012-05-03 15:00:40 -0700242 GrowableList* blockList = &cUnit->blockList;
243 BasicBlock* bb;
244 unsigned int i;
245 SafeMap<unsigned int, BasicBlock*>::iterator it;
buzbee67bf8852011-08-17 17:51:35 -0700246
Bill Buzbeea114add2012-05-03 15:00:40 -0700247 it = cUnit->blockMap.find(codeOffset);
248 if (it != cUnit->blockMap.end()) {
249 return it->second;
250 } else if (!create) {
251 return NULL;
252 }
253
254 if (split) {
255 for (i = 0; i < blockList->numUsed; i++) {
256 bb = (BasicBlock *) blockList->elemList[i];
257 if (bb->blockType != kDalvikByteCode) continue;
258 /* Check if a branch jumps into the middle of an existing block */
259 if ((codeOffset > bb->startOffset) && (bb->lastMIRInsn != NULL) &&
260 (codeOffset <= bb->lastMIRInsn->offset)) {
261 BasicBlock *newBB = splitBlock(cUnit, codeOffset, bb,
262 bb == *immedPredBlockP ?
263 immedPredBlockP : NULL);
264 return newBB;
265 }
buzbee5b537102012-01-17 17:33:47 -0800266 }
Bill Buzbeea114add2012-05-03 15:00:40 -0700267 }
buzbee5b537102012-01-17 17:33:47 -0800268
Bill Buzbeea114add2012-05-03 15:00:40 -0700269 /* Create a new one */
270 bb = oatNewBB(cUnit, kDalvikByteCode, cUnit->numBlocks++);
271 oatInsertGrowableList(cUnit, &cUnit->blockList, (intptr_t) bb);
272 bb->startOffset = codeOffset;
273 cUnit->blockMap.Put(bb->startOffset, bb);
274 return bb;
buzbee67bf8852011-08-17 17:51:35 -0700275}
276
buzbeef58c12c2012-07-03 15:06:29 -0700277/* Find existing block */
278BasicBlock* oatFindBlock(CompilationUnit* cUnit, unsigned int codeOffset)
279{
280 return findBlock(cUnit, codeOffset, false, false, NULL);
281}
282
buzbeead8f15e2012-06-18 14:49:45 -0700283/* Turn method name into a legal Linux file name */
284void oatReplaceSpecialChars(std::string& str)
285{
286 static const struct { const char before; const char after; } match[] =
287 {{'/','-'}, {';','#'}, {' ','#'}, {'$','+'},
288 {'(','@'}, {')','@'}, {'<','='}, {'>','='}};
289 for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) {
290 std::replace(str.begin(), str.end(), match[i].before, match[i].after);
291 }
292}
293
buzbee67bf8852011-08-17 17:51:35 -0700294/* Dump the CFG into a DOT graph */
295void oatDumpCFG(CompilationUnit* cUnit, const char* dirPrefix)
296{
Bill Buzbeea114add2012-05-03 15:00:40 -0700297 FILE* file;
buzbeead8f15e2012-06-18 14:49:45 -0700298 std::string fname(PrettyMethod(cUnit->method_idx, *cUnit->dex_file));
299 oatReplaceSpecialChars(fname);
300 fname = StringPrintf("%s%s%x.dot", dirPrefix, fname.c_str(),
301 cUnit->entryBlock->fallThrough->startOffset);
302 file = fopen(fname.c_str(), "w");
Bill Buzbeea114add2012-05-03 15:00:40 -0700303 if (file == NULL) {
304 return;
305 }
306 fprintf(file, "digraph G {\n");
307
308 fprintf(file, " rankdir=TB\n");
309
310 int numReachableBlocks = cUnit->numReachableBlocks;
311 int idx;
312 const GrowableList *blockList = &cUnit->blockList;
313
314 for (idx = 0; idx < numReachableBlocks; idx++) {
315 int blockIdx = cUnit->dfsOrder.elemList[idx];
316 BasicBlock *bb = (BasicBlock *) oatGrowableListGetElement(blockList,
317 blockIdx);
318 if (bb == NULL) break;
buzbeed1643e42012-09-05 14:06:51 -0700319 if (bb->blockType == kDead) continue;
Bill Buzbeea114add2012-05-03 15:00:40 -0700320 if (bb->blockType == kEntryBlock) {
Bill Buzbeec9f40dd2012-08-15 11:35:25 -0700321 fprintf(file, " entry_%d [shape=Mdiamond];\n", bb->id);
Bill Buzbeea114add2012-05-03 15:00:40 -0700322 } else if (bb->blockType == kExitBlock) {
Bill Buzbeec9f40dd2012-08-15 11:35:25 -0700323 fprintf(file, " exit_%d [shape=Mdiamond];\n", bb->id);
Bill Buzbeea114add2012-05-03 15:00:40 -0700324 } else if (bb->blockType == kDalvikByteCode) {
Bill Buzbeec9f40dd2012-08-15 11:35:25 -0700325 fprintf(file, " block%04x_%d [shape=record,label = \"{ \\\n",
326 bb->startOffset, bb->id);
Bill Buzbeea114add2012-05-03 15:00:40 -0700327 const MIR *mir;
328 fprintf(file, " {block id %d\\l}%s\\\n", bb->id,
329 bb->firstMIRInsn ? " | " : " ");
330 for (mir = bb->firstMIRInsn; mir; mir = mir->next) {
331 fprintf(file, " {%04x %s\\l}%s\\\n", mir->offset,
332 mir->ssaRep ? oatFullDisassembler(cUnit, mir) :
333 Instruction::Name(mir->dalvikInsn.opcode),
334 mir->next ? " | " : " ");
335 }
336 fprintf(file, " }\"];\n\n");
337 } else if (bb->blockType == kExceptionHandling) {
338 char blockName[BLOCK_NAME_LEN];
339
340 oatGetBlockName(bb, blockName);
341 fprintf(file, " %s [shape=invhouse];\n", blockName);
buzbee67bf8852011-08-17 17:51:35 -0700342 }
buzbee67bf8852011-08-17 17:51:35 -0700343
Bill Buzbeea114add2012-05-03 15:00:40 -0700344 char blockName1[BLOCK_NAME_LEN], blockName2[BLOCK_NAME_LEN];
buzbee67bf8852011-08-17 17:51:35 -0700345
Bill Buzbeea114add2012-05-03 15:00:40 -0700346 if (bb->taken) {
347 oatGetBlockName(bb, blockName1);
348 oatGetBlockName(bb->taken, blockName2);
349 fprintf(file, " %s:s -> %s:n [style=dotted]\n",
350 blockName1, blockName2);
buzbee67bf8852011-08-17 17:51:35 -0700351 }
Bill Buzbeea114add2012-05-03 15:00:40 -0700352 if (bb->fallThrough) {
353 oatGetBlockName(bb, blockName1);
354 oatGetBlockName(bb->fallThrough, blockName2);
355 fprintf(file, " %s:s -> %s:n\n", blockName1, blockName2);
356 }
357
358 if (bb->successorBlockList.blockListType != kNotUsed) {
Bill Buzbeec9f40dd2012-08-15 11:35:25 -0700359 fprintf(file, " succ%04x_%d [shape=%s,label = \"{ \\\n",
360 bb->startOffset, bb->id,
Bill Buzbeea114add2012-05-03 15:00:40 -0700361 (bb->successorBlockList.blockListType == kCatch) ?
362 "Mrecord" : "record");
363 GrowableListIterator iterator;
364 oatGrowableListIteratorInit(&bb->successorBlockList.blocks,
365 &iterator);
366 SuccessorBlockInfo *successorBlockInfo =
367 (SuccessorBlockInfo *) oatGrowableListIteratorNext(&iterator);
368
369 int succId = 0;
370 while (true) {
371 if (successorBlockInfo == NULL) break;
372
373 BasicBlock *destBlock = successorBlockInfo->block;
374 SuccessorBlockInfo *nextSuccessorBlockInfo =
375 (SuccessorBlockInfo *) oatGrowableListIteratorNext(&iterator);
376
377 fprintf(file, " {<f%d> %04x: %04x\\l}%s\\\n",
378 succId++,
379 successorBlockInfo->key,
380 destBlock->startOffset,
381 (nextSuccessorBlockInfo != NULL) ? " | " : " ");
382
383 successorBlockInfo = nextSuccessorBlockInfo;
384 }
385 fprintf(file, " }\"];\n\n");
386
387 oatGetBlockName(bb, blockName1);
Bill Buzbeec9f40dd2012-08-15 11:35:25 -0700388 fprintf(file, " %s:s -> succ%04x_%d:n [style=dashed]\n",
389 blockName1, bb->startOffset, bb->id);
Bill Buzbeea114add2012-05-03 15:00:40 -0700390
391 if (bb->successorBlockList.blockListType == kPackedSwitch ||
392 bb->successorBlockList.blockListType == kSparseSwitch) {
393
394 oatGrowableListIteratorInit(&bb->successorBlockList.blocks,
395 &iterator);
396
397 succId = 0;
398 while (true) {
399 SuccessorBlockInfo *successorBlockInfo = (SuccessorBlockInfo *)
400 oatGrowableListIteratorNext(&iterator);
401 if (successorBlockInfo == NULL) break;
402
403 BasicBlock *destBlock = successorBlockInfo->block;
404
405 oatGetBlockName(destBlock, blockName2);
Bill Buzbeec9f40dd2012-08-15 11:35:25 -0700406 fprintf(file, " succ%04x_%d:f%d:e -> %s:n\n", bb->startOffset,
407 bb->id, succId++, blockName2);
Bill Buzbeea114add2012-05-03 15:00:40 -0700408 }
409 }
410 }
411 fprintf(file, "\n");
412
413 /* Display the dominator tree */
414 oatGetBlockName(bb, blockName1);
415 fprintf(file, " cfg%s [label=\"%s\", shape=none];\n",
416 blockName1, blockName1);
417 if (bb->iDom) {
418 oatGetBlockName(bb->iDom, blockName2);
419 fprintf(file, " cfg%s:s -> cfg%s:n\n\n", blockName2, blockName1);
420 }
421 }
422 fprintf(file, "}\n");
423 fclose(file);
buzbee67bf8852011-08-17 17:51:35 -0700424}
425
426/* Verify if all the successor is connected with all the claimed predecessors */
buzbee31a4a6f2012-02-28 15:36:15 -0800427bool verifyPredInfo(CompilationUnit* cUnit, BasicBlock* bb)
buzbee67bf8852011-08-17 17:51:35 -0700428{
Bill Buzbeea114add2012-05-03 15:00:40 -0700429 GrowableListIterator iter;
buzbee67bf8852011-08-17 17:51:35 -0700430
Bill Buzbeea114add2012-05-03 15:00:40 -0700431 oatGrowableListIteratorInit(bb->predecessors, &iter);
432 while (true) {
433 BasicBlock *predBB = (BasicBlock*)oatGrowableListIteratorNext(&iter);
434 if (!predBB) break;
435 bool found = false;
436 if (predBB->taken == bb) {
437 found = true;
438 } else if (predBB->fallThrough == bb) {
439 found = true;
440 } else if (predBB->successorBlockList.blockListType != kNotUsed) {
441 GrowableListIterator iterator;
442 oatGrowableListIteratorInit(&predBB->successorBlockList.blocks,
443 &iterator);
444 while (true) {
445 SuccessorBlockInfo *successorBlockInfo = (SuccessorBlockInfo *)
446 oatGrowableListIteratorNext(&iterator);
447 if (successorBlockInfo == NULL) break;
448 BasicBlock *succBB = successorBlockInfo->block;
449 if (succBB == bb) {
buzbee67bf8852011-08-17 17:51:35 -0700450 found = true;
Bill Buzbeea114add2012-05-03 15:00:40 -0700451 break;
buzbee67bf8852011-08-17 17:51:35 -0700452 }
Bill Buzbeea114add2012-05-03 15:00:40 -0700453 }
buzbee67bf8852011-08-17 17:51:35 -0700454 }
Bill Buzbeea114add2012-05-03 15:00:40 -0700455 if (found == false) {
456 char blockName1[BLOCK_NAME_LEN], blockName2[BLOCK_NAME_LEN];
457 oatGetBlockName(bb, blockName1);
458 oatGetBlockName(predBB, blockName2);
459 oatDumpCFG(cUnit, "/sdcard/cfg/");
460 LOG(FATAL) << "Successor " << blockName1 << "not found from "
461 << blockName2;
462 }
463 }
464 return true;
buzbee67bf8852011-08-17 17:51:35 -0700465}
466
467/* Identify code range in try blocks and set up the empty catch blocks */
buzbee31a4a6f2012-02-28 15:36:15 -0800468void processTryCatchBlocks(CompilationUnit* cUnit)
buzbee67bf8852011-08-17 17:51:35 -0700469{
Bill Buzbeea114add2012-05-03 15:00:40 -0700470 const DexFile::CodeItem* code_item = cUnit->code_item;
471 int triesSize = code_item->tries_size_;
472 int offset;
buzbee67bf8852011-08-17 17:51:35 -0700473
Bill Buzbeea114add2012-05-03 15:00:40 -0700474 if (triesSize == 0) {
475 return;
476 }
477
478 ArenaBitVector* tryBlockAddr = cUnit->tryBlockAddr;
479
480 for (int i = 0; i < triesSize; i++) {
481 const DexFile::TryItem* pTry =
482 DexFile::GetTryItems(*code_item, i);
483 int startOffset = pTry->start_addr_;
484 int endOffset = startOffset + pTry->insn_count_;
485 for (offset = startOffset; offset < endOffset; offset++) {
486 oatSetBit(cUnit, tryBlockAddr, offset);
buzbee67bf8852011-08-17 17:51:35 -0700487 }
Bill Buzbeea114add2012-05-03 15:00:40 -0700488 }
buzbee67bf8852011-08-17 17:51:35 -0700489
Bill Buzbeea114add2012-05-03 15:00:40 -0700490 // Iterate over each of the handlers to enqueue the empty Catch blocks
491 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
492 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
493 for (uint32_t idx = 0; idx < handlers_size; idx++) {
494 CatchHandlerIterator iterator(handlers_ptr);
495 for (; iterator.HasNext(); iterator.Next()) {
496 uint32_t address = iterator.GetHandlerAddress();
497 findBlock(cUnit, address, false /* split */, true /*create*/,
498 /* immedPredBlockP */ NULL);
buzbee67bf8852011-08-17 17:51:35 -0700499 }
Bill Buzbeea114add2012-05-03 15:00:40 -0700500 handlers_ptr = iterator.EndDataPointer();
501 }
buzbee67bf8852011-08-17 17:51:35 -0700502}
503
Elliott Hughesadb8c672012-03-06 16:49:32 -0800504/* Process instructions with the kBranch flag */
buzbee31a4a6f2012-02-28 15:36:15 -0800505BasicBlock* processCanBranch(CompilationUnit* cUnit, BasicBlock* curBlock,
Bill Buzbeea114add2012-05-03 15:00:40 -0700506 MIR* insn, int curOffset, int width, int flags,
507 const u2* codePtr, const u2* codeEnd)
buzbee67bf8852011-08-17 17:51:35 -0700508{
Bill Buzbeea114add2012-05-03 15:00:40 -0700509 int target = curOffset;
510 switch (insn->dalvikInsn.opcode) {
511 case Instruction::GOTO:
512 case Instruction::GOTO_16:
513 case Instruction::GOTO_32:
514 target += (int) insn->dalvikInsn.vA;
515 break;
516 case Instruction::IF_EQ:
517 case Instruction::IF_NE:
518 case Instruction::IF_LT:
519 case Instruction::IF_GE:
520 case Instruction::IF_GT:
521 case Instruction::IF_LE:
522 target += (int) insn->dalvikInsn.vC;
523 break;
524 case Instruction::IF_EQZ:
525 case Instruction::IF_NEZ:
526 case Instruction::IF_LTZ:
527 case Instruction::IF_GEZ:
528 case Instruction::IF_GTZ:
529 case Instruction::IF_LEZ:
530 target += (int) insn->dalvikInsn.vB;
531 break;
532 default:
533 LOG(FATAL) << "Unexpected opcode(" << (int)insn->dalvikInsn.opcode
534 << ") with kBranch set";
535 }
536 BasicBlock *takenBlock = findBlock(cUnit, target,
537 /* split */
538 true,
539 /* create */
540 true,
541 /* immedPredBlockP */
542 &curBlock);
543 curBlock->taken = takenBlock;
544 oatInsertGrowableList(cUnit, takenBlock->predecessors, (intptr_t)curBlock);
buzbee67bf8852011-08-17 17:51:35 -0700545
Bill Buzbeea114add2012-05-03 15:00:40 -0700546 /* Always terminate the current block for conditional branches */
547 if (flags & Instruction::kContinue) {
548 BasicBlock *fallthroughBlock = findBlock(cUnit,
549 curOffset + width,
550 /*
551 * If the method is processed
552 * in sequential order from the
553 * beginning, we don't need to
554 * specify split for continue
555 * blocks. However, this
556 * routine can be called by
557 * compileLoop, which starts
558 * parsing the method from an
559 * arbitrary address in the
560 * method body.
561 */
562 true,
563 /* create */
564 true,
565 /* immedPredBlockP */
566 &curBlock);
567 curBlock->fallThrough = fallthroughBlock;
568 oatInsertGrowableList(cUnit, fallthroughBlock->predecessors,
569 (intptr_t)curBlock);
570 } else if (codePtr < codeEnd) {
571 /* Create a fallthrough block for real instructions (incl. NOP) */
572 if (contentIsInsn(codePtr)) {
573 findBlock(cUnit, curOffset + width,
574 /* split */
575 false,
576 /* create */
577 true,
578 /* immedPredBlockP */
579 NULL);
buzbee67bf8852011-08-17 17:51:35 -0700580 }
Bill Buzbeea114add2012-05-03 15:00:40 -0700581 }
582 return curBlock;
buzbee67bf8852011-08-17 17:51:35 -0700583}
584
Elliott Hughesadb8c672012-03-06 16:49:32 -0800585/* Process instructions with the kSwitch flag */
buzbee31a4a6f2012-02-28 15:36:15 -0800586void processCanSwitch(CompilationUnit* cUnit, BasicBlock* curBlock,
587 MIR* insn, int curOffset, int width, int flags)
buzbee67bf8852011-08-17 17:51:35 -0700588{
Bill Buzbeea114add2012-05-03 15:00:40 -0700589 u2* switchData= (u2 *) (cUnit->insns + curOffset + insn->dalvikInsn.vB);
590 int size;
591 int* keyTable;
592 int* targetTable;
593 int i;
594 int firstKey;
buzbee67bf8852011-08-17 17:51:35 -0700595
Bill Buzbeea114add2012-05-03 15:00:40 -0700596 /*
597 * Packed switch data format:
598 * ushort ident = 0x0100 magic value
599 * ushort size number of entries in the table
600 * int first_key first (and lowest) switch case value
601 * int targets[size] branch targets, relative to switch opcode
602 *
603 * Total size is (4+size*2) 16-bit code units.
604 */
605 if (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) {
606 DCHECK_EQ(static_cast<int>(switchData[0]),
607 static_cast<int>(Instruction::kPackedSwitchSignature));
608 size = switchData[1];
609 firstKey = switchData[2] | (switchData[3] << 16);
610 targetTable = (int *) &switchData[4];
611 keyTable = NULL; // Make the compiler happy
612 /*
613 * Sparse switch data format:
614 * ushort ident = 0x0200 magic value
615 * ushort size number of entries in the table; > 0
616 * int keys[size] keys, sorted low-to-high; 32-bit aligned
617 * int targets[size] branch targets, relative to switch opcode
618 *
619 * Total size is (2+size*4) 16-bit code units.
620 */
621 } else {
622 DCHECK_EQ(static_cast<int>(switchData[0]),
623 static_cast<int>(Instruction::kSparseSwitchSignature));
624 size = switchData[1];
625 keyTable = (int *) &switchData[2];
626 targetTable = (int *) &switchData[2 + size*2];
627 firstKey = 0; // To make the compiler happy
628 }
buzbee67bf8852011-08-17 17:51:35 -0700629
Bill Buzbeea114add2012-05-03 15:00:40 -0700630 if (curBlock->successorBlockList.blockListType != kNotUsed) {
631 LOG(FATAL) << "Successor block list already in use: "
632 << (int)curBlock->successorBlockList.blockListType;
633 }
634 curBlock->successorBlockList.blockListType =
635 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
636 kPackedSwitch : kSparseSwitch;
637 oatInitGrowableList(cUnit, &curBlock->successorBlockList.blocks, size,
638 kListSuccessorBlocks);
639
640 for (i = 0; i < size; i++) {
641 BasicBlock *caseBlock = findBlock(cUnit, curOffset + targetTable[i],
642 /* split */
643 true,
644 /* create */
645 true,
646 /* immedPredBlockP */
647 &curBlock);
648 SuccessorBlockInfo *successorBlockInfo =
649 (SuccessorBlockInfo *) oatNew(cUnit, sizeof(SuccessorBlockInfo),
650 false, kAllocSuccessor);
651 successorBlockInfo->block = caseBlock;
652 successorBlockInfo->key =
Elliott Hughesadb8c672012-03-06 16:49:32 -0800653 (insn->dalvikInsn.opcode == Instruction::PACKED_SWITCH) ?
Bill Buzbeea114add2012-05-03 15:00:40 -0700654 firstKey + i : keyTable[i];
655 oatInsertGrowableList(cUnit, &curBlock->successorBlockList.blocks,
656 (intptr_t) successorBlockInfo);
657 oatInsertGrowableList(cUnit, caseBlock->predecessors,
buzbeeba938cb2012-02-03 14:47:55 -0800658 (intptr_t)curBlock);
Bill Buzbeea114add2012-05-03 15:00:40 -0700659 }
660
661 /* Fall-through case */
662 BasicBlock* fallthroughBlock = findBlock(cUnit,
663 curOffset + width,
664 /* split */
665 false,
666 /* create */
667 true,
668 /* immedPredBlockP */
669 NULL);
670 curBlock->fallThrough = fallthroughBlock;
671 oatInsertGrowableList(cUnit, fallthroughBlock->predecessors,
672 (intptr_t)curBlock);
buzbee67bf8852011-08-17 17:51:35 -0700673}
674
Elliott Hughesadb8c672012-03-06 16:49:32 -0800675/* Process instructions with the kThrow flag */
Bill Buzbeec9f40dd2012-08-15 11:35:25 -0700676BasicBlock* processCanThrow(CompilationUnit* cUnit, BasicBlock* curBlock,
677 MIR* insn, int curOffset, int width, int flags,
678 ArenaBitVector* tryBlockAddr, const u2* codePtr,
679 const u2* codeEnd)
buzbee67bf8852011-08-17 17:51:35 -0700680{
Bill Buzbeea114add2012-05-03 15:00:40 -0700681 const DexFile::CodeItem* code_item = cUnit->code_item;
Bill Buzbeec9f40dd2012-08-15 11:35:25 -0700682 bool inTryBlock = oatIsBitSet(tryBlockAddr, curOffset);
buzbee67bf8852011-08-17 17:51:35 -0700683
Bill Buzbeea114add2012-05-03 15:00:40 -0700684 /* In try block */
Bill Buzbeec9f40dd2012-08-15 11:35:25 -0700685 if (inTryBlock) {
Bill Buzbeea114add2012-05-03 15:00:40 -0700686 CatchHandlerIterator iterator(*code_item, curOffset);
buzbee67bf8852011-08-17 17:51:35 -0700687
Bill Buzbeea114add2012-05-03 15:00:40 -0700688 if (curBlock->successorBlockList.blockListType != kNotUsed) {
Bill Buzbeec9f40dd2012-08-15 11:35:25 -0700689 LOG(INFO) << PrettyMethod(cUnit->method_idx, *cUnit->dex_file);
Bill Buzbeea114add2012-05-03 15:00:40 -0700690 LOG(FATAL) << "Successor block list already in use: "
691 << (int)curBlock->successorBlockList.blockListType;
buzbee67bf8852011-08-17 17:51:35 -0700692 }
693
Bill Buzbeea114add2012-05-03 15:00:40 -0700694 curBlock->successorBlockList.blockListType = kCatch;
695 oatInitGrowableList(cUnit, &curBlock->successorBlockList.blocks, 2,
696 kListSuccessorBlocks);
697
698 for (;iterator.HasNext(); iterator.Next()) {
699 BasicBlock *catchBlock = findBlock(cUnit, iterator.GetHandlerAddress(),
700 false /* split*/,
701 false /* creat */,
702 NULL /* immedPredBlockP */);
703 catchBlock->catchEntry = true;
704 SuccessorBlockInfo *successorBlockInfo = (SuccessorBlockInfo *)
705 oatNew(cUnit, sizeof(SuccessorBlockInfo), false, kAllocSuccessor);
706 successorBlockInfo->block = catchBlock;
707 successorBlockInfo->key = iterator.GetHandlerTypeIndex();
708 oatInsertGrowableList(cUnit, &curBlock->successorBlockList.blocks,
709 (intptr_t) successorBlockInfo);
710 oatInsertGrowableList(cUnit, catchBlock->predecessors,
711 (intptr_t)curBlock);
buzbee67bf8852011-08-17 17:51:35 -0700712 }
Bill Buzbeea114add2012-05-03 15:00:40 -0700713 } else {
714 BasicBlock *ehBlock = oatNewBB(cUnit, kExceptionHandling,
715 cUnit->numBlocks++);
716 curBlock->taken = ehBlock;
717 oatInsertGrowableList(cUnit, &cUnit->blockList, (intptr_t) ehBlock);
718 ehBlock->startOffset = curOffset;
719 oatInsertGrowableList(cUnit, ehBlock->predecessors, (intptr_t)curBlock);
720 }
721
Bill Buzbeec9f40dd2012-08-15 11:35:25 -0700722 if (insn->dalvikInsn.opcode == Instruction::THROW){
723 if ((codePtr < codeEnd) && contentIsInsn(codePtr)) {
724 // Force creation of new block following THROW via side-effect
725 findBlock(cUnit, curOffset + width, /* split */ false,
726 /* create */ true, /* immedPredBlockP */ NULL);
727 }
728 if (!inTryBlock) {
729 // Don't split a THROW that can't rethrow - we're done.
730 return curBlock;
Bill Buzbeea114add2012-05-03 15:00:40 -0700731 }
732 }
Bill Buzbeec9f40dd2012-08-15 11:35:25 -0700733
734 /*
735 * Split the potentially-throwing instruction into two parts.
736 * The first half will be a pseudo-op that captures the exception
737 * edges and terminates the basic block. It always falls through.
738 * Then, create a new basic block that begins with the throwing instruction
739 * (minus exceptions). Note: this new basic block must NOT be entered into
740 * the blockMap. If the potentially-throwing instruction is the target of a
741 * future branch, we need to find the check psuedo half. The new
742 * basic block containing the work portion of the instruction should
743 * only be entered via fallthrough from the block containing the
744 * pseudo exception edge MIR. Note also that this new block is
745 * not automatically terminated after the work portion, and may
746 * contain following instructions.
747 */
748 BasicBlock *newBlock = oatNewBB(cUnit, kDalvikByteCode, cUnit->numBlocks++);
749 oatInsertGrowableList(cUnit, &cUnit->blockList, (intptr_t)newBlock);
750 newBlock->startOffset = insn->offset;
751 curBlock->fallThrough = newBlock;
752 oatInsertGrowableList(cUnit, newBlock->predecessors, (intptr_t)curBlock);
753 MIR* newInsn = (MIR*)oatNew(cUnit, sizeof(MIR), true, kAllocMIR);
754 *newInsn = *insn;
755 insn->dalvikInsn.opcode =
756 static_cast<Instruction::Code>(kMirOpCheck);
757 // Associate the two halves
758 insn->meta.throwInsn = newInsn;
759 newInsn->meta.throwInsn = insn;
760 oatAppendMIR(newBlock, newInsn);
761 return newBlock;
buzbee67bf8852011-08-17 17:51:35 -0700762}
763
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800764void oatInit(CompilationUnit* cUnit, const Compiler& compiler) {
765 if (!oatArchInit()) {
766 LOG(FATAL) << "Failed to initialize oat";
767 }
768 if (!oatHeapInit(cUnit)) {
769 LOG(FATAL) << "Failed to initialize oat heap";
770 }
771}
772
Elliott Hughes3fa1b7e2012-03-13 17:06:22 -0700773CompiledMethod* oatCompileMethod(Compiler& compiler,
774 const DexFile::CodeItem* code_item,
Ian Rogers08f753d2012-08-24 14:35:25 -0700775 uint32_t access_flags, InvokeType invoke_type,
776 uint32_t method_idx,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700777 jobject class_loader,
Elliott Hughes3fa1b7e2012-03-13 17:06:22 -0700778 const DexFile& dex_file)
buzbee67bf8852011-08-17 17:51:35 -0700779{
Bill Buzbeea114add2012-05-03 15:00:40 -0700780 VLOG(compiler) << "Compiling " << PrettyMethod(method_idx, dex_file) << "...";
Brian Carlstrom94496d32011-08-22 09:22:47 -0700781
Bill Buzbeea114add2012-05-03 15:00:40 -0700782 const u2* codePtr = code_item->insns_;
783 const u2* codeEnd = code_item->insns_ + code_item->insns_size_in_code_units_;
784 int numBlocks = 0;
785 unsigned int curOffset = 0;
buzbee67bf8852011-08-17 17:51:35 -0700786
Bill Buzbeea114add2012-05-03 15:00:40 -0700787 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
788 UniquePtr<CompilationUnit> cUnit(new CompilationUnit);
buzbeeba938cb2012-02-03 14:47:55 -0800789
Bill Buzbeea114add2012-05-03 15:00:40 -0700790 oatInit(cUnit.get(), compiler);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800791
Bill Buzbeea114add2012-05-03 15:00:40 -0700792 cUnit->compiler = &compiler;
793 cUnit->class_linker = class_linker;
794 cUnit->dex_file = &dex_file;
Bill Buzbeea114add2012-05-03 15:00:40 -0700795 cUnit->method_idx = method_idx;
796 cUnit->code_item = code_item;
797 cUnit->access_flags = access_flags;
Ian Rogers08f753d2012-08-24 14:35:25 -0700798 cUnit->invoke_type = invoke_type;
Bill Buzbeea114add2012-05-03 15:00:40 -0700799 cUnit->shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
800 cUnit->instructionSet = compiler.GetInstructionSet();
801 cUnit->insns = code_item->insns_;
802 cUnit->insnsSize = code_item->insns_size_in_code_units_;
803 cUnit->numIns = code_item->ins_size_;
804 cUnit->numRegs = code_item->registers_size_ - cUnit->numIns;
805 cUnit->numOuts = code_item->outs_size_;
buzbee2cfc6392012-05-07 14:51:40 -0700806#if defined(ART_USE_QUICK_COMPILER)
Bill Buzbeec9f40dd2012-08-15 11:35:25 -0700807 DCHECK((cUnit->instructionSet == kThumb2) ||
808 (cUnit->instructionSet == kX86) ||
809 (cUnit->instructionSet == kMips));
810 if (cUnit->instructionSet == kThumb2) {
811 // TODO: remove this once x86 is tested
buzbee85eee022012-07-16 22:12:38 -0700812 cUnit->genBitcode = true;
813 }
buzbee2a83e8f2012-07-13 16:42:30 -0700814#endif
Bill Buzbeea114add2012-05-03 15:00:40 -0700815 /* Adjust this value accordingly once inlining is performed */
816 cUnit->numDalvikRegisters = code_item->registers_size_;
817 // TODO: set this from command line
818 cUnit->compilerFlipMatch = false;
819 bool useMatch = !cUnit->compilerMethodMatch.empty();
820 bool match = useMatch && (cUnit->compilerFlipMatch ^
821 (PrettyMethod(method_idx, dex_file).find(cUnit->compilerMethodMatch) !=
822 std::string::npos));
823 if (!useMatch || match) {
824 cUnit->disableOpt = kCompilerOptimizerDisableFlags;
825 cUnit->enableDebug = kCompilerDebugFlags;
826 cUnit->printMe = VLOG_IS_ON(compiler) ||
827 (cUnit->enableDebug & (1 << kDebugVerbose));
828 }
buzbee2cfc6392012-05-07 14:51:40 -0700829#if defined(ART_USE_QUICK_COMPILER)
buzbee6969d502012-06-15 16:40:31 -0700830 if (cUnit->genBitcode) {
Bill Buzbeec9f40dd2012-08-15 11:35:25 -0700831 //cUnit->enableDebug |= (1 << kDebugVerifyBitcode);
buzbee2a83e8f2012-07-13 16:42:30 -0700832 //cUnit->printMe = true;
833 //cUnit->enableDebug |= (1 << kDebugDumpBitcodeFile);
buzbee6969d502012-06-15 16:40:31 -0700834 }
buzbee2cfc6392012-05-07 14:51:40 -0700835#endif
jeffhao7fbee072012-08-24 17:56:54 -0700836 if (cUnit->instructionSet == kMips) {
837 // Disable some optimizations for mips for now
838 cUnit->disableOpt |= (
839 (1 << kLoadStoreElimination) |
840 (1 << kLoadHoisting) |
841 (1 << kSuppressLoads) |
842 (1 << kNullCheckElimination) |
843 (1 << kPromoteRegs) |
844 (1 << kTrackLiveTemps) |
845 (1 << kSkipLargeMethodOptimization) |
846 (1 << kSafeOptimizations) |
847 (1 << kBBOpt) |
848 (1 << kMatch) |
849 (1 << kPromoteCompilerTemps));
850 }
Bill Buzbeea114add2012-05-03 15:00:40 -0700851 /* Are we generating code for the debugger? */
852 if (compiler.IsDebuggingSupported()) {
853 cUnit->genDebugger = true;
854 // Yes, disable most optimizations
855 cUnit->disableOpt |= (
856 (1 << kLoadStoreElimination) |
857 (1 << kLoadHoisting) |
858 (1 << kSuppressLoads) |
859 (1 << kPromoteRegs) |
860 (1 << kBBOpt) |
861 (1 << kMatch) |
862 (1 << kTrackLiveTemps));
863 }
864
865 /* Gathering opcode stats? */
866 if (kCompilerDebugFlags & (1 << kDebugCountOpcodes)) {
867 cUnit->opcodeCount = (int*)oatNew(cUnit.get(),
868 kNumPackedOpcodes * sizeof(int), true, kAllocMisc);
869 }
870
871 /* Assume non-throwing leaf */
872 cUnit->attrs = (METHOD_IS_LEAF | METHOD_IS_THROW_FREE);
873
874 /* Initialize the block list, estimate size based on insnsSize */
875 oatInitGrowableList(cUnit.get(), &cUnit->blockList, cUnit->insnsSize,
876 kListBlockList);
877
878 /* Initialize the switchTables list */
879 oatInitGrowableList(cUnit.get(), &cUnit->switchTables, 4,
880 kListSwitchTables);
881
882 /* Intialize the fillArrayData list */
883 oatInitGrowableList(cUnit.get(), &cUnit->fillArrayData, 4,
884 kListFillArrayData);
885
886 /* Intialize the throwLaunchpads list, estimate size based on insnsSize */
887 oatInitGrowableList(cUnit.get(), &cUnit->throwLaunchpads, cUnit->insnsSize,
888 kListThrowLaunchPads);
889
890 /* Intialize the instrinsicLaunchpads list */
891 oatInitGrowableList(cUnit.get(), &cUnit->intrinsicLaunchpads, 4,
892 kListMisc);
893
894
895 /* Intialize the suspendLaunchpads list */
896 oatInitGrowableList(cUnit.get(), &cUnit->suspendLaunchpads, 2048,
897 kListSuspendLaunchPads);
898
899 /* Allocate the bit-vector to track the beginning of basic blocks */
900 ArenaBitVector *tryBlockAddr = oatAllocBitVector(cUnit.get(),
901 cUnit->insnsSize,
902 true /* expandable */);
903 cUnit->tryBlockAddr = tryBlockAddr;
904
905 /* Create the default entry and exit blocks and enter them to the list */
906 BasicBlock *entryBlock = oatNewBB(cUnit.get(), kEntryBlock, numBlocks++);
907 BasicBlock *exitBlock = oatNewBB(cUnit.get(), kExitBlock, numBlocks++);
908
909 cUnit->entryBlock = entryBlock;
910 cUnit->exitBlock = exitBlock;
911
912 oatInsertGrowableList(cUnit.get(), &cUnit->blockList, (intptr_t) entryBlock);
913 oatInsertGrowableList(cUnit.get(), &cUnit->blockList, (intptr_t) exitBlock);
914
915 /* Current block to record parsed instructions */
916 BasicBlock *curBlock = oatNewBB(cUnit.get(), kDalvikByteCode, numBlocks++);
917 curBlock->startOffset = 0;
918 oatInsertGrowableList(cUnit.get(), &cUnit->blockList, (intptr_t) curBlock);
919 /* Add first block to the fast lookup cache */
920 cUnit->blockMap.Put(curBlock->startOffset, curBlock);
921 entryBlock->fallThrough = curBlock;
922 oatInsertGrowableList(cUnit.get(), curBlock->predecessors,
923 (intptr_t)entryBlock);
924
925 /*
926 * Store back the number of blocks since new blocks may be created of
927 * accessing cUnit.
928 */
929 cUnit->numBlocks = numBlocks;
930
931 /* Identify code range in try blocks and set up the empty catch blocks */
932 processTryCatchBlocks(cUnit.get());
933
934 /* Set up for simple method detection */
935 int numPatterns = sizeof(specialPatterns)/sizeof(specialPatterns[0]);
936 bool livePattern = (numPatterns > 0) && !(cUnit->disableOpt & (1 << kMatch));
Elliott Hughesabe64aa2012-05-30 17:34:45 -0700937 bool* deadPattern = (bool*)oatNew(cUnit.get(), sizeof(bool) * numPatterns, true,
Bill Buzbeea114add2012-05-03 15:00:40 -0700938 kAllocMisc);
939 SpecialCaseHandler specialCase = kNoHandler;
940 int patternPos = 0;
941
942 /* Parse all instructions and put them into containing basic blocks */
943 while (codePtr < codeEnd) {
944 MIR *insn = (MIR *) oatNew(cUnit.get(), sizeof(MIR), true, kAllocMIR);
945 insn->offset = curOffset;
946 int width = parseInsn(cUnit.get(), codePtr, &insn->dalvikInsn, false);
947 insn->width = width;
948 Instruction::Code opcode = insn->dalvikInsn.opcode;
949 if (cUnit->opcodeCount != NULL) {
950 cUnit->opcodeCount[static_cast<int>(opcode)]++;
buzbee44b412b2012-02-04 08:50:53 -0800951 }
952
Bill Buzbeea114add2012-05-03 15:00:40 -0700953 /* Terminate when the data section is seen */
954 if (width == 0)
955 break;
956
957 /* Possible simple method? */
958 if (livePattern) {
959 livePattern = false;
960 specialCase = kNoHandler;
961 for (int i = 0; i < numPatterns; i++) {
962 if (!deadPattern[i]) {
963 if (specialPatterns[i].opcodes[patternPos] == opcode) {
964 livePattern = true;
965 specialCase = specialPatterns[i].handlerCode;
966 } else {
967 deadPattern[i] = true;
968 }
969 }
970 }
971 patternPos++;
buzbeea7c12682012-03-19 13:13:53 -0700972 }
973
Bill Buzbeea114add2012-05-03 15:00:40 -0700974 oatAppendMIR(curBlock, insn);
buzbeecefd1872011-09-09 09:59:52 -0700975
Bill Buzbeea114add2012-05-03 15:00:40 -0700976 codePtr += width;
977 int flags = Instruction::Flags(insn->dalvikInsn.opcode);
buzbee67bf8852011-08-17 17:51:35 -0700978
Bill Buzbeea114add2012-05-03 15:00:40 -0700979 int dfFlags = oatDataFlowAttributes[insn->dalvikInsn.opcode];
buzbee67bf8852011-08-17 17:51:35 -0700980
Bill Buzbeea114add2012-05-03 15:00:40 -0700981 if (dfFlags & DF_HAS_DEFS) {
buzbeebff24652012-05-06 16:22:05 -0700982 cUnit->defCount += (dfFlags & DF_A_WIDE) ? 2 : 1;
Bill Buzbeea114add2012-05-03 15:00:40 -0700983 }
buzbee67bf8852011-08-17 17:51:35 -0700984
Bill Buzbeea114add2012-05-03 15:00:40 -0700985 if (flags & Instruction::kBranch) {
986 curBlock = processCanBranch(cUnit.get(), curBlock, insn, curOffset,
987 width, flags, codePtr, codeEnd);
988 } else if (flags & Instruction::kReturn) {
989 curBlock->fallThrough = exitBlock;
990 oatInsertGrowableList(cUnit.get(), exitBlock->predecessors,
991 (intptr_t)curBlock);
992 /*
993 * Terminate the current block if there are instructions
994 * afterwards.
995 */
996 if (codePtr < codeEnd) {
997 /*
998 * Create a fallthrough block for real instructions
999 * (incl. NOP).
1000 */
1001 if (contentIsInsn(codePtr)) {
1002 findBlock(cUnit.get(), curOffset + width,
1003 /* split */
1004 false,
1005 /* create */
1006 true,
1007 /* immedPredBlockP */
1008 NULL);
1009 }
1010 }
1011 } else if (flags & Instruction::kThrow) {
Bill Buzbeec9f40dd2012-08-15 11:35:25 -07001012 curBlock = processCanThrow(cUnit.get(), curBlock, insn, curOffset,
1013 width, flags, tryBlockAddr, codePtr, codeEnd);
Bill Buzbeea114add2012-05-03 15:00:40 -07001014 } else if (flags & Instruction::kSwitch) {
1015 processCanSwitch(cUnit.get(), curBlock, insn, curOffset, width, flags);
1016 }
1017 curOffset += width;
1018 BasicBlock *nextBlock = findBlock(cUnit.get(), curOffset,
1019 /* split */
1020 false,
1021 /* create */
1022 false,
1023 /* immedPredBlockP */
1024 NULL);
1025 if (nextBlock) {
1026 /*
1027 * The next instruction could be the target of a previously parsed
1028 * forward branch so a block is already created. If the current
1029 * instruction is not an unconditional branch, connect them through
1030 * the fall-through link.
1031 */
1032 DCHECK(curBlock->fallThrough == NULL ||
1033 curBlock->fallThrough == nextBlock ||
1034 curBlock->fallThrough == exitBlock);
buzbee5ade1d22011-09-09 14:44:52 -07001035
Bill Buzbeea114add2012-05-03 15:00:40 -07001036 if ((curBlock->fallThrough == NULL) && (flags & Instruction::kContinue)) {
1037 curBlock->fallThrough = nextBlock;
1038 oatInsertGrowableList(cUnit.get(), nextBlock->predecessors,
1039 (intptr_t)curBlock);
1040 }
1041 curBlock = nextBlock;
1042 }
1043 }
buzbeefc9e6fa2012-03-23 15:14:29 -07001044
Bill Buzbeea114add2012-05-03 15:00:40 -07001045 if (!(cUnit->disableOpt & (1 << kSkipLargeMethodOptimization))) {
1046 if ((cUnit->numBlocks > MANY_BLOCKS) ||
1047 ((cUnit->numBlocks > MANY_BLOCKS_INITIALIZER) &&
1048 PrettyMethod(method_idx, dex_file, false).find("init>") !=
1049 std::string::npos)) {
1050 cUnit->qdMode = true;
1051 }
1052 }
buzbeefc9e6fa2012-03-23 15:14:29 -07001053
Bill Buzbeea114add2012-05-03 15:00:40 -07001054 if (cUnit->qdMode) {
buzbeed1643e42012-09-05 14:06:51 -07001055#if !defined(ART_USE_QUICK_COMPILER)
1056 // Bitcode generation requires full dataflow analysis
Bill Buzbeea114add2012-05-03 15:00:40 -07001057 cUnit->disableDataflow = true;
buzbeed1643e42012-09-05 14:06:51 -07001058#endif
Bill Buzbeea114add2012-05-03 15:00:40 -07001059 // Disable optimization which require dataflow/ssa
1060 cUnit->disableOpt |=
buzbeed1643e42012-09-05 14:06:51 -07001061#if !defined(ART_USE_QUICK_COMPILER)
Bill Buzbeea114add2012-05-03 15:00:40 -07001062 (1 << kNullCheckElimination) |
buzbeed1643e42012-09-05 14:06:51 -07001063#endif
Bill Buzbeea114add2012-05-03 15:00:40 -07001064 (1 << kBBOpt) |
1065 (1 << kPromoteRegs);
1066 if (cUnit->printMe) {
1067 LOG(INFO) << "QD mode enabled: "
1068 << PrettyMethod(method_idx, dex_file)
1069 << " too big: " << cUnit->numBlocks;
1070 }
1071 }
buzbeec1f45042011-09-21 16:03:19 -07001072
Bill Buzbeea114add2012-05-03 15:00:40 -07001073 if (cUnit->printMe) {
1074 oatDumpCompilationUnit(cUnit.get());
1075 }
buzbee67bf8852011-08-17 17:51:35 -07001076
Bill Buzbeea114add2012-05-03 15:00:40 -07001077 if (cUnit->enableDebug & (1 << kDebugVerifyDataflow)) {
1078 /* Verify if all blocks are connected as claimed */
1079 oatDataFlowAnalysisDispatcher(cUnit.get(), verifyPredInfo, kAllNodes,
1080 false /* isIterative */);
1081 }
buzbee67bf8852011-08-17 17:51:35 -07001082
Bill Buzbeea114add2012-05-03 15:00:40 -07001083 /* Perform SSA transformation for the whole method */
1084 oatMethodSSATransformation(cUnit.get());
buzbee67bf8852011-08-17 17:51:35 -07001085
buzbee2cfc6392012-05-07 14:51:40 -07001086 /* Do constant propagation */
1087 // TODO: Probably need to make these expandable to support new ssa names
1088 // introducted during MIR optimization passes
1089 cUnit->isConstantV = oatAllocBitVector(cUnit.get(), cUnit->numSSARegs,
1090 false /* not expandable */);
1091 cUnit->constantValues =
1092 (int*)oatNew(cUnit.get(), sizeof(int) * cUnit->numSSARegs, true,
1093 kAllocDFInfo);
1094 oatDataFlowAnalysisDispatcher(cUnit.get(), oatDoConstantPropagation,
1095 kAllNodes,
1096 false /* isIterative */);
1097
Bill Buzbeea114add2012-05-03 15:00:40 -07001098 /* Detect loops */
1099 oatMethodLoopDetection(cUnit.get());
buzbee67bf8852011-08-17 17:51:35 -07001100
Bill Buzbeea114add2012-05-03 15:00:40 -07001101 /* Count uses */
1102 oatMethodUseCount(cUnit.get());
buzbee67bf8852011-08-17 17:51:35 -07001103
Bill Buzbeea114add2012-05-03 15:00:40 -07001104 /* Perform null check elimination */
1105 oatMethodNullCheckElimination(cUnit.get());
1106
buzbeed1643e42012-09-05 14:06:51 -07001107 /* Combine basic blocks where possible */
1108 oatMethodBasicBlockCombine(cUnit.get());
1109
Bill Buzbeea114add2012-05-03 15:00:40 -07001110 /* Do some basic block optimizations */
1111 oatMethodBasicBlockOptimization(cUnit.get());
1112
buzbeed1643e42012-09-05 14:06:51 -07001113 if (cUnit->enableDebug & (1 << kDebugDumpCheckStats)) {
1114 oatDumpCheckStats(cUnit.get());
1115 }
1116
Bill Buzbeea114add2012-05-03 15:00:40 -07001117 oatInitializeRegAlloc(cUnit.get()); // Needs to happen after SSA naming
1118
1119 /* Allocate Registers using simple local allocation scheme */
1120 oatSimpleRegAlloc(cUnit.get());
1121
buzbee2cfc6392012-05-07 14:51:40 -07001122#if defined(ART_USE_QUICK_COMPILER)
1123 /* Go the LLVM path? */
1124 if (cUnit->genBitcode) {
1125 // MIR->Bitcode
1126 oatMethodMIR2Bitcode(cUnit.get());
1127 // Bitcode->LIR
1128 oatMethodBitcode2LIR(cUnit.get());
1129 } else {
1130#endif
1131 if (specialCase != kNoHandler) {
1132 /*
1133 * Custom codegen for special cases. If for any reason the
1134 * special codegen doesn't succeed, cUnit->firstLIRInsn will
1135 * set to NULL;
1136 */
1137 oatSpecialMIR2LIR(cUnit.get(), specialCase);
1138 }
buzbee67bf8852011-08-17 17:51:35 -07001139
buzbee2cfc6392012-05-07 14:51:40 -07001140 /* Convert MIR to LIR, etc. */
1141 if (cUnit->firstLIRInsn == NULL) {
1142 oatMethodMIR2LIR(cUnit.get());
1143 }
1144#if defined(ART_USE_QUICK_COMPILER)
Bill Buzbeea114add2012-05-03 15:00:40 -07001145 }
buzbee2cfc6392012-05-07 14:51:40 -07001146#endif
buzbee67bf8852011-08-17 17:51:35 -07001147
Bill Buzbeea114add2012-05-03 15:00:40 -07001148 // Debugging only
1149 if (cUnit->enableDebug & (1 << kDebugDumpCFG)) {
1150 oatDumpCFG(cUnit.get(), "/sdcard/cfg/");
1151 }
buzbee16da88c2012-03-20 10:38:17 -07001152
Bill Buzbeea114add2012-05-03 15:00:40 -07001153 /* Method is not empty */
1154 if (cUnit->firstLIRInsn) {
buzbee67bf8852011-08-17 17:51:35 -07001155
Bill Buzbeea114add2012-05-03 15:00:40 -07001156 // mark the targets of switch statement case labels
1157 oatProcessSwitchTables(cUnit.get());
buzbee67bf8852011-08-17 17:51:35 -07001158
Bill Buzbeea114add2012-05-03 15:00:40 -07001159 /* Convert LIR into machine code. */
1160 oatAssembleLIR(cUnit.get());
buzbee99ba9642012-01-25 14:23:14 -08001161
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07001162 if (cUnit->printMe) {
Bill Buzbeea114add2012-05-03 15:00:40 -07001163 oatCodegenDump(cUnit.get());
buzbee67bf8852011-08-17 17:51:35 -07001164 }
1165
Bill Buzbeea114add2012-05-03 15:00:40 -07001166 if (cUnit->opcodeCount != NULL) {
1167 LOG(INFO) << "Opcode Count";
1168 for (int i = 0; i < kNumPackedOpcodes; i++) {
1169 if (cUnit->opcodeCount[i] != 0) {
1170 LOG(INFO) << "-C- "
1171 << Instruction::Name(static_cast<Instruction::Code>(i))
1172 << " " << cUnit->opcodeCount[i];
buzbee67bf8852011-08-17 17:51:35 -07001173 }
Bill Buzbeea114add2012-05-03 15:00:40 -07001174 }
1175 }
1176 }
buzbeea7c12682012-03-19 13:13:53 -07001177
Bill Buzbeea114add2012-05-03 15:00:40 -07001178 // Combine vmap tables - core regs, then fp regs - into vmapTable
1179 std::vector<uint16_t> vmapTable;
buzbeeca7a5e42012-08-20 11:12:18 -07001180 // Core regs may have been inserted out of order - sort first
1181 std::sort(cUnit->coreVmapTable.begin(), cUnit->coreVmapTable.end());
Bill Buzbeea114add2012-05-03 15:00:40 -07001182 for (size_t i = 0 ; i < cUnit->coreVmapTable.size(); i++) {
buzbeeca7a5e42012-08-20 11:12:18 -07001183 // Copy, stripping out the phys register sort key
1184 vmapTable.push_back(~(-1 << VREG_NUM_WIDTH) & cUnit->coreVmapTable[i]);
Bill Buzbeea114add2012-05-03 15:00:40 -07001185 }
1186 // If we have a frame, push a marker to take place of lr
1187 if (cUnit->frameSize > 0) {
1188 vmapTable.push_back(INVALID_VREG);
1189 } else {
1190 DCHECK_EQ(__builtin_popcount(cUnit->coreSpillMask), 0);
1191 DCHECK_EQ(__builtin_popcount(cUnit->fpSpillMask), 0);
1192 }
buzbeeca7a5e42012-08-20 11:12:18 -07001193 // Combine vmap tables - core regs, then fp regs. fp regs already sorted
Bill Buzbeea114add2012-05-03 15:00:40 -07001194 for (uint32_t i = 0; i < cUnit->fpVmapTable.size(); i++) {
1195 vmapTable.push_back(cUnit->fpVmapTable[i]);
1196 }
1197 CompiledMethod* result =
1198 new CompiledMethod(cUnit->instructionSet, cUnit->codeBuffer,
1199 cUnit->frameSize, cUnit->coreSpillMask,
1200 cUnit->fpSpillMask, cUnit->mappingTable, vmapTable);
buzbee67bf8852011-08-17 17:51:35 -07001201
Bill Buzbeea114add2012-05-03 15:00:40 -07001202 VLOG(compiler) << "Compiled " << PrettyMethod(method_idx, dex_file)
1203 << " (" << (cUnit->codeBuffer.size() * sizeof(cUnit->codeBuffer[0]))
1204 << " bytes)";
buzbee5abfa3e2012-01-31 17:01:43 -08001205
1206#ifdef WITH_MEMSTATS
Bill Buzbeea114add2012-05-03 15:00:40 -07001207 if (cUnit->enableDebug & (1 << kDebugShowMemoryUsage)) {
1208 oatDumpMemStats(cUnit.get());
1209 }
buzbee5abfa3e2012-01-31 17:01:43 -08001210#endif
buzbee67bf8852011-08-17 17:51:35 -07001211
Bill Buzbeea114add2012-05-03 15:00:40 -07001212 oatArenaReset(cUnit.get());
buzbeeba938cb2012-02-03 14:47:55 -08001213
Bill Buzbeea114add2012-05-03 15:00:40 -07001214 return result;
buzbee67bf8852011-08-17 17:51:35 -07001215}
1216
Elliott Hughes11d1b0c2012-01-23 16:57:47 -08001217} // namespace art
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001218
Bill Buzbeea114add2012-05-03 15:00:40 -07001219extern "C" art::CompiledMethod*
1220 ArtCompileMethod(art::Compiler& compiler,
1221 const art::DexFile::CodeItem* code_item,
Ian Rogers08f753d2012-08-24 14:35:25 -07001222 uint32_t access_flags, art::InvokeType invoke_type,
1223 uint32_t method_idx, jobject class_loader,
Bill Buzbeea114add2012-05-03 15:00:40 -07001224 const art::DexFile& dex_file)
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001225{
1226 CHECK_EQ(compiler.GetInstructionSet(), art::oatInstructionSet());
Ian Rogers08f753d2012-08-24 14:35:25 -07001227 return art::oatCompileMethod(compiler, code_item, access_flags, invoke_type,
1228 method_idx, class_loader, dex_file);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001229}