blob: 7a1894b26e4aa986fd71e8056900586e414dd10c [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"
Brian Carlstrom7940e442013-07-12 13:46:57 -070017#include "file_output_stream.h"
Brian Carlstrom1db91132013-07-12 18:05:20 -070018#include "instruction_tools.h"
Dragos Sbirlea0e260a32013-06-21 09:20:34 -070019#include "sea.h"
20#include "code_gen.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 }
38
39 std::vector<InstructionNode*>* instructions = region->GetInstructions();
40 for (std::vector<InstructionNode*>::const_iterator cit = instructions->begin();
41 cit != instructions->end(); cit++) {
42 (*cit)->Accept(this);
43 }
44}
45
46void IRVisitor::Traverse(SeaGraph* graph) {
47 for (std::vector<Region*>::const_iterator cit = ordered_regions_.begin();
48 cit != ordered_regions_.end(); cit++ ) {
49 (*cit)->Accept(this);
50 }
51}
Brian Carlstrom7940e442013-07-12 13:46:57 -070052
Dragos Sbirlea6bee4452013-07-26 12:05:03 -070053SeaGraph* SeaGraph::GetCurrentGraph(const art::DexFile& dex_file) {
54 return new SeaGraph(dex_file);
Brian Carlstrom7940e442013-07-12 13:46:57 -070055}
56
57void SeaGraph::DumpSea(std::string filename) const {
Brian Carlstrom1db91132013-07-12 18:05:20 -070058 LOG(INFO) << "Starting to write SEA string to file.";
Brian Carlstrom7940e442013-07-12 13:46:57 -070059 std::string result;
Dragos Sbirlea6bee4452013-07-26 12:05:03 -070060 result += "digraph seaOfNodes {\ncompound=true\n";
Brian Carlstrom7940e442013-07-12 13:46:57 -070061 for (std::vector<Region*>::const_iterator cit = regions_.begin(); cit != regions_.end(); cit++) {
Dragos Sbirlea6bee4452013-07-26 12:05:03 -070062 (*cit)->ToDot(result, dex_file_);
Brian Carlstrom7940e442013-07-12 13:46:57 -070063 }
64 result += "}\n";
65 art::File* file = art::OS::OpenFile(filename.c_str(), true, true);
66 art::FileOutputStream fos(file);
67 fos.WriteFully(result.c_str(), result.size());
68 LOG(INFO) << "Written SEA string to file.";
69}
70
71void SeaGraph::AddEdge(Region* src, Region* dst) const {
72 src->AddSuccessor(dst);
73 dst->AddPredecessor(src);
74}
75
Brian Carlstrom1db91132013-07-12 18:05:20 -070076void SeaGraph::ComputeRPO(Region* current_region, int& current_rpo) {
77 current_region->SetRPO(VISITING);
78 std::vector<sea_ir::Region*>* succs = current_region->GetSuccessors();
79 for (std::vector<sea_ir::Region*>::iterator succ_it = succs->begin();
80 succ_it != succs->end(); ++succ_it) {
81 if (NOT_VISITED == (*succ_it)->GetRPO()) {
82 SeaGraph::ComputeRPO(*succ_it, current_rpo);
83 }
84 }
85 current_region->SetRPO(current_rpo--);
86}
87
88void SeaGraph::ComputeIDominators() {
89 bool changed = true;
90 while (changed) {
91 changed = false;
92 // Entry node has itself as IDOM.
93 std::vector<Region*>::iterator crt_it;
94 std::set<Region*> processedNodes;
95 // Find and mark the entry node(s).
96 for (crt_it = regions_.begin(); crt_it != regions_.end(); ++crt_it) {
97 if ((*crt_it)->GetPredecessors()->size() == 0) {
98 processedNodes.insert(*crt_it);
99 (*crt_it)->SetIDominator(*crt_it);
100 }
101 }
102 for (crt_it = regions_.begin(); crt_it != regions_.end(); ++crt_it) {
103 if ((*crt_it)->GetPredecessors()->size() == 0) {
104 continue;
105 }
106 // NewIDom = first (processed) predecessor of b.
107 Region* new_dom = NULL;
108 std::vector<Region*>* preds = (*crt_it)->GetPredecessors();
109 DCHECK(NULL != preds);
110 Region* root_pred = NULL;
111 for (std::vector<Region*>::iterator pred_it = preds->begin();
112 pred_it != preds->end(); ++pred_it) {
113 if (processedNodes.end() != processedNodes.find((*pred_it))) {
114 root_pred = *pred_it;
115 new_dom = root_pred;
116 break;
117 }
118 }
119 // For all other predecessors p of b, if idom is not set,
120 // then NewIdom = Intersect(p, NewIdom)
121 for (std::vector<Region*>::const_iterator pred_it = preds->begin();
122 pred_it != preds->end(); ++pred_it) {
123 DCHECK(NULL != *pred_it);
124 // if IDOMS[p] != UNDEFINED
125 if ((*pred_it != root_pred) && (*pred_it)->GetIDominator() != NULL) {
126 DCHECK(NULL != new_dom);
127 new_dom = SeaGraph::Intersect(*pred_it, new_dom);
128 }
129 }
130 DCHECK(NULL != *crt_it);
131 if ((*crt_it)->GetIDominator() != new_dom) {
132 (*crt_it)->SetIDominator(new_dom);
133 changed = true;
134 }
135 processedNodes.insert(*crt_it);
136 }
137 }
138
139 // For easily ordering of regions we need edges dominator->dominated.
140 for (std::vector<Region*>::iterator region_it = regions_.begin();
141 region_it != regions_.end(); region_it++) {
142 Region* idom = (*region_it)->GetIDominator();
143 if (idom != *region_it) {
144 idom->AddToIDominatedSet(*region_it);
145 }
146 }
147}
148
149Region* SeaGraph::Intersect(Region* i, Region* j) {
150 Region* finger1 = i;
151 Region* finger2 = j;
152 while (finger1 != finger2) {
153 while (finger1->GetRPO() > finger2->GetRPO()) {
154 DCHECK(NULL != finger1);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700155 finger1 = finger1->GetIDominator(); // should have: finger1 != NULL
Brian Carlstrom1db91132013-07-12 18:05:20 -0700156 DCHECK(NULL != finger1);
157 }
158 while (finger1->GetRPO() < finger2->GetRPO()) {
159 DCHECK(NULL != finger2);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700160 finger2 = finger2->GetIDominator(); // should have: finger1 != NULL
Brian Carlstrom1db91132013-07-12 18:05:20 -0700161 DCHECK(NULL != finger2);
162 }
163 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700164 return finger1; // finger1 should be equal to finger2 at this point.
Brian Carlstrom1db91132013-07-12 18:05:20 -0700165}
166
Brian Carlstrom7940e442013-07-12 13:46:57 -0700167void SeaGraph::ComputeDownExposedDefs() {
168 for (std::vector<Region*>::iterator region_it = regions_.begin();
169 region_it != regions_.end(); region_it++) {
170 (*region_it)->ComputeDownExposedDefs();
171 }
172}
173
174void SeaGraph::ComputeReachingDefs() {
175 // Iterate until the reaching definitions set doesn't change anymore.
176 // (See Cooper & Torczon, "Engineering a Compiler", second edition, page 487)
177 bool changed = true;
178 int iteration = 0;
179 while (changed && (iteration < MAX_REACHING_DEF_ITERERATIONS)) {
180 iteration++;
181 changed = false;
182 // TODO: optimize the ordering if this becomes performance bottleneck.
183 for (std::vector<Region*>::iterator regions_it = regions_.begin();
184 regions_it != regions_.end();
185 regions_it++) {
186 changed |= (*regions_it)->UpdateReachingDefs();
187 }
188 }
189 DCHECK(!changed) << "Reaching definitions computation did not reach a fixed point.";
190}
191
192
Brian Carlstrom1db91132013-07-12 18:05:20 -0700193void SeaGraph::BuildMethodSeaGraph(const art::DexFile::CodeItem* code_item,
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700194 const art::DexFile& dex_file, uint32_t class_def_idx, uint32_t method_idx) {
195 class_def_idx_ = class_def_idx;
196 method_idx_ = method_idx;
197
Brian Carlstrom7940e442013-07-12 13:46:57 -0700198 const uint16_t* code = code_item->insns_;
199 const size_t size_in_code_units = code_item->insns_size_in_code_units_;
Brian Carlstrom1db91132013-07-12 18:05:20 -0700200 // This maps target instruction pointers to their corresponding region objects.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700201 std::map<const uint16_t*, Region*> target_regions;
202 size_t i = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700203 // Pass: Find the start instruction of basic blocks
204 // by locating targets and flow-though instructions of branches.
205 while (i < size_in_code_units) {
206 const art::Instruction* inst = art::Instruction::At(&code[i]);
Brian Carlstrom1db91132013-07-12 18:05:20 -0700207 if (inst->IsBranch() || inst->IsUnconditional()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700208 int32_t offset = inst->GetTargetOffset();
Brian Carlstrom1db91132013-07-12 18:05:20 -0700209 if (target_regions.end() == target_regions.find(&code[i + offset])) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700210 Region* region = GetNewRegion();
Brian Carlstrom1db91132013-07-12 18:05:20 -0700211 target_regions.insert(std::pair<const uint16_t*, Region*>(&code[i + offset], region));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700212 }
Brian Carlstrom1db91132013-07-12 18:05:20 -0700213 if (inst->CanFlowThrough()
214 && (target_regions.end() == target_regions.find(&code[i + inst->SizeInCodeUnits()]))) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700215 Region* region = GetNewRegion();
Brian Carlstrom1db91132013-07-12 18:05:20 -0700216 target_regions.insert(
217 std::pair<const uint16_t*, Region*>(&code[i + inst->SizeInCodeUnits()], region));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700218 }
219 }
220 i += inst->SizeInCodeUnits();
221 }
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700222
223
224 Region* r = GetNewRegion();
225 // Insert one SignatureNode per function argument,
226 // to serve as placeholder definitions in dataflow analysis.
227 for (unsigned int crt_offset = 0; crt_offset < code_item->ins_size_; crt_offset++) {
228 SignatureNode* parameter_def_node =
229 new sea_ir::SignatureNode(code_item->registers_size_ - 1 - crt_offset);
230 AddParameterNode(parameter_def_node);
231 r->AddChild(parameter_def_node);
232 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700233 // Pass: Assign instructions to region nodes and
234 // assign branches their control flow successors.
235 i = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700236 sea_ir::InstructionNode* last_node = NULL;
237 sea_ir::InstructionNode* node = NULL;
238 while (i < size_in_code_units) {
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700239 const art::Instruction* inst = art::Instruction::At(&code[i]);
240 std::vector<InstructionNode*> sea_instructions_for_dalvik = sea_ir::InstructionNode::Create(inst);
241 for (std::vector<InstructionNode*>::const_iterator cit = sea_instructions_for_dalvik.begin();
242 sea_instructions_for_dalvik.end() != cit; ++cit) {
243 last_node = node;
244 node = *cit;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700245
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700246 if (inst->IsBranch() || inst->IsUnconditional()) {
247 int32_t offset = inst->GetTargetOffset();
248 std::map<const uint16_t*, Region*>::iterator it = target_regions.find(&code[i + offset]);
249 DCHECK(it != target_regions.end());
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700250 AddEdge(r, it->second); // Add edge to branch target.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700251 }
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700252
253 std::map<const uint16_t*, Region*>::iterator it = target_regions.find(&code[i]);
254 if (target_regions.end() != it) {
255 // Get the already created region because this is a branch target.
256 Region* nextRegion = it->second;
257 if (last_node->GetInstruction()->IsBranch()
258 && last_node->GetInstruction()->CanFlowThrough()) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700259 AddEdge(r, it->second); // Add flow-through edge.
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700260 }
261 r = nextRegion;
262 }
263 bool definesRegister = (0 != InstructionTools::instruction_attributes_[inst->Opcode()]
264 && (1 << kDA));
265 LOG(INFO)<< inst->GetDexPc(code) << "*** " << inst->DumpString(&dex_file)
266 << " region:" <<r->StringId() << "Definition?" << definesRegister << std::endl;
267 r->AddChild(node);
268 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700269 i += inst->SizeInCodeUnits();
270 }
Brian Carlstrom1db91132013-07-12 18:05:20 -0700271}
Brian Carlstrom7940e442013-07-12 13:46:57 -0700272
Brian Carlstrom1db91132013-07-12 18:05:20 -0700273void SeaGraph::ComputeRPO() {
274 int rpo_id = regions_.size() - 1;
275 for (std::vector<Region*>::const_iterator crt_it = regions_.begin(); crt_it != regions_.end();
276 ++crt_it) {
277 if ((*crt_it)->GetPredecessors()->size() == 0) {
278 ComputeRPO(*crt_it, rpo_id);
279 }
280 }
281}
282
283// Performs the renaming phase in traditional SSA transformations.
284// See: Cooper & Torczon, "Engineering a Compiler", second edition, page 505.)
285void SeaGraph::RenameAsSSA() {
286 utils::ScopedHashtable<int, InstructionNode*> scoped_table;
287 scoped_table.OpenScope();
288 for (std::vector<Region*>::iterator region_it = regions_.begin(); region_it != regions_.end();
289 region_it++) {
290 if ((*region_it)->GetIDominator() == *region_it) {
291 RenameAsSSA(*region_it, &scoped_table);
292 }
293 }
Brian Carlstrom1db91132013-07-12 18:05:20 -0700294 scoped_table.CloseScope();
295}
296
297void SeaGraph::ConvertToSSA() {
298 // Pass: find global names.
299 // The map @block maps registers to the blocks in which they are defined.
300 std::map<int, std::set<Region*> > blocks;
301 // The set @globals records registers whose use
302 // is in a different block than the corresponding definition.
303 std::set<int> globals;
304 for (std::vector<Region*>::iterator region_it = regions_.begin(); region_it != regions_.end();
305 region_it++) {
306 std::set<int> var_kill;
307 std::vector<InstructionNode*>* instructions = (*region_it)->GetInstructions();
308 for (std::vector<InstructionNode*>::iterator inst_it = instructions->begin();
309 inst_it != instructions->end(); inst_it++) {
310 std::vector<int> used_regs = (*inst_it)->GetUses();
311 for (std::size_t i = 0; i < used_regs.size(); i++) {
312 int used_reg = used_regs[i];
313 if (var_kill.find(used_reg) == var_kill.end()) {
314 globals.insert(used_reg);
315 }
316 }
317 const int reg_def = (*inst_it)->GetResultRegister();
318 if (reg_def != NO_REGISTER) {
319 var_kill.insert(reg_def);
320 }
321
322 blocks.insert(std::pair<int, std::set<Region*> >(reg_def, std::set<Region*>()));
323 std::set<Region*>* reg_def_blocks = &(blocks.find(reg_def)->second);
324 reg_def_blocks->insert(*region_it);
325 }
326 }
327
328 // Pass: Actually add phi-nodes to regions.
329 for (std::set<int>::const_iterator globals_it = globals.begin();
330 globals_it != globals.end(); globals_it++) {
331 int global = *globals_it;
332 // Copy the set, because we will modify the worklist as we go.
333 std::set<Region*> worklist((*(blocks.find(global))).second);
334 for (std::set<Region*>::const_iterator b_it = worklist.begin(); b_it != worklist.end(); b_it++) {
335 std::set<Region*>* df = (*b_it)->GetDominanceFrontier();
336 for (std::set<Region*>::const_iterator df_it = df->begin(); df_it != df->end(); df_it++) {
337 if ((*df_it)->InsertPhiFor(global)) {
338 // Check that the dominance frontier element is in the worklist already
339 // because we only want to break if the element is actually not there yet.
340 if (worklist.find(*df_it) == worklist.end()) {
341 worklist.insert(*df_it);
342 b_it = worklist.begin();
343 break;
344 }
345 }
346 }
347 }
348 }
349 // Pass: Build edges to the definition corresponding to each use.
350 // (This corresponds to the renaming phase in traditional SSA transformations.
351 // See: Cooper & Torczon, "Engineering a Compiler", second edition, page 505.)
352 RenameAsSSA();
353}
354
355void SeaGraph::RenameAsSSA(Region* crt_region,
356 utils::ScopedHashtable<int, InstructionNode*>* scoped_table) {
357 scoped_table->OpenScope();
358 // Rename phi nodes defined in the current region.
359 std::vector<PhiInstructionNode*>* phis = crt_region->GetPhiNodes();
360 for (std::vector<PhiInstructionNode*>::iterator phi_it = phis->begin();
361 phi_it != phis->end(); phi_it++) {
362 int reg_no = (*phi_it)->GetRegisterNumber();
363 scoped_table->Add(reg_no, (*phi_it));
364 }
365 // Rename operands of instructions from the current region.
366 std::vector<InstructionNode*>* instructions = crt_region->GetInstructions();
367 for (std::vector<InstructionNode*>::const_iterator instructions_it = instructions->begin();
368 instructions_it != instructions->end(); instructions_it++) {
369 InstructionNode* current_instruction = (*instructions_it);
370 // Rename uses.
371 std::vector<int> used_regs = current_instruction->GetUses();
372 for (std::vector<int>::const_iterator reg_it = used_regs.begin();
373 reg_it != used_regs.end(); reg_it++) {
374 int current_used_reg = (*reg_it);
375 InstructionNode* definition = scoped_table->Lookup(current_used_reg);
376 current_instruction->RenameToSSA(current_used_reg, definition);
377 }
378 // Update scope table with latest definitions.
379 std::vector<int> def_regs = current_instruction->GetDefinitions();
380 for (std::vector<int>::const_iterator reg_it = def_regs.begin();
381 reg_it != def_regs.end(); reg_it++) {
382 int current_defined_reg = (*reg_it);
383 scoped_table->Add(current_defined_reg, current_instruction);
384 }
385 }
386 // Fill in uses of phi functions in CFG successor regions.
387 const std::vector<Region*>* successors = crt_region->GetSuccessors();
388 for (std::vector<Region*>::const_iterator successors_it = successors->begin();
389 successors_it != successors->end(); successors_it++) {
390 Region* successor = (*successors_it);
391 successor->SetPhiDefinitionsForUses(scoped_table, crt_region);
392 }
393
394 // Rename all successors in the dominators tree.
395 const std::set<Region*>* dominated_nodes = crt_region->GetIDominatedSet();
396 for (std::set<Region*>::const_iterator dominated_nodes_it = dominated_nodes->begin();
397 dominated_nodes_it != dominated_nodes->end(); dominated_nodes_it++) {
398 Region* dominated_node = (*dominated_nodes_it);
399 RenameAsSSA(dominated_node, scoped_table);
400 }
401 scoped_table->CloseScope();
402}
403
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700404void SeaGraph::GenerateLLVM() {
405 // Pass: Generate LLVM IR.
406 CodeGenPrepassVisitor code_gen_prepass_visitor;
407 std::cout << "Generating code..." << std::endl;
408 std::cout << "=== PRE VISITING ===" << std::endl;
409 Accept(&code_gen_prepass_visitor);
410 CodeGenVisitor code_gen_visitor(code_gen_prepass_visitor.GetData());
411 std::cout << "=== VISITING ===" << std::endl;
412 Accept(&code_gen_visitor);
413 std::cout << "=== POST VISITING ===" << std::endl;
414 CodeGenPostpassVisitor code_gen_postpass_visitor(code_gen_visitor.GetData());
415 Accept(&code_gen_postpass_visitor);
416 code_gen_postpass_visitor.Write(std::string("my_file.llvm"));
417}
418
Brian Carlstrom1db91132013-07-12 18:05:20 -0700419void SeaGraph::CompileMethod(const art::DexFile::CodeItem* code_item,
420 uint32_t class_def_idx, uint32_t method_idx, const art::DexFile& dex_file) {
421 // Two passes: Builds the intermediate structure (non-SSA) of the sea-ir for the function.
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700422 BuildMethodSeaGraph(code_item, dex_file, class_def_idx, method_idx);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700423 // Pass: Compute reverse post-order of regions.
Brian Carlstrom1db91132013-07-12 18:05:20 -0700424 ComputeRPO();
425 // Multiple passes: compute immediate dominators.
426 ComputeIDominators();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700427 // Pass: compute downward-exposed definitions.
428 ComputeDownExposedDefs();
Brian Carlstrom1db91132013-07-12 18:05:20 -0700429 // Multiple Passes (iterative fixed-point algorithm): Compute reaching definitions
Brian Carlstrom7940e442013-07-12 13:46:57 -0700430 ComputeReachingDefs();
Brian Carlstrom1db91132013-07-12 18:05:20 -0700431 // Pass (O(nlogN)): Compute the dominance frontier for region nodes.
432 ComputeDominanceFrontier();
433 // Two Passes: Phi node insertion.
434 ConvertToSSA();
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700435 // Pass: Generate LLVM IR.
436 GenerateLLVM();
Brian Carlstrom1db91132013-07-12 18:05:20 -0700437}
438
Brian Carlstrom1db91132013-07-12 18:05:20 -0700439void SeaGraph::ComputeDominanceFrontier() {
440 for (std::vector<Region*>::iterator region_it = regions_.begin();
441 region_it != regions_.end(); region_it++) {
442 std::vector<Region*>* preds = (*region_it)->GetPredecessors();
443 if (preds->size() > 1) {
444 for (std::vector<Region*>::iterator pred_it = preds->begin();
445 pred_it != preds->end(); pred_it++) {
446 Region* runner = *pred_it;
447 while (runner != (*region_it)->GetIDominator()) {
448 runner->AddToDominanceFrontier(*region_it);
449 runner = runner->GetIDominator();
450 }
451 }
452 }
453 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700454}
455
456Region* SeaGraph::GetNewRegion() {
457 Region* new_region = new Region();
458 AddRegion(new_region);
459 return new_region;
460}
461
462void SeaGraph::AddRegion(Region* r) {
463 DCHECK(r) << "Tried to add NULL region to SEA graph.";
464 regions_.push_back(r);
465}
466
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700467/*
Brian Carlstrom1db91132013-07-12 18:05:20 -0700468void SeaNode::AddSuccessor(Region* successor) {
469 DCHECK(successor) << "Tried to add NULL successor to SEA node.";
470 successors_.push_back(successor);
471 return;
472}
473
474void SeaNode::AddPredecessor(Region* predecessor) {
475 DCHECK(predecessor) << "Tried to add NULL predecessor to SEA node.";
476 predecessors_.push_back(predecessor);
477}
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700478*/
Brian Carlstrom7940e442013-07-12 13:46:57 -0700479void Region::AddChild(sea_ir::InstructionNode* instruction) {
480 DCHECK(instruction) << "Tried to add NULL instruction to region node.";
481 instructions_.push_back(instruction);
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700482 instruction->SetRegion(this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700483}
484
485SeaNode* Region::GetLastChild() const {
486 if (instructions_.size() > 0) {
487 return instructions_.back();
488 }
489 return NULL;
490}
491
Dragos Sbirlea6bee4452013-07-26 12:05:03 -0700492void Region::ToDot(std::string& result, const art::DexFile& dex_file) const {
493 result += "\n// Region: \nsubgraph " + StringId() + " { label=\"region " + StringId() + "(rpo=";
Dragos Sbirleadb063062013-07-23 16:29:09 -0700494 result += art::StringPrintf("%d", rpo_number_);
Brian Carlstrom1db91132013-07-12 18:05:20 -0700495 if (NULL != GetIDominator()) {
496 result += " dom=" + GetIDominator()->StringId();
497 }
Dragos Sbirlea6bee4452013-07-26 12:05:03 -0700498 result += ")\";\n";
499
500 for (std::vector<PhiInstructionNode*>::const_iterator cit = phi_instructions_.begin();
501 cit != phi_instructions_.end(); cit++) {
502 result += (*cit)->StringId() +";\n";
503 }
504
505 for (std::vector<InstructionNode*>::const_iterator cit = instructions_.begin();
506 cit != instructions_.end(); cit++) {
507 result += (*cit)->StringId() +";\n";
508 // result += StringId() + " -> " + (*cit)->StringId() + "; // region -> instruction \n";
509 }
510
511 result += "} // End Region.\n";
Brian Carlstrom1db91132013-07-12 18:05:20 -0700512
513 // Save phi-nodes.
514 for (std::vector<PhiInstructionNode*>::const_iterator cit = phi_instructions_.begin();
515 cit != phi_instructions_.end(); cit++) {
Dragos Sbirlea6bee4452013-07-26 12:05:03 -0700516 (*cit)->ToDot(result, dex_file);
517 // result += StringId() + " -> " + (*cit)->StringId() + "; // region -> phi-function \n";
Brian Carlstrom1db91132013-07-12 18:05:20 -0700518 }
519
520 // Save instruction nodes.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700521 for (std::vector<InstructionNode*>::const_iterator cit = instructions_.begin();
522 cit != instructions_.end(); cit++) {
Dragos Sbirlea6bee4452013-07-26 12:05:03 -0700523 (*cit)->ToDot(result, dex_file);
524 //result += StringId() + " -> " + (*cit)->StringId() + "; // region -> instruction \n";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700525 }
526
527 for (std::vector<Region*>::const_iterator cit = successors_.begin(); cit != successors_.end();
528 cit++) {
529 DCHECK(NULL != *cit) << "Null successor found for SeaNode" << GetLastChild()->StringId() << ".";
Dragos Sbirlea6bee4452013-07-26 12:05:03 -0700530 result += GetLastChild()->StringId() + " -> " + (*cit)->GetLastChild()->StringId() +
531 "[lhead=" + (*cit)->StringId() + ", " + "ltail=" + StringId() + "];\n\n";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700532 }
Dragos Sbirlea6bee4452013-07-26 12:05:03 -0700533 /*
Brian Carlstrom7940e442013-07-12 13:46:57 -0700534 // Save reaching definitions.
535 for (std::map<int, std::set<sea_ir::InstructionNode*>* >::const_iterator cit =
536 reaching_defs_.begin();
537 cit != reaching_defs_.end(); cit++) {
538 for (std::set<sea_ir::InstructionNode*>::const_iterator
539 reaching_set_it = (*cit).second->begin();
540 reaching_set_it != (*cit).second->end();
541 reaching_set_it++) {
542 result += (*reaching_set_it)->StringId() +
543 " -> " + StringId() +
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700544 " [style=dotted]; // Reaching def.\n";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700545 }
546 }
Brian Carlstrom1db91132013-07-12 18:05:20 -0700547 // Save dominance frontier.
548 for (std::set<Region*>::const_iterator cit = df_.begin(); cit != df_.end(); cit++) {
549 result += StringId() +
550 " -> " + (*cit)->StringId() +
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700551 " [color=gray]; // Dominance frontier.\n";
Brian Carlstrom1db91132013-07-12 18:05:20 -0700552 }
Dragos Sbirlea6bee4452013-07-26 12:05:03 -0700553 */
Brian Carlstrom7940e442013-07-12 13:46:57 -0700554}
555
Brian Carlstrom7940e442013-07-12 13:46:57 -0700556void Region::ComputeDownExposedDefs() {
557 for (std::vector<InstructionNode*>::const_iterator inst_it = instructions_.begin();
558 inst_it != instructions_.end(); inst_it++) {
559 int reg_no = (*inst_it)->GetResultRegister();
560 std::map<int, InstructionNode*>::iterator res = de_defs_.find(reg_no);
561 if ((reg_no != NO_REGISTER) && (res == de_defs_.end())) {
562 de_defs_.insert(std::pair<int, InstructionNode*>(reg_no, *inst_it));
563 } else {
564 res->second = *inst_it;
565 }
566 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700567 for (std::map<int, sea_ir::InstructionNode*>::const_iterator cit = de_defs_.begin();
568 cit != de_defs_.end(); cit++) {
569 (*cit).second->MarkAsDEDef();
570 }
571}
572
Brian Carlstrom7940e442013-07-12 13:46:57 -0700573const std::map<int, sea_ir::InstructionNode*>* Region::GetDownExposedDefs() const {
574 return &de_defs_;
575}
576
577std::map<int, std::set<sea_ir::InstructionNode*>* >* Region::GetReachingDefs() {
578 return &reaching_defs_;
579}
580
581bool Region::UpdateReachingDefs() {
582 std::map<int, std::set<sea_ir::InstructionNode*>* > new_reaching;
583 for (std::vector<Region*>::const_iterator pred_it = predecessors_.begin();
584 pred_it != predecessors_.end(); pred_it++) {
585 // The reaching_defs variable will contain reaching defs __for current predecessor only__
586 std::map<int, std::set<sea_ir::InstructionNode*>* > reaching_defs;
587 std::map<int, std::set<sea_ir::InstructionNode*>* >* pred_reaching = (*pred_it)->GetReachingDefs();
588 const std::map<int, InstructionNode*>* de_defs = (*pred_it)->GetDownExposedDefs();
589
590 // The definitions from the reaching set of the predecessor
591 // may be shadowed by downward exposed definitions from the predecessor,
592 // otherwise the defs from the reaching set are still good.
593 for (std::map<int, InstructionNode*>::const_iterator de_def = de_defs->begin();
594 de_def != de_defs->end(); de_def++) {
595 std::set<InstructionNode*>* solo_def;
596 solo_def = new std::set<InstructionNode*>();
597 solo_def->insert(de_def->second);
598 reaching_defs.insert(
599 std::pair<int const, std::set<InstructionNode*>*>(de_def->first, solo_def));
600 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700601 reaching_defs.insert(pred_reaching->begin(), pred_reaching->end());
602
603 // Now we combine the reaching map coming from the current predecessor (reaching_defs)
604 // with the accumulated set from all predecessors so far (from new_reaching).
605 std::map<int, std::set<sea_ir::InstructionNode*>*>::iterator reaching_it = reaching_defs.begin();
606 for (; reaching_it != reaching_defs.end(); reaching_it++) {
607 std::map<int, std::set<sea_ir::InstructionNode*>*>::iterator crt_entry =
608 new_reaching.find(reaching_it->first);
609 if (new_reaching.end() != crt_entry) {
610 crt_entry->second->insert(reaching_it->second->begin(), reaching_it->second->end());
611 } else {
612 new_reaching.insert(
613 std::pair<int, std::set<sea_ir::InstructionNode*>*>(
614 reaching_it->first,
615 reaching_it->second) );
616 }
617 }
618 }
619 bool changed = false;
620 // Because the sets are monotonically increasing,
621 // we can compare sizes instead of using set comparison.
622 // TODO: Find formal proof.
623 int old_size = 0;
624 if (-1 == reaching_defs_size_) {
625 std::map<int, std::set<sea_ir::InstructionNode*>*>::iterator reaching_it = reaching_defs_.begin();
626 for (; reaching_it != reaching_defs_.end(); reaching_it++) {
627 old_size += (*reaching_it).second->size();
628 }
629 } else {
630 old_size = reaching_defs_size_;
631 }
632 int new_size = 0;
633 std::map<int, std::set<sea_ir::InstructionNode*>*>::iterator reaching_it = new_reaching.begin();
634 for (; reaching_it != new_reaching.end(); reaching_it++) {
635 new_size += (*reaching_it).second->size();
636 }
637 if (old_size != new_size) {
638 changed = true;
639 }
640 if (changed) {
641 reaching_defs_ = new_reaching;
642 reaching_defs_size_ = new_size;
643 }
644 return changed;
645}
646
Brian Carlstrom1db91132013-07-12 18:05:20 -0700647bool Region::InsertPhiFor(int reg_no) {
648 if (!ContainsPhiFor(reg_no)) {
649 phi_set_.insert(reg_no);
650 PhiInstructionNode* new_phi = new PhiInstructionNode(reg_no);
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700651 new_phi->SetRegion(this);
Brian Carlstrom1db91132013-07-12 18:05:20 -0700652 phi_instructions_.push_back(new_phi);
653 return true;
654 }
655 return false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700656}
657
Brian Carlstrom1db91132013-07-12 18:05:20 -0700658void Region::SetPhiDefinitionsForUses(
659 const utils::ScopedHashtable<int, InstructionNode*>* scoped_table, Region* predecessor) {
660 int predecessor_id = -1;
661 for (unsigned int crt_pred_id = 0; crt_pred_id < predecessors_.size(); crt_pred_id++) {
662 if (predecessors_.at(crt_pred_id) == predecessor) {
663 predecessor_id = crt_pred_id;
664 }
665 }
666 DCHECK_NE(-1, predecessor_id);
667 for (std::vector<PhiInstructionNode*>::iterator phi_it = phi_instructions_.begin();
668 phi_it != phi_instructions_.end(); phi_it++) {
669 PhiInstructionNode* phi = (*phi_it);
670 int reg_no = phi->GetRegisterNumber();
671 InstructionNode* definition = scoped_table->Lookup(reg_no);
672 phi->RenameToSSA(reg_no, definition, predecessor_id);
673 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700674}
675
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700676std::vector<InstructionNode*> InstructionNode::Create(const art::Instruction* in) {
677 std::vector<InstructionNode*> sea_instructions;
678 switch (in->Opcode()) {
679 case art::Instruction::CONST_4:
680 sea_instructions.push_back(new ConstInstructionNode(in));
681 break;
682 case art::Instruction::RETURN:
683 sea_instructions.push_back(new ReturnInstructionNode(in));
684 break;
685 case art::Instruction::IF_NE:
686 sea_instructions.push_back(new IfNeInstructionNode(in));
687 break;
688 case art::Instruction::ADD_INT_LIT8:
689 sea_instructions.push_back(new UnnamedConstInstructionNode(in, in->VRegB_22b()));
690 sea_instructions.push_back(new AddIntLitInstructionNode(in));
691 break;
692 case art::Instruction::MOVE_RESULT:
693 sea_instructions.push_back(new MoveResultInstructionNode(in));
694 break;
695 case art::Instruction::INVOKE_STATIC:
696 sea_instructions.push_back(new InvokeStaticInstructionNode(in));
697 break;
698 case art::Instruction::ADD_INT:
699 sea_instructions.push_back(new AddIntInstructionNode(in));
700 break;
701 case art::Instruction::GOTO:
702 sea_instructions.push_back(new GotoInstructionNode(in));
703 break;
704 case art::Instruction::IF_EQZ:
705 sea_instructions.push_back(new IfEqzInstructionNode(in));
706 break;
707 default:
708 // Default, generic IR instruction node; default case should never be reached
709 // when support for all instructions ahs been added.
710 sea_instructions.push_back(new InstructionNode(in));
711 }
712 return sea_instructions;
713}
714
Dragos Sbirlea6bee4452013-07-26 12:05:03 -0700715void InstructionNode::ToDot(std::string& result, const art::DexFile& dex_file) const {
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700716 result += "// Instruction ("+StringId()+"): \n" + StringId() +
Dragos Sbirlea6bee4452013-07-26 12:05:03 -0700717 " [label=\"" + instruction_->DumpString(&dex_file) + "\"";
Brian Carlstrom1db91132013-07-12 18:05:20 -0700718 if (de_def_) {
719 result += "style=bold";
720 }
721 result += "];\n";
722 // SSA definitions:
723 for (std::map<int, InstructionNode* >::const_iterator def_it = definition_edges_.begin();
724 def_it != definition_edges_.end(); def_it++) {
725 if (NULL != def_it->second) {
Dragos Sbirlea6bee4452013-07-26 12:05:03 -0700726 result += def_it->second->StringId() + " -> " + StringId() +"[color=gray,label=\"";
727 result += art::StringPrintf("vR = %d", def_it->first);
728 result += "\"] ; // ssa edge\n";
Brian Carlstrom1db91132013-07-12 18:05:20 -0700729 }
730 }
731}
732
733void InstructionNode::MarkAsDEDef() {
734 de_def_ = true;
735}
736
737int InstructionNode::GetResultRegister() const {
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700738 if (instruction_->HasVRegA() && InstructionTools::IsDefinition(instruction_)) {
Brian Carlstrom1db91132013-07-12 18:05:20 -0700739 return instruction_->VRegA();
740 }
741 return NO_REGISTER;
742}
743
744std::vector<int> InstructionNode::GetDefinitions() const {
745 // TODO: Extend this to handle instructions defining more than one register (if any)
746 // The return value should be changed to pointer to field then; for now it is an object
747 // so that we avoid possible memory leaks from allocating objects dynamically.
748 std::vector<int> definitions;
749 int result = GetResultRegister();
750 if (NO_REGISTER != result) {
751 definitions.push_back(result);
752 }
753 return definitions;
754}
755
756std::vector<int> InstructionNode::GetUses() {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700757 std::vector<int> uses; // Using vector<> instead of set<> because order matters.
Brian Carlstrom1db91132013-07-12 18:05:20 -0700758 if (!InstructionTools::IsDefinition(instruction_) && (instruction_->HasVRegA())) {
759 int vA = instruction_->VRegA();
760 uses.push_back(vA);
761 }
762 if (instruction_->HasVRegB()) {
763 int vB = instruction_->VRegB();
764 uses.push_back(vB);
765 }
766 if (instruction_->HasVRegC()) {
767 int vC = instruction_->VRegC();
768 uses.push_back(vC);
769 }
Brian Carlstrom1db91132013-07-12 18:05:20 -0700770 return uses;
771}
772
Dragos Sbirlea6bee4452013-07-26 12:05:03 -0700773void PhiInstructionNode::ToDot(std::string& result, const art::DexFile& dex_file) const {
Brian Carlstrom1db91132013-07-12 18:05:20 -0700774 result += "// PhiInstruction: \n" + StringId() +
775 " [label=\"" + "PHI(";
Dragos Sbirlea81f79a62013-07-23 14:31:47 -0700776 result += art::StringPrintf("%d", register_no_);
Brian Carlstrom1db91132013-07-12 18:05:20 -0700777 result += ")\"";
778 result += "];\n";
779
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700780 for (std::vector<std::vector<InstructionNode*>*>::const_iterator pred_it = definition_edges_.begin();
Brian Carlstrom1db91132013-07-12 18:05:20 -0700781 pred_it != definition_edges_.end(); pred_it++) {
Dragos Sbirlea0e260a32013-06-21 09:20:34 -0700782 std::vector<InstructionNode*>* defs_from_pred = *pred_it;
783 for (std::vector<InstructionNode* >::const_iterator def_it = defs_from_pred->begin();
Brian Carlstrom1db91132013-07-12 18:05:20 -0700784 def_it != defs_from_pred->end(); def_it++) {
Dragos Sbirlea6bee4452013-07-26 12:05:03 -0700785 result += (*def_it)->StringId() + " -> " + StringId() +"[color=gray,label=\"vR = ";
Dragos Sbirleadb063062013-07-23 16:29:09 -0700786 result += art::StringPrintf("%d", GetRegisterNumber());
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700787 result += "\"] ; // phi-ssa edge\n";
Brian Carlstrom1db91132013-07-12 18:05:20 -0700788 }
789 }
790}
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700791} // namespace sea_ir