blob: 51b9d9d2924351973940a0a40b8d3872888611e8 [file] [log] [blame]
buzbee311ca162013-02-28 15:56:43 -08001/*
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 "compiler_internals.h"
18#include "local_value_numbering.h"
19#include "dataflow_iterator.h"
20
21namespace art {
22
23static unsigned int Predecessors(BasicBlock* bb)
24{
25 return bb->predecessors->num_used;
26}
27
28/* Setup a constant value for opcodes thare have the DF_SETS_CONST attribute */
29void MIRGraph::SetConstant(int32_t ssa_reg, int value)
30{
31 SetBit(cu_, is_constant_v_, ssa_reg);
32 constant_values_[ssa_reg] = value;
33}
34
35void MIRGraph::SetConstantWide(int ssa_reg, int64_t value)
36{
37 SetBit(cu_, is_constant_v_, ssa_reg);
38 constant_values_[ssa_reg] = Low32Bits(value);
39 constant_values_[ssa_reg + 1] = High32Bits(value);
40}
41
42bool MIRGraph::DoConstantPropogation(BasicBlock* bb)
43{
44 MIR* mir;
45 ArenaBitVector *is_constant_v = is_constant_v_;
46
47 for (mir = bb->first_mir_insn; mir != NULL; mir = mir->next) {
buzbee1fd33462013-03-25 13:40:45 -070048 int df_attributes = oat_data_flow_attributes_[mir->dalvikInsn.opcode];
buzbee311ca162013-02-28 15:56:43 -080049
50 DecodedInstruction *d_insn = &mir->dalvikInsn;
51
52 if (!(df_attributes & DF_HAS_DEFS)) continue;
53
54 /* Handle instructions that set up constants directly */
55 if (df_attributes & DF_SETS_CONST) {
56 if (df_attributes & DF_DA) {
57 int32_t vB = static_cast<int32_t>(d_insn->vB);
58 switch (d_insn->opcode) {
59 case Instruction::CONST_4:
60 case Instruction::CONST_16:
61 case Instruction::CONST:
62 SetConstant(mir->ssa_rep->defs[0], vB);
63 break;
64 case Instruction::CONST_HIGH16:
65 SetConstant(mir->ssa_rep->defs[0], vB << 16);
66 break;
67 case Instruction::CONST_WIDE_16:
68 case Instruction::CONST_WIDE_32:
69 SetConstantWide(mir->ssa_rep->defs[0], static_cast<int64_t>(vB));
70 break;
71 case Instruction::CONST_WIDE:
72 SetConstantWide(mir->ssa_rep->defs[0],d_insn->vB_wide);
73 break;
74 case Instruction::CONST_WIDE_HIGH16:
75 SetConstantWide(mir->ssa_rep->defs[0], static_cast<int64_t>(vB) << 48);
76 break;
77 default:
78 break;
79 }
80 }
81 /* Handle instructions that set up constants directly */
82 } else if (df_attributes & DF_IS_MOVE) {
83 int i;
84
85 for (i = 0; i < mir->ssa_rep->num_uses; i++) {
86 if (!IsBitSet(is_constant_v, mir->ssa_rep->uses[i])) break;
87 }
88 /* Move a register holding a constant to another register */
89 if (i == mir->ssa_rep->num_uses) {
90 SetConstant(mir->ssa_rep->defs[0], constant_values_[mir->ssa_rep->uses[0]]);
91 if (df_attributes & DF_A_WIDE) {
92 SetConstant(mir->ssa_rep->defs[1], constant_values_[mir->ssa_rep->uses[1]]);
93 }
94 }
95 }
96 }
97 /* TODO: implement code to handle arithmetic operations */
98 return true;
99}
100
101void MIRGraph::PropagateConstants()
102{
103 is_constant_v_ = AllocBitVector(cu_, GetNumSSARegs(), false);
104 constant_values_ = static_cast<int*>(NewMem(cu_, sizeof(int) * GetNumSSARegs(), true,
105 kAllocDFInfo));
buzbee0665fe02013-03-21 12:32:21 -0700106 AllNodesIterator iter(this, false /* not iterative */);
buzbee311ca162013-02-28 15:56:43 -0800107 for (BasicBlock* bb = iter.Next(); bb != NULL; bb = iter.Next()) {
108 DoConstantPropogation(bb);
109 }
buzbee311ca162013-02-28 15:56:43 -0800110}
111
112/* Advance to next strictly dominated MIR node in an extended basic block */
113static MIR* AdvanceMIR(BasicBlock** p_bb, MIR* mir)
114{
115 BasicBlock* bb = *p_bb;
116 if (mir != NULL) {
117 mir = mir->next;
118 if (mir == NULL) {
119 bb = bb->fall_through;
120 if ((bb == NULL) || Predecessors(bb) != 1) {
121 mir = NULL;
122 } else {
123 *p_bb = bb;
124 mir = bb->first_mir_insn;
125 }
126 }
127 }
128 return mir;
129}
130
131/*
132 * To be used at an invoke mir. If the logically next mir node represents
133 * a move-result, return it. Else, return NULL. If a move-result exists,
134 * it is required to immediately follow the invoke with no intervening
135 * opcodes or incoming arcs. However, if the result of the invoke is not
136 * used, a move-result may not be present.
137 */
138MIR* MIRGraph::FindMoveResult(BasicBlock* bb, MIR* mir)
139{
140 BasicBlock* tbb = bb;
141 mir = AdvanceMIR(&tbb, mir);
142 while (mir != NULL) {
143 int opcode = mir->dalvikInsn.opcode;
144 if ((mir->dalvikInsn.opcode == Instruction::MOVE_RESULT) ||
145 (mir->dalvikInsn.opcode == Instruction::MOVE_RESULT_OBJECT) ||
146 (mir->dalvikInsn.opcode == Instruction::MOVE_RESULT_WIDE)) {
147 break;
148 }
149 // Keep going if pseudo op, otherwise terminate
150 if (opcode < kNumPackedOpcodes) {
151 mir = NULL;
152 } else {
153 mir = AdvanceMIR(&tbb, mir);
154 }
155 }
156 return mir;
157}
158
159static BasicBlock* NextDominatedBlock(BasicBlock* bb)
160{
161 if (bb->block_type == kDead) {
162 return NULL;
163 }
164 DCHECK((bb->block_type == kEntryBlock) || (bb->block_type == kDalvikByteCode)
165 || (bb->block_type == kExitBlock));
166 bb = bb->fall_through;
167 if (bb == NULL || (Predecessors(bb) != 1)) {
168 return NULL;
169 }
170 DCHECK((bb->block_type == kDalvikByteCode) || (bb->block_type == kExitBlock));
171 return bb;
172}
173
174static MIR* FindPhi(BasicBlock* bb, int ssa_name)
175{
176 for (MIR* mir = bb->first_mir_insn; mir != NULL; mir = mir->next) {
177 if (static_cast<int>(mir->dalvikInsn.opcode) == kMirOpPhi) {
178 for (int i = 0; i < mir->ssa_rep->num_uses; i++) {
179 if (mir->ssa_rep->uses[i] == ssa_name) {
180 return mir;
181 }
182 }
183 }
184 }
185 return NULL;
186}
187
188static SelectInstructionKind SelectKind(MIR* mir)
189{
190 switch (mir->dalvikInsn.opcode) {
191 case Instruction::MOVE:
192 case Instruction::MOVE_OBJECT:
193 case Instruction::MOVE_16:
194 case Instruction::MOVE_OBJECT_16:
195 case Instruction::MOVE_FROM16:
196 case Instruction::MOVE_OBJECT_FROM16:
197 return kSelectMove;
198 case Instruction::CONST:
199 case Instruction::CONST_4:
200 case Instruction::CONST_16:
201 return kSelectConst;
202 case Instruction::GOTO:
203 case Instruction::GOTO_16:
204 case Instruction::GOTO_32:
205 return kSelectGoto;
206 default:;
207 }
208 return kSelectNone;
209}
210
211int MIRGraph::GetSSAUseCount(int s_reg)
212{
213 DCHECK(s_reg < static_cast<int>(raw_use_counts_.num_used));
214 return raw_use_counts_.elem_list[s_reg];
215}
216
217
218/* Do some MIR-level extended basic block optimizations */
219bool MIRGraph::BasicBlockOpt(BasicBlock* bb)
220{
221 if (bb->block_type == kDead) {
222 return true;
223 }
224 int num_temps = 0;
225 LocalValueNumbering local_valnum(cu_);
226 while (bb != NULL) {
227 for (MIR* mir = bb->first_mir_insn; mir != NULL; mir = mir->next) {
228 // TUNING: use the returned value number for CSE.
229 local_valnum.GetValueNumber(mir);
230 // Look for interesting opcodes, skip otherwise
231 Instruction::Code opcode = mir->dalvikInsn.opcode;
232 switch (opcode) {
233 case Instruction::CMPL_FLOAT:
234 case Instruction::CMPL_DOUBLE:
235 case Instruction::CMPG_FLOAT:
236 case Instruction::CMPG_DOUBLE:
237 case Instruction::CMP_LONG:
buzbee1fd33462013-03-25 13:40:45 -0700238 if ((cu_->disable_opt & (1 << kBranchFusing)) != 0) {
buzbee311ca162013-02-28 15:56:43 -0800239 // Bitcode doesn't allow this optimization.
240 break;
241 }
242 if (mir->next != NULL) {
243 MIR* mir_next = mir->next;
244 Instruction::Code br_opcode = mir_next->dalvikInsn.opcode;
245 ConditionCode ccode = kCondNv;
246 switch(br_opcode) {
247 case Instruction::IF_EQZ:
248 ccode = kCondEq;
249 break;
250 case Instruction::IF_NEZ:
251 ccode = kCondNe;
252 break;
253 case Instruction::IF_LTZ:
254 ccode = kCondLt;
255 break;
256 case Instruction::IF_GEZ:
257 ccode = kCondGe;
258 break;
259 case Instruction::IF_GTZ:
260 ccode = kCondGt;
261 break;
262 case Instruction::IF_LEZ:
263 ccode = kCondLe;
264 break;
265 default:
266 break;
267 }
268 // Make sure result of cmp is used by next insn and nowhere else
269 if ((ccode != kCondNv) &&
270 (mir->ssa_rep->defs[0] == mir_next->ssa_rep->uses[0]) &&
271 (GetSSAUseCount(mir->ssa_rep->defs[0]) == 1)) {
272 mir_next->dalvikInsn.arg[0] = ccode;
273 switch(opcode) {
274 case Instruction::CMPL_FLOAT:
275 mir_next->dalvikInsn.opcode =
276 static_cast<Instruction::Code>(kMirOpFusedCmplFloat);
277 break;
278 case Instruction::CMPL_DOUBLE:
279 mir_next->dalvikInsn.opcode =
280 static_cast<Instruction::Code>(kMirOpFusedCmplDouble);
281 break;
282 case Instruction::CMPG_FLOAT:
283 mir_next->dalvikInsn.opcode =
284 static_cast<Instruction::Code>(kMirOpFusedCmpgFloat);
285 break;
286 case Instruction::CMPG_DOUBLE:
287 mir_next->dalvikInsn.opcode =
288 static_cast<Instruction::Code>(kMirOpFusedCmpgDouble);
289 break;
290 case Instruction::CMP_LONG:
291 mir_next->dalvikInsn.opcode =
292 static_cast<Instruction::Code>(kMirOpFusedCmpLong);
293 break;
294 default: LOG(ERROR) << "Unexpected opcode: " << opcode;
295 }
296 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
297 mir_next->ssa_rep->num_uses = mir->ssa_rep->num_uses;
298 mir_next->ssa_rep->uses = mir->ssa_rep->uses;
299 mir_next->ssa_rep->fp_use = mir->ssa_rep->fp_use;
300 mir_next->ssa_rep->num_defs = 0;
301 mir->ssa_rep->num_uses = 0;
302 mir->ssa_rep->num_defs = 0;
303 }
304 }
305 break;
306 case Instruction::GOTO:
307 case Instruction::GOTO_16:
308 case Instruction::GOTO_32:
309 case Instruction::IF_EQ:
310 case Instruction::IF_NE:
311 case Instruction::IF_LT:
312 case Instruction::IF_GE:
313 case Instruction::IF_GT:
314 case Instruction::IF_LE:
315 case Instruction::IF_EQZ:
316 case Instruction::IF_NEZ:
317 case Instruction::IF_LTZ:
318 case Instruction::IF_GEZ:
319 case Instruction::IF_GTZ:
320 case Instruction::IF_LEZ:
321 if (bb->taken->dominates_return) {
322 mir->optimization_flags |= MIR_IGNORE_SUSPEND_CHECK;
323 if (cu_->verbose) {
324 LOG(INFO) << "Suppressed suspend check on branch to return at 0x" << std::hex << mir->offset;
325 }
326 }
327 break;
328 default:
329 break;
330 }
331 // Is this the select pattern?
332 // TODO: flesh out support for Mips and X86. NOTE: llvm's select op doesn't quite work here.
333 // TUNING: expand to support IF_xx compare & branches
buzbee1fd33462013-03-25 13:40:45 -0700334 if (!(cu_->compiler_backend == kPortable) && (cu_->instruction_set == kThumb2) &&
buzbee311ca162013-02-28 15:56:43 -0800335 ((mir->dalvikInsn.opcode == Instruction::IF_EQZ) ||
336 (mir->dalvikInsn.opcode == Instruction::IF_NEZ))) {
337 BasicBlock* ft = bb->fall_through;
338 DCHECK(ft != NULL);
339 BasicBlock* ft_ft = ft->fall_through;
340 BasicBlock* ft_tk = ft->taken;
341
342 BasicBlock* tk = bb->taken;
343 DCHECK(tk != NULL);
344 BasicBlock* tk_ft = tk->fall_through;
345 BasicBlock* tk_tk = tk->taken;
346
347 /*
348 * In the select pattern, the taken edge goes to a block that unconditionally
349 * transfers to the rejoin block and the fall_though edge goes to a block that
350 * unconditionally falls through to the rejoin block.
351 */
352 if ((tk_ft == NULL) && (ft_tk == NULL) && (tk_tk == ft_ft) &&
353 (Predecessors(tk) == 1) && (Predecessors(ft) == 1)) {
354 /*
355 * Okay - we have the basic diamond shape. At the very least, we can eliminate the
356 * suspend check on the taken-taken branch back to the join point.
357 */
358 if (SelectKind(tk->last_mir_insn) == kSelectGoto) {
359 tk->last_mir_insn->optimization_flags |= (MIR_IGNORE_SUSPEND_CHECK);
360 }
361 // Are the block bodies something we can handle?
362 if ((ft->first_mir_insn == ft->last_mir_insn) &&
363 (tk->first_mir_insn != tk->last_mir_insn) &&
364 (tk->first_mir_insn->next == tk->last_mir_insn) &&
365 ((SelectKind(ft->first_mir_insn) == kSelectMove) ||
366 (SelectKind(ft->first_mir_insn) == kSelectConst)) &&
367 (SelectKind(ft->first_mir_insn) == SelectKind(tk->first_mir_insn)) &&
368 (SelectKind(tk->last_mir_insn) == kSelectGoto)) {
369 // Almost there. Are the instructions targeting the same vreg?
370 MIR* if_true = tk->first_mir_insn;
371 MIR* if_false = ft->first_mir_insn;
372 // It's possible that the target of the select isn't used - skip those (rare) cases.
373 MIR* phi = FindPhi(tk_tk, if_true->ssa_rep->defs[0]);
374 if ((phi != NULL) && (if_true->dalvikInsn.vA == if_false->dalvikInsn.vA)) {
375 /*
376 * We'll convert the IF_EQZ/IF_NEZ to a SELECT. We need to find the
377 * Phi node in the merge block and delete it (while using the SSA name
378 * of the merge as the target of the SELECT. Delete both taken and
379 * fallthrough blocks, and set fallthrough to merge block.
380 * NOTE: not updating other dataflow info (no longer used at this point).
381 * If this changes, need to update i_dom, etc. here (and in CombineBlocks).
382 */
383 if (opcode == Instruction::IF_NEZ) {
384 // Normalize.
385 MIR* tmp_mir = if_true;
386 if_true = if_false;
387 if_false = tmp_mir;
388 }
389 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpSelect);
390 bool const_form = (SelectKind(if_true) == kSelectConst);
391 if ((SelectKind(if_true) == kSelectMove)) {
392 if (IsConst(if_true->ssa_rep->uses[0]) &&
393 IsConst(if_false->ssa_rep->uses[0])) {
394 const_form = true;
395 if_true->dalvikInsn.vB = ConstantValue(if_true->ssa_rep->uses[0]);
396 if_false->dalvikInsn.vB = ConstantValue(if_false->ssa_rep->uses[0]);
397 }
398 }
399 if (const_form) {
400 // "true" set val in vB
401 mir->dalvikInsn.vB = if_true->dalvikInsn.vB;
402 // "false" set val in vC
403 mir->dalvikInsn.vC = if_false->dalvikInsn.vB;
404 } else {
405 DCHECK_EQ(SelectKind(if_true), kSelectMove);
406 DCHECK_EQ(SelectKind(if_false), kSelectMove);
407 int* src_ssa = static_cast<int*>(NewMem(cu_, sizeof(int) * 3, false,
408 kAllocDFInfo));
409 src_ssa[0] = mir->ssa_rep->uses[0];
410 src_ssa[1] = if_true->ssa_rep->uses[0];
411 src_ssa[2] = if_false->ssa_rep->uses[0];
412 mir->ssa_rep->uses = src_ssa;
413 mir->ssa_rep->num_uses = 3;
414 }
415 mir->ssa_rep->num_defs = 1;
416 mir->ssa_rep->defs = static_cast<int*>(NewMem(cu_, sizeof(int) * 1, false,
417 kAllocDFInfo));
418 mir->ssa_rep->fp_def = static_cast<bool*>(NewMem(cu_, sizeof(bool) * 1, false,
419 kAllocDFInfo));
420 mir->ssa_rep->fp_def[0] = if_true->ssa_rep->fp_def[0];
421 /*
422 * There is usually a Phi node in the join block for our two cases. If the
423 * Phi node only contains our two cases as input, we will use the result
424 * SSA name of the Phi node as our select result and delete the Phi. If
425 * the Phi node has more than two operands, we will arbitrarily use the SSA
426 * name of the "true" path, delete the SSA name of the "false" path from the
427 * Phi node (and fix up the incoming arc list).
428 */
429 if (phi->ssa_rep->num_uses == 2) {
430 mir->ssa_rep->defs[0] = phi->ssa_rep->defs[0];
431 phi->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
432 } else {
433 int dead_def = if_false->ssa_rep->defs[0];
434 int live_def = if_true->ssa_rep->defs[0];
435 mir->ssa_rep->defs[0] = live_def;
436 int* incoming = reinterpret_cast<int*>(phi->dalvikInsn.vB);
437 for (int i = 0; i < phi->ssa_rep->num_uses; i++) {
438 if (phi->ssa_rep->uses[i] == live_def) {
439 incoming[i] = bb->id;
440 }
441 }
442 for (int i = 0; i < phi->ssa_rep->num_uses; i++) {
443 if (phi->ssa_rep->uses[i] == dead_def) {
444 int last_slot = phi->ssa_rep->num_uses - 1;
445 phi->ssa_rep->uses[i] = phi->ssa_rep->uses[last_slot];
446 incoming[i] = incoming[last_slot];
447 }
448 }
449 }
450 phi->ssa_rep->num_uses--;
451 bb->taken = NULL;
452 tk->block_type = kDead;
453 for (MIR* tmir = ft->first_mir_insn; tmir != NULL; tmir = tmir->next) {
454 tmir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
455 }
456 }
457 }
458 }
459 }
460 }
461 bb = NextDominatedBlock(bb);
462 }
463
464 if (num_temps > cu_->num_compiler_temps) {
465 cu_->num_compiler_temps = num_temps;
466 }
467 return true;
468}
469
470bool MIRGraph::NullCheckEliminationInit(struct BasicBlock* bb)
471{
472 if (bb->data_flow_info == NULL) return false;
473 bb->data_flow_info->ending_null_check_v =
474 AllocBitVector(cu_, GetNumSSARegs(), false, kBitMapNullCheck);
475 ClearAllBits(bb->data_flow_info->ending_null_check_v);
476 return true;
477}
478
479/* Collect stats on number of checks removed */
480bool MIRGraph::CountChecks(struct BasicBlock* bb)
481{
482 if (bb->data_flow_info == NULL) return false;
483 for (MIR* mir = bb->first_mir_insn; mir != NULL; mir = mir->next) {
484 if (mir->ssa_rep == NULL) {
485 continue;
486 }
buzbee1fd33462013-03-25 13:40:45 -0700487 int df_attributes = oat_data_flow_attributes_[mir->dalvikInsn.opcode];
buzbee311ca162013-02-28 15:56:43 -0800488 if (df_attributes & DF_HAS_NULL_CHKS) {
buzbee1fd33462013-03-25 13:40:45 -0700489 checkstats_->null_checks++;
buzbee311ca162013-02-28 15:56:43 -0800490 if (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) {
buzbee1fd33462013-03-25 13:40:45 -0700491 checkstats_->null_checks_eliminated++;
buzbee311ca162013-02-28 15:56:43 -0800492 }
493 }
494 if (df_attributes & DF_HAS_RANGE_CHKS) {
buzbee1fd33462013-03-25 13:40:45 -0700495 checkstats_->range_checks++;
buzbee311ca162013-02-28 15:56:43 -0800496 if (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) {
buzbee1fd33462013-03-25 13:40:45 -0700497 checkstats_->range_checks_eliminated++;
buzbee311ca162013-02-28 15:56:43 -0800498 }
499 }
500 }
501 return false;
502}
503
504/* Try to make common case the fallthrough path */
505static bool LayoutBlocks(struct BasicBlock* bb)
506{
507 // TODO: For now, just looking for direct throws. Consider generalizing for profile feedback
508 if (!bb->explicit_throw) {
509 return false;
510 }
511 BasicBlock* walker = bb;
512 while (true) {
513 // Check termination conditions
514 if ((walker->block_type == kEntryBlock) || (Predecessors(walker) != 1)) {
515 break;
516 }
517 BasicBlock* prev = GET_ELEM_N(walker->predecessors, BasicBlock*, 0);
518 if (prev->conditional_branch) {
519 if (prev->fall_through == walker) {
520 // Already done - return
521 break;
522 }
523 DCHECK_EQ(walker, prev->taken);
524 // Got one. Flip it and exit
525 Instruction::Code opcode = prev->last_mir_insn->dalvikInsn.opcode;
526 switch (opcode) {
527 case Instruction::IF_EQ: opcode = Instruction::IF_NE; break;
528 case Instruction::IF_NE: opcode = Instruction::IF_EQ; break;
529 case Instruction::IF_LT: opcode = Instruction::IF_GE; break;
530 case Instruction::IF_GE: opcode = Instruction::IF_LT; break;
531 case Instruction::IF_GT: opcode = Instruction::IF_LE; break;
532 case Instruction::IF_LE: opcode = Instruction::IF_GT; break;
533 case Instruction::IF_EQZ: opcode = Instruction::IF_NEZ; break;
534 case Instruction::IF_NEZ: opcode = Instruction::IF_EQZ; break;
535 case Instruction::IF_LTZ: opcode = Instruction::IF_GEZ; break;
536 case Instruction::IF_GEZ: opcode = Instruction::IF_LTZ; break;
537 case Instruction::IF_GTZ: opcode = Instruction::IF_LEZ; break;
538 case Instruction::IF_LEZ: opcode = Instruction::IF_GTZ; break;
539 default: LOG(FATAL) << "Unexpected opcode " << opcode;
540 }
541 prev->last_mir_insn->dalvikInsn.opcode = opcode;
542 BasicBlock* t_bb = prev->taken;
543 prev->taken = prev->fall_through;
544 prev->fall_through = t_bb;
545 break;
546 }
547 walker = prev;
548 }
549 return false;
550}
551
552/* Combine any basic blocks terminated by instructions that we now know can't throw */
553bool MIRGraph::CombineBlocks(struct BasicBlock* bb)
554{
555 // Loop here to allow combining a sequence of blocks
556 while (true) {
557 // Check termination conditions
558 if ((bb->first_mir_insn == NULL)
559 || (bb->data_flow_info == NULL)
560 || (bb->block_type == kExceptionHandling)
561 || (bb->block_type == kExitBlock)
562 || (bb->block_type == kDead)
563 || ((bb->taken == NULL) || (bb->taken->block_type != kExceptionHandling))
564 || (bb->successor_block_list.block_list_type != kNotUsed)
565 || (static_cast<int>(bb->last_mir_insn->dalvikInsn.opcode) != kMirOpCheck)) {
566 break;
567 }
568
569 // Test the kMirOpCheck instruction
570 MIR* mir = bb->last_mir_insn;
571 // Grab the attributes from the paired opcode
572 MIR* throw_insn = mir->meta.throw_insn;
buzbee1fd33462013-03-25 13:40:45 -0700573 int df_attributes = oat_data_flow_attributes_[throw_insn->dalvikInsn.opcode];
buzbee311ca162013-02-28 15:56:43 -0800574 bool can_combine = true;
575 if (df_attributes & DF_HAS_NULL_CHKS) {
576 can_combine &= ((throw_insn->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0);
577 }
578 if (df_attributes & DF_HAS_RANGE_CHKS) {
579 can_combine &= ((throw_insn->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0);
580 }
581 if (!can_combine) {
582 break;
583 }
584 // OK - got one. Combine
585 BasicBlock* bb_next = bb->fall_through;
586 DCHECK(!bb_next->catch_entry);
587 DCHECK_EQ(Predecessors(bb_next), 1U);
588 MIR* t_mir = bb->last_mir_insn->prev;
589 // Overwrite the kOpCheck insn with the paired opcode
590 DCHECK_EQ(bb_next->first_mir_insn, throw_insn);
591 *bb->last_mir_insn = *throw_insn;
592 bb->last_mir_insn->prev = t_mir;
593 // Use the successor info from the next block
594 bb->successor_block_list = bb_next->successor_block_list;
595 // Use the ending block linkage from the next block
596 bb->fall_through = bb_next->fall_through;
597 bb->taken->block_type = kDead; // Kill the unused exception block
598 bb->taken = bb_next->taken;
599 // Include the rest of the instructions
600 bb->last_mir_insn = bb_next->last_mir_insn;
601 /*
602 * If lower-half of pair of blocks to combine contained a return, move the flag
603 * to the newly combined block.
604 */
605 bb->terminated_by_return = bb_next->terminated_by_return;
606
607 /*
608 * NOTE: we aren't updating all dataflow info here. Should either make sure this pass
609 * happens after uses of i_dominated, dom_frontier or update the dataflow info here.
610 */
611
612 // Kill bb_next and remap now-dead id to parent
613 bb_next->block_type = kDead;
buzbee1fd33462013-03-25 13:40:45 -0700614 block_id_map_.Overwrite(bb_next->id, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800615
616 // Now, loop back and see if we can keep going
617 }
618 return false;
619}
620
621/* Eliminate unnecessary null checks for a basic block. */
622bool MIRGraph::EliminateNullChecks(struct BasicBlock* bb)
623{
624 if (bb->data_flow_info == NULL) return false;
625
626 /*
627 * Set initial state. Be conservative with catch
628 * blocks and start with no assumptions about null check
629 * status (except for "this").
630 */
631 if ((bb->block_type == kEntryBlock) | bb->catch_entry) {
632 ClearAllBits(temp_ssa_register_v_);
633 if ((cu_->access_flags & kAccStatic) == 0) {
634 // If non-static method, mark "this" as non-null
635 int this_reg = cu_->num_dalvik_registers - cu_->num_ins;
636 SetBit(cu_, temp_ssa_register_v_, this_reg);
637 }
638 } else {
639 // Starting state is intesection of all incoming arcs
640 GrowableListIterator iter;
641 GrowableListIteratorInit(bb->predecessors, &iter);
642 BasicBlock* pred_bb = reinterpret_cast<BasicBlock*>(GrowableListIteratorNext(&iter));
643 DCHECK(pred_bb != NULL);
644 CopyBitVector(temp_ssa_register_v_, pred_bb->data_flow_info->ending_null_check_v);
645 while (true) {
646 pred_bb = reinterpret_cast<BasicBlock*>(GrowableListIteratorNext(&iter));
647 if (!pred_bb) break;
648 if ((pred_bb->data_flow_info == NULL) ||
649 (pred_bb->data_flow_info->ending_null_check_v == NULL)) {
650 continue;
651 }
652 IntersectBitVectors(temp_ssa_register_v_, temp_ssa_register_v_,
653 pred_bb->data_flow_info->ending_null_check_v);
654 }
655 }
656
657 // Walk through the instruction in the block, updating as necessary
658 for (MIR* mir = bb->first_mir_insn; mir != NULL; mir = mir->next) {
659 if (mir->ssa_rep == NULL) {
660 continue;
661 }
buzbee1fd33462013-03-25 13:40:45 -0700662 int df_attributes = oat_data_flow_attributes_[mir->dalvikInsn.opcode];
buzbee311ca162013-02-28 15:56:43 -0800663
664 // Mark target of NEW* as non-null
665 if (df_attributes & DF_NON_NULL_DST) {
666 SetBit(cu_, temp_ssa_register_v_, mir->ssa_rep->defs[0]);
667 }
668
669 // Mark non-null returns from invoke-style NEW*
670 if (df_attributes & DF_NON_NULL_RET) {
671 MIR* next_mir = mir->next;
672 // Next should be an MOVE_RESULT_OBJECT
673 if (next_mir &&
674 next_mir->dalvikInsn.opcode == Instruction::MOVE_RESULT_OBJECT) {
675 // Mark as null checked
676 SetBit(cu_, temp_ssa_register_v_, next_mir->ssa_rep->defs[0]);
677 } else {
678 if (next_mir) {
679 LOG(WARNING) << "Unexpected opcode following new: " << next_mir->dalvikInsn.opcode;
680 } else if (bb->fall_through) {
681 // Look in next basic block
682 struct BasicBlock* next_bb = bb->fall_through;
683 for (MIR* tmir = next_bb->first_mir_insn; tmir != NULL;
684 tmir =tmir->next) {
685 if (static_cast<int>(tmir->dalvikInsn.opcode) >= static_cast<int>(kMirOpFirst)) {
686 continue;
687 }
688 // First non-pseudo should be MOVE_RESULT_OBJECT
689 if (tmir->dalvikInsn.opcode == Instruction::MOVE_RESULT_OBJECT) {
690 // Mark as null checked
691 SetBit(cu_, temp_ssa_register_v_, tmir->ssa_rep->defs[0]);
692 } else {
693 LOG(WARNING) << "Unexpected op after new: " << tmir->dalvikInsn.opcode;
694 }
695 break;
696 }
697 }
698 }
699 }
700
701 /*
702 * Propagate nullcheck state on register copies (including
703 * Phi pseudo copies. For the latter, nullcheck state is
704 * the "and" of all the Phi's operands.
705 */
706 if (df_attributes & (DF_NULL_TRANSFER_0 | DF_NULL_TRANSFER_N)) {
707 int tgt_sreg = mir->ssa_rep->defs[0];
708 int operands = (df_attributes & DF_NULL_TRANSFER_0) ? 1 :
709 mir->ssa_rep->num_uses;
710 bool null_checked = true;
711 for (int i = 0; i < operands; i++) {
712 null_checked &= IsBitSet(temp_ssa_register_v_,
713 mir->ssa_rep->uses[i]);
714 }
715 if (null_checked) {
716 SetBit(cu_, temp_ssa_register_v_, tgt_sreg);
717 }
718 }
719
720 // Already nullchecked?
721 if ((df_attributes & DF_HAS_NULL_CHKS) && !(mir->optimization_flags & MIR_IGNORE_NULL_CHECK)) {
722 int src_idx;
723 if (df_attributes & DF_NULL_CHK_1) {
724 src_idx = 1;
725 } else if (df_attributes & DF_NULL_CHK_2) {
726 src_idx = 2;
727 } else {
728 src_idx = 0;
729 }
730 int src_sreg = mir->ssa_rep->uses[src_idx];
731 if (IsBitSet(temp_ssa_register_v_, src_sreg)) {
732 // Eliminate the null check
733 mir->optimization_flags |= MIR_IGNORE_NULL_CHECK;
734 } else {
735 // Mark s_reg as null-checked
736 SetBit(cu_, temp_ssa_register_v_, src_sreg);
737 }
738 }
739 }
740
741 // Did anything change?
742 bool res = CompareBitVectors(bb->data_flow_info->ending_null_check_v,
743 temp_ssa_register_v_);
744 if (res) {
745 CopyBitVector(bb->data_flow_info->ending_null_check_v,
746 temp_ssa_register_v_);
747 }
748 return res;
749}
750
751void MIRGraph::NullCheckElimination()
752{
753 if (!(cu_->disable_opt & (1 << kNullCheckElimination))) {
754 DCHECK(temp_ssa_register_v_ != NULL);
buzbee0665fe02013-03-21 12:32:21 -0700755 AllNodesIterator iter(this, false /* not iterative */);
buzbee311ca162013-02-28 15:56:43 -0800756 for (BasicBlock* bb = iter.Next(); bb != NULL; bb = iter.Next()) {
757 NullCheckEliminationInit(bb);
758 }
buzbee0665fe02013-03-21 12:32:21 -0700759 PreOrderDfsIterator iter2(this, true /* iterative */);
buzbee311ca162013-02-28 15:56:43 -0800760 bool change = false;
761 for (BasicBlock* bb = iter2.Next(change); bb != NULL; bb = iter2.Next(change)) {
762 change = EliminateNullChecks(bb);
763 }
764 }
765 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
766 DumpCFG("/sdcard/4_post_nce_cfg/", false);
767 }
768}
769
770void MIRGraph::BasicBlockCombine()
771{
buzbee0665fe02013-03-21 12:32:21 -0700772 PreOrderDfsIterator iter(this, false /* not iterative */);
buzbee311ca162013-02-28 15:56:43 -0800773 for (BasicBlock* bb = iter.Next(); bb != NULL; bb = iter.Next()) {
774 CombineBlocks(bb);
775 }
776 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
777 DumpCFG("/sdcard/5_post_bbcombine_cfg/", false);
778 }
779}
780
781void MIRGraph::CodeLayout()
782{
buzbee1fd33462013-03-25 13:40:45 -0700783 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
784 VerifyDataflow();
785 }
buzbee0665fe02013-03-21 12:32:21 -0700786 AllNodesIterator iter(this, false /* not iterative */);
buzbee311ca162013-02-28 15:56:43 -0800787 for (BasicBlock* bb = iter.Next(); bb != NULL; bb = iter.Next()) {
788 LayoutBlocks(bb);
789 }
790 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
791 DumpCFG("/sdcard/2_post_layout_cfg/", true);
792 }
793}
794
795void MIRGraph::DumpCheckStats()
796{
797 Checkstats* stats =
798 static_cast<Checkstats*>(NewMem(cu_, sizeof(Checkstats), true, kAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -0700799 checkstats_ = stats;
buzbee0665fe02013-03-21 12:32:21 -0700800 AllNodesIterator iter(this, false /* not iterative */);
buzbee311ca162013-02-28 15:56:43 -0800801 for (BasicBlock* bb = iter.Next(); bb != NULL; bb = iter.Next()) {
802 CountChecks(bb);
803 }
804 if (stats->null_checks > 0) {
805 float eliminated = static_cast<float>(stats->null_checks_eliminated);
806 float checks = static_cast<float>(stats->null_checks);
807 LOG(INFO) << "Null Checks: " << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " "
808 << stats->null_checks_eliminated << " of " << stats->null_checks << " -> "
809 << (eliminated/checks) * 100.0 << "%";
810 }
811 if (stats->range_checks > 0) {
812 float eliminated = static_cast<float>(stats->range_checks_eliminated);
813 float checks = static_cast<float>(stats->range_checks);
814 LOG(INFO) << "Range Checks: " << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " "
815 << stats->range_checks_eliminated << " of " << stats->range_checks << " -> "
816 << (eliminated/checks) * 100.0 << "%";
817 }
818}
819
820bool MIRGraph::BuildExtendedBBList(struct BasicBlock* bb)
821{
822 if (bb->visited) return false;
823 if (!((bb->block_type == kEntryBlock) || (bb->block_type == kDalvikByteCode)
824 || (bb->block_type == kExitBlock))) {
825 // Ignore special blocks
826 bb->visited = true;
827 return false;
828 }
829 // Must be head of extended basic block.
830 BasicBlock* start_bb = bb;
831 extended_basic_blocks_.push_back(bb);
832 bool terminated_by_return = false;
833 // Visit blocks strictly dominated by this head.
834 while (bb != NULL) {
835 bb->visited = true;
836 terminated_by_return |= bb->terminated_by_return;
837 bb = NextDominatedBlock(bb);
838 }
839 if (terminated_by_return) {
840 // This extended basic block contains a return, so mark all members.
841 bb = start_bb;
842 while (bb != NULL) {
843 bb->dominates_return = true;
844 bb = NextDominatedBlock(bb);
845 }
846 }
847 return false; // Not iterative - return value will be ignored
848}
849
850
851void MIRGraph::BasicBlockOptimization()
852{
853 if (!(cu_->disable_opt & (1 << kBBOpt))) {
buzbee1fd33462013-03-25 13:40:45 -0700854 CompilerInitGrowableList(cu_, &compiler_temps_, 6, kListMisc);
buzbee311ca162013-02-28 15:56:43 -0800855 DCHECK_EQ(cu_->num_compiler_temps, 0);
856 // Mark all blocks as not visited
buzbee0665fe02013-03-21 12:32:21 -0700857 AllNodesIterator iter(this, false /* not iterative */);
buzbee311ca162013-02-28 15:56:43 -0800858 for (BasicBlock* bb = iter.Next(); bb != NULL; bb = iter.Next()) {
859 ClearVisitedFlag(bb);
860 }
buzbee0665fe02013-03-21 12:32:21 -0700861 PreOrderDfsIterator iter2(this, false /* not iterative */);
buzbee311ca162013-02-28 15:56:43 -0800862 for (BasicBlock* bb = iter2.Next(); bb != NULL; bb = iter2.Next()) {
863 BuildExtendedBBList(bb);
864 }
865 // Perform extended basic block optimizations.
866 for (unsigned int i = 0; i < extended_basic_blocks_.size(); i++) {
867 BasicBlockOpt(extended_basic_blocks_[i]);
868 }
869 }
870 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
871 DumpCFG("/sdcard/6_post_bbo_cfg/", false);
872 }
873}
874
875} // namespace art