blob: 9f98c205a521617c311f8623b9d4daf852f67cec [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2013 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 */
Dragos Sbirleadb063062013-07-23 16:29:09 -070016#include "base/stringprintf.h"
Dragos Sbirleabfaf44f2013-08-06 15:41:44 -070017#include "sea_ir/ir/instruction_tools.h"
18#include "sea_ir/ir/sea.h"
19#include "sea_ir/code_gen/code_gen.h"
20#include "sea_ir/types/type_inference.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070021
22#define MAX_REACHING_DEF_ITERERATIONS (10)
Dragos Sbirlea0e260a32013-06-21 09:20:34 -070023// TODO: When development is done, this define should not
24// be needed, it is currently used as a cutoff
25// for cases where the iterative fixed point algorithm
26// does not reach a fixed point because of a bug.
Brian Carlstrom7940e442013-07-12 13:46:57 -070027
28namespace sea_ir {
29
Brian Carlstrom7940e442013-07-12 13:46:57 -070030int SeaNode::current_max_node_id_ = 0;
31
Dragos Sbirlea0e260a32013-06-21 09:20:34 -070032void IRVisitor::Traverse(Region* region) {
33 std::vector<PhiInstructionNode*>* phis = region->GetPhiNodes();
34 for (std::vector<PhiInstructionNode*>::const_iterator cit = phis->begin();
35 cit != phis->end(); cit++) {
36 (*cit)->Accept(this);
37 }
Dragos Sbirlea0e260a32013-06-21 09:20:34 -070038 std::vector<InstructionNode*>* instructions = region->GetInstructions();
39 for (std::vector<InstructionNode*>::const_iterator cit = instructions->begin();
40 cit != instructions->end(); cit++) {
41 (*cit)->Accept(this);
42 }
43}
44
45void IRVisitor::Traverse(SeaGraph* graph) {
46 for (std::vector<Region*>::const_iterator cit = ordered_regions_.begin();
47 cit != ordered_regions_.end(); cit++ ) {
48 (*cit)->Accept(this);
49 }
50}
Brian Carlstrom7940e442013-07-12 13:46:57 -070051
Dragos Sbirlea6bee4452013-07-26 12:05:03 -070052SeaGraph* SeaGraph::GetCurrentGraph(const art::DexFile& dex_file) {
53 return new SeaGraph(dex_file);
Brian Carlstrom7940e442013-07-12 13:46:57 -070054}
55
Brian Carlstrom7940e442013-07-12 13:46:57 -070056void SeaGraph::AddEdge(Region* src, Region* dst) const {
57 src->AddSuccessor(dst);
58 dst->AddPredecessor(src);
59}
60
Brian Carlstrom1db91132013-07-12 18:05:20 -070061void SeaGraph::ComputeRPO(Region* current_region, int& current_rpo) {
62 current_region->SetRPO(VISITING);
63 std::vector<sea_ir::Region*>* succs = current_region->GetSuccessors();
64 for (std::vector<sea_ir::Region*>::iterator succ_it = succs->begin();
65 succ_it != succs->end(); ++succ_it) {
66 if (NOT_VISITED == (*succ_it)->GetRPO()) {
67 SeaGraph::ComputeRPO(*succ_it, current_rpo);
68 }
69 }
70 current_region->SetRPO(current_rpo--);
71}
72
73void SeaGraph::ComputeIDominators() {
74 bool changed = true;
75 while (changed) {
76 changed = false;
77 // Entry node has itself as IDOM.
78 std::vector<Region*>::iterator crt_it;
79 std::set<Region*> processedNodes;
80 // Find and mark the entry node(s).
81 for (crt_it = regions_.begin(); crt_it != regions_.end(); ++crt_it) {
82 if ((*crt_it)->GetPredecessors()->size() == 0) {
83 processedNodes.insert(*crt_it);
84 (*crt_it)->SetIDominator(*crt_it);
85 }
86 }
87 for (crt_it = regions_.begin(); crt_it != regions_.end(); ++crt_it) {
88 if ((*crt_it)->GetPredecessors()->size() == 0) {
89 continue;
90 }
91 // NewIDom = first (processed) predecessor of b.
92 Region* new_dom = NULL;
93 std::vector<Region*>* preds = (*crt_it)->GetPredecessors();
94 DCHECK(NULL != preds);
95 Region* root_pred = NULL;
96 for (std::vector<Region*>::iterator pred_it = preds->begin();
97 pred_it != preds->end(); ++pred_it) {
98 if (processedNodes.end() != processedNodes.find((*pred_it))) {
99 root_pred = *pred_it;
100 new_dom = root_pred;
101 break;
102 }
103 }
104 // For all other predecessors p of b, if idom is not set,
105 // then NewIdom = Intersect(p, NewIdom)
106 for (std::vector<Region*>::const_iterator pred_it = preds->begin();
107 pred_it != preds->end(); ++pred_it) {
108 DCHECK(NULL != *pred_it);
109 // if IDOMS[p] != UNDEFINED
110 if ((*pred_it != root_pred) && (*pred_it)->GetIDominator() != NULL) {
111 DCHECK(NULL != new_dom);
112 new_dom = SeaGraph::Intersect(*pred_it, new_dom);
113 }
114 }
115 DCHECK(NULL != *crt_it);
116 if ((*crt_it)->GetIDominator() != new_dom) {
117 (*crt_it)->SetIDominator(new_dom);
118 changed = true;
119 }
120 processedNodes.insert(*crt_it);
121 }
122 }
123
124 // For easily ordering of regions we need edges dominator->dominated.
125 for (std::vector<Region*>::iterator region_it = regions_.begin();
126 region_it != regions_.end(); region_it++) {
127 Region* idom = (*region_it)->GetIDominator();
128 if (idom != *region_it) {
129 idom->AddToIDominatedSet(*region_it);
130 }
131 }
132}
133
134Region* SeaGraph::Intersect(Region* i, Region* j) {
135 Region* finger1 = i;
136 Region* finger2 = j;
137 while (finger1 != finger2) {
138 while (finger1->GetRPO() > finger2->GetRPO()) {
139 DCHECK(NULL != finger1);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700140 finger1 = finger1->GetIDominator(); // should have: finger1 != NULL
Brian Carlstrom1db91132013-07-12 18:05:20 -0700141 DCHECK(NULL != finger1);
142 }
143 while (finger1->GetRPO() < finger2->GetRPO()) {
144 DCHECK(NULL != finger2);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700145 finger2 = finger2->GetIDominator(); // should have: finger1 != NULL
Brian Carlstrom1db91132013-07-12 18:05:20 -0700146 DCHECK(NULL != finger2);
147 }
148 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700149 return finger1; // finger1 should be equal to finger2 at this point.
Brian Carlstrom1db91132013-07-12 18:05:20 -0700150}
151
Brian Carlstrom7940e442013-07-12 13:46:57 -0700152void SeaGraph::ComputeDownExposedDefs() {
153 for (std::vector<Region*>::iterator region_it = regions_.begin();
154 region_it != regions_.end(); region_it++) {
155 (*region_it)->ComputeDownExposedDefs();
156 }
157}
158
159void SeaGraph::ComputeReachingDefs() {
160 // Iterate until the reaching definitions set doesn't change anymore.
161 // (See Cooper & Torczon, "Engineering a Compiler", second edition, page 487)
162 bool changed = true;
163 int iteration = 0;
164 while (changed && (iteration < MAX_REACHING_DEF_ITERERATIONS)) {
165 iteration++;
166 changed = false;
167 // TODO: optimize the ordering if this becomes performance bottleneck.
168 for (std::vector<Region*>::iterator regions_it = regions_.begin();
169 regions_it != regions_.end();
170 regions_it++) {
171 changed |= (*regions_it)->UpdateReachingDefs();
172 }
173 }
174 DCHECK(!changed) << "Reaching definitions computation did not reach a fixed point.";
175}
176
177
Brian Carlstrom1db91132013-07-12 18:05:20 -0700178void SeaGraph::BuildMethodSeaGraph(const art::DexFile::CodeItem* code_item,
Dragos Sbirleab40eddf2013-07-31 13:37:31 -0700179 const art::DexFile& dex_file, uint32_t class_def_idx,
180 uint32_t method_idx, uint32_t method_access_flags) {
181 code_item_ = code_item;
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700182 class_def_idx_ = class_def_idx;
183 method_idx_ = method_idx;
Dragos Sbirleab40eddf2013-07-31 13:37:31 -0700184 method_access_flags_ = method_access_flags;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700185 const uint16_t* code = code_item->insns_;
186 const size_t size_in_code_units = code_item->insns_size_in_code_units_;
Brian Carlstrom1db91132013-07-12 18:05:20 -0700187 // This maps target instruction pointers to their corresponding region objects.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700188 std::map<const uint16_t*, Region*> target_regions;
189 size_t i = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700190 // Pass: Find the start instruction of basic blocks
191 // by locating targets and flow-though instructions of branches.
192 while (i < size_in_code_units) {
193 const art::Instruction* inst = art::Instruction::At(&code[i]);
Brian Carlstrom1db91132013-07-12 18:05:20 -0700194 if (inst->IsBranch() || inst->IsUnconditional()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700195 int32_t offset = inst->GetTargetOffset();
Brian Carlstrom1db91132013-07-12 18:05:20 -0700196 if (target_regions.end() == target_regions.find(&code[i + offset])) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700197 Region* region = GetNewRegion();
Brian Carlstrom1db91132013-07-12 18:05:20 -0700198 target_regions.insert(std::pair<const uint16_t*, Region*>(&code[i + offset], region));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700199 }
Brian Carlstrom1db91132013-07-12 18:05:20 -0700200 if (inst->CanFlowThrough()
201 && (target_regions.end() == target_regions.find(&code[i + inst->SizeInCodeUnits()]))) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700202 Region* region = GetNewRegion();
Brian Carlstrom1db91132013-07-12 18:05:20 -0700203 target_regions.insert(
204 std::pair<const uint16_t*, Region*>(&code[i + inst->SizeInCodeUnits()], region));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700205 }
206 }
207 i += inst->SizeInCodeUnits();
208 }
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700209
210
211 Region* r = GetNewRegion();
212 // Insert one SignatureNode per function argument,
213 // to serve as placeholder definitions in dataflow analysis.
214 for (unsigned int crt_offset = 0; crt_offset < code_item->ins_size_; crt_offset++) {
Dragos Sbirleab40eddf2013-07-31 13:37:31 -0700215 int position = crt_offset; // TODO: Is this the correct offset in the signature?
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700216 SignatureNode* parameter_def_node =
Dragos Sbirleab40eddf2013-07-31 13:37:31 -0700217 new sea_ir::SignatureNode(code_item->registers_size_ - 1 - crt_offset, position);
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700218 AddParameterNode(parameter_def_node);
219 r->AddChild(parameter_def_node);
220 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700221 // Pass: Assign instructions to region nodes and
222 // assign branches their control flow successors.
223 i = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700224 sea_ir::InstructionNode* last_node = NULL;
225 sea_ir::InstructionNode* node = NULL;
226 while (i < size_in_code_units) {
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700227 const art::Instruction* inst = art::Instruction::At(&code[i]);
Dragos Sbirleac16c5b42013-07-26 18:08:35 -0700228 std::vector<InstructionNode*> sea_instructions_for_dalvik =
229 sea_ir::InstructionNode::Create(inst);
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700230 for (std::vector<InstructionNode*>::const_iterator cit = sea_instructions_for_dalvik.begin();
231 sea_instructions_for_dalvik.end() != cit; ++cit) {
232 last_node = node;
233 node = *cit;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700234
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700235 if (inst->IsBranch() || inst->IsUnconditional()) {
236 int32_t offset = inst->GetTargetOffset();
237 std::map<const uint16_t*, Region*>::iterator it = target_regions.find(&code[i + offset]);
238 DCHECK(it != target_regions.end());
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700239 AddEdge(r, it->second); // Add edge to branch target.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700240 }
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700241 std::map<const uint16_t*, Region*>::iterator it = target_regions.find(&code[i]);
242 if (target_regions.end() != it) {
243 // Get the already created region because this is a branch target.
244 Region* nextRegion = it->second;
245 if (last_node->GetInstruction()->IsBranch()
246 && last_node->GetInstruction()->CanFlowThrough()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700247 AddEdge(r, it->second); // Add flow-through edge.
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700248 }
249 r = nextRegion;
250 }
Dragos Sbirlea64479192013-08-01 15:38:43 -0700251 r->AddChild(node);
Dragos Sbirleab40eddf2013-07-31 13:37:31 -0700252 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700253 i += inst->SizeInCodeUnits();
254 }
Brian Carlstrom1db91132013-07-12 18:05:20 -0700255}
Brian Carlstrom7940e442013-07-12 13:46:57 -0700256
Brian Carlstrom1db91132013-07-12 18:05:20 -0700257void SeaGraph::ComputeRPO() {
258 int rpo_id = regions_.size() - 1;
259 for (std::vector<Region*>::const_iterator crt_it = regions_.begin(); crt_it != regions_.end();
260 ++crt_it) {
261 if ((*crt_it)->GetPredecessors()->size() == 0) {
262 ComputeRPO(*crt_it, rpo_id);
263 }
264 }
265}
266
267// Performs the renaming phase in traditional SSA transformations.
268// See: Cooper & Torczon, "Engineering a Compiler", second edition, page 505.)
269void SeaGraph::RenameAsSSA() {
270 utils::ScopedHashtable<int, InstructionNode*> scoped_table;
271 scoped_table.OpenScope();
272 for (std::vector<Region*>::iterator region_it = regions_.begin(); region_it != regions_.end();
273 region_it++) {
274 if ((*region_it)->GetIDominator() == *region_it) {
275 RenameAsSSA(*region_it, &scoped_table);
276 }
277 }
Brian Carlstrom1db91132013-07-12 18:05:20 -0700278 scoped_table.CloseScope();
279}
280
281void SeaGraph::ConvertToSSA() {
282 // Pass: find global names.
283 // The map @block maps registers to the blocks in which they are defined.
284 std::map<int, std::set<Region*> > blocks;
285 // The set @globals records registers whose use
286 // is in a different block than the corresponding definition.
287 std::set<int> globals;
288 for (std::vector<Region*>::iterator region_it = regions_.begin(); region_it != regions_.end();
289 region_it++) {
290 std::set<int> var_kill;
291 std::vector<InstructionNode*>* instructions = (*region_it)->GetInstructions();
292 for (std::vector<InstructionNode*>::iterator inst_it = instructions->begin();
293 inst_it != instructions->end(); inst_it++) {
294 std::vector<int> used_regs = (*inst_it)->GetUses();
295 for (std::size_t i = 0; i < used_regs.size(); i++) {
296 int used_reg = used_regs[i];
297 if (var_kill.find(used_reg) == var_kill.end()) {
298 globals.insert(used_reg);
299 }
300 }
301 const int reg_def = (*inst_it)->GetResultRegister();
302 if (reg_def != NO_REGISTER) {
303 var_kill.insert(reg_def);
304 }
305
306 blocks.insert(std::pair<int, std::set<Region*> >(reg_def, std::set<Region*>()));
307 std::set<Region*>* reg_def_blocks = &(blocks.find(reg_def)->second);
308 reg_def_blocks->insert(*region_it);
309 }
310 }
311
312 // Pass: Actually add phi-nodes to regions.
313 for (std::set<int>::const_iterator globals_it = globals.begin();
314 globals_it != globals.end(); globals_it++) {
315 int global = *globals_it;
316 // Copy the set, because we will modify the worklist as we go.
317 std::set<Region*> worklist((*(blocks.find(global))).second);
Dragos Sbirleac16c5b42013-07-26 18:08:35 -0700318 for (std::set<Region*>::const_iterator b_it = worklist.begin();
319 b_it != worklist.end(); b_it++) {
Brian Carlstrom1db91132013-07-12 18:05:20 -0700320 std::set<Region*>* df = (*b_it)->GetDominanceFrontier();
321 for (std::set<Region*>::const_iterator df_it = df->begin(); df_it != df->end(); df_it++) {
322 if ((*df_it)->InsertPhiFor(global)) {
323 // Check that the dominance frontier element is in the worklist already
324 // because we only want to break if the element is actually not there yet.
325 if (worklist.find(*df_it) == worklist.end()) {
326 worklist.insert(*df_it);
327 b_it = worklist.begin();
328 break;
329 }
330 }
331 }
332 }
333 }
334 // Pass: Build edges to the definition corresponding to each use.
335 // (This corresponds to the renaming phase in traditional SSA transformations.
336 // See: Cooper & Torczon, "Engineering a Compiler", second edition, page 505.)
337 RenameAsSSA();
338}
339
340void SeaGraph::RenameAsSSA(Region* crt_region,
341 utils::ScopedHashtable<int, InstructionNode*>* scoped_table) {
342 scoped_table->OpenScope();
343 // Rename phi nodes defined in the current region.
344 std::vector<PhiInstructionNode*>* phis = crt_region->GetPhiNodes();
345 for (std::vector<PhiInstructionNode*>::iterator phi_it = phis->begin();
346 phi_it != phis->end(); phi_it++) {
347 int reg_no = (*phi_it)->GetRegisterNumber();
348 scoped_table->Add(reg_no, (*phi_it));
349 }
350 // Rename operands of instructions from the current region.
351 std::vector<InstructionNode*>* instructions = crt_region->GetInstructions();
352 for (std::vector<InstructionNode*>::const_iterator instructions_it = instructions->begin();
353 instructions_it != instructions->end(); instructions_it++) {
354 InstructionNode* current_instruction = (*instructions_it);
355 // Rename uses.
356 std::vector<int> used_regs = current_instruction->GetUses();
357 for (std::vector<int>::const_iterator reg_it = used_regs.begin();
358 reg_it != used_regs.end(); reg_it++) {
359 int current_used_reg = (*reg_it);
360 InstructionNode* definition = scoped_table->Lookup(current_used_reg);
361 current_instruction->RenameToSSA(current_used_reg, definition);
362 }
363 // Update scope table with latest definitions.
364 std::vector<int> def_regs = current_instruction->GetDefinitions();
365 for (std::vector<int>::const_iterator reg_it = def_regs.begin();
366 reg_it != def_regs.end(); reg_it++) {
367 int current_defined_reg = (*reg_it);
368 scoped_table->Add(current_defined_reg, current_instruction);
369 }
370 }
371 // Fill in uses of phi functions in CFG successor regions.
372 const std::vector<Region*>* successors = crt_region->GetSuccessors();
373 for (std::vector<Region*>::const_iterator successors_it = successors->begin();
374 successors_it != successors->end(); successors_it++) {
375 Region* successor = (*successors_it);
376 successor->SetPhiDefinitionsForUses(scoped_table, crt_region);
377 }
378
379 // Rename all successors in the dominators tree.
380 const std::set<Region*>* dominated_nodes = crt_region->GetIDominatedSet();
381 for (std::set<Region*>::const_iterator dominated_nodes_it = dominated_nodes->begin();
382 dominated_nodes_it != dominated_nodes->end(); dominated_nodes_it++) {
383 Region* dominated_node = (*dominated_nodes_it);
384 RenameAsSSA(dominated_node, scoped_table);
385 }
386 scoped_table->CloseScope();
387}
388
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700389void SeaGraph::GenerateLLVM() {
390 // Pass: Generate LLVM IR.
391 CodeGenPrepassVisitor code_gen_prepass_visitor;
392 std::cout << "Generating code..." << std::endl;
393 std::cout << "=== PRE VISITING ===" << std::endl;
394 Accept(&code_gen_prepass_visitor);
395 CodeGenVisitor code_gen_visitor(code_gen_prepass_visitor.GetData());
396 std::cout << "=== VISITING ===" << std::endl;
397 Accept(&code_gen_visitor);
398 std::cout << "=== POST VISITING ===" << std::endl;
399 CodeGenPostpassVisitor code_gen_postpass_visitor(code_gen_visitor.GetData());
400 Accept(&code_gen_postpass_visitor);
401 code_gen_postpass_visitor.Write(std::string("my_file.llvm"));
402}
403
Dragos Sbirleab40eddf2013-07-31 13:37:31 -0700404void SeaGraph::CompileMethod(const art::DexFile::CodeItem* code_item, uint32_t class_def_idx,
405 uint32_t method_idx, uint32_t method_access_flags, const art::DexFile& dex_file) {
Brian Carlstrom1db91132013-07-12 18:05:20 -0700406 // Two passes: Builds the intermediate structure (non-SSA) of the sea-ir for the function.
Dragos Sbirleab40eddf2013-07-31 13:37:31 -0700407 BuildMethodSeaGraph(code_item, dex_file, class_def_idx, method_idx, method_access_flags);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700408 // Pass: Compute reverse post-order of regions.
Brian Carlstrom1db91132013-07-12 18:05:20 -0700409 ComputeRPO();
410 // Multiple passes: compute immediate dominators.
411 ComputeIDominators();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700412 // Pass: compute downward-exposed definitions.
413 ComputeDownExposedDefs();
Brian Carlstrom1db91132013-07-12 18:05:20 -0700414 // Multiple Passes (iterative fixed-point algorithm): Compute reaching definitions
Brian Carlstrom7940e442013-07-12 13:46:57 -0700415 ComputeReachingDefs();
Brian Carlstrom1db91132013-07-12 18:05:20 -0700416 // Pass (O(nlogN)): Compute the dominance frontier for region nodes.
417 ComputeDominanceFrontier();
418 // Two Passes: Phi node insertion.
419 ConvertToSSA();
Dragos Sbirleab40eddf2013-07-31 13:37:31 -0700420 // Pass: type inference
Dragos Sbirlea64479192013-08-01 15:38:43 -0700421 ti_->ComputeTypes(this);
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700422 // Pass: Generate LLVM IR.
423 GenerateLLVM();
Brian Carlstrom1db91132013-07-12 18:05:20 -0700424}
425
Brian Carlstrom1db91132013-07-12 18:05:20 -0700426void SeaGraph::ComputeDominanceFrontier() {
427 for (std::vector<Region*>::iterator region_it = regions_.begin();
428 region_it != regions_.end(); region_it++) {
429 std::vector<Region*>* preds = (*region_it)->GetPredecessors();
430 if (preds->size() > 1) {
431 for (std::vector<Region*>::iterator pred_it = preds->begin();
432 pred_it != preds->end(); pred_it++) {
433 Region* runner = *pred_it;
434 while (runner != (*region_it)->GetIDominator()) {
435 runner->AddToDominanceFrontier(*region_it);
436 runner = runner->GetIDominator();
437 }
438 }
439 }
440 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700441}
442
443Region* SeaGraph::GetNewRegion() {
444 Region* new_region = new Region();
445 AddRegion(new_region);
446 return new_region;
447}
448
449void SeaGraph::AddRegion(Region* r) {
450 DCHECK(r) << "Tried to add NULL region to SEA graph.";
451 regions_.push_back(r);
452}
453
Dragos Sbirlea64479192013-08-01 15:38:43 -0700454SeaGraph::SeaGraph(const art::DexFile& df)
455 :ti_(new TypeInference()), class_def_idx_(0), method_idx_(0), method_access_flags_(),
456 regions_(), parameters_(), dex_file_(df), code_item_(NULL) { }
Brian Carlstrom1db91132013-07-12 18:05:20 -0700457
Brian Carlstrom7940e442013-07-12 13:46:57 -0700458void Region::AddChild(sea_ir::InstructionNode* instruction) {
459 DCHECK(instruction) << "Tried to add NULL instruction to region node.";
460 instructions_.push_back(instruction);
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700461 instruction->SetRegion(this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700462}
463
464SeaNode* Region::GetLastChild() const {
465 if (instructions_.size() > 0) {
466 return instructions_.back();
467 }
468 return NULL;
469}
470
Brian Carlstrom7940e442013-07-12 13:46:57 -0700471void Region::ComputeDownExposedDefs() {
472 for (std::vector<InstructionNode*>::const_iterator inst_it = instructions_.begin();
473 inst_it != instructions_.end(); inst_it++) {
474 int reg_no = (*inst_it)->GetResultRegister();
475 std::map<int, InstructionNode*>::iterator res = de_defs_.find(reg_no);
476 if ((reg_no != NO_REGISTER) && (res == de_defs_.end())) {
477 de_defs_.insert(std::pair<int, InstructionNode*>(reg_no, *inst_it));
478 } else {
479 res->second = *inst_it;
480 }
481 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700482 for (std::map<int, sea_ir::InstructionNode*>::const_iterator cit = de_defs_.begin();
483 cit != de_defs_.end(); cit++) {
484 (*cit).second->MarkAsDEDef();
485 }
486}
487
Brian Carlstrom7940e442013-07-12 13:46:57 -0700488const std::map<int, sea_ir::InstructionNode*>* Region::GetDownExposedDefs() const {
489 return &de_defs_;
490}
491
492std::map<int, std::set<sea_ir::InstructionNode*>* >* Region::GetReachingDefs() {
493 return &reaching_defs_;
494}
495
496bool Region::UpdateReachingDefs() {
497 std::map<int, std::set<sea_ir::InstructionNode*>* > new_reaching;
498 for (std::vector<Region*>::const_iterator pred_it = predecessors_.begin();
499 pred_it != predecessors_.end(); pred_it++) {
500 // The reaching_defs variable will contain reaching defs __for current predecessor only__
501 std::map<int, std::set<sea_ir::InstructionNode*>* > reaching_defs;
Dragos Sbirleac16c5b42013-07-26 18:08:35 -0700502 std::map<int, std::set<sea_ir::InstructionNode*>* >* pred_reaching =
503 (*pred_it)->GetReachingDefs();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700504 const std::map<int, InstructionNode*>* de_defs = (*pred_it)->GetDownExposedDefs();
505
506 // The definitions from the reaching set of the predecessor
507 // may be shadowed by downward exposed definitions from the predecessor,
508 // otherwise the defs from the reaching set are still good.
509 for (std::map<int, InstructionNode*>::const_iterator de_def = de_defs->begin();
510 de_def != de_defs->end(); de_def++) {
511 std::set<InstructionNode*>* solo_def;
512 solo_def = new std::set<InstructionNode*>();
513 solo_def->insert(de_def->second);
514 reaching_defs.insert(
515 std::pair<int const, std::set<InstructionNode*>*>(de_def->first, solo_def));
516 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700517 reaching_defs.insert(pred_reaching->begin(), pred_reaching->end());
518
519 // Now we combine the reaching map coming from the current predecessor (reaching_defs)
520 // with the accumulated set from all predecessors so far (from new_reaching).
Dragos Sbirleac16c5b42013-07-26 18:08:35 -0700521 std::map<int, std::set<sea_ir::InstructionNode*>*>::iterator reaching_it =
522 reaching_defs.begin();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700523 for (; reaching_it != reaching_defs.end(); reaching_it++) {
524 std::map<int, std::set<sea_ir::InstructionNode*>*>::iterator crt_entry =
525 new_reaching.find(reaching_it->first);
526 if (new_reaching.end() != crt_entry) {
527 crt_entry->second->insert(reaching_it->second->begin(), reaching_it->second->end());
528 } else {
529 new_reaching.insert(
530 std::pair<int, std::set<sea_ir::InstructionNode*>*>(
531 reaching_it->first,
532 reaching_it->second) );
533 }
534 }
535 }
536 bool changed = false;
537 // Because the sets are monotonically increasing,
538 // we can compare sizes instead of using set comparison.
539 // TODO: Find formal proof.
540 int old_size = 0;
541 if (-1 == reaching_defs_size_) {
Dragos Sbirleac16c5b42013-07-26 18:08:35 -0700542 std::map<int, std::set<sea_ir::InstructionNode*>*>::iterator reaching_it =
543 reaching_defs_.begin();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700544 for (; reaching_it != reaching_defs_.end(); reaching_it++) {
545 old_size += (*reaching_it).second->size();
546 }
547 } else {
548 old_size = reaching_defs_size_;
549 }
550 int new_size = 0;
551 std::map<int, std::set<sea_ir::InstructionNode*>*>::iterator reaching_it = new_reaching.begin();
552 for (; reaching_it != new_reaching.end(); reaching_it++) {
553 new_size += (*reaching_it).second->size();
554 }
555 if (old_size != new_size) {
556 changed = true;
557 }
558 if (changed) {
559 reaching_defs_ = new_reaching;
560 reaching_defs_size_ = new_size;
561 }
562 return changed;
563}
564
Brian Carlstrom1db91132013-07-12 18:05:20 -0700565bool Region::InsertPhiFor(int reg_no) {
566 if (!ContainsPhiFor(reg_no)) {
567 phi_set_.insert(reg_no);
568 PhiInstructionNode* new_phi = new PhiInstructionNode(reg_no);
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700569 new_phi->SetRegion(this);
Brian Carlstrom1db91132013-07-12 18:05:20 -0700570 phi_instructions_.push_back(new_phi);
571 return true;
572 }
573 return false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700574}
575
Brian Carlstrom1db91132013-07-12 18:05:20 -0700576void Region::SetPhiDefinitionsForUses(
577 const utils::ScopedHashtable<int, InstructionNode*>* scoped_table, Region* predecessor) {
578 int predecessor_id = -1;
579 for (unsigned int crt_pred_id = 0; crt_pred_id < predecessors_.size(); crt_pred_id++) {
580 if (predecessors_.at(crt_pred_id) == predecessor) {
581 predecessor_id = crt_pred_id;
582 }
583 }
584 DCHECK_NE(-1, predecessor_id);
585 for (std::vector<PhiInstructionNode*>::iterator phi_it = phi_instructions_.begin();
586 phi_it != phi_instructions_.end(); phi_it++) {
587 PhiInstructionNode* phi = (*phi_it);
588 int reg_no = phi->GetRegisterNumber();
589 InstructionNode* definition = scoped_table->Lookup(reg_no);
590 phi->RenameToSSA(reg_no, definition, predecessor_id);
591 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700592}
593
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700594std::vector<InstructionNode*> InstructionNode::Create(const art::Instruction* in) {
595 std::vector<InstructionNode*> sea_instructions;
596 switch (in->Opcode()) {
597 case art::Instruction::CONST_4:
598 sea_instructions.push_back(new ConstInstructionNode(in));
599 break;
600 case art::Instruction::RETURN:
601 sea_instructions.push_back(new ReturnInstructionNode(in));
602 break;
603 case art::Instruction::IF_NE:
604 sea_instructions.push_back(new IfNeInstructionNode(in));
605 break;
606 case art::Instruction::ADD_INT_LIT8:
607 sea_instructions.push_back(new UnnamedConstInstructionNode(in, in->VRegB_22b()));
608 sea_instructions.push_back(new AddIntLitInstructionNode(in));
609 break;
610 case art::Instruction::MOVE_RESULT:
611 sea_instructions.push_back(new MoveResultInstructionNode(in));
612 break;
613 case art::Instruction::INVOKE_STATIC:
614 sea_instructions.push_back(new InvokeStaticInstructionNode(in));
615 break;
616 case art::Instruction::ADD_INT:
617 sea_instructions.push_back(new AddIntInstructionNode(in));
618 break;
619 case art::Instruction::GOTO:
620 sea_instructions.push_back(new GotoInstructionNode(in));
621 break;
622 case art::Instruction::IF_EQZ:
623 sea_instructions.push_back(new IfEqzInstructionNode(in));
624 break;
625 default:
626 // Default, generic IR instruction node; default case should never be reached
627 // when support for all instructions ahs been added.
628 sea_instructions.push_back(new InstructionNode(in));
629 }
630 return sea_instructions;
631}
632
Brian Carlstrom1db91132013-07-12 18:05:20 -0700633void InstructionNode::MarkAsDEDef() {
634 de_def_ = true;
635}
636
637int InstructionNode::GetResultRegister() const {
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700638 if (instruction_->HasVRegA() && InstructionTools::IsDefinition(instruction_)) {
Brian Carlstrom1db91132013-07-12 18:05:20 -0700639 return instruction_->VRegA();
640 }
641 return NO_REGISTER;
642}
643
644std::vector<int> InstructionNode::GetDefinitions() const {
645 // TODO: Extend this to handle instructions defining more than one register (if any)
646 // The return value should be changed to pointer to field then; for now it is an object
647 // so that we avoid possible memory leaks from allocating objects dynamically.
648 std::vector<int> definitions;
649 int result = GetResultRegister();
650 if (NO_REGISTER != result) {
651 definitions.push_back(result);
652 }
653 return definitions;
654}
655
Dragos Sbirlea64479192013-08-01 15:38:43 -0700656std::vector<int> InstructionNode::GetUses() const {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700657 std::vector<int> uses; // Using vector<> instead of set<> because order matters.
Brian Carlstrom1db91132013-07-12 18:05:20 -0700658 if (!InstructionTools::IsDefinition(instruction_) && (instruction_->HasVRegA())) {
659 int vA = instruction_->VRegA();
660 uses.push_back(vA);
661 }
662 if (instruction_->HasVRegB()) {
663 int vB = instruction_->VRegB();
664 uses.push_back(vB);
665 }
666 if (instruction_->HasVRegC()) {
667 int vC = instruction_->VRegC();
668 uses.push_back(vC);
669 }
Brian Carlstrom1db91132013-07-12 18:05:20 -0700670 return uses;
671}
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700672} // namespace sea_ir