• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "compiler_logger.h"
17 #include "optimizer/analysis/dominators_tree.h"
18 #include "optimizer/analysis/loop_analyzer.h"
19 #include "optimizer/analysis/linear_order.h"
20 #include "optimizer/ir/graph.h"
21 #include "optimizer/ir/graph_cloner.h"
22 
23 namespace panda::compiler {
GraphCloner(Graph * graph,ArenaAllocator * allocator,ArenaAllocator * local_allocator)24 GraphCloner::GraphCloner(Graph *graph, ArenaAllocator *allocator, ArenaAllocator *local_allocator)
25     : graph_(graph),
26       allocator_(allocator),
27       local_allocator_(local_allocator),
28       clone_blocks_(allocator->Adapter()),
29       clone_instructions_(allocator->Adapter())
30 {
31 }
32 
33 /**
34  * Clone the whole graph
35  */
CloneGraph()36 Graph *GraphCloner::CloneGraph()
37 {
38     auto new_graph =
39         allocator_->New<Graph>(allocator_, local_allocator_, GetGraph()->GetArch(), GetGraph()->GetMethod(),
40                                GetGraph()->GetRuntime(), GetGraph()->GetParentGraph(), GetGraph()->GetMode());
41     new_graph->SetCurrentInstructionId(GetGraph()->GetCurrentInstructionId());
42     CloneBlocksAndInstructions<InstCloneType::CLONE_ALL, false>(GetGraph()->GetVectorBlocks(), new_graph);
43     BuildControlFlow();
44     BuildDataFlow();
45     new_graph->GetPassManager()->SetCheckMode(GetGraph()->GetPassManager()->IsCheckMode());
46     // Clone all flags
47     new_graph->SetBitFields(GetGraph()->GetBitFields());
48     new_graph->InitUsedRegs<DataType::INT64>(GetGraph()->GetUsedRegs<DataType::INT64>());
49     new_graph->InitUsedRegs<DataType::FLOAT64>(GetGraph()->GetUsedRegs<DataType::FLOAT64>());
50 #ifndef NDEBUG
51     CloneAnalyses(new_graph);
52 #endif
53     return new_graph;
54 }
55 
CloneAnalyses(Graph * new_graph)56 void GraphCloner::CloneAnalyses(Graph *new_graph)
57 {
58     // Clone dominators if analysis is valid to check dom-tree
59     ASSERT(!new_graph->IsAnalysisValid<DominatorsTree>());
60     if (GetGraph()->IsAnalysisValid<DominatorsTree>()) {
61         new_graph->GetAnalysis<DominatorsTree>().SetValid(true);
62         for (auto block : GetGraph()->GetBlocksRPO()) {
63             auto clone = GetClone(block);
64             if (block->GetDominator() != nullptr) {
65                 auto clone_dom = GetClone(block->GetDominator());
66                 clone->SetDominator(clone_dom);
67             }
68             for (auto dom_blocks : block->GetDominatedBlocks()) {
69                 clone->AddDominatedBlock(GetClone(dom_blocks));
70             }
71         }
72     }
73 
74     // Clone loops if analysis is valid to check loop-tree
75     ASSERT(!new_graph->IsAnalysisValid<LoopAnalyzer>());
76     if (GetGraph()->IsAnalysisValid<LoopAnalyzer>()) {
77         auto &cloned_la = new_graph->GetAnalysis<LoopAnalyzer>();
78         cloned_la.SetValid(true);
79         cloned_la.CreateRootLoop();
80         CopyLoop(GetGraph()->GetRootLoop(), new_graph->GetRootLoop());
81         new_graph->SetHasIrreducibleLoop(GetGraph()->HasIrreducibleLoop());
82         new_graph->SetHasInfiniteLoop(GetGraph()->HasInfiniteLoop());
83     }
84 
85     ASSERT(!new_graph->IsAnalysisValid<LinearOrder>());
86     if (GetGraph()->IsAnalysisValid<LinearOrder>()) {
87         new_graph->GetAnalysis<LinearOrder>().SetValid(true);
88         CloneLinearOrder(new_graph);
89     }
90 }
91 
CopyLoop(Loop * loop,Loop * cloned_loop)92 void GraphCloner::CopyLoop(Loop *loop, Loop *cloned_loop)
93 {
94     if (!loop->IsRoot() && !loop->IsIrreducible() && !loop->IsTryCatchLoop()) {
95         ASSERT(GetClone(loop->GetHeader()) == cloned_loop->GetHeader());
96         cloned_loop->SetPreHeader(GetClone(loop->GetPreHeader()));
97     }
98     for (auto block : loop->GetBlocks()) {
99         if (block->IsLoopHeader()) {
100             continue;
101         }
102         cloned_loop->AppendBlock(GetClone(block));
103     }
104 
105     for (auto back_edge : loop->GetBackEdges()) {
106         cloned_loop->AppendBackEdge(GetClone(back_edge));
107     }
108     cloned_loop->SetIsIrreducible(loop->IsIrreducible());
109     cloned_loop->SetIsInfinite(loop->IsInfinite());
110 
111     // clone inner loops
112     for (const auto &inner_loop : loop->GetInnerLoops()) {
113         auto cloned_header = GetClone(inner_loop->GetHeader());
114         auto &cloned_la = cloned_header->GetGraph()->GetAnalysis<LoopAnalyzer>();
115         auto cloned_inner_loop = cloned_la.CreateNewLoop(cloned_header);
116         cloned_inner_loop->SetOuterLoop(cloned_loop);
117         cloned_loop->AppendInnerLoop(cloned_inner_loop);
118         CopyLoop(inner_loop, cloned_inner_loop);
119     }
120 }
121 
CloneLinearOrder(Graph * new_graph)122 void GraphCloner::CloneLinearOrder([[maybe_unused]] Graph *new_graph)
123 {
124     ASSERT(new_graph != nullptr);
125     ASSERT(GetGraph()->IsAnalysisValid<LinearOrder>());
126     auto &clone_linear_blocks = new_graph->GetAnalysis<LinearOrder>().GetBlocks();
127     clone_linear_blocks.reserve(GetGraph()->GetBlocksLinearOrder().size());
128     for (auto block : GetGraph()->GetBlocksLinearOrder()) {
129         clone_linear_blocks.push_back(GetClone(block));
130     }
131 }
132 
133 /**
134  * Clone the whole graph control-flow
135  */
BuildControlFlow()136 void GraphCloner::BuildControlFlow()
137 {
138     for (const auto &block : GetGraph()->GetVectorBlocks()) {
139         if (block == nullptr) {
140             continue;
141         }
142         CloneEdges<CloneEdgeType::EDGE_PRED>(block);
143         CloneEdges<CloneEdgeType::EDGE_SUCC>(block);
144     }
145 }
146 
147 /**
148  * Clone the whole graph data-flow
149  */
BuildDataFlow()150 void GraphCloner::BuildDataFlow()
151 {
152     for (const auto &block : GetGraph()->GetVectorBlocks()) {
153         if (block == nullptr) {
154             continue;
155         }
156         auto block_clone = GetClone(block);
157         for (const auto &inst : block->Insts()) {
158             SetCloneInputs<false>(inst);
159             GetClone(inst)->SetId(inst->GetId());
160             UpdateCaller(inst);
161         }
162         for (const auto &inst : block->PhiInsts()) {
163             auto phi = inst->CastToPhi();
164             auto inst_clone = GetClone(inst);
165             inst_clone->SetId(inst->GetId());
166             for (const auto &clone_pred_block : block_clone->GetPredsBlocks()) {
167                 auto it = std::find(clone_blocks_.begin(), clone_blocks_.end(), clone_pred_block);
168                 ASSERT(it != clone_blocks_.end());
169                 size_t index = std::distance(clone_blocks_.begin(), it);
170                 ASSERT(GetGraph()->GetVectorBlocks().size() > index);
171                 auto pred_block = GetGraph()->GetVectorBlocks()[index];
172                 inst_clone->AppendInput(GetClone(phi->GetPhiInput(pred_block)));
173             }
174         }
175     }
176 }
177 
178 /*
179  * Create resolver-block - common successor for all loop side-exits
180  */
CreateResolverBlock(Loop * loop,BasicBlock * back_edge)181 BasicBlock *GraphCloner::CreateResolverBlock(Loop *loop, BasicBlock *back_edge)
182 {
183     auto outside_succ = GetLoopOutsideSuccessor(loop);
184     auto resolver = back_edge->InsertNewBlockToSuccEdge(outside_succ);
185     back_edge->GetLoop()->GetOuterLoop()->AppendBlock(resolver);
186     // Populate resolver-block with phis for each instruction which has outside-loop user
187     for (auto block : loop->GetBlocks()) {
188         for (auto inst : block->AllInsts()) {
189             Inst *phi_resolver = nullptr;
190             auto user_it = inst->GetUsers().begin();
191             while (user_it != inst->GetUsers().end()) {
192                 auto user = user_it->GetInst();
193                 auto input_idx = user_it->GetIndex();
194                 ++user_it;
195                 ASSERT(user->GetBasicBlock() != nullptr);
196                 if (user->GetBasicBlock()->GetLoop() != loop) {
197                     if (phi_resolver == nullptr) {
198                         phi_resolver = GetGraph()->CreateInstPhi(inst->GetType(), inst->GetPc());
199                         phi_resolver->AppendInput(inst);
200                         resolver->AppendPhi(phi_resolver);
201                     }
202                     user->SetInput(input_idx, phi_resolver);
203                 }
204             }
205         }
206     }
207     return resolver;
208 }
209 
210 /*
211  * Split back-edge for cloning without side exits - in order not to clone `Compare` and `IfImm` instructions
212  */
SplitBackEdge(LoopUnrollData * unroll_data,Loop * loop,BasicBlock * back_edge)213 BasicBlock *GraphCloner::SplitBackEdge(LoopUnrollData *unroll_data, Loop *loop, BasicBlock *back_edge)
214 {
215     auto ifimm = back_edge->GetLastInst();
216     ASSERT(ifimm->GetOpcode() == Opcode::IfImm);
217     auto compare = ifimm->GetInput(0).GetInst();
218     ASSERT(compare->GetOpcode() == Opcode::Compare);
219     // If there are intructions between `Compare` and `IfImm`, clone `Compare` and insert before `IfImm`
220     if (ifimm->GetPrev() != compare) {
221         auto new_cmp = compare->Clone(compare->GetBasicBlock()->GetGraph());
222         new_cmp->SetInput(0, compare->GetInput(0).GetInst());
223         new_cmp->SetInput(1, compare->GetInput(1).GetInst());
224         ifimm->InsertBefore(new_cmp);
225         ifimm->SetInput(0, new_cmp);
226         compare = new_cmp;
227     }
228     if (compare->GetPrev() != nullptr) {
229         auto back_edge_split = back_edge->SplitBlockAfterInstruction(compare->GetPrev(), true);
230         loop->ReplaceBackEdge(back_edge, back_edge_split);
231         back_edge = back_edge_split;
232     } else {
233         ASSERT(back_edge->GetPredsBlocks().size() == 1);
234         auto it = std::find(unroll_data->blocks->begin(), unroll_data->blocks->end(), back_edge);
235         ASSERT(it != unroll_data->blocks->end());
236         unroll_data->blocks->erase(it);
237     }
238     [[maybe_unused]] static constexpr auto BACK_EDGE_INST_COUNT = 2;
239     ASSERT(std::distance(back_edge->AllInsts().begin(), back_edge->AllInsts().end()) == BACK_EDGE_INST_COUNT);
240     return back_edge;
241 }
242 
243 /**
244  *   - Split loop-header into two blocks, header phis will not be cloned:
245  *   [phi-insts]
246  *   -----------
247  *   [all-insts]
248  *
249  *  - If loop is cloing with side-exits create common successor for them;
250  *  - Otherwise split back-edge to cut `Compare` and `IfImm` instructions and not clone them;
251  */
PrepareLoopToUnroll(Loop * loop,bool clone_side_exits)252 GraphCloner::LoopUnrollData *GraphCloner::PrepareLoopToUnroll(Loop *loop, bool clone_side_exits)
253 {
254     ASSERT(loop != nullptr);
255     // Populate `LoopUnrollData`
256     auto allocator = loop->GetHeader()->GetGraph()->GetLocalAllocator();
257     auto unroll_data = allocator->New<LoopUnrollData>();
258     unroll_data->blocks = allocator->New<ArenaVector<BasicBlock *>>(allocator->Adapter());
259     unroll_data->blocks->resize(loop->GetBlocks().size());
260     std::copy(loop->GetBlocks().begin(), loop->GetBlocks().end(), unroll_data->blocks->begin());
261     // Split loop-header
262     ASSERT(loop->GetBackEdges().size() == 1U);
263     auto back_edge = loop->GetBackEdges()[0];
264     ASSERT(back_edge != nullptr);
265     auto header_block = loop->GetHeader();
266     ASSERT(!header_block->IsEmpty());
267     if (header_block->HasPhi()) {
268         auto last_phi = header_block->GetFirstInst()->GetPrev();
269         ASSERT(last_phi != nullptr && last_phi->IsPhi());
270         auto header_split = header_block->SplitBlockAfterInstruction(last_phi, true);
271         ASSERT(loop->GetBlocks().front() == header_block);
272         unroll_data->blocks->at(0) = header_split;
273 
274         if (back_edge == header_block) {
275             loop->ReplaceBackEdge(header_block, header_split);
276             back_edge = header_split;
277         }
278     }
279     unroll_data->exit_block = back_edge;
280     if (clone_side_exits) {
281         unroll_data->outer = CreateResolverBlock(loop, back_edge);
282     } else {
283         back_edge = SplitBackEdge(unroll_data, loop, back_edge);
284     }
285     // Save replaceable phi inputs
286 
287     unroll_data->phi_update_inputs = allocator->New<InstVector>(allocator->Adapter());
288     for (auto phi : header_block->PhiInsts()) {
289         unroll_data->phi_update_inputs->push_back(phi->CastToPhi()->GetPhiInput(back_edge));
290     }
291     unroll_data->header = header_block;
292     unroll_data->backedge = back_edge;
293     return unroll_data;
294 }
295 
296 /**
297  * Update data-flow after unrolling without side-exits
298  */
UpdateUsersAfterNoSideExitsUnroll(const LoopUnrollData * unroll_data)299 void GraphCloner::UpdateUsersAfterNoSideExitsUnroll(const LoopUnrollData *unroll_data)
300 {
301     auto loop = unroll_data->header->GetLoop();
302     // Update outloop users: replace inputs located in the original loop by theirs clones
303     auto compare = unroll_data->backedge->GetLastInst()->GetPrev();
304     ASSERT(compare->GetOpcode() == Opcode::Compare);
305     for (size_t i = 0; i < compare->GetInputsCount(); i++) {
306         auto input = compare->GetInput(i).GetInst();
307         if (HasClone(input)) {
308             compare->SetInput(i, GetClone(input));
309         }
310     }
311     // update outloop users
312     for (auto block : *unroll_data->blocks) {
313         for (auto inst : block->AllInsts()) {
314             auto user_it = inst->GetUsers().begin();
315             while (user_it != inst->GetUsers().end()) {
316                 auto user = user_it->GetInst();
317                 auto input_idx = user_it->GetIndex();
318                 ++user_it;
319                 ASSERT(user->GetBasicBlock() != nullptr);
320                 if (user->GetBasicBlock()->GetLoop() != loop) {
321                     user->SetInput(input_idx, GetClone(inst));
322                 }
323             }
324         }
325     }
326 
327     // All header-phi's outloop users are placed in the outer_bb after cloning the original loop
328     // So it's enough to to iterate outer_bb's phis and repalce header-phi by its backedge input
329     auto outer_idx = 1U - unroll_data->backedge->GetSuccBlockIndex(unroll_data->header);
330     auto outer_bb = unroll_data->backedge->GetSuccessor(outer_idx);
331     for (auto outer_phi : outer_bb->PhiInsts()) {
332         auto header_phi = outer_phi->CastToPhi()->GetPhiInput(unroll_data->backedge);
333         if (header_phi->IsPhi() && header_phi->GetBasicBlock() == unroll_data->header) {
334             outer_phi->ReplaceInput(header_phi, header_phi->CastToPhi()->GetPhiInput(unroll_data->backedge));
335         }
336     }
337 }
338 
339 /**
340  * Link cloned blocks with each other and insert them to the graph between the last-block and the output-block
341  *
342  * - No-side-exits case:
343  *  /---->[header]
344  *  |        |
345  *  |        v
346  *  |     [loop-body]   << last-block << exit-block
347  *  |        |
348  *  |        v
349  *  \-----[backedge]----> ...
350  *
351  *  New control-flow:
352  *  /---->[header]
353  *  |        |
354  *  |        v
355  *  |     [loop-body]   << exit-block
356  *  |        |
357  *  |        v
358  *  |     [loop-body-clone] << last-block
359  *  |        |
360  *  |        v
361  *  \-----[backedge]----> ...
362  *
363  *
364  *  Side-exits case:
365  *  /---->[header]
366  *  |        |
367  *  |        v
368  *  |     [loop-body]
369  *  |        |
370  *  |        v
371  *  \-----[backedge]    << last-block << exit-block
372  *           |
373  *           v
374  *        [outer]-----> ...
375  *
376  *  New control-flow:
377  *  /---->[header]
378  *  |         |
379  *  |         v
380  *  |     [loop-body]
381  *  |         |
382  *  |         v
383  *  |     [backedge]------------\   << exit-block
384  *  |         |                 |
385  *  |         v                 |
386  *  |    [loop-body-clone]      |
387  *  |         |                 |
388  *  |         v                 |
389  *  \-----[backedge-clone]----->|       << last-block
390  *                              |
391  *                              v
392  *                           [outer]-----> ...
393  */
BuildLoopUnrollControlFlow(LoopUnrollData * unroll_data)394 void GraphCloner::BuildLoopUnrollControlFlow(LoopUnrollData *unroll_data)
395 {
396     auto front_block = unroll_data->blocks->front();
397     auto loop = front_block->GetLoop();
398 
399     // Copy 'blocks' control-flow to the 'clones'
400     for (auto block : *unroll_data->blocks) {
401         ASSERT(block->GetLoop() == loop);
402         loop->AppendBlock(GetClone(block));
403 
404         if (block != front_block) {
405             CloneEdges<CloneEdgeType::EDGE_PRED>(block);
406         }
407         if (block != unroll_data->exit_block) {
408             CloneEdges<CloneEdgeType::EDGE_SUCC>(block);
409         }
410     }
411 
412     auto front_clone = GetClone(front_block);
413     auto exit_clone = GetClone(unroll_data->exit_block);
414     if (unroll_data->outer == nullptr) {
415         ASSERT(unroll_data->backedge->GetPredsBlocks().size() == 1);
416         auto last_block = unroll_data->backedge->GetPredsBlocks()[0];
417         last_block->ReplaceSucc(unroll_data->backedge, front_clone);
418         unroll_data->backedge->ReplacePred(last_block, exit_clone);
419     } else {
420         ASSERT(!unroll_data->outer->GetPredsBlocks().empty());
421         auto last_block = unroll_data->outer->GetPredsBlocks().back();
422         last_block->ReplaceSucc(unroll_data->header, front_clone);
423         unroll_data->header->ReplacePred(last_block, exit_clone);
424 
425         exit_clone->AddSucc(unroll_data->outer);
426         if (exit_clone->GetSuccBlockIndex(unroll_data->outer) != last_block->GetSuccBlockIndex(unroll_data->outer)) {
427             exit_clone->SwapTrueFalseSuccessors();
428         }
429         auto new_backedge = GetClone(unroll_data->exit_block);
430         loop->ReplaceBackEdge(unroll_data->backedge, new_backedge);
431         unroll_data->backedge = new_backedge;
432     }
433 }
434 
435 /**
436  * Construct dataflow for the cloned instructions
437  * if input of the original instruction is front-block phi - insert replaceable input of this phi
438  */
BuildLoopUnrollDataFlow(LoopUnrollData * unroll_data)439 void GraphCloner::BuildLoopUnrollDataFlow(LoopUnrollData *unroll_data)
440 {
441     for (auto block : *unroll_data->blocks) {
442         for (auto inst : block->AllInsts()) {
443             if (inst->IsMarked(clone_marker_)) {
444                 SetCloneInputs<true>(inst, unroll_data->backedge);
445                 UpdateCaller(inst);
446             }
447         }
448     }
449 
450     // Append input to the phi-resolver from outer block, it holds all instructions which have outside loop users
451     auto loop = unroll_data->blocks->front()->GetLoop();
452     if (unroll_data->outer != nullptr) {
453         for (auto phi : unroll_data->outer->PhiInsts()) {
454             auto inst = phi->GetInput(0).GetInst();
455             if (IsInstLoopHeaderPhi(inst, loop)) {
456                 auto update = inst->CastToPhi()->GetPhiInput(unroll_data->backedge);
457                 phi->AppendInput(update);
458             } else {
459                 phi->AppendInput(GetClone(inst));
460             }
461         }
462     }
463 
464     // TODO (a.popov) use temp container after if would be possible to reset local allocator
465     if (unroll_data->phi_replaced_inputs == nullptr) {
466         unroll_data->phi_replaced_inputs = allocator_->New<PhiInputsMap>(allocator_->Adapter());
467     } else {
468         unroll_data->phi_replaced_inputs->clear();
469     }
470 
471     // Set new update inputs for header phis
472     size_t phi_count = 0;
473     for (auto phi : loop->GetHeader()->PhiInsts()) {
474         auto input = unroll_data->phi_update_inputs->at(phi_count);
475         if (HasClone(input)) {
476             input = GetClone(input);
477         } else if (input->IsPhi() && input->GetBasicBlock()->GetLoop() == loop) {
478             if (phi->IsDominate(input)) {
479                 input = input->CastToPhi()->GetPhiInput(unroll_data->backedge);
480             } else {
481                 // phi should be visited and its input should be added to the map
482                 ASSERT(unroll_data->phi_replaced_inputs->count(input) == 1);
483                 input = unroll_data->phi_replaced_inputs->at(input);
484             }
485         }
486 
487         auto phi_update_input_idx = phi->CastToPhi()->GetPredBlockIndex(unroll_data->backedge);
488         unroll_data->phi_replaced_inputs->emplace(phi, phi->GetInput(phi_update_input_idx).GetInst());
489         phi->SetInput(phi_update_input_idx, input);
490         phi_count++;
491     }
492 }
493 
RemoveLoopBackEdge(const LoopUnrollData * unroll_data)494 void GraphCloner::RemoveLoopBackEdge(const LoopUnrollData *unroll_data)
495 {
496     ASSERT(unroll_data->outer != nullptr);
497     ASSERT(!unroll_data->outer->GetPredsBlocks().empty());
498     auto last_block = unroll_data->outer->GetPredsBlocks().back();
499     // Erase control-flow instruction
500     auto ifimm = last_block->GetLastInst();
501     ASSERT(ifimm->GetOpcode() == Opcode::IfImm);
502     last_block->RemoveInst(ifimm);
503     // Remove back-edge
504     auto header = unroll_data->header;
505     // Clear header block, it should only contain phi
506     ASSERT(header->GetFirstInst() == nullptr);
507     for (auto phi : header->PhiInstsSafe()) {
508         auto remaining_inst = phi->CastToPhi()->GetPhiInput(header->GetLoop()->GetPreHeader());
509         phi->ReplaceUsers(remaining_inst);
510         header->RemoveInst(phi);
511     }
512 
513     last_block->RemoveSucc(header);
514     header->RemovePred(last_block);
515 
516     // Clear outer phis if it has single predecessor
517     if (unroll_data->outer->GetPredsBlocks().size() == 1U) {
518         for (auto phi : unroll_data->outer->PhiInstsSafe()) {
519             auto remaining_inst = phi->GetInput(0).GetInst();
520             phi->ReplaceUsers(remaining_inst);
521             unroll_data->outer->RemoveInst(phi);
522         }
523     }
524 }
525 
BuildClonedLoopHeaderDataFlow(const BasicBlock & block,BasicBlock * resolver,BasicBlock * clone)526 void GraphCloner::BuildClonedLoopHeaderDataFlow(const BasicBlock &block, BasicBlock *resolver, BasicBlock *clone)
527 {
528     for (auto inst : block.Insts()) {
529         if (inst->IsMarked(clone_marker_)) {
530             SetCloneInputs<true>(inst, clone);
531             UpdateUsersForClonedLoopHeader(inst, resolver);
532             UpdateCaller(inst);
533         }
534     }
535     for (auto phi : block.PhiInsts()) {
536         ASSERT(phi->GetInputsCount() == 2U);
537         auto preloop_input = phi->CastToPhi()->GetPhiInput(clone);
538         // Create phi instruction in the `resolver` block with two inputs: current phi and phi's preloop_input
539         auto resolver_phi = GetGraph()->CreateInstPhi(phi->GetType(), phi->GetPc());
540         for (auto user_it = phi->GetUsers().begin(); user_it != phi->GetUsers().end();) {
541             auto user = user_it->GetInst();
542             auto input_index = user_it->GetIndex();
543             ++user_it;
544             ASSERT(user->GetBasicBlock() != nullptr);
545             if (user->GetBasicBlock()->GetLoop() != block.GetLoop()) {
546                 user->SetInput(input_index, resolver_phi);
547             }
548         }
549         if (resolver_phi->HasUsers()) {
550             resolver_phi->AppendInput(phi);
551             resolver_phi->AppendInput(preloop_input);
552             resolver->AppendPhi(resolver_phi);
553         }
554     }
555 }
556 
557 /**
558  *  Used by Loop peeling to clone loop-header and insert this clone before loop-header.
559  *  Created block-resolved - common succesor for loop-header and its clone
560  *
561  *      [replaceable_pred]
562  *              |
563  *              v
564  *   ... --->[block]--------\
565  *              |           |
566  *              v           v
567  *             ...       [outer]
568  *
569  *
570  *      [replaceable_pred]
571  *              |
572  *              v
573  *        [clone_block]---------\
574  *              |               |
575  *              v               |
576  *   ... --->[block]--------\   |
577  *              |           |   |
578  *              v           v   v
579  *             ...        [resolver]
580  *                            |
581  *                            v
582  *                          [outer]
583  */
CloneLoopHeader(BasicBlock * block,BasicBlock * outer,BasicBlock * replaceable_pred)584 BasicBlock *GraphCloner::CloneLoopHeader(BasicBlock *block, BasicBlock *outer, BasicBlock *replaceable_pred)
585 {
586     ASSERT(GetGraph()->IsAnalysisValid<DominatorsTree>());
587     ASSERT(clone_marker_ == UNDEF_MARKER);
588     auto marker_holder = MarkerHolder(GetGraph());
589     clone_marker_ = marker_holder.GetMarker();
590     clone_instructions_.clear();
591     size_t inst_count = 0;
592     // Build control-flow
593     auto resolver = block->InsertNewBlockToSuccEdge(outer);
594     outer->GetLoop()->AppendBlock(resolver);
595     if (outer->GetLoop()->HasBackEdge(block)) {
596         outer->GetLoop()->ReplaceBackEdge(block, resolver);
597     }
598     auto clone_block = replaceable_pred->InsertNewBlockToSuccEdge(block);
599     ASSERT(block->GetLoop()->GetPreHeader() == replaceable_pred);
600     block->GetLoop()->SetPreHeader(clone_block);
601     replaceable_pred->GetLoop()->AppendBlock(clone_block);
602     clone_block->AddSucc(resolver);
603     // Check the order of true-false successors
604     if (clone_block->GetSuccBlockIndex(resolver) != block->GetSuccBlockIndex(resolver)) {
605         clone_block->SwapTrueFalseSuccessors();
606     }
607     // Fix Dominators info
608     auto &dom_tree = GetGraph()->GetAnalysis<DominatorsTree>();
609     dom_tree.SetValid(true);
610     ASSERT(block->GetDominator() == replaceable_pred);
611     replaceable_pred->RemoveDominatedBlock(block);
612     dom_tree.SetDomPair(clone_block, block);
613     dom_tree.SetDomPair(replaceable_pred, clone_block);
614     dom_tree.SetDomPair(clone_block, resolver);
615     if (outer->GetDominator() == block) {
616         block->RemoveDominatedBlock(outer);
617         dom_tree.SetDomPair(resolver, outer);
618     }
619     CloneInstructions<InstCloneType::CLONE_INSTS, true>(block, clone_block, &inst_count);
620     BuildClonedLoopHeaderDataFlow(*block, resolver, clone_block);
621     clone_block->SetAllFields(block->GetAllFields());
622     return clone_block;
623 }
624 
625 /**
626  * Use the following logic cloning the users:
627  * - replace inputs of all users, placed OUTSIDE cloneable loop, by the new `phi_out` instruction
628  * - `phi_out` is appended to the outer-block
629  * - replace inputs of all users, placed INSIDE cloneable loop, but not cloned, by the new `phi_in` instruction
630  * - `phi_in` is appended to the `inst` basic block
631  * - `phi_in\phi_out` have `inst` and its clone as inputs
632  */
UpdateUsersForClonedLoopHeader(Inst * inst,BasicBlock * outer_block)633 void GraphCloner::UpdateUsersForClonedLoopHeader(Inst *inst, BasicBlock *outer_block)
634 {
635     if (!inst->HasUsers()) {
636         return;
637     }
638     auto inst_block = inst->GetBasicBlock();
639     auto clone = GetClone(inst);
640     auto clone_block = clone->GetBasicBlock();
641     ASSERT(clone_block != nullptr);
642     // phi for inside users
643     auto phi_in = GetGraph()->CreateInstPhi(inst->GetType(), inst->GetPc());
644     // phi for outside users
645     auto phi_out = GetGraph()->CreateInstPhi(inst->GetType(), inst->GetPc());
646     auto user_it = inst->GetUsers().begin();
647     while (user_it != inst->GetUsers().end()) {
648         auto user = user_it->GetInst();
649         auto input_idx = user_it->GetIndex();
650         ++user_it;
651         ASSERT(user->GetBasicBlock() != nullptr);
652         if (user->GetBasicBlock()->GetLoop() == inst_block->GetLoop()) {
653             // user inside loop
654             // skip users that will be moved to the loop-exit block
655             if (user->GetBasicBlock()->IsLoopHeader() && !user->IsPhi()) {
656                 continue;
657             }
658             ASSERT(user->GetBasicBlock() != inst_block || user->IsPhi());
659             user->SetInput(input_idx, phi_in);
660         } else {
661             // user outside loop
662             user->SetInput(input_idx, phi_out);
663         }
664     }
665 
666     if (phi_in->HasUsers()) {
667         auto clone_index {inst_block->GetPredBlockIndex(clone_block)};
668         phi_in->AppendInput(clone);
669         phi_in->AppendInput(inst);
670         phi_in->CastToPhi()->SetPhiInputBbNum(0, clone_index);
671         phi_in->CastToPhi()->SetPhiInputBbNum(1, 1 - clone_index);
672 
673         auto first_phi = inst_block->GetFirstPhi();
674         if (first_phi == nullptr) {
675             inst_block->AppendPhi(phi_in);
676         } else {
677             inst_block->InsertBefore(phi_in, first_phi);
678         }
679     }
680 
681     if (phi_out->HasUsers()) {
682         phi_out->AppendInput(inst);
683         phi_out->AppendInput(clone);
684         outer_block->AppendPhi(phi_out);
685     }
686 }
687 
IsInstLoopHeaderPhi(Inst * inst,Loop * loop)688 inline bool GraphCloner::IsInstLoopHeaderPhi(Inst *inst, Loop *loop)
689 {
690     return inst->IsPhi() && inst->GetBasicBlock() == loop->GetHeader();
691 }
692 
693 /**
694  * Create clone of loop and insert it after original loop:
695  *
696  *      /----[pre-loop]
697  *      |        |
698  *      |        v
699  *      |    [loop-body]<----\
700  *      |        |   |       |
701  *      |        |   \-------/
702  *      |        |
703  *      |        v
704  *      \--->[outside-block]
705  *               |
706  *               v
707  *      /----[pre-loop']
708  *      |        |
709  *      |        v
710  *      |    [loop-body']<----\
711  *      |        |   |       |
712  *      |        |   \-------/
713  *      |        |
714  *      |        v
715  *      \--->[outside-block']
716  */
CloneLoop(Loop * loop)717 Loop *GraphCloner::CloneLoop(Loop *loop)
718 {
719     ASSERT(loop != nullptr && !loop->IsRoot());
720     ASSERT_PRINT(IsLoopSingleBackEdgeExitPoint(loop), "Cloning blocks doesn't have single entry/exit point");
721     ASSERT(loop->GetPreHeader() != nullptr);
722     ASSERT(clone_marker_ == UNDEF_MARKER);
723 
724     auto marker_holder = MarkerHolder(GetGraph());
725     clone_marker_ = marker_holder.GetMarker();
726     auto unroll_data = PrepareLoopToClone(loop);
727 
728     CloneBlocksAndInstructions<InstCloneType::CLONE_ALL, true>(*unroll_data->blocks, GetGraph());
729     BuildLoopCloneControlFlow(unroll_data);
730     BuildLoopCloneDataFlow(unroll_data);
731     MakeLoopCloneInfo(unroll_data);
732     GetGraph()->RunPass<DominatorsTree>();
733 
734     auto clone_loop = GetClone(loop->GetHeader())->GetLoop();
735     ASSERT(clone_loop != loop && clone_loop->GetOuterLoop() == loop->GetOuterLoop());
736     COMPILER_LOG(DEBUG, GRAPH_CLONER) << "Loop " << loop->GetId() << " is copied";
737     COMPILER_LOG(DEBUG, GRAPH_CLONER) << "Created new loop, id = " << clone_loop->GetId();
738     return clone_loop;
739 }
740 
CreateNewOutsideSucc(BasicBlock * outside_succ,BasicBlock * back_edge,BasicBlock * pre_header)741 BasicBlock *GraphCloner::CreateNewOutsideSucc(BasicBlock *outside_succ, BasicBlock *back_edge, BasicBlock *pre_header)
742 {
743     auto back_edge_idx = outside_succ->GetPredBlockIndex(back_edge);
744     auto pre_header_idx = outside_succ->GetPredBlockIndex(pre_header);
745     auto rm_idx_max = std::max(back_edge_idx, pre_header_idx);
746     auto rm_idx_min = std::min(back_edge_idx, pre_header_idx);
747     auto new_outside_succ = GetGraph()->CreateEmptyBlock();
748     outside_succ->GetLoop()->AppendBlock(new_outside_succ);
749     back_edge->ReplaceSucc(outside_succ, new_outside_succ);
750     pre_header->ReplaceSucc(outside_succ, new_outside_succ);
751     new_outside_succ->AddSucc(outside_succ);
752     for (auto phi : outside_succ->PhiInsts()) {
753         auto new_phi = GetGraph()->CreateInstPhi(phi->GetType(), phi->GetPc());
754         new_phi->AppendInput(phi->CastToPhi()->GetPhiInput(back_edge));
755         new_phi->AppendInput(phi->CastToPhi()->GetPhiInput(pre_header));
756         phi->AppendInput(new_phi);
757         auto phi_back_edge_idx {phi->CastToPhi()->GetPredBlockIndex(back_edge)};
758         auto phi_pre_header_idx {phi->CastToPhi()->GetPredBlockIndex(pre_header)};
759         phi->RemoveInput(rm_idx_max == back_edge_idx ? phi_back_edge_idx : phi_pre_header_idx);
760         phi->RemoveInput(rm_idx_min == pre_header_idx ? phi_pre_header_idx : phi_back_edge_idx);
761         new_outside_succ->AppendPhi(new_phi);
762     }
763     outside_succ->RemovePred(rm_idx_max);
764     outside_succ->RemovePred(rm_idx_min);
765 
766     COMPILER_LOG(DEBUG, GRAPH_CLONER) << "New loop outside block created: " << new_outside_succ->GetId();
767     return new_outside_succ;
768 }
769 
770 /**
771  * - Split pre-header to contain `Compare` and `IfImm` instructions only;
772  * - Make sure `outside_succ` has 2 predecessors only: loop header and back-edge;
773  * - Split `outside_succ` to contain phi-instructions only;
774  */
PrepareLoopToClone(Loop * loop)775 GraphCloner::LoopClonerData *GraphCloner::PrepareLoopToClone(Loop *loop)
776 {
777     auto pre_header = loop->GetPreHeader();
778     auto ifimm = pre_header->GetLastInst();
779     ASSERT(ifimm->GetOpcode() == Opcode::IfImm);
780     auto compare = ifimm->GetInput(0).GetInst();
781     ASSERT(compare->GetOpcode() == Opcode::Compare);
782     if (ifimm->GetPrev() != compare) {
783         auto new_cmp = compare->Clone(compare->GetBasicBlock()->GetGraph());
784         new_cmp->SetInput(0, compare->GetInput(0).GetInst());
785         new_cmp->SetInput(1, compare->GetInput(1).GetInst());
786         ifimm->InsertBefore(new_cmp);
787         ifimm->SetInput(0, new_cmp);
788         compare = new_cmp;
789     }
790     if (compare->GetPrev() != nullptr) {
791         auto new_pre_header = pre_header->SplitBlockAfterInstruction(compare->GetPrev(), true);
792         loop->SetPreHeader(new_pre_header);
793         pre_header = new_pre_header;
794     }
795     [[maybe_unused]] static constexpr auto PRE_HEADER_INST_COUNT = 2;
796     ASSERT(std::distance(pre_header->AllInsts().begin(), pre_header->AllInsts().end()) == PRE_HEADER_INST_COUNT);
797     // If `outside_succ` has more than 2 predecessors, create a new one
798     // with loop header and back-edge predecessors only and insert it before `outside_succ`
799     auto outside_succ = GetLoopOutsideSuccessor(loop);
800     constexpr auto PREDS_NUM = 2;
801     if (outside_succ->GetPredsBlocks().size() > PREDS_NUM) {
802         auto back_edge = loop->GetBackEdges()[0];
803         outside_succ = CreateNewOutsideSucc(outside_succ, back_edge, pre_header);
804     }
805     // Split outside succ after last phi
806     // create empty block before outside succ if outside succ don't contain phi insts
807     if (outside_succ->HasPhi() && outside_succ->GetFirstInst() != nullptr) {
808         auto last_phi = outside_succ->GetFirstInst()->GetPrev();
809         auto block = outside_succ->SplitBlockAfterInstruction(last_phi, true);
810         // if `outside_succ` is pre-header replace it by `block`
811         for (auto in_loop : loop->GetOuterLoop()->GetInnerLoops()) {
812             if (in_loop->GetPreHeader() == outside_succ) {
813                 in_loop->SetPreHeader(block);
814             }
815         }
816     } else if (outside_succ->GetFirstInst() != nullptr) {
817         auto block = outside_succ->InsertEmptyBlockBefore();
818         outside_succ->GetLoop()->AppendBlock(block);
819         outside_succ = block;
820     }
821     // Populate `LoopClonerData`
822     auto allocator = GetGraph()->GetLocalAllocator();
823     auto unroll_data = allocator->New<LoopClonerData>();
824     unroll_data->blocks = allocator->New<ArenaVector<BasicBlock *>>(allocator->Adapter());
825     unroll_data->blocks->resize(loop->GetBlocks().size() + 1);
826     unroll_data->blocks->at(0) = pre_header;
827     std::copy(loop->GetBlocks().begin(), loop->GetBlocks().end(), unroll_data->blocks->begin() + 1);
828     unroll_data->blocks->push_back(outside_succ);
829     unroll_data->outer = outside_succ;
830     unroll_data->header = loop->GetHeader();
831     unroll_data->pre_header = loop->GetPreHeader();
832     return unroll_data;
833 }
834 
835 /**
836  * Create new loop, populate it with cloned blocks and build conrlow-flow
837  */
BuildLoopCloneControlFlow(LoopClonerData * unroll_data)838 void GraphCloner::BuildLoopCloneControlFlow(LoopClonerData *unroll_data)
839 {
840     ASSERT(unroll_data != nullptr);
841     auto outer_clone = GetClone(unroll_data->outer);
842     auto pre_header_clone = GetClone(unroll_data->pre_header);
843 
844     while (!unroll_data->outer->GetSuccsBlocks().empty()) {
845         auto succ = unroll_data->outer->GetSuccsBlocks().front();
846         succ->ReplacePred(unroll_data->outer, outer_clone);
847         unroll_data->outer->RemoveSucc(succ);
848     }
849     unroll_data->outer->AddSucc(pre_header_clone);
850 
851     for (auto &block : *unroll_data->blocks) {
852         if (block != unroll_data->pre_header) {
853             CloneEdges<CloneEdgeType::EDGE_PRED>(block);
854         }
855         if (block != unroll_data->outer) {
856             CloneEdges<CloneEdgeType::EDGE_SUCC>(block);
857         }
858     }
859     ASSERT(unroll_data->outer->GetPredBlockIndex(unroll_data->pre_header) ==
860            outer_clone->GetPredBlockIndex(pre_header_clone));
861     ASSERT(unroll_data->header->GetPredBlockIndex(unroll_data->pre_header) ==
862            GetClone(unroll_data->header)->GetPredBlockIndex(pre_header_clone));
863 }
864 
865 /**
866  * Insert cloned loop into loop-tree and populated with cloned blocks
867  */
MakeLoopCloneInfo(LoopClonerData * unroll_data)868 void GraphCloner::MakeLoopCloneInfo(LoopClonerData *unroll_data)
869 {
870     ASSERT(unroll_data != nullptr);
871     // Update loop tree
872     auto loop = unroll_data->header->GetLoop();
873     auto header_clone = GetClone(loop->GetHeader());
874     auto clone_loop = GetGraph()->GetAnalysis<LoopAnalyzer>().CreateNewLoop(header_clone);
875     auto outer_loop = loop->GetOuterLoop();
876     outer_loop->AppendInnerLoop(clone_loop);
877     clone_loop->SetOuterLoop(outer_loop);
878 
879     // Populate cloned loop
880     auto pre_loop_clone = GetClone(unroll_data->pre_header);
881     auto outside_succ_clone = GetClone(unroll_data->outer);
882     clone_loop->SetPreHeader(pre_loop_clone);
883     outer_loop->AppendBlock(pre_loop_clone);
884     outer_loop->AppendBlock(outside_succ_clone);
885     for (auto &block : loop->GetBlocks()) {
886         if (!block->IsLoopHeader()) {
887             clone_loop->AppendBlock(GetClone(block));
888         }
889     }
890     for (auto back_edge : loop->GetBackEdges()) {
891         clone_loop->AppendBackEdge(GetClone(back_edge));
892     }
893 }
894 
895 /**
896  * Find or create phi in the outside_succ block with the same inputs as `check_phi`
897  */
GetPhiResolver(Inst * check_phi,BasicBlock * outside_succ,BasicBlock * pre_header)898 Inst *GetPhiResolver(Inst *check_phi, BasicBlock *outside_succ, BasicBlock *pre_header)
899 {
900     [[maybe_unused]] constexpr auto MAX_PREDS_NUM = 2;
901     ASSERT(outside_succ->GetPredsBlocks().size() == MAX_PREDS_NUM);
902     ASSERT(check_phi->GetBasicBlock()->IsLoopHeader());
903     auto init_idx = check_phi->CastToPhi()->GetPredBlockIndex(pre_header);
904     auto init_input = check_phi->GetInput(init_idx).GetInst();
905     auto update_input = check_phi->GetInput(1 - init_idx).GetInst();
906 
907     for (auto phi : outside_succ->PhiInsts()) {
908         auto idx {phi->CastToPhi()->GetPredBlockIndex(pre_header)};
909         if (phi->GetInput(idx).GetInst() == init_input && phi->GetInput(1 - idx).GetInst() == update_input) {
910             return phi;
911         }
912     }
913 
914     auto phi_resolver = outside_succ->GetGraph()->CreateInstPhi(check_phi->GetType(), check_phi->GetPc());
915     auto out_init_idx = outside_succ->GetPredBlockIndex(pre_header);
916     phi_resolver->AppendInput(init_input);
917     phi_resolver->AppendInput(update_input);
918     phi_resolver->SetPhiInputBbNum(0, out_init_idx);
919     phi_resolver->SetPhiInputBbNum(1, 1 - out_init_idx);
920 
921     outside_succ->AppendPhi(phi_resolver);
922     return phi_resolver;
923 }
924 
925 /**
926  * Build data-flow for cloned instructions
927  */
BuildLoopCloneDataFlow(LoopClonerData * unroll_data)928 void GraphCloner::BuildLoopCloneDataFlow(LoopClonerData *unroll_data)
929 {
930     ASSERT(unroll_data != nullptr);
931     for (const auto &block : *unroll_data->blocks) {
932         for (const auto &inst : block->AllInsts()) {
933             if (inst->IsMarked(clone_marker_)) {
934                 SetCloneInputs<false>(inst);
935                 UpdateCaller(inst);
936             }
937         }
938     }
939 
940     auto pre_loop_clone = GetClone(unroll_data->pre_header);
941     for (auto phi : unroll_data->outer->PhiInsts()) {
942         auto phi_clone = GetClone(phi);
943         phi->ReplaceUsers(phi_clone);
944         auto idx = phi_clone->CastToPhi()->GetPredBlockIndex(pre_loop_clone);
945         phi_clone->SetInput(idx, phi);
946     }
947 
948     auto compare = pre_loop_clone->GetFirstInst();
949     auto exit_block = unroll_data->outer->GetPredBlockByIndex(0);
950     if (exit_block == unroll_data->pre_header) {
951         exit_block = unroll_data->outer->GetPredBlockByIndex(1);
952     } else {
953         ASSERT(unroll_data->outer->GetPredBlockByIndex(1) == unroll_data->pre_header);
954     }
955     auto back_edge_compare = exit_block->GetLastInst()->GetInput(0).GetInst();
956     ASSERT(compare->GetOpcode() == Opcode::Compare);
957     ASSERT(back_edge_compare->GetOpcode() == Opcode::Compare);
958     for (auto phi : unroll_data->header->PhiInsts()) {
959         auto init_idx = phi->CastToPhi()->GetPredBlockIndex(unroll_data->pre_header);
960         ASSERT(GetClone(phi)->CastToPhi()->GetPredBlockIndex(pre_loop_clone) == init_idx);
961 
962         auto init = phi->GetInput(init_idx).GetInst();
963         auto update = phi->GetInput(1 - init_idx).GetInst();
964         auto resolver_phi = GetPhiResolver(phi, unroll_data->outer, unroll_data->pre_header);
965         auto clone_phi = GetClone(phi);
966         ASSERT(clone_phi->GetInput(init_idx).GetInst() == init);
967         clone_phi->SetInput(init_idx, resolver_phi);
968         for (size_t i = 0; i < compare->GetInputsCount(); i++) {
969             if (compare->GetInput(i).GetInst() == init && back_edge_compare->GetInput(i).GetInst() == update) {
970                 compare->SetInput(i, resolver_phi);
971                 break;
972             }
973         }
974     }
975 }
976 
UpdateCaller(Inst * inst)977 void GraphCloner::UpdateCaller(Inst *inst)
978 {
979 }
980 
IsLoopClonable(Loop * loop,size_t inst_limit)981 bool GraphCloner::IsLoopClonable(Loop *loop, size_t inst_limit)
982 {
983     // TODO(schernykh) : implement case when we have inner loops
984     if (!loop->GetOuterLoop()->IsRoot() || !loop->GetInnerLoops().empty() || !IsLoopSingleBackEdgeExitPoint(loop)) {
985         return false;
986     }
987 
988     auto pre_header = loop->GetPreHeader();
989     auto ifimm = pre_header->GetLastInst();
990     ASSERT(ifimm->GetOpcode() == Opcode::IfImm);
991     auto compare = ifimm->GetInput(0).GetInst();
992     ASSERT(compare->GetOpcode() == Opcode::Compare);
993     // TODO(schernykh) : Implement case when compare is not before of ifimm
994     if (ifimm->GetPrev() != compare) {
995         return false;
996     }
997 
998     // Count instructions for copy
999     // in pre header copied compare + ifimm inst
1000     uint32_t inst_count = 1;
1001     for (const auto &block : loop->GetBlocks()) {
1002         inst_count += std::distance(block->AllInsts().begin(), block->AllInsts().end());
1003         if (inst_count > inst_limit) {
1004             return false;
1005         }
1006     }
1007     for ([[maybe_unused]] auto phi : GetLoopOutsideSuccessor(loop)->PhiInsts()) {
1008         inst_count++;
1009     }
1010     return (inst_count <= inst_limit);
1011 }
1012 }  // namespace panda::compiler
1013