blob: a843d514521ed500a949a630d831a1fc7ffe68d7 [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 "Dataflow.h"
19
20/* Enter the node to the dfsOrder list then visit its successors */
21static void recordDFSPreOrder(CompilationUnit* cUnit, BasicBlock* block)
22{
23
24 if (block->visited || block->hidden) return;
25 block->visited = true;
26
27 /* Enqueue the block id */
28 oatInsertGrowableList(&cUnit->dfsOrder, block->id);
29
30 if (block->fallThrough) recordDFSPreOrder(cUnit, block->fallThrough);
31 if (block->taken) recordDFSPreOrder(cUnit, block->taken);
32 if (block->successorBlockList.blockListType != kNotUsed) {
33 GrowableListIterator iterator;
34 oatGrowableListIteratorInit(&block->successorBlockList.blocks,
35 &iterator);
36 while (true) {
37 SuccessorBlockInfo *successorBlockInfo =
38 (SuccessorBlockInfo *) oatGrowableListIteratorNext(&iterator);
39 if (successorBlockInfo == NULL) break;
40 BasicBlock* succBB = successorBlockInfo->block;
41 recordDFSPreOrder(cUnit, succBB);
42 }
43 }
44 return;
45}
46
47/* Sort the blocks by the Depth-First-Search pre-order */
48static void computeDFSOrder(CompilationUnit* cUnit)
49{
50 /* Initialize or reset the DFS order list */
51 if (cUnit->dfsOrder.elemList == NULL) {
52 oatInitGrowableList(&cUnit->dfsOrder, cUnit->numBlocks);
53 } else {
54 /* Just reset the used length on the counter */
55 cUnit->dfsOrder.numUsed = 0;
56 }
57
58 oatDataFlowAnalysisDispatcher(cUnit, oatClearVisitedFlag,
59 kAllNodes,
60 false /* isIterative */);
61
62 recordDFSPreOrder(cUnit, cUnit->entryBlock);
63 cUnit->numReachableBlocks = cUnit->dfsOrder.numUsed;
64}
65
66/*
67 * Mark block bit on the per-Dalvik register vector to denote that Dalvik
68 * register idx is defined in BasicBlock bb.
69 */
70static bool fillDefBlockMatrix(CompilationUnit* cUnit, BasicBlock* bb)
71{
72 if (bb->dataFlowInfo == NULL) return false;
73
74 ArenaBitVectorIterator iterator;
75
76 oatBitVectorIteratorInit(bb->dataFlowInfo->defV, &iterator);
77 while (true) {
78 int idx = oatBitVectorIteratorNext(&iterator);
79 if (idx == -1) break;
80 /* Block bb defines register idx */
81 oatSetBit(cUnit->defBlockMatrix[idx], bb->id);
82 }
83 return true;
84}
85
86static void computeDefBlockMatrix(CompilationUnit* cUnit)
87{
88 int numRegisters = cUnit->numDalvikRegisters;
89 /* Allocate numDalvikRegisters bit vector pointers */
90 cUnit->defBlockMatrix = (ArenaBitVector **)
91 oatNew(sizeof(ArenaBitVector *) * numRegisters, true);
92 int i;
93
94 /* Initialize numRegister vectors with numBlocks bits each */
95 for (i = 0; i < numRegisters; i++) {
96 cUnit->defBlockMatrix[i] = oatAllocBitVector(cUnit->numBlocks,
97 false);
98 }
99 oatDataFlowAnalysisDispatcher(cUnit, oatFindLocalLiveIn,
100 kAllNodes,
101 false /* isIterative */);
102 oatDataFlowAnalysisDispatcher(cUnit, fillDefBlockMatrix,
103 kAllNodes,
104 false /* isIterative */);
105
106 /*
107 * Also set the incoming parameters as defs in the entry block.
108 * Only need to handle the parameters for the outer method.
109 */
110 int inReg = cUnit->method->registersSize - cUnit->method->insSize;
111 for (; inReg < cUnit->method->registersSize; inReg++) {
112 oatSetBit(cUnit->defBlockMatrix[inReg],
113 cUnit->entryBlock->id);
114 }
115}
116
117/* Compute the post-order traversal of the CFG */
118static void computeDomPostOrderTraversal(CompilationUnit* cUnit, BasicBlock* bb)
119{
120 ArenaBitVectorIterator bvIterator;
121 oatBitVectorIteratorInit(bb->iDominated, &bvIterator);
122 GrowableList* blockList = &cUnit->blockList;
123
124 /* Iterate through the dominated blocks first */
125 while (true) {
126 int bbIdx = oatBitVectorIteratorNext(&bvIterator);
127 if (bbIdx == -1) break;
128 BasicBlock* dominatedBB =
129 (BasicBlock* ) oatGrowableListGetElement(blockList, bbIdx);
130 computeDomPostOrderTraversal(cUnit, dominatedBB);
131 }
132
133 /* Enter the current block id */
134 oatInsertGrowableList(&cUnit->domPostOrderTraversal, bb->id);
135
136 /* hacky loop detection */
137 if (bb->taken && oatIsBitSet(bb->dominators, bb->taken->id)) {
138 cUnit->hasLoop = true;
139 }
140}
141
142static void checkForDominanceFrontier(BasicBlock* domBB,
143 const BasicBlock* succBB)
144{
145 /*
146 * TODO - evaluate whether phi will ever need to be inserted into exit
147 * blocks.
148 */
149 if (succBB->iDom != domBB &&
150 succBB->blockType == kDalvikByteCode &&
151 succBB->hidden == false) {
152 oatSetBit(domBB->domFrontier, succBB->id);
153 }
154}
155
156/* Worker function to compute the dominance frontier */
157static bool computeDominanceFrontier(CompilationUnit* cUnit, BasicBlock* bb)
158{
159 GrowableList* blockList = &cUnit->blockList;
160
161 /* Calculate DF_local */
162 if (bb->taken) {
163 checkForDominanceFrontier(bb, bb->taken);
164 }
165 if (bb->fallThrough) {
166 checkForDominanceFrontier(bb, bb->fallThrough);
167 }
168 if (bb->successorBlockList.blockListType != kNotUsed) {
169 GrowableListIterator iterator;
170 oatGrowableListIteratorInit(&bb->successorBlockList.blocks,
171 &iterator);
172 while (true) {
173 SuccessorBlockInfo *successorBlockInfo =
174 (SuccessorBlockInfo *) oatGrowableListIteratorNext(&iterator);
175 if (successorBlockInfo == NULL) break;
176 BasicBlock* succBB = successorBlockInfo->block;
177 checkForDominanceFrontier(bb, succBB);
178 }
179 }
180
181 /* Calculate DF_up */
182 ArenaBitVectorIterator bvIterator;
183 oatBitVectorIteratorInit(bb->iDominated, &bvIterator);
184 while (true) {
185 int dominatedIdx = oatBitVectorIteratorNext(&bvIterator);
186 if (dominatedIdx == -1) break;
187 BasicBlock* dominatedBB = (BasicBlock* )
188 oatGrowableListGetElement(blockList, dominatedIdx);
189 ArenaBitVectorIterator dfIterator;
190 oatBitVectorIteratorInit(dominatedBB->domFrontier, &dfIterator);
191 while (true) {
192 int dfUpIdx = oatBitVectorIteratorNext(&dfIterator);
193 if (dfUpIdx == -1) break;
194 BasicBlock* dfUpBlock = (BasicBlock* )
195 oatGrowableListGetElement(blockList, dfUpIdx);
196 checkForDominanceFrontier(bb, dfUpBlock);
197 }
198 }
199
200 return true;
201}
202
203/* Worker function for initializing domination-related data structures */
204static bool initializeDominationInfo(CompilationUnit* cUnit, BasicBlock* bb)
205{
206 int numTotalBlocks = cUnit->blockList.numUsed;
207
208 if (bb->dominators == NULL ) {
209 bb->dominators = oatAllocBitVector(numTotalBlocks,
210 false /* expandable */);
211 bb->iDominated = oatAllocBitVector(numTotalBlocks,
212 false /* expandable */);
213 bb->domFrontier = oatAllocBitVector(numTotalBlocks,
214 false /* expandable */);
215 } else {
216 oatClearAllBits(bb->dominators);
217 oatClearAllBits(bb->iDominated);
218 oatClearAllBits(bb->domFrontier);
219 }
220 /* Set all bits in the dominator vector */
221 oatSetInitialBits(bb->dominators, numTotalBlocks);
222
223 return true;
224}
225
226/* Worker function to compute each block's dominators */
227static bool computeBlockDominators(CompilationUnit* cUnit, BasicBlock* bb)
228{
229 GrowableList* blockList = &cUnit->blockList;
230 int numTotalBlocks = blockList->numUsed;
231 ArenaBitVector* tempBlockV = cUnit->tempBlockV;
232 ArenaBitVectorIterator bvIterator;
233
234 /*
235 * The dominator of the entry block has been preset to itself and we need
236 * to skip the calculation here.
237 */
238 if (bb == cUnit->entryBlock) return false;
239
240 oatSetInitialBits(tempBlockV, numTotalBlocks);
241
242 /* Iterate through the predecessors */
243 oatBitVectorIteratorInit(bb->predecessors, &bvIterator);
244 while (true) {
245 int predIdx = oatBitVectorIteratorNext(&bvIterator);
246 if (predIdx == -1) break;
247 BasicBlock* predBB = (BasicBlock* ) oatGrowableListGetElement(
248 blockList, predIdx);
249 /* tempBlockV = tempBlockV ^ dominators */
250 oatIntersectBitVectors(tempBlockV, tempBlockV, predBB->dominators);
251 }
252 oatSetBit(tempBlockV, bb->id);
253 if (oatCompareBitVectors(tempBlockV, bb->dominators)) {
254 oatCopyBitVector(bb->dominators, tempBlockV);
255 return true;
256 }
257 return false;
258}
259
260/* Worker function to compute the idom */
261static bool computeImmediateDominator(CompilationUnit* cUnit, BasicBlock* bb)
262{
263 GrowableList* blockList = &cUnit->blockList;
264 ArenaBitVector* tempBlockV = cUnit->tempBlockV;
265 ArenaBitVectorIterator bvIterator;
266 BasicBlock* iDom;
267
268 if (bb == cUnit->entryBlock) return false;
269
270 oatCopyBitVector(tempBlockV, bb->dominators);
271 oatClearBit(tempBlockV, bb->id);
272 oatBitVectorIteratorInit(tempBlockV, &bvIterator);
273
274 /* Should not see any dead block */
275 assert(oatCountSetBits(tempBlockV) != 0);
276 if (oatCountSetBits(tempBlockV) == 1) {
277 iDom = (BasicBlock* ) oatGrowableListGetElement(
278 blockList, oatBitVectorIteratorNext(&bvIterator));
279 bb->iDom = iDom;
280 } else {
281 int iDomIdx = oatBitVectorIteratorNext(&bvIterator);
282 assert(iDomIdx != -1);
283 while (true) {
284 int nextDom = oatBitVectorIteratorNext(&bvIterator);
285 if (nextDom == -1) break;
286 BasicBlock* nextDomBB = (BasicBlock* )
287 oatGrowableListGetElement(blockList, nextDom);
288 /* iDom dominates nextDom - set new iDom */
289 if (oatIsBitSet(nextDomBB->dominators, iDomIdx)) {
290 iDomIdx = nextDom;
291 }
292
293 }
294 iDom = (BasicBlock* ) oatGrowableListGetElement(blockList, iDomIdx);
295 /* Set the immediate dominator block for bb */
296 bb->iDom = iDom;
297 }
298 /* Add bb to the iDominated set of the immediate dominator block */
299 oatSetBit(iDom->iDominated, bb->id);
300 return true;
301}
302
303/* Compute dominators, immediate dominator, and dominance fronter */
304static void computeDominators(CompilationUnit* cUnit)
305{
306 int numReachableBlocks = cUnit->numReachableBlocks;
307 int numTotalBlocks = cUnit->blockList.numUsed;
308
309 /* Initialize domination-related data structures */
310 oatDataFlowAnalysisDispatcher(cUnit, initializeDominationInfo,
311 kReachableNodes,
312 false /* isIterative */);
313
314 /* Set the dominator for the root node */
315 oatClearAllBits(cUnit->entryBlock->dominators);
316 oatSetBit(cUnit->entryBlock->dominators, cUnit->entryBlock->id);
317
318 if (cUnit->tempBlockV == NULL) {
319 cUnit->tempBlockV = oatAllocBitVector(numTotalBlocks,
320 false /* expandable */);
321 } else {
322 oatClearAllBits(cUnit->tempBlockV);
323 }
324 oatDataFlowAnalysisDispatcher(cUnit, computeBlockDominators,
325 kPreOrderDFSTraversal,
326 true /* isIterative */);
327
328 cUnit->entryBlock->iDom = NULL;
329 oatDataFlowAnalysisDispatcher(cUnit, computeImmediateDominator,
330 kReachableNodes,
331 false /* isIterative */);
332
333 /*
334 * Now go ahead and compute the post order traversal based on the
335 * iDominated sets.
336 */
337 if (cUnit->domPostOrderTraversal.elemList == NULL) {
338 oatInitGrowableList(&cUnit->domPostOrderTraversal, numReachableBlocks);
339 } else {
340 cUnit->domPostOrderTraversal.numUsed = 0;
341 }
342
343 computeDomPostOrderTraversal(cUnit, cUnit->entryBlock);
344 assert(cUnit->domPostOrderTraversal.numUsed ==
345 (unsigned) cUnit->numReachableBlocks);
346
347 /* Now compute the dominance frontier for each block */
348 oatDataFlowAnalysisDispatcher(cUnit, computeDominanceFrontier,
349 kPostOrderDOMTraversal,
350 false /* isIterative */);
351}
352
353/*
354 * Perform dest U= src1 ^ ~src2
355 * This is probably not general enough to be placed in BitVector.[ch].
356 */
357static void computeSuccLiveIn(ArenaBitVector* dest,
358 const ArenaBitVector* src1,
359 const ArenaBitVector* src2)
360{
361 if (dest->storageSize != src1->storageSize ||
362 dest->storageSize != src2->storageSize ||
363 dest->expandable != src1->expandable ||
364 dest->expandable != src2->expandable) {
365 LOG(FATAL) << "Incompatible set properties";
366 }
367
368 unsigned int idx;
369 for (idx = 0; idx < dest->storageSize; idx++) {
370 dest->storage[idx] |= src1->storage[idx] & ~src2->storage[idx];
371 }
372}
373
374/*
375 * Iterate through all successor blocks and propagate up the live-in sets.
376 * The calculated result is used for phi-node pruning - where we only need to
377 * insert a phi node if the variable is live-in to the block.
378 */
379static bool computeBlockLiveIns(CompilationUnit* cUnit, BasicBlock* bb)
380{
381 ArenaBitVector* tempDalvikRegisterV = cUnit->tempDalvikRegisterV;
382
383 if (bb->dataFlowInfo == NULL) return false;
384 oatCopyBitVector(tempDalvikRegisterV, bb->dataFlowInfo->liveInV);
385 if (bb->taken && bb->taken->dataFlowInfo)
386 computeSuccLiveIn(tempDalvikRegisterV, bb->taken->dataFlowInfo->liveInV,
387 bb->dataFlowInfo->defV);
388 if (bb->fallThrough && bb->fallThrough->dataFlowInfo)
389 computeSuccLiveIn(tempDalvikRegisterV,
390 bb->fallThrough->dataFlowInfo->liveInV,
391 bb->dataFlowInfo->defV);
392 if (bb->successorBlockList.blockListType != kNotUsed) {
393 GrowableListIterator iterator;
394 oatGrowableListIteratorInit(&bb->successorBlockList.blocks,
395 &iterator);
396 while (true) {
397 SuccessorBlockInfo *successorBlockInfo =
398 (SuccessorBlockInfo *) oatGrowableListIteratorNext(&iterator);
399 if (successorBlockInfo == NULL) break;
400 BasicBlock* succBB = successorBlockInfo->block;
401 if (succBB->dataFlowInfo) {
402 computeSuccLiveIn(tempDalvikRegisterV,
403 succBB->dataFlowInfo->liveInV,
404 bb->dataFlowInfo->defV);
405 }
406 }
407 }
408 if (oatCompareBitVectors(tempDalvikRegisterV, bb->dataFlowInfo->liveInV)) {
409 oatCopyBitVector(bb->dataFlowInfo->liveInV, tempDalvikRegisterV);
410 return true;
411 }
412 return false;
413}
414
415/* Insert phi nodes to for each variable to the dominance frontiers */
416static void insertPhiNodes(CompilationUnit* cUnit)
417{
418 int dalvikReg;
419 const GrowableList* blockList = &cUnit->blockList;
420 ArenaBitVector* phiBlocks =
421 oatAllocBitVector(cUnit->numBlocks, false);
422 ArenaBitVector* tmpBlocks =
423 oatAllocBitVector(cUnit->numBlocks, false);
424 ArenaBitVector* inputBlocks =
425 oatAllocBitVector(cUnit->numBlocks, false);
426
427 cUnit->tempDalvikRegisterV =
428 oatAllocBitVector(cUnit->numDalvikRegisters, false);
429
430 oatDataFlowAnalysisDispatcher(cUnit, computeBlockLiveIns,
431 kPostOrderDFSTraversal,
432 true /* isIterative */);
433
434 /* Iterate through each Dalvik register */
435 for (dalvikReg = 0; dalvikReg < cUnit->numDalvikRegisters; dalvikReg++) {
436 bool change;
437 ArenaBitVectorIterator iterator;
438
439 oatCopyBitVector(inputBlocks, cUnit->defBlockMatrix[dalvikReg]);
440 oatClearAllBits(phiBlocks);
441
442 /* Calculate the phi blocks for each Dalvik register */
443 do {
444 change = false;
445 oatClearAllBits(tmpBlocks);
446 oatBitVectorIteratorInit(inputBlocks, &iterator);
447
448 while (true) {
449 int idx = oatBitVectorIteratorNext(&iterator);
450 if (idx == -1) break;
451 BasicBlock* defBB =
452 (BasicBlock* ) oatGrowableListGetElement(blockList, idx);
453
454 /* Merge the dominance frontier to tmpBlocks */
455 oatUnifyBitVectors(tmpBlocks, tmpBlocks, defBB->domFrontier);
456 }
457 if (oatCompareBitVectors(phiBlocks, tmpBlocks)) {
458 change = true;
459 oatCopyBitVector(phiBlocks, tmpBlocks);
460
461 /*
462 * Iterate through the original blocks plus the new ones in
463 * the dominance frontier.
464 */
465 oatCopyBitVector(inputBlocks, phiBlocks);
466 oatUnifyBitVectors(inputBlocks, inputBlocks,
467 cUnit->defBlockMatrix[dalvikReg]);
468 }
469 } while (change);
470
471 /*
472 * Insert a phi node for dalvikReg in the phiBlocks if the Dalvik
473 * register is in the live-in set.
474 */
475 oatBitVectorIteratorInit(phiBlocks, &iterator);
476 while (true) {
477 int idx = oatBitVectorIteratorNext(&iterator);
478 if (idx == -1) break;
479 BasicBlock* phiBB =
480 (BasicBlock* ) oatGrowableListGetElement(blockList, idx);
481 /* Variable will be clobbered before being used - no need for phi */
482 if (!oatIsBitSet(phiBB->dataFlowInfo->liveInV, dalvikReg)) continue;
483 MIR *phi = (MIR *) oatNew(sizeof(MIR), true);
484 phi->dalvikInsn.opcode = (Opcode)kMirOpPhi;
485 phi->dalvikInsn.vA = dalvikReg;
486 phi->offset = phiBB->startOffset;
487 oatPrependMIR(phiBB, phi);
488 }
489 }
490}
491
492/*
493 * Worker function to insert phi-operands with latest SSA names from
494 * predecessor blocks
495 */
496static bool insertPhiNodeOperands(CompilationUnit* cUnit, BasicBlock* bb)
497{
498 ArenaBitVector* ssaRegV = cUnit->tempSSARegisterV;
499 ArenaBitVectorIterator bvIterator;
500 GrowableList* blockList = &cUnit->blockList;
501 MIR *mir;
502
503 /* Phi nodes are at the beginning of each block */
504 for (mir = bb->firstMIRInsn; mir; mir = mir->next) {
505 if (mir->dalvikInsn.opcode != (Opcode)kMirOpPhi)
506 return true;
507 int ssaReg = mir->ssaRep->defs[0];
508 int encodedDalvikValue =
509 (int) oatGrowableListGetElement(cUnit->ssaToDalvikMap, ssaReg);
510 int dalvikReg = DECODE_REG(encodedDalvikValue);
511
512 oatClearAllBits(ssaRegV);
513
514 /* Iterate through the predecessors */
515 oatBitVectorIteratorInit(bb->predecessors, &bvIterator);
516 while (true) {
517 int predIdx = oatBitVectorIteratorNext(&bvIterator);
518 if (predIdx == -1) break;
519 BasicBlock* predBB = (BasicBlock* ) oatGrowableListGetElement(
520 blockList, predIdx);
521 int encodedSSAValue =
522 predBB->dataFlowInfo->dalvikToSSAMap[dalvikReg];
523 int ssaReg = DECODE_REG(encodedSSAValue);
524 oatSetBit(ssaRegV, ssaReg);
525 }
526
527 /* Count the number of SSA registers for a Dalvik register */
528 int numUses = oatCountSetBits(ssaRegV);
529 mir->ssaRep->numUses = numUses;
530 mir->ssaRep->uses =
531 (int *) oatNew(sizeof(int) * numUses, false);
532 mir->ssaRep->fpUse =
533 (bool *) oatNew(sizeof(bool) * numUses, true);
534
535 ArenaBitVectorIterator phiIterator;
536
537 oatBitVectorIteratorInit(ssaRegV, &phiIterator);
538 int *usePtr = mir->ssaRep->uses;
539
540 /* Set the uses array for the phi node */
541 while (true) {
542 int ssaRegIdx = oatBitVectorIteratorNext(&phiIterator);
543 if (ssaRegIdx == -1) break;
544 *usePtr++ = ssaRegIdx;
545 }
546 }
547
548 return true;
549}
550
551/* Perform SSA transformation for the whole method */
552void oatMethodSSATransformation(CompilationUnit* cUnit)
553{
554 /* Compute the DFS order */
555 computeDFSOrder(cUnit);
556
557 /* Compute the dominator info */
558 computeDominators(cUnit);
559
560 /* Allocate data structures in preparation for SSA conversion */
561 oatInitializeSSAConversion(cUnit);
562
563 /* Find out the "Dalvik reg def x block" relation */
564 computeDefBlockMatrix(cUnit);
565
566 /* Insert phi nodes to dominance frontiers for all variables */
567 insertPhiNodes(cUnit);
568
569 /* Rename register names by local defs and phi nodes */
570 oatDataFlowAnalysisDispatcher(cUnit, oatDoSSAConversion,
571 kPreOrderDFSTraversal,
572 false /* isIterative */);
573
574 /*
575 * Shared temp bit vector used by each block to count the number of defs
576 * from all the predecessor blocks.
577 */
578 cUnit->tempSSARegisterV = oatAllocBitVector(cUnit->numSSARegs,
579 false);
580
581 /* Insert phi-operands with latest SSA names from predecessor blocks */
582 oatDataFlowAnalysisDispatcher(cUnit, insertPhiNodeOperands,
583 kReachableNodes,
584 false /* isIterative */);
585}