• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2023 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 "optimizer/ir/inst.h"
17 #include "optimizer/ir/basicblock.h"
18 #include "optimizer/ir/graph.h"
19 #include "liveness_analyzer.h"
20 #include "optimizer/analysis/dominators_tree.h"
21 #include "optimizer/analysis/loop_analyzer.h"
22 #include "optimizer/optimizations/locations_builder.h"
23 #include "optimizer/optimizations/regalloc/reg_type.h"
24 
25 namespace panda::compiler {
LivenessAnalyzer(Graph * graph)26 LivenessAnalyzer::LivenessAnalyzer(Graph *graph)
27     : Analysis(graph),
28       allocator_(graph->GetAllocator()),
29       linearBlocks_(graph->GetAllocator()->Adapter()),
30       instLifeNumbers_(graph->GetAllocator()->Adapter()),
31       instLifeIntervals_(graph->GetAllocator()->Adapter()),
32       instsByLifeNumber_(graph->GetAllocator()->Adapter()),
33       blockLiveRanges_(graph->GetAllocator()->Adapter()),
34       blockLiveSets_(graph->GetLocalAllocator()->Adapter()),
35       pendingCatchPhiInputs_(graph->GetAllocator()->Adapter()),
36       physicalGeneralIntervals_(graph->GetAllocator()->Adapter()),
37       physicalVectorIntervals_(graph->GetAllocator()->Adapter()),
38       intervalsForTemps_(graph->GetAllocator()->Adapter()),
39       useTable_(graph->GetAllocator()),
40       hasSafepointDuringCall_(graph->GetRuntime()->HasSafepointDuringCall())
41 {
42 }
43 
RunImpl()44 bool LivenessAnalyzer::RunImpl()
45 {
46     if (!RunLocationsBuilder(GetGraph())) {
47         return false;
48     }
49     GetGraph()->RunPass<DominatorsTree>();
50     GetGraph()->RunPass<LoopAnalyzer>();
51     ResetLiveness();
52     BuildBlocksLinearOrder();
53     BuildInstLifeNumbers();
54     BuildInstLifeIntervals();
55     Finalize();
56     if (!pendingCatchPhiInputs_.empty()) {
57         COMPILER_LOG(ERROR, LIVENESS_ANALYZER)
58             << "Graph contains CatchPhi instructions whose inputs were not processed";
59         return false;
60     }
61     std::copy_if(physicalGeneralIntervals_.begin(), physicalGeneralIntervals_.end(),
62                  std::back_inserter(instLifeIntervals_), [](auto li) { return li != nullptr; });
63     std::copy_if(physicalVectorIntervals_.begin(), physicalVectorIntervals_.end(),
64                  std::back_inserter(instLifeIntervals_), [](auto li) { return li != nullptr; });
65     std::copy(intervalsForTemps_.begin(), intervalsForTemps_.end(), std::back_inserter(instLifeIntervals_));
66     COMPILER_LOG(DEBUG, LIVENESS_ANALYZER) << "Liveness analysis is constructed";
67     return true;
68 }
69 
ResetLiveness()70 void LivenessAnalyzer::ResetLiveness()
71 {
72     instLifeNumbers_.clear();
73     instLifeIntervals_.clear();
74     blockLiveSets_.clear();
75     blockLiveRanges_.clear();
76     physicalGeneralIntervals_.clear();
77     physicalVectorIntervals_.clear();
78     intervalsForTemps_.clear();
79     if (GetGraph()->GetArch() != Arch::NONE) {
80         physicalGeneralIntervals_.resize(REGISTERS_NUM);
81         physicalVectorIntervals_.resize(VREGISTERS_NUM);
82     }
83 #ifndef NDEBUG
84     finalized_ = false;
85 #endif
86 }
87 
88 /*
89  * Linear blocks order means:
90  * - all dominators of a block are visiting before this block;
91  * - all blocks belonging to the same loop are contiguous;
92  */
BuildBlocksLinearOrder()93 void LivenessAnalyzer::BuildBlocksLinearOrder()
94 {
95     ASSERT_PRINT(GetGraph()->IsAnalysisValid<DominatorsTree>(), "Liveness Analyzer needs valid Dom Tree");
96     auto size = GetGraph()->GetBlocksRPO().size();
97     linearBlocks_.reserve(size);
98     linearBlocks_.clear();
99     marker_ = GetGraph()->NewMarker();
100     ASSERT_PRINT(marker_ != UNDEF_MARKER, "There are no free markers");
101     if (GetGraph()->IsBytecodeOptimizer() && !GetGraph()->GetTryBeginBlocks().empty()) {
102         LinearizeBlocks<true>();
103     } else {
104         LinearizeBlocks<false>();
105     }
106     ASSERT(linearBlocks_.size() == size);
107     GetGraph()->EraseMarker(marker_);
108     ASSERT_PRINT(CheckLinearOrder(), "Linear block order isn't correct");
109 
110     blockLiveSets_.resize(GetGraph()->GetVectorBlocks().size());
111     blockLiveRanges_.resize(GetGraph()->GetVectorBlocks().size());
112 }
113 
114 /*
115  * Check if all forward edges of loop header were visited to get the resulting block order in RPO.
116  * Predecessors which are not in the same loop with a header - are forward edges.
117  */
AllForwardEdgesVisited(BasicBlock * block)118 bool LivenessAnalyzer::AllForwardEdgesVisited(BasicBlock *block)
119 {
120     if (!block->IsLoopHeader()) {
121         for (auto pred : block->GetPredsBlocks()) {
122             if (!pred->IsMarked(marker_)) {
123                 return false;
124             }
125         }
126     } else {
127         // Head of irreducible loop can not dominate other blocks in the loop
128         if (block->GetLoop()->IsIrreducible()) {
129             return true;
130         }
131         // Predecessors which are not dominated - are forward edges,
132         for (auto pred : block->GetPredsBlocks()) {
133             if (!block->IsDominate(pred) && !pred->IsMarked(marker_)) {
134                 return false;
135             }
136         }
137     }
138     return true;
139 }
140 
141 template <bool USE_PC_ORDER>
LinearizeBlocks()142 void LivenessAnalyzer::LinearizeBlocks()
143 {
144     ArenaList<BasicBlock *> pending {GetGraph()->GetLocalAllocator()->Adapter()};
145     pending.push_back(GetGraph()->GetStartBlock());
146 
147     while (!pending.empty()) {
148         auto current = pending.front();
149         pending.pop_front();
150 
151         linearBlocks_.push_back(current);
152         current->SetMarker(marker_);
153 
154         auto succs = current->GetSuccsBlocks();
155         // Each block is inserted into pending list before all already inserted blocks
156         // from the same loop. To process edges forwarding to a "true" branches successors
157         // should be processed in reversed order.
158         for (auto it = succs.rbegin(); it != succs.rend(); ++it) {
159             auto succ = *it;
160             if (succ->IsMarked(marker_) || !AllForwardEdgesVisited(succ)) {
161                 continue;
162             }
163 
164             if constexpr (USE_PC_ORDER) {  // NOLINT(readability-braces-around-statements)
165                 auto pcCompare = [succ](auto block) { return block->GetGuestPc() > succ->GetGuestPc(); };
166                 auto insertBefore = std::find_if(pending.begin(), pending.end(), pcCompare);
167                 pending.insert(insertBefore, succ);
168             } else {
169                 // Insert successor right before the first block not from an inner loop.
170                 // Such ordering guarantee that a loop and all it's inner loops will be processed
171                 // before following edges leading to outer loop blocks.
172                 auto isNotInnerLoop = [succ](auto block) { return !block->GetLoop()->IsInside(succ->GetLoop()); };
173                 auto insertBefore = std::find_if(pending.begin(), pending.end(), isNotInnerLoop);
174                 pending.insert(insertBefore, succ);
175             }
176         }
177     }
178 }
179 
180 /*
181  * Check linear order correctness, using dominators tree
182  */
CheckLinearOrder()183 bool LivenessAnalyzer::CheckLinearOrder()
184 {
185     ArenaVector<size_t> blockPos(GetGraph()->GetVectorBlocks().size(), 0, GetAllocator()->Adapter());
186     size_t position = 0;
187     for (auto block : linearBlocks_) {
188         blockPos[block->GetId()] = position++;
189     }
190 
191     for (auto block : linearBlocks_) {
192         if (block->GetDominator() != nullptr) {
193             ASSERT_PRINT(blockPos[block->GetDominator()->GetId()] < blockPos[block->GetId()],
194                          "Each block should be visited after its dominator");
195         }
196         if (!block->IsTryEnd()) {
197             continue;
198         }
199         ASSERT(block->GetTryId() != INVALID_ID);
200         for (auto bb : linearBlocks_) {
201             if (bb->IsTry() && bb->GetTryId() == block->GetTryId()) {
202                 ASSERT_PRINT(blockPos[bb->GetId()] < blockPos[block->GetId()],
203                              "Each try-block should be visited before its try-end block");
204             }
205         }
206     }
207 
208     return true;
209 }
210 
211 /*
212  * Set lifetime number and visiting number for each instruction
213  */
BuildInstLifeNumbers()214 void LivenessAnalyzer::BuildInstLifeNumbers()
215 {
216     LifeNumber blockBegin;
217     LifeNumber lifeNumber = 0;
218     LinearNumber linearNumber = 0;
219 
220     for (auto block : GetLinearizedBlocks()) {
221         blockBegin = lifeNumber;
222         // set the same number for each phi in the block
223         for (auto phi : block->PhiInsts()) {
224             phi->SetLinearNumber(linearNumber++);
225             SetInstLifeNumber(phi, lifeNumber);
226             CreateLifeIntervals(phi);
227         }
228         // ignore PHI instructions
229         instsByLifeNumber_.push_back(nullptr);
230         // set a unique number for each instruction in the block, differing by 2
231         // for the reason of adding spill/fill instructions
232         for (auto inst : block->Insts()) {
233             inst->SetLinearNumber(linearNumber++);
234             CreateLifeIntervals(inst);
235             if (IsPseudoUserOfMultiOutput(inst)) {
236                 // Should be the same life number as pseudo-user, since actually they have the same definition
237                 SetInstLifeNumber(inst, lifeNumber);
238                 GetInstLifeIntervals(inst)->AddUsePosition(lifeNumber);
239                 continue;
240             }
241             lifeNumber += LIFE_NUMBER_GAP;
242             SetInstLifeNumber(inst, lifeNumber);
243             SetUsePositions(inst, lifeNumber);
244             instsByLifeNumber_.push_back(inst);
245 
246             if (inst->RequireTmpReg()) {
247                 CreateIntervalForTemp(lifeNumber);
248             }
249         }
250         lifeNumber += LIFE_NUMBER_GAP;
251         SetBlockLiveRange(block, {blockBegin, lifeNumber});
252     }
253 }
254 
SetUsePositions(Inst * userInst,LifeNumber lifeNumber)255 void LivenessAnalyzer::SetUsePositions(Inst *userInst, LifeNumber lifeNumber)
256 {
257     if (GetGraph()->IsBytecodeOptimizer()) {
258         return;
259     }
260     if (userInst->IsCatchPhi() || userInst->IsSaveState()) {
261         return;
262     }
263     for (size_t i = 0; i < userInst->GetInputsCount(); i++) {
264         auto location = userInst->GetLocation(i);
265         if (!location.IsAnyRegister()) {
266             continue;
267         }
268         auto inputInst = userInst->GetDataFlowInput(i);
269         auto li = GetInstLifeIntervals(inputInst);
270         if (location.IsRegisterValid()) {
271             useTable_.AddUseOnFixedLocation(inputInst, location, lifeNumber);
272         } else if (location.IsUnallocatedRegister()) {
273             li->AddUsePosition(lifeNumber);
274         }
275     }
276 
277     // Constant can be defined without register
278     if (userInst->IsConst() && g_options.IsCompilerRematConst()) {
279         return;
280     }
281 
282     // If instruction required dst register, set use position in the beginning of the interval
283     auto li = GetInstLifeIntervals(userInst);
284     if (!li->NoDest()) {
285         li->AddUsePosition(lifeNumber);
286     }
287 }
288 
289 /*
290  * Get lifetime intervals for each instruction
291  */
BuildInstLifeIntervals()292 void LivenessAnalyzer::BuildInstLifeIntervals()
293 {
294     for (auto it = GetLinearizedBlocks().rbegin(); it != GetLinearizedBlocks().rend(); it++) {
295         auto block = *it;
296         auto liveSet = GetInitInstLiveSet(block);
297         ProcessBlockLiveInstructions(block, liveSet);
298     }
299 }
300 
301 /*
302  * The initial set of live instructions in the `block` is the the union of all live instructions at the beginning of
303  * the block's successors.
304  * Also for each phi-instruction of the successors: input corresponding to the `block` is added to the live set.
305  */
GetInitInstLiveSet(BasicBlock * block)306 InstLiveSet *LivenessAnalyzer::GetInitInstLiveSet(BasicBlock *block)
307 {
308     unsigned instructionCount = instLifeIntervals_.size();
309     auto liveSet = GetAllocator()->New<InstLiveSet>(instructionCount, GetAllocator());
310     for (auto succ : block->GetSuccsBlocks()) {
311         // catch-begin is pseudo successor, its live set will be processed for blocks with throwable instructions
312         if (succ->IsCatchBegin()) {
313             continue;
314         }
315         liveSet->Union(GetBlockLiveSet(succ));
316         for (auto phi : succ->PhiInsts()) {
317             auto phiInput = phi->CastToPhi()->GetPhiDataflowInput(block);
318             liveSet->Add(phiInput->GetLinearNumber());
319         }
320     }
321 
322     // if basic block contains throwable instruction, all instructions live in the catch-handlers should be live in this
323     // block
324     if (auto inst = block->GetFistThrowableInst(); inst != nullptr) {
325         auto handlers = GetGraph()->GetThrowableInstHandlers(inst);
326         for (auto catchHandler : handlers) {
327             liveSet->Union(GetBlockLiveSet(catchHandler));
328         }
329     }
330     return liveSet;
331 }
332 
GetLoopEnd(Loop * loop)333 LifeNumber LivenessAnalyzer::GetLoopEnd(Loop *loop)
334 {
335     LifeNumber loopEnd = 0;
336     // find max LifeNumber of inner loops
337     for (auto inner : loop->GetInnerLoops()) {
338         loopEnd = std::max(loopEnd, GetLoopEnd(inner));
339     }
340     // find max LifeNumber of back_edges
341     for (auto backEdge : loop->GetBackEdges()) {
342         loopEnd = std::max(loopEnd, GetBlockLiveRange(backEdge).GetEnd());
343     }
344     return loopEnd;
345 }
346 
347 /*
348  * Append and adjust the lifetime intervals for each instruction live in the block and for their inputs
349  */
ProcessBlockLiveInstructions(BasicBlock * block,InstLiveSet * liveSet)350 void LivenessAnalyzer::ProcessBlockLiveInstructions(BasicBlock *block, InstLiveSet *liveSet)
351 {
352     // For each live instruction set initial life range equals to the block life range
353     for (auto &interval : instLifeIntervals_) {
354         if (liveSet->IsSet(interval->GetInst()->GetLinearNumber())) {
355             interval->AppendRange(GetBlockLiveRange(block));
356         }
357     }
358 
359     for (Inst *inst : block->InstsSafeReverse()) {
360         // Shorten instruction lifetime to the position where its defined
361         // and remove from the block's live set
362         auto instLifeNumber = GetInstLifeNumber(inst);
363         auto interval = GetInstLifeIntervals(inst);
364         interval->StartFrom(instLifeNumber);
365         liveSet->Remove(inst->GetLinearNumber());
366         if (inst->IsCatchPhi()) {
367             // catch-phi's liveness should overlap all linked try blocks' livenesses
368             for (auto pred : inst->GetBasicBlock()->GetPredsBlocks()) {
369                 instLifeNumber = std::min(instLifeNumber, GetBlockLiveRange(pred).GetBegin());
370             }
371             interval->StartFrom(instLifeNumber);
372             AdjustCatchPhiInputsLifetime(inst);
373         } else {
374             if (inst->GetOpcode() == Opcode::LiveOut) {
375                 if (block->GetSuccsBlocks().size() == 1 && block->GetSuccessor(0)->IsEndBlock()) {
376                     interval->AppendRange({instLifeNumber, GetBlockLiveRange(block).GetEnd()});
377                 } else {
378                     interval->AppendRange({instLifeNumber, GetBlockLiveRange(GetGraph()->GetEndBlock()).GetBegin()});
379                 }
380             }
381             auto currentLiveRange = LiveRange {GetBlockLiveRange(block).GetBegin(), instLifeNumber};
382             AdjustInputsLifetime(inst, currentLiveRange, liveSet);
383         }
384 
385         BlockFixedRegisters(inst);
386     }
387 
388     // The lifetime interval of phis instructions starts at the beginning of the block
389     for (auto phi : block->PhiInsts()) {
390         liveSet->Remove(phi->GetLinearNumber());
391     }
392 
393     // All instructions live at the beginning ot the loop header
394     // must be live for the entire loop
395     if (block->IsLoopHeader()) {
396         LifeNumber loopEndPosition = GetLoopEnd(block->GetLoop());
397 
398         for (auto &interval : instLifeIntervals_) {
399             if (liveSet->IsSet(interval->GetInst()->GetLinearNumber())) {
400                 interval->AppendGroupRange({GetBlockLiveRange(block).GetBegin(), loopEndPosition});
401             }
402         }
403     }
404     SetBlockLiveSet(block, liveSet);
405 }
406 
407 /* static */
GetPropagatedLiveRange(Inst * inst,LiveRange liveRange)408 LiveRange LivenessAnalyzer::GetPropagatedLiveRange(Inst *inst, LiveRange liveRange)
409 {
410     /*
411      * Implicit null check encoded as no-op and if the reference to check is null
412      * then SIGSEGV will be raised at the first (closest) user. Regmap generated for
413      * NullCheck's SaveState should be valid at that user so we need to extend
414      * life intervals of SaveState's inputs until NullCheck user.
415      */
416     if (inst->IsNullCheck() && !inst->GetUsers().Empty() && inst->CastToNullCheck()->IsImplicit()) {
417         auto extendUntil = std::numeric_limits<LifeNumber>::max();
418         for (auto &user : inst->GetUsers()) {
419             // Skip the users dominating the NullCheck as their live ranges
420             // start earlier than NullCheck's live range.
421             if (!user.GetInst()->IsDominate(inst)) {
422                 auto li = GetInstLifeIntervals(user.GetInst());
423                 ASSERT(li != nullptr);
424                 extendUntil = std::min<LifeNumber>(extendUntil, li->GetBegin() + 1);
425             }
426         }
427         liveRange.SetEnd(extendUntil);
428         return liveRange;
429     }
430     /*
431      * We need to propagate liveness for instruction with CallRuntime to save registers before call;
432      * Otherwise, we will not be able to restore the value of the virtual registers
433      */
434     if (inst->IsPropagateLiveness()) {
435         liveRange.SetEnd(liveRange.GetEnd() + 1);
436     } else if (inst->GetOpcode() == Opcode::ReturnInlined && inst->CastToReturnInlined()->IsExtendedLiveness()) {
437         /*
438          * [ReturnInlined]
439          * [ReturnInlined]
440          * ...
441          * [Deoptimize/Throw]
442          *
443          * In this case we propagate ReturnInlined inputs liveness up to the end of basic block
444          */
445         liveRange.SetEnd(GetBlockLiveRange(inst->GetBasicBlock()).GetEnd());
446     }
447     return liveRange;
448 }
449 
450 /*
451  * Adjust instruction inputs lifetime and add them to the block's live set
452  */
AdjustInputsLifetime(Inst * inst,LiveRange liveRange,InstLiveSet * liveSet)453 void LivenessAnalyzer::AdjustInputsLifetime(Inst *inst, LiveRange liveRange, InstLiveSet *liveSet)
454 {
455     for (auto input : inst->GetInputs()) {
456         auto inputInst = inst->GetDataFlowInput(input.GetInst());
457         liveSet->Add(inputInst->GetLinearNumber());
458         SetInputRange(inst, inputInst, liveRange);
459     }
460 
461     // Extend SaveState inputs lifetime to the end of SaveState's lifetime
462     if (inst->RequireState()) {
463         auto saveState = inst->GetSaveState();
464         auto propagatedRange = GetPropagatedLiveRange(inst, liveRange);
465         while (true) {
466             ASSERT(saveState != nullptr);
467             for (auto ssInput : saveState->GetInputs()) {
468                 auto inputInst = saveState->GetDataFlowInput(ssInput.GetInst());
469                 liveSet->Add(inputInst->GetLinearNumber());
470                 GetInstLifeIntervals(inputInst)->AppendRange(propagatedRange);
471             }
472             auto callerInst = saveState->GetCallerInst();
473             if (callerInst == nullptr) {
474                 break;
475             }
476             saveState = callerInst->GetSaveState();
477         }
478     }
479 
480     // Handle CatchPhi inputs associated with inst
481     auto range = pendingCatchPhiInputs_.equal_range(inst);
482     for (auto it = range.first; it != range.second; ++it) {
483         auto throwableInput = it->second;
484         auto throwableInputInterval = GetInstLifeIntervals(throwableInput);
485         liveSet->Add(throwableInput->GetLinearNumber());
486         throwableInputInterval->AppendRange(liveRange);
487     }
488     pendingCatchPhiInputs_.erase(inst);
489 }
490 
491 /*
492  * Increase ref-input liveness in the 'no-async-jit' mode, since GC can be triggered and delete ref during callee-method
493  * compilation
494  */
SetInputRange(const Inst * inst,const Inst * input,LiveRange liveRange) const495 void LivenessAnalyzer::SetInputRange(const Inst *inst, const Inst *input, LiveRange liveRange) const
496 {
497     if (hasSafepointDuringCall_ && inst->IsCall() && DataType::IsReference(input->GetType())) {
498         GetInstLifeIntervals(input)->AppendRange(liveRange.GetBegin(), liveRange.GetEnd() + 1U);
499     } else {
500         GetInstLifeIntervals(input)->AppendRange(liveRange);
501     }
502 }
503 
504 /*
505  * CatchPhi does not handle inputs as regular instructions - instead of performing
506  * some action at CatchPhi's definition copy instruction are added before throwable instructions.
507  * Instead of extending input life interval until CatchPhi it is extended until throwable instruction.
508  */
AdjustCatchPhiInputsLifetime(Inst * inst)509 void LivenessAnalyzer::AdjustCatchPhiInputsLifetime(Inst *inst)
510 {
511     auto catchPhi = inst->CastToCatchPhi();
512 
513     for (ssize_t inputIdx = catchPhi->GetInputsCount() - 1; inputIdx >= 0; inputIdx--) {
514         auto inputInst = catchPhi->GetDataFlowInput(inputIdx);
515         auto throwableInst = const_cast<Inst *>(catchPhi->GetThrowableInst(inputIdx));
516 
517         pendingCatchPhiInputs_.insert({throwableInst, inputInst});
518     }
519 }
520 
SetInstLifeNumber(const Inst * inst,LifeNumber number)521 void LivenessAnalyzer::SetInstLifeNumber([[maybe_unused]] const Inst *inst, LifeNumber number)
522 {
523     ASSERT(instLifeNumbers_.size() == inst->GetLinearNumber());
524     instLifeNumbers_.push_back(number);
525 }
526 
GetInstLifeNumber(const Inst * inst) const527 LifeNumber LivenessAnalyzer::GetInstLifeNumber(const Inst *inst) const
528 {
529     return instLifeNumbers_[inst->GetLinearNumber()];
530 }
531 
532 /*
533  * Create new lifetime intervals for instruction, check that instruction linear number is equal to intervals
534  * position in vector
535  */
CreateLifeIntervals(Inst * inst)536 void LivenessAnalyzer::CreateLifeIntervals(Inst *inst)
537 {
538     ASSERT(!finalized_);
539     ASSERT(inst->GetLinearNumber() == instLifeIntervals_.size());
540     auto interval = GetAllocator()->New<LifeIntervals>(GetAllocator(), inst);
541     instLifeIntervals_.push_back(interval);
542 }
543 
CreateIntervalForTemp(LifeNumber ln)544 void LivenessAnalyzer::CreateIntervalForTemp(LifeNumber ln)
545 {
546     ASSERT(!finalized_);
547     auto interval = GetAllocator()->New<LifeIntervals>(GetAllocator());
548     interval->AppendRange({ln - 1, ln});
549     interval->AddUsePosition(ln);
550     // DataType is INT64, since general register is reserved (for 32-bits arch will be converted to INT32)
551     interval->SetType(ConvertRegType(GetGraph(), DataType::INT64));
552     intervalsForTemps_.push_back(interval);
553 }
554 
GetInstLifeIntervals(const Inst * inst) const555 LifeIntervals *LivenessAnalyzer::GetInstLifeIntervals(const Inst *inst) const
556 {
557     ASSERT(inst->GetLinearNumber() != INVALID_LINEAR_NUM);
558     return instLifeIntervals_[inst->GetLinearNumber()];
559 }
560 
SetBlockLiveRange(BasicBlock * block,LiveRange lifeRange)561 void LivenessAnalyzer::SetBlockLiveRange(BasicBlock *block, LiveRange lifeRange)
562 {
563     blockLiveRanges_[block->GetId()] = lifeRange;
564 }
565 
GetBlockLiveRange(const BasicBlock * block) const566 LiveRange LivenessAnalyzer::GetBlockLiveRange(const BasicBlock *block) const
567 {
568     return blockLiveRanges_[block->GetId()];
569 }
570 
SetBlockLiveSet(BasicBlock * block,InstLiveSet * liveSet)571 void LivenessAnalyzer::SetBlockLiveSet(BasicBlock *block, InstLiveSet *liveSet)
572 {
573     blockLiveSets_[block->GetId()] = liveSet;
574 }
575 
GetBlockLiveSet(BasicBlock * block) const576 InstLiveSet *LivenessAnalyzer::GetBlockLiveSet(BasicBlock *block) const
577 {
578     return blockLiveSets_[block->GetId()];
579 }
580 
DumpLifeIntervals(std::ostream & out) const581 void LivenessAnalyzer::DumpLifeIntervals(std::ostream &out) const
582 {
583     for (auto bb : GetGraph()->GetBlocksRPO()) {
584         if (bb->GetId() >= GetBlocksCount()) {
585             continue;
586         }
587         auto blockRange = GetBlockLiveRange(bb);
588         out << "BB " << bb->GetId() << "\t" << blockRange.ToString() << std::endl;
589 
590         for (auto inst : bb->AllInsts()) {
591             if (inst->GetLinearNumber() == INVALID_LINEAR_NUM) {
592                 continue;
593             }
594             auto interval = GetInstLifeIntervals(inst);
595 
596             out << "v" << inst->GetId() << "\t";
597             for (auto sibling = interval; sibling != nullptr; sibling = sibling->GetSibling()) {
598                 out << sibling->ToString<false>() << "@ " << sibling->GetLocation().ToString(GetGraph()->GetArch())
599                     << "; ";
600             }
601             out << std::endl;
602         }
603     }
604 
605     out << "Temps:" << std::endl;
606     for (auto interval : intervalsForTemps_) {
607         out << interval->ToString<false>() << "@ " << interval->GetLocation().ToString(GetGraph()->GetArch())
608             << std::endl;
609     }
610     DumpLocationsUsage(out);
611 }
612 
DumpLocationsUsage(std::ostream & out) const613 void LivenessAnalyzer::DumpLocationsUsage(std::ostream &out) const
614 {
615     std::map<Register, std::vector<LifeIntervals *>> regsIntervals;
616     std::map<Register, std::vector<LifeIntervals *>> vregsIntervals;
617     std::map<Register, std::vector<LifeIntervals *>> slotsIntervals;
618     for (auto &interval : instLifeIntervals_) {
619         for (auto sibling = interval; sibling != nullptr; sibling = sibling->GetSibling()) {
620             auto location = sibling->GetLocation();
621             if (location.IsFpRegister()) {
622                 ASSERT(DataType::IsFloatType(interval->GetType()));
623                 vregsIntervals[location.GetValue()].push_back(sibling);
624             } else if (location.IsRegister()) {
625                 regsIntervals[location.GetValue()].push_back(sibling);
626             } else if (location.IsStack()) {
627                 slotsIntervals[location.GetValue()].push_back(sibling);
628             }
629         }
630     }
631 
632     for (auto intervalsMap : {&regsIntervals, &vregsIntervals, &slotsIntervals}) {
633         std::string locSymbol;
634         if (intervalsMap == &regsIntervals) {
635             out << std::endl << "Registers intervals" << std::endl;
636             locSymbol = "r";
637         } else if (intervalsMap == &vregsIntervals) {
638             out << std::endl << "Vector registers intervals" << std::endl;
639             locSymbol = "vr";
640         } else {
641             ASSERT(intervalsMap == &slotsIntervals);
642             out << std::endl << "Stack slots intervals" << std::endl;
643             locSymbol = "s";
644         }
645 
646         if (intervalsMap->empty()) {
647             out << "-" << std::endl;
648             continue;
649         }
650         for (auto &[reg, intervals] : *intervalsMap) {
651             std::sort(intervals.begin(), intervals.end(),
652                       [](const auto &lhs, const auto &rhs) { return lhs->GetBegin() < rhs->GetBegin(); });
653             out << locSymbol << std::to_string(reg) << ": ";
654             auto delim = "";
655             for (auto &interval : intervals) {
656                 out << delim << interval->ToString<false>();
657                 delim = "; ";
658             }
659             out << std::endl;
660         }
661     }
662 }
663 
BlockFixedRegisters(Inst * inst)664 void LivenessAnalyzer::BlockFixedRegisters(Inst *inst)
665 {
666     if (GetGraph()->IsBytecodeOptimizer() || GetGraph()->GetMode().IsFastPath()) {
667         return;
668     }
669 
670     auto blockFrom = GetInstLifeNumber(inst);
671     if (IsCallBlockingRegisters(inst)) {
672         BlockPhysicalRegisters<false>(blockFrom);
673         BlockPhysicalRegisters<true>(blockFrom);
674     }
675     for (auto i = 0U; i < inst->GetInputsCount(); ++i) {
676         BlockFixedLocationRegister(inst->GetLocation(i), blockFrom);
677     }
678     BlockFixedLocationRegister(inst->GetDstLocation(), blockFrom);
679 
680     if (inst->IsParameter()) {
681         // Block a register starting from the position preceding entry block start to
682         // correctly handle register blocked by "current" instruction from registers blocked
683         // by other instructions during register allocation.
684         constexpr auto FIRST_AVAILABLE_LIFE_NUMBER = LIFE_NUMBER_GAP - 1;
685         // Registers holding parameters should be blocked starting from the beginning of entry block
686         // to avoid its assignment to parameter instructions in case of high register pressure.
687         // The required interval is blocked using two calls to correctly mark first use position of a
688         // blocked register.
689         BlockFixedLocationRegister(inst->CastToParameter()->GetLocationData().GetSrc(), blockFrom);
690         BlockFixedLocationRegister(inst->CastToParameter()->GetLocationData().GetSrc(), FIRST_AVAILABLE_LIFE_NUMBER,
691                                    blockFrom - 1, false);
692         // Block second parameter register that contains number of actual arguments in case of
693         // dynamic methods as it is used in parameter's code generation
694         if (GetGraph()->GetMode().IsDynamicMethod() &&
695             GetGraph()->FindParameter(ParameterInst::DYNAMIC_NUM_ARGS) == nullptr) {
696             BlockReg<false>(Target(GetGraph()->GetArch()).GetParamRegId(1), blockFrom, blockFrom + 1U, true);
697             BlockReg<false>(Target(GetGraph()->GetArch()).GetParamRegId(1), FIRST_AVAILABLE_LIFE_NUMBER, blockFrom - 1,
698                             false);
699         }
700     }
701 }
702 
703 template <bool IS_FP>
BlockPhysicalRegisters(LifeNumber blockFrom)704 void LivenessAnalyzer::BlockPhysicalRegisters(LifeNumber blockFrom)
705 {
706     auto arch = GetGraph()->GetArch();
707     RegMask callerRegs {GetCallerRegsMask(arch, IS_FP)};
708     for (auto reg = GetFirstCallerReg(arch, IS_FP); reg <= GetLastCallerReg(arch, IS_FP); ++reg) {
709         if (callerRegs.test(reg)) {
710             BlockReg<IS_FP>(reg, blockFrom, blockFrom + 1U, true);
711         }
712     }
713 }
714 
BlockFixedLocationRegister(Location location,LifeNumber blockFrom,LifeNumber blockTo,bool isUse)715 void LivenessAnalyzer::BlockFixedLocationRegister(Location location, LifeNumber blockFrom, LifeNumber blockTo,
716                                                   bool isUse)
717 {
718     if (location.IsRegister() && location.IsRegisterValid()) {
719         BlockReg<false>(location.GetValue(), blockFrom, blockTo, isUse);
720     } else if (location.IsFpRegister() && location.IsRegisterValid()) {
721         BlockReg<true>(location.GetValue(), blockFrom, blockTo, isUse);
722     }
723 }
724 
725 template <bool IS_FP>
BlockReg(Register reg,LifeNumber blockFrom,LifeNumber blockTo,bool isUse)726 void LivenessAnalyzer::BlockReg(Register reg, LifeNumber blockFrom, LifeNumber blockTo, bool isUse)
727 {
728     ASSERT(!finalized_);
729     auto &intervals = IS_FP ? physicalVectorIntervals_ : physicalGeneralIntervals_;
730     auto interval = intervals.at(reg);
731     if (interval == nullptr) {
732         interval = GetGraph()->GetAllocator()->New<LifeIntervals>(GetGraph()->GetAllocator());
733         interval->SetPhysicalReg(reg, IS_FP ? DataType::FLOAT64 : DataType::UINT64);
734         intervals.at(reg) = interval;
735     }
736     interval->AppendRange(blockFrom, blockTo);
737     if (isUse) {
738         interval->AddUsePosition(blockFrom);
739     }
740 }
741 
IsCallBlockingRegisters(Inst * inst) const742 bool LivenessAnalyzer::IsCallBlockingRegisters(Inst *inst) const
743 {
744     if (inst->IsCall() && !inst->IsLaunchCall() && !static_cast<CallInst *>(inst)->IsInlined()) {
745         return true;
746     }
747     if (inst->IsIntrinsic() && inst->CastToIntrinsic()->IsNativeCall()) {
748         return true;
749     }
750     return false;
751 }
752 
SplitAt(LifeNumber ln,ArenaAllocator * alloc)753 LifeIntervals *LifeIntervals::SplitAt(LifeNumber ln, ArenaAllocator *alloc)
754 {
755     ASSERT(!IsPhysical());
756     ASSERT(ln > GetBegin() && ln <= GetEnd());
757     auto splitChild = alloc->New<LifeIntervals>(alloc, GetInst());
758 #ifndef NDEBUG
759     ASSERT(finalized_);
760     splitChild->finalized_ = true;
761 #endif
762     if (sibling_ != nullptr) {
763         splitChild->sibling_ = sibling_;
764     }
765     splitChild->isSplitSibling_ = true;
766 
767     sibling_ = splitChild;
768     splitChild->SetType(GetType());
769 
770     auto i = liveRanges_.size();
771     while (i > 0 && liveRanges_[i - 1].GetEnd() <= ln) {
772         i--;
773     }
774     if (i > 0) {
775         auto &range = liveRanges_[i - 1];
776         if (range.GetBegin() < ln) {
777             splitChild->AppendRange(range.GetBegin(), ln);
778             range.SetBegin(ln);
779         }
780     }
781     splitChild->liveRanges_.insert(splitChild->liveRanges_.end(), liveRanges_.begin() + i, liveRanges_.end());
782     liveRanges_.erase(liveRanges_.begin() + i, liveRanges_.end());
783     std::swap(liveRanges_, splitChild->liveRanges_);
784 
785     // Move use positions to the child
786     auto it = std::lower_bound(usePositions_.begin(), usePositions_.end(), ln);
787     splitChild->usePositions_.insert(splitChild->usePositions_.end(), it, usePositions_.end());
788     usePositions_.erase(it, usePositions_.end());
789 
790     return splitChild;
791 }
792 
SplitAroundUses(ArenaAllocator * alloc)793 void LifeIntervals::SplitAroundUses(ArenaAllocator *alloc)
794 {
795     if (GetUsePositions().empty()) {
796         return;
797     }
798     auto use = *GetUsePositions().begin();
799     if (use > GetBegin() + 1) {
800         auto split = SplitAt(use - 1, alloc);
801         split->SplitAroundUses(alloc);
802     } else if (use < GetEnd() - 1) {
803         auto split = SplitAt(use + 1, alloc);
804         split->SplitAroundUses(alloc);
805     }
806 }
807 
MergeSibling()808 void LifeIntervals::MergeSibling()
809 {
810     ASSERT(sibling_ != nullptr);
811 #ifndef NDEBUG
812     ASSERT(finalized_);
813     ASSERT(sibling_->finalized_);
814     if (!usePositions_.empty() && !sibling_->usePositions_.empty()) {
815         ASSERT(usePositions_.back() <= sibling_->usePositions_.front());
816     }
817 #endif
818     for (auto range : liveRanges_) {
819         sibling_->AppendRange(range);
820     }
821     liveRanges_ = std::move(sibling_->liveRanges_);
822 
823     for (auto &usePos : sibling_->usePositions_) {
824         AddUsePosition(usePos);
825     }
826     sibling_ = nullptr;
827 }
828 
FindSiblingAt(LifeNumber ln)829 LifeIntervals *LifeIntervals::FindSiblingAt(LifeNumber ln)
830 {
831     ASSERT(!IsSplitSibling());
832     for (auto head = this; head != nullptr; head = head->GetSibling()) {
833         if (head->GetBegin() <= ln && ln <= head->GetEnd()) {
834             return head;
835         }
836     }
837     return nullptr;
838 }
839 
Intersects(const LiveRange & range) const840 bool LifeIntervals::Intersects(const LiveRange &range) const
841 {
842     return  // the interval starts within the range
843         (range.GetBegin() <= GetBegin() && GetBegin() <= range.GetEnd()) ||
844         // the interval ends within the range
845         (range.GetBegin() <= GetEnd() && GetEnd() <= range.GetEnd()) ||
846         // the range is fully covered by the interval
847         (GetBegin() <= range.GetBegin() && range.GetEnd() <= GetEnd());
848 }
849 
GetFirstIntersectionWith(const LifeIntervals * other,LifeNumber searchFrom) const850 LifeNumber LifeIntervals::GetFirstIntersectionWith(const LifeIntervals *other, LifeNumber searchFrom) const
851 {
852     for (auto it = GetRanges().rbegin(); it != GetRanges().rend(); it++) {
853         auto range = *it;
854         if (range.GetEnd() <= searchFrom) {
855             continue;
856         }
857         for (auto otherIt = other->GetRanges().rbegin(); otherIt != other->GetRanges().rend(); otherIt++) {
858             auto otherRange = *otherIt;
859             if (otherRange.GetEnd() <= searchFrom) {
860                 continue;
861             }
862             auto rangeBegin = std::max<LifeNumber>(searchFrom, range.GetBegin());
863             auto otherRangeBegin = std::max<LifeNumber>(searchFrom, otherRange.GetBegin());
864             if (rangeBegin <= otherRangeBegin && otherRangeBegin < range.GetEnd()) {
865                 // [range]
866                 //    [other]
867                 return otherRangeBegin;
868                 // NOLINTNEXTLINE(readability-else-after-return)
869             } else if (rangeBegin > otherRangeBegin && rangeBegin < otherRange.GetEnd()) {
870                 //     [range]
871                 // [other]
872                 return rangeBegin;
873             }
874         }
875     }
876     return INVALID_LIFE_NUMBER;
877 }
878 
FindRangeCoveringPosition(LifeNumber ln,LiveRange * dst) const879 bool LifeIntervals::FindRangeCoveringPosition(LifeNumber ln, LiveRange *dst) const
880 {
881     for (auto &range : GetRanges()) {
882         if (range.Contains(ln)) {
883             *dst = range;
884             return true;
885         }
886     }
887 
888     return false;
889 }
890 
GetSpillWeightAt(const LivenessAnalyzer & la,LifeNumber ln)891 static float GetSpillWeightAt(const LivenessAnalyzer &la, LifeNumber ln)
892 {
893     static constexpr float LOOP_MULT = 10.0;
894     auto block = la.GetBlockCoversPoint(ln);
895     return std::pow<float>(LOOP_MULT, block->GetLoop()->GetDepth());
896 }
897 
CalcSpillWeight(const LivenessAnalyzer & la,LifeIntervals * interval)898 float CalcSpillWeight(const LivenessAnalyzer &la, LifeIntervals *interval)
899 {
900     if (interval->IsPhysical()) {
901         return std::numeric_limits<float>::max();
902     }
903 
904     size_t length = interval->GetEnd() - interval->GetBegin();
905     // Interval can't be splitted
906     if (length <= LIFE_NUMBER_GAP) {
907         return std::numeric_limits<float>::max();
908     }
909 
910     // Constant intervals are the first candidates to spill
911     if (interval->GetInst()->IsConst()) {
912         return std::numeric_limits<float>::min();
913     }
914 
915     float useWeight = 0;
916     if (interval->GetInst()->IsPhi()) {
917         useWeight += GetSpillWeightAt(la, interval->GetBegin());
918     }
919 
920     for (auto use : interval->GetUsePositions()) {
921         if (use == interval->GetBegin()) {
922             useWeight += GetSpillWeightAt(la, use + 1);
923         } else {
924             useWeight += GetSpillWeightAt(la, use - 1);
925         }
926     }
927     return useWeight;
928 }
929 
930 }  // namespace panda::compiler
931