LLVM 24.0.0git
HexagonLiveVariables.cpp
Go to the documentation of this file.
1
2//===----------------- HexagonLiveVariables.cpp ---------------------------===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9// Hexagon Live Variable Analysis
10// This file implements the Hexagon specific LiveVariables analysis pass.
11// This pass recomputes physical register liveness and updates live-ins for
12// non-entry blocks based on use/def information.
13//===----------------------------------------------------------------------===//
14#define DEBUG_TYPE "hexagon_live_vars"
15
21#include "llvm/CodeGen/Passes.h"
23#include "llvm/Support/Debug.h"
25
26using namespace llvm;
27
30
32 "Hexagon Live Variable Analysis", false, false)
33
34// TODO: Establish a protocol to handle liveness of predicated instructions.
35// Liveness for predicated instruction is a little convoluted.
36// TODO: In PhysRegDef and PhysRegUse, use a bit vector instead of 126 elems.
37class HexagonLiveVariablesImpl {
38 // Intermediate data structures
39 friend class llvm::HexagonLiveVariables;
41
43
45
46 const HexagonInstrInfo *QII;
47
48 unsigned NumRegs;
49
50 /// PhysRegInfo - Keep track of which instruction was the last def of a
51 /// physical register (possibly after a use). This is purely local to a BB.
53
54 /// PhysRegInfo - Keep track of which instruction was the last use of a
55 /// physical register (before any def). This is purely local property to a BB.
57
58 /// MBB -> (Uses, Defs)
59 /// Uses - use before any def in that MBB.
60 /// Defs - def before any uses in that MBB.
61 MBBUseDef_t MBBUseDefs;
62
63 /// MI -> (Uses, Defs)
64 MIUseDef_t MIUseDefs;
65
66 /// Live-out data for each MBB => U LiveIns (For all Successors of a MBB).
68
69 /// Each MachineBasicBlock is assigned a Distance which is
70 /// an approximation of MBB->size()*INSTR_SIZE+Some offsets.
71 /// This is helpful in quickly finding distance between
72 /// a branch and its target.
73 /// @note A pass which moves instructions should update this.
74 /// @note The data in distance map should be used carefully because
75 /// difference in the distances of two MI might not give relative distances
76 /// between them. The DistanceMap is mainly useful during pullup.
78
79 // Blocks in depth first order
81
82 /// @brief Constructs use-defs of \p MBB by analyzing each MachineOperand.
83 /// Collects relevant information so that global liveness can be updated.
85
86 /// Collects used-before-define set of registers.
87 /// A register is considered to be completely defined if
88 /// 1. The register
89 /// 2. Any of its super-reg
90 /// 3. All of its subregs
91 /// are defined. In these cases the register is not considered as
92 /// used-before-defined. In case of partial definition of a register
93 /// before its use, only the remaining subregs are included in the use-set.
94 /// @note: Assumes that a register can be completely defined, by defining
95 /// all of its sub-regs (if any).
96 void handlePhysRegUse(MachineOperand *MO, MachineInstr *MI, BitVector &Uses);
97
98 /// Collects defined-before-use set of registers. If there is any
99 /// use of register or its aliases then the register is not counted
100 /// as defined-before-use
101 /// @note: Assumes that a register can be completely defined, by defining
102 /// all of its sub-regs (if any).
103 void handlePhysRegDef(MachineOperand *MO, MachineInstr *MI, BitVector &Defs);
104
105 /// updateGlobalLiveness - wrapper around another overload
106 inline bool updateGlobalLiveness(MachineFunction &Fn);
107 bool updateGlobalLiveness(MachineBasicBlock *X, MachineBasicBlock *Y);
108
109 /// updateGlobalLiveness - updates liveness based on
110 /// livein and liveout entries.
111 bool updateGlobalLiveness(MachineBasicBlock *MBB, BitVector &Defs,
112 BitVector &LiveIns);
113
114 /// update live-ins when live-out has been calculated
115 bool updateLiveIns(MachineBasicBlock *MBB, BitVector &LiveIns,
116 const BitVector &LiveOuts);
117
118 bool updateLiveOuts(MachineBasicBlock *MBB, BitVector &LiveOuts);
119
120 /// updateLocalLiveness - update only kill flags of operands.
121 inline bool updateLocalLiveness(MachineFunction &Fn);
122
123 /// updateLocalLiveness - update only kill flags of operands.
125
126 /// incrementalUpdate - update the liveness when \p MIDelta is moved from
127 /// \p From to \p To.
128 /// @note: This is extremely fragile now. It 'assumes' that the other
129 /// successor(s) of \p To do not use Defs of MIDelta.
130 /// It deletes the live-in of the \p From MBB.
133
134 /// addNewMBB - inform the LiveVariable Analysis that new MBB has been added.
135 /// update the liveness of this new MBB.
136 /// @note MBB should be empty. If we want to add an MI, add it after calling
137 /// this function.
139
141 unsigned getNumRegs() const { return NumRegs; }
142
143 // Useful for clearing out after passes which move instructions around.
144 // e.g. GlobalScheduler.
145 void clearDistanceMap() { DistanceMap.clear(); }
146
147 /// Computes \p DistanceMap.
148 void generateDistanceMap(const MachineFunction &Fn);
149
150public:
153};
154
155//===----------------------------------------------------------------------===//
156// HexagonLiveVariables Functions
157//===----------------------------------------------------------------------===//
163
171
173 if (HLVComplete)
174 return;
175 auto &MDT = getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
176 auto &MPDT =
178 HLV->runOnMachineFunction(MF, MDT, MPDT);
179}
180
182 return HLV->updateLocalLiveness(Fn);
183}
184
186 bool updateBundle) {
187 HLV->constructUseDef(MBB); // XXX: This destroys MBBLiveOuts!
188 return HLV->updateLocalLiveness(MBB, updateBundle);
189}
190
192 MachineBasicBlock *From,
193 MachineBasicBlock *To) {
194 assert(MIDelta->getParent() == To);
195 assert(From != To);
196 return HLV->incrementalUpdate(MIDelta, From, To);
197}
198
200 assert(MBB->empty());
201 HLV->addNewMBB(MBB);
202}
203
207
209 HLV->constructUseDef(MBB);
210}
211
213 auto &MDT = getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
214 auto &MPDT =
216 HLVComplete = !HLV->runOnMachineFunction(Fn, MDT, MPDT);
217 return HLVComplete;
218}
219
221 unsigned Reg) const {
222 assert(HLVComplete && "Liveness Analysis not available");
223 auto It = HLV->MBBLiveOuts.find(MBB);
224 if (It == HLV->MBBLiveOuts.end())
225 llvm_unreachable("MBB not found in liveness map");
226 if (Reg >= It->second.size())
227 llvm_unreachable("Register index out of bounds");
228 return It->second[Reg];
229}
230
231const BitVector &
233 assert(HLVComplete && "Liveness Analysis not available");
234 auto It = HLV->MBBLiveOuts.find(MBB);
235 if (It == HLV->MBBLiveOuts.end())
236 llvm_unreachable("MBB not found in liveness map");
237 return It->second;
238}
239
240// Returns true when \p Reg is used within [MIBegin, MIEnd)
241// @note: MIBegin and MIEnd should be from same MBB
242// @note: It returns just the first use found in the range.
243// The Use is closest to MIEnd.
244// Takes care of aliases and predicated defs as well.
246 MICInstIterType MIBegin, MICInstIterType MIEnd, unsigned Reg,
248 SmallPtrSet<MachineInstr *, 2> *ExceptionsList) const {
249 assert(HLVComplete && "Liveness Analysis not available");
250 Use = MIEnd;
251 if (MIBegin == MIEnd) // NULL Range.
252 return false;
253 MICInstIterType MII = MIEnd;
254 do {
255 --MII;
256 if (MII->isBundle() || MII->isDebugInstr())
257 continue;
258 if (ExceptionsList && ExceptionsList->contains(&*MII))
259 continue;
260 auto It = HLV->MIUseDefs.find(&*MII);
261 assert(It != HLV->MIUseDefs.end());
262 for (MCRegAliasIterator AI(Reg, HLV->TRI, true); AI.isValid(); ++AI)
263 if (It->second.first[*AI]) {
264 Use = MII;
265 return true;
266 }
267 } while (MII != MIBegin);
268 return false;
269}
270
271// Returns true when \p Reg id defined within [MIBegin, MIEnd)
272// @note: MIBegin and MIEnd should be from same MBB
273// The Def is closest to MIEnd.
274// Takes care of aliases and predicated defs as well.
276 MICInstIterType MIEnd, unsigned Reg,
277 MICInstIterType &Def) const {
278 assert(HLVComplete && "Liveness Analysis not available");
279 Def = MIEnd;
280 if (MIBegin == MIEnd) // NULL Range.
281 return false;
282 MICInstIterType MII = MIEnd;
283 do {
284 --MII;
285 if (MII->isBundle() || MII->isDebugInstr())
286 continue;
287 auto It = HLV->MIUseDefs.find(&*MII);
288 assert(It != HLV->MIUseDefs.end());
289 for (MCRegAliasIterator AI(Reg, HLV->TRI, true); AI.isValid(); ++AI)
290 if (It->second.second[*AI]) {
291 Def = MII;
292 return true;
293 }
294 } while (MII != MIBegin);
295 return false;
296}
297
298// Returns true if any of the defs of MII is live-in in the MBB.
300 const MachineBasicBlock *MBB) const {
301 assert(HLVComplete && "Liveness Analysis not available");
302 assert(MI && "Invalid machine instruction");
303 assert(MBB && "Invalid machine basic block");
304 auto It = HLV->MIUseDefs.find(MI);
305 assert(It != HLV->MIUseDefs.end() && "Missing MI use/def information");
306 BitVector MBBLiveIns(HLV->NumRegs);
307 for (MachineBasicBlock::livein_iterator lit = MBB->livein_begin();
308 lit != MBB->livein_end(); ++lit) {
309 // Include all the aliases of reg *lit.
310 for (MCRegAliasIterator AI((*lit).PhysReg, HLV->TRI, true); AI.isValid();
311 ++AI)
312 MBBLiveIns.set(*AI);
313 }
314 // Intersect.
315 return MBBLiveIns.anyCommon(It->second.second);
316}
317
319
321
323 const MachineBasicBlock *To,
324 unsigned BufferPerMBB) const {
325 assert(HLV->DistanceMap.find(From) != HLV->DistanceMap.end());
326 assert(HLV->DistanceMap.find(To) != HLV->DistanceMap.end());
327 unsigned FromSize = HLV->DistanceMap[From];
328 if (From == To)
329 return FromSize;
330 const MachineFunction *MF = From->getParent();
332 unsigned S = BufferPerMBB;
333 bool ToFirst = false;
334 while (MBBI != MF->end()) {
335 const MachineBasicBlock *MBB = &*MBBI;
336 if (MBB == From)
337 break;
338 else if (MBB == To) {
339 ToFirst = true;
340 break;
341 }
342 ++MBBI;
343 }
344 const MachineBasicBlock *ToFind = To;
345 if (ToFirst)
346 ToFind = From;
347 while (MBBI != MF->end()) {
348 const MachineBasicBlock *MBB = &*MBBI;
349 if (MBB == ToFind)
350 break;
351 S += HLV->DistanceMap[MBB] + BufferPerMBB;
352 ++MBBI;
353 }
354 if (ToFirst) // Jump in the opposite direction.
355 S += FromSize + HLV->DistanceMap[To] + 2 * BufferPerMBB;
356 return S;
357}
358
360 HLV->clearDistanceMap();
361 HLV->generateDistanceMap(Fn);
362}
363
364//===----------------------------------------------------------------------===//
365// HexagonLiveVariablesImpl Functions
366//===----------------------------------------------------------------------===//
367bool HexagonLiveVariablesImpl::runOnMachineFunction(
370 LLVM_DEBUG(dbgs() << "\nHexagon Live Variables";);
371 Fn.RenumberBlocks();
372
373 MRI = &Fn.getRegInfo();
374 auto &ST = Fn.getSubtarget<HexagonSubtarget>();
375 TRI = ST.getRegisterInfo();
376 QII = ST.getInstrInfo();
377
378 NumRegs = TRI->getNumRegs();
379
380 MBBUseDefs.clear();
381 MIUseDefs.clear();
382 MBBLiveOuts.clear();
383
384 LLVM_DEBUG(dbgs() << "\nNumber of registers in Hexagon is:" << NumRegs);
385
386 PhysRegDef.resize(NumRegs);
387 PhysRegUse.resize(NumRegs);
388
389 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end(); MBBI != E;
390 ++MBBI) {
391 constructUseDef(&*MBBI);
392 }
393 updateGlobalLiveness(Fn);
394 return false;
395}
396
397void HexagonLiveVariablesImpl::constructUseDef(MachineBasicBlock *MBB) {
398 std::fill(PhysRegDef.begin(), PhysRegDef.end(), (MachineInstr *)0);
399 std::fill(PhysRegUse.begin(), PhysRegUse.end(), (MachineInstr *)0);
400
401 // Loop over all of the instructions, processing them.
402 std::pair<BitVector, BitVector> &UseDef = MBBUseDefs[MBB];
403 // Use before any def in a BB.
404 BitVector &Uses = UseDef.first;
405 // Defs before any use in a BB.
406 BitVector &Defs = UseDef.second;
407 // Initializing the LiveOut bit vector.
408 BitVector &LiveOuts = MBBLiveOuts[MBB];
409 Uses.resize(NumRegs, false);
410 Defs.resize(NumRegs, false);
411 LiveOuts.resize(NumRegs, false);
412 // BitVector might contain set bits out of previous liveness updates.
413 Uses.reset();
414 Defs.reset();
415 LiveOuts.reset();
416 LLVM_DEBUG(dbgs() << "\nBB#" << MBB->getNumber(););
417 // MBB Number in the MSB 32 bits.
418 unsigned MBBInsSize = 0;
420 E = MBB->instr_end();
421 MII != E; ++MII) {
422 MachineInstr *MI = &*MII;
423 MBBInsSize += QII->getSize(*MI);
424 // TODO: Handle isDebugInstr
425 if (MI->isBundle() || MI->isDebugInstr())
426 continue;
427 LLVM_DEBUG(dbgs() << "\n\n" << *MI;);
428 // Clear kill and dead markers. LV will recompute them.
429 UseDef_t &MIUseDef = MIUseDefs[MI];
430 MIUseDef.first.resize(NumRegs); // Uses
431 MIUseDef.second.resize(NumRegs); // Defs
432 MIUseDef.first.reset(); // Uses
433 MIUseDef.second.reset(); // Defs
434
437 // Process all of the operands of the instruction...
438 unsigned NumOperandsToProcess = MI->getNumOperands();
439 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
440 MachineOperand &MO = MI->getOperand(i);
441 if (MO.isRegMask()) {
442 // Assuming that predicated defs are not defs, for now.
443 if (!QII->isPredicated(*MI))
444 DefRegs.push_back(&MO);
445 continue;
446 }
447 if (!MO.isReg() || MO.getReg() == 0)
448 continue;
449 unsigned Reg = MO.getReg();
450 if (MO.isUse()) {
451 // Assuming that the kill-flags on call-instructions are correct.
452 MO.setIsKill(false);
453 // Undef reads do not make a register live-in. Keep them in the MI
454 // uses so that scheduling still orders them conservatively.
455 if (!MO.isUndef())
456 UseRegs.push_back(&MO);
457 MIUseDef.first.set(Reg);
458 } else /*MO.isDef()*/ {
459 assert(MO.isDef());
460 if (!QII->isPredicated(*MI) && !MI->isKill()) {
461 // Assuming that predicated defs are not defs, for now.
462 // KILL instructions are no-ops
463 MO.setIsDead(false);
464 DefRegs.push_back(&MO);
465 }
466 MIUseDef.second.set(Reg); // Set all defs (including predicated).
467 }
468 }
469 // Process all uses.
470 for (unsigned i = 0, e = UseRegs.size(); i != e; ++i)
471 handlePhysRegUse(UseRegs[i], MI, Uses);
472 // Process all defs.
473 for (unsigned i = 0, e = DefRegs.size(); i != e; ++i)
474 handlePhysRegDef(DefRegs[i], MI, Defs);
475 }
476 DistanceMap[MBB] = MBBInsSize;
477}
478
479void HexagonLiveVariablesImpl::handlePhysRegUse(MachineOperand *MO,
481 BitVector &Uses) {
482 unsigned Reg = MO->getReg();
483 LLVM_DEBUG(dbgs() << "\nLooking at:";);
484 // If the reg/super-reg is already defined in this MBB => return.
485 for (MCSuperRegIterator SupI(Reg, TRI, true); SupI.isValid(); ++SupI) {
486 LLVM_DEBUG(dbgs() << printReg(*SupI, TRI););
487 if (PhysRegDef[*SupI])
488 return;
489 }
490 // Handle if sub-regs are defined.
491 SmallVector<unsigned, 2> undefSubRegs;
492 bool subRegDefined = false;
493 for (MCSubRegIterator SubI(Reg, TRI); SubI.isValid(); ++SubI) {
494 LLVM_DEBUG(dbgs() << printReg(*SubI, TRI););
495 if (PhysRegDef[*SubI])
496 subRegDefined = true;
497 else
498 undefSubRegs.push_back(*SubI);
499 }
500
501 LLVM_DEBUG(dbgs() << "\nUses:");
502 if (undefSubRegs.empty()) {
503 if (!subRegDefined) { // None of the subregs are defined.
504 // Include all subregs (including self) to the uses.
505 for (MCSubRegIterator SubI(Reg, TRI, true); SubI.isValid(); ++SubI) {
506 LLVM_DEBUG(dbgs() << printReg(*SubI, TRI));
507 PhysRegUse[*SubI] = MI;
508 Uses.set(*SubI);
509 }
510 } // All subregs defined.
511 return;
512 }
513 // Some subregs are defined.
514 for (unsigned i = 0; i < undefSubRegs.size(); ++i) {
515 LLVM_DEBUG(dbgs() << printReg(undefSubRegs[i], TRI));
516 PhysRegUse[undefSubRegs[i]] = MI;
517 Uses.set(undefSubRegs[i]);
518 }
519}
520
521// Assumes that an MI cannot have a reg and its super/sub reg as uses.
522void HexagonLiveVariablesImpl::handlePhysRegDef(MachineOperand *MO,
524 BitVector &Defs) {
525 auto SetRegDef = [&](unsigned Reg) -> void {
526 PhysRegDef[Reg] = MI;
527 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
528 if (PhysRegUse[*AI]) {
529 LLVM_DEBUG(dbgs() << "\nUsed in current BB:" << printReg(*AI, TRI));
530 return;
531 }
532 }
533 LLVM_DEBUG(dbgs() << "\nDefs:" << printReg(Reg, TRI));
534 Defs.set(Reg);
535 };
536
537 if (MO->isReg()) {
538 SetRegDef(MO->getReg());
539 } else if (MO->isRegMask()) {
540 for (unsigned R = 1, NR = TRI->getNumRegs(); R != NR; ++R)
541 if (MO->clobbersPhysReg(R))
542 SetRegDef(R);
543 }
544}
545
546namespace {
547struct BlockState {
548 bool SuccQueued : 1;
549 bool Done : 1;
550 BlockState() : SuccQueued(false), Done(false) {}
551};
552} // namespace
553
554// Populates 'Blocks' with basic blocks of 'Fn' in depth-first order
557 Blocks->clear();
558 Blocks->reserve(Fn.size());
559
562 WorkStack.push_back(&Fn.front());
563 while (!WorkStack.empty()) {
564 MachineBasicBlock *W = WorkStack.back();
565 BlockState &WState = State[W->getNumber()];
566 if (WState.Done) {
567 WorkStack.pop_back();
568 continue;
569 }
570 if (W->succ_empty() || WState.SuccQueued) {
571 WorkStack.pop_back();
572 Blocks->push_back(W);
573 WState.SuccQueued = true;
574 WState.Done = true;
575 continue;
576 }
577 WState.SuccQueued = true;
578 for (MachineBasicBlock::succ_iterator I = W->succ_begin(),
579 E = W->succ_end();
580 I != E; ++I) {
581 MachineBasicBlock *S = *I;
582 if (State[S->getNumber()].SuccQueued)
583 continue;
584 WorkStack.push_back(S);
585 }
586 }
587
589 dbgs() << "gatherBlocksDF: {";
591 BE = Blocks->end();
592 B != BE; ++B) { dbgs() << " BB#" << (*B)->getNumber(); } dbgs()
593 << " }\n";);
594}
595
596bool HexagonLiveVariablesImpl::updateGlobalLiveness(MachineFunction &Fn) {
597 bool Changed = false;
598 // Removing live-ins and recomputing.
599 MachineFunction::iterator I = Fn.begin(), E = Fn.end();
600 // Not touching the live-ins of entry basic block.
601 for (++I; I != E; ++I) {
602 std::vector<MachineBasicBlock::RegisterMaskPair> OldLiveIn(
603 I->livein_begin(), I->livein_end());
604 for (unsigned i = 0; i < OldLiveIn.size(); ++i)
605 I->removeLiveIn(OldLiveIn[i].PhysReg);
606 }
607
608 gatherBlocksDF(Fn, &BlocksDepthFirst);
609
610 BitVector Defs;
611 BitVector LiveIns;
612 bool Repeat;
613 do {
614 Repeat = false;
616 B = BlocksDepthFirst.begin(),
617 BE = BlocksDepthFirst.end();
618 B != BE; ++B) {
619 Repeat |= updateGlobalLiveness(*B, Defs, LiveIns);
620 }
621 Changed |= Repeat;
622 } while (Repeat);
623
624 Changed |= updateLocalLiveness(Fn);
625 return Changed;
626}
627
628bool HexagonLiveVariablesImpl::updateGlobalLiveness(MachineBasicBlock *X,
630 assert(X && "Invalid start block");
631 assert(Y && "Invalid end block");
632
633 bool Changed = false;
634 BitVector Defs;
635 BitVector LiveIns;
636
638 BlocksDepthFirst.end();
640 for (B = BlocksDepthFirst.begin(); (B != BE); ++B) {
641 if (*B == X)
642 break;
643 if (*B == Y)
644 break;
645 }
646
647 bool Repeat;
648 do {
649 Repeat = false;
650 for (; B != BE; ++B)
651 Repeat |= updateGlobalLiveness(*B, Defs, LiveIns);
652 Changed |= Repeat;
653 B = BlocksDepthFirst.begin();
654 } while (Repeat);
655
656 return Changed;
657}
658
659// Defs and LiveIns could be local variables within updateGlobalLiveness, but
660// have been pulled out to (hopefully) improve performance.
661bool HexagonLiveVariablesImpl::updateGlobalLiveness(MachineBasicBlock *MBB,
662 BitVector &Defs,
663 BitVector &LiveIns) {
664 LLVM_DEBUG(dbgs() << "\nTrying to Update Liveness MBB#" << MBB->getNumber());
665 bool Changed = false;
666 LLVM_DEBUG(dbgs() << "\nUpdating Liveness MBB#" << MBB->getNumber());
667 // Update live-outs
668 auto LiveOutIt = MBBLiveOuts.find(MBB);
669 if (LiveOutIt == MBBLiveOuts.end())
670 LiveOutIt = MBBLiveOuts.insert({MBB, BitVector(NumRegs)}).first;
671 BitVector &LiveOuts = LiveOutIt->second;
673 MBBSucc != MBB->succ_end(); ++MBBSucc) {
674 MachineBasicBlock *Succ = *MBBSucc;
675 LLVM_DEBUG(dbgs() << "\n\t\tAdding LiveOut:";);
677 LE = Succ->livein_end();
678 LI != LE; ++LI) {
679 if (!LiveOuts[(*LI).PhysReg]) {
680 LLVM_DEBUG(dbgs() << " " << printReg((*LI).PhysReg, TRI););
681 LiveOuts.set((*LI).PhysReg);
682 Changed = true;
683 }
684 }
685 }
686 LLVM_DEBUG(dbgs() << "\nUpdated Successors of MBB#" << MBB->getNumber());
687 // Update live-ins
688 Changed |= updateLiveIns(MBB, LiveIns, LiveOuts);
689
690 return Changed;
691}
692
693// update live-ins when live-out has been calculated
694bool HexagonLiveVariablesImpl::updateLiveIns(MachineBasicBlock *MBB,
695 BitVector &LiveIns,
696 const BitVector &LiveOuts) {
697 LLVM_DEBUG(dbgs() << "\n[updateLiveIns] MBB#" << MBB->getNumber());
698 bool Changed = false;
699 const std::pair<BitVector, BitVector> &UseDefs = MBBUseDefs[MBB];
700 LiveIns = LiveOuts;
701 // LiveIns = (LiveOuts - Defs) | Uses
702 // Equivalent to: LiveIns = (LiveOuts & ~Defs) | Uses
703 LiveIns.reset(UseDefs.second);
704 LiveIns |= UseDefs.first;
705 LLVM_DEBUG(dbgs() << "\n\t\tAdded LiveIn:";);
706 for (int i = LiveIns.find_first(); i >= 0; i = LiveIns.find_next(i)) {
707 // TODO: remove costly check of MBB->isLiveIn when fully functional.
708 if (!MBB->isLiveIn(i) && MRI->isAllocatable(i)) {
709 LLVM_DEBUG(dbgs() << " " << printReg(i, TRI));
710 MBB->addLiveIn(i);
711 Changed = true;
712 }
713 }
714 return Changed;
715}
716
717bool HexagonLiveVariablesImpl::updateLiveOuts(MachineBasicBlock *MBB,
718 BitVector &LiveOuts) {
719 bool Changed = false;
720 for (auto SI = MBB->succ_begin(), SE = MBB->succ_end(); SI != SE; ++SI) {
721 MachineBasicBlock *SB = *SI;
722 for (auto I = SB->livein_begin(), E = SB->livein_end(); I != E; ++I) {
723 unsigned R = (*I).PhysReg;
724 if (LiveOuts[R])
725 continue;
726 LiveOuts.set(R);
727 Changed = true;
728 }
729 }
730 return Changed;
731}
732
733bool HexagonLiveVariablesImpl::updateLocalLiveness(MachineFunction &Fn) {
734 LLVM_DEBUG(dbgs() << "\n[updateLocalLiveness]");
735 for (MachineFunction::iterator B = Fn.begin(), E = Fn.end(); B != E; ++B)
736 updateLocalLiveness(&*B, false);
737 return true;
738}
739
740bool HexagonLiveVariablesImpl::updateLocalLiveness(MachineBasicBlock *MBB,
741 bool UpdateBundle) {
742 assert(MBB && "Invalid basic block");
743 LLVM_DEBUG(dbgs() << "\n[updateLocalLiveness] MBB#" << MBB->getNumber());
744
745 BitVector &LiveOut = MBBLiveOuts[MBB];
746 updateLiveOuts(MBB, LiveOut);
747
748 BitVector Used = LiveOut;
750 // Bottom up traversal of MBB.
752 MIREnd = MBB->instr_rend();
753 MII != MIREnd; ++MII) {
754 MachineInstr *MI = &*MII;
755 // The bundle liveness is updated differently.
756 if (MI->isBundle()) {
757 if (UpdateBundle)
758 BundleHeads.push_back(MI);
759 continue;
760 }
761 if (MI->isDebugInstr()) // DBG_VALUE may have invalid reg.
762 continue;
765 for (unsigned i = 0; i < MI->getNumOperands(); ++i) {
766 MachineOperand &MO = MI->getOperand(i);
767 if (MO.isReg()) { // DBG_VALUE may have invalid reg.
768 if (MO.isUse()) {
769 if (!MO.isUndef())
770 UseRegs.push_back(&MO);
771 } else { // Def
772 if (!QII->isPredicated(*MI) && !MI->isKill()) {
773 // Assuming that predicated defs are not defs, for now.
774 // KILL instructions are no-ops
775 DefRegs.push_back(&MO);
776 }
777 }
778 } else if (MO.isRegMask()) {
779 if (!QII->isPredicated(*MI))
780 DefRegs.push_back(&MO);
781 }
782 }
783 // In case of a def. remove Reg and its sub-regs from Used list
784 // such that uses in the same MI can be marked as kill.
785 auto RemoveDef = [&](unsigned Reg, bool Implicit) -> void {
786 for (MCSubRegIterator SI(Reg, TRI, true); SI.isValid(); ++SI) {
787 Used.reset(*SI);
788 if (Implicit) {
789 // For implicit defs, check if there is an implicit use of an
790 // aliased register. If so, mark the aliased reg as used.
791 for (auto *UseOp : UseRegs)
792 if (UseOp->isImplicit() && TRI->regsOverlap(*SI, UseOp->getReg()))
793 Used.set(UseOp->getReg());
794 }
795 }
796 };
797 for (unsigned i = 0; i < DefRegs.size(); ++i) {
798 MachineOperand &MO = *DefRegs[i];
799 if (MO.isReg()) {
800 RemoveDef(MO.getReg(), MO.isImplicit());
801 } else if (MO.isRegMask()) {
802 for (unsigned R = 1, NR = TRI->getNumRegs(); R != NR; ++R)
803 if (MO.clobbersPhysReg(R))
804 RemoveDef(R, true);
805 }
806 }
807 // The order is important as we are looking from right to left.
808 for (unsigned i = UseRegs.size(); i > 0;) {
809 --i;
810 unsigned UseReg = UseRegs[i]->getReg();
811 bool Killed = true;
812 for (MCRegAliasIterator AI(UseReg, TRI, true); AI.isValid(); ++AI) {
813 if (Used[*AI])
814 Killed = false;
815 }
816 Used.set(UseReg);
817 if (Killed && !UseRegs[i]->isDebug())
818 UseRegs[i]->setIsKill(true);
819 }
820 }
821 // Recreates bundle for updating liveness.
822 for (SmallVectorImpl<MachineInstr *>::iterator MII = BundleHeads.begin();
823 MII != BundleHeads.end(); ++MII) {
824 MachineInstr *MI = *MII;
825 assert(MI && "Invalid bundle head");
826 assert(MI->isBundle() && "Expected a bundle head instruction");
827 assert(MI->getParent() == MBB && "Bundle head not in expected block");
828 MachineBasicBlock::instr_iterator BS = MI->getIterator();
830 for (++BS; BS != BE; ++BS)
831 // Remove from bundle so that BUNDLE head can be erased.
832 BS->unbundleFromPred();
833
834 BS = MI->getIterator();
835 ++BS;
836 bool memShufDisabled = QII->getBundleNoShuf(*MI);
837 MI->eraseFromParent();
838 finalizeBundle(*MBB, BS, BE);
839 MachineBasicBlock::instr_iterator BundleMII = std::prev(BS);
840 if (memShufDisabled)
841 QII->setBundleNoShuf(BundleMII);
842 }
843 return true;
844}
845
846// It deletes the live-in of the \p From MBB.
847bool HexagonLiveVariablesImpl::incrementalUpdate(MICInstIterType MIDelta,
848 MachineBasicBlock *From,
849 MachineBasicBlock *To) {
850 while (!From->livein_empty())
851 From->removeLiveIn((*From->livein_begin()).PhysReg);
852 // Handle MI use-def of From.
853 constructUseDef(From);
854 // Handle MI use-def of To.
855 constructUseDef(To);
856 // Calculate live-in of From and To
857 // Reuse this by setting all MBBs except From and To as visited.
858 updateGlobalLiveness(From, To);
859 // Update local liveness of To.
860 updateLocalLiveness(From, true);
861 updateLocalLiveness(To, true);
862
863 // Do this after the liveness update because MIDelta might not be in the
864 // MIUseDefs before liveness update (since MIDelta might be newly inserted).
865 MIUseDef_t::const_iterator MIUseDef = MIUseDefs.find(&*MIDelta);
866 if (MIUseDef == MIUseDefs.end())
867 llvm_unreachable("MIDelta not found in MIUseDefs after liveness update");
868 const BitVector &Defs = MIUseDef->second.second;
869 int Reg = Defs.find_first();
870 // Adding all the defs as live-ins. This is conservative approach but we
871 // need to add them so as to avoid dealing with callee saved registers and
872 // any unwanted errors in liveness that might arise.
873 while (Reg >= 0) {
874 From->addLiveIn(Reg);
875 Reg = Defs.find_next(Reg);
876 }
877 return true;
878}
879
880void HexagonLiveVariablesImpl::addNewMBB(MachineBasicBlock *MBB) {
881 // Resize and init.
882 constructUseDef(MBB); // This is to set up some containers for MBB.
883 gatherBlocksDF(*MBB->getParent(), &BlocksDepthFirst);
884 updateGlobalLiveness(MBB, MBB);
885}
886
887// TODO: This is a slow implementation because constructUseDef destroys
888// the MBBLiveOuts which is generated again by updateGlobalLiveness.
889void HexagonLiveVariablesImpl::addNewMI(MachineInstr *MI,
891 constructUseDef(MBB); // This is to set up some containers for MBB.
892 updateGlobalLiveness(MBB, MBB);
893}
894
895void HexagonLiveVariablesImpl::generateDistanceMap(const MachineFunction &Fn) {
896 assert(DistanceMap.empty() && "DistanceMap not empty, first clear!");
897 for (MachineFunction::const_iterator MBBI = Fn.begin(), E = Fn.end();
898 MBBI != E; ++MBBI) {
899 const MachineBasicBlock *MBB = &*MBBI;
900 unsigned MBBInsSize = 0;
902 E = MBB->instr_end();
903 MII != E; ++MII) {
904 const MachineInstr *MI = &*MII;
905 MBBInsSize += QII->getSize(*MI);
906 }
907 DistanceMap[MBB] = MBBInsSize;
908 }
909}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator MBBI
Function Alias Analysis false
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static Register UseReg(const MachineOperand &MO)
static bool isDebug()
static void UpdateBundle(MachineInstr *BundleHead)
static void gatherBlocksDF(MachineFunction &Fn, SmallVectorImpl< MachineBasicBlock * > *Blocks)
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
MachineRegisterInfo & MRI
Remove Loads Into Fake Uses
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
BitVector & reset()
Reset all bits in the bitvector.
Definition BitVector.h:410
int find_first() const
Returns the index of the first set bit, -1 if none of the bits are set.
Definition BitVector.h:318
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
Definition BitVector.h:356
bool anyCommon(const BitVector &RHS) const
Test if any common bits are set.
Definition BitVector.h:529
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:367
int find_next(unsigned Prev) const
Returns the index of the next set bit following the "Prev" bit.
Definition BitVector.h:325
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT, true > const_iterator
Definition DenseMap.h:679
MachineBasicBlock::const_instr_iterator MICInstIterType
void recalculate(MachineFunction &MF)
recalculate - recalculates the liveness from scratch.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void constructUseDef(MachineBasicBlock *MBB)
Constructs use-defs of MBB by analyzing each MachineOperand.
unsigned getDistanceBetween(const MachineBasicBlock *From, const MachineBasicBlock *To, unsigned BufferPerMBB=HEXAGON_INSTR_SIZE) const
Returns the linear distance (as per layout) of MI from the Function.
bool isUsedWithin(MICInstIterType MIBegin, MICInstIterType MIEnd, unsigned Reg, MICInstIterType &Use, SmallPtrSet< MachineInstr *, 2 > *ExceptionsList=nullptr) const
bool incrementalUpdate(MICInstIterType MIDelta, MachineBasicBlock *From, MachineBasicBlock *To)
incrementalUpdate - update the liveness when MIDelta is moved from From to To.
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
bool updateLocalLiveness(MachineFunction &Fn)
updateLocalLiveness - update only kill flags of operands.
const BitVector & getLiveOuts(const MachineBasicBlock *MBB) const
bool isDefLiveIn(const MachineInstr *MI, const MachineBasicBlock *MBB) const
void regenerateDistanceMap(const MachineFunction &Fn)
void addNewMBB(MachineBasicBlock *MBB)
addNewMBB - inform the LiveVariable Analysis that new MBB has been added.
bool isLiveOut(const MachineBasicBlock *MBB, unsigned Reg) const
bool isDefinedWithin(MICInstIterType MIBegin, MICInstIterType MIEnd, unsigned Reg, MICInstIterType &Def) const
void addNewMI(MachineInstr *MI, MachineBasicBlock *MBB)
MCRegAliasIterator enumerates all registers aliasing Reg.
MCSubRegIterator enumerates all sub-registers of Reg.
bool isValid() const
Returns true if this iterator is not yet at the end.
MCSuperRegIterator enumerates all super-registers of Reg.
bool isValid() const
Returns true if this iterator is not yet at the end.
livein_iterator livein_end() const
reverse_instr_iterator instr_rbegin()
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
LLVM_ABI void removeLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll())
Remove the specified register from the live in set.
LiveInVector::const_iterator livein_iterator
LLVM_ABI livein_iterator livein_begin() const
SmallVectorImpl< MachineBasicBlock * >::iterator succ_iterator
reverse_instr_iterator instr_rend()
Instructions::iterator instr_iterator
Instructions::const_iterator const_instr_iterator
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI bool isLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
Instructions::reverse_iterator reverse_instr_iterator
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
BasicBlockListType::iterator iterator
void RenumberBlocks(MachineBasicBlock *MBBFrom=nullptr)
RenumberBlocks - This discards all of the MachineBasicBlock numbers and recomputes them.
const MachineBasicBlock & front() const
BasicBlockListType::const_iterator const_iterator
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
void setIsDead(bool Val=true)
void setIsKill(bool Val=true)
Register getReg() const
getReg - Returns the register number.
static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
MachinePostDominatorTree - an analysis pass wrapper for DominatorTree used to compute the post-domina...
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
bool isAllocatable(MCRegister PhysReg) const
isAllocatable - Returns true when PhysReg belongs to an allocatable register class and it hasn't been...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
typename SuperClass::iterator iterator
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI void finalizeBundle(MachineBasicBlock &MBB, MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
finalizeBundle - Finalize a machine instruction bundle which includes a sequence of instructions star...
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Done
Definition Threading.h:60
char & HexagonLiveVariablesID
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
MachineBasicBlock::instr_iterator getBundleEnd(MachineBasicBlock::instr_iterator I)
Returns an iterator pointing beyond the bundle containing I.
DenseMap< MachineBasicBlock *, UseDef_t > MBBUseDef_t
void initializeHexagonLiveVariablesPass(PassRegistry &)
std::pair< BitVector, BitVector > UseDef_t
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
DenseMap< const MachineInstr *, UseDef_t > MIUseDef_t
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879