LLVM 22.0.0git
PHIElimination.cpp
Go to the documentation of this file.
1//===- PhiElimination.cpp - Eliminate PHI nodes by inserting copies -------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass eliminates machine instruction PHI nodes by inserting copy
10// instructions. This destroys SSA information, but is the desired input for
11// some register allocators.
12//
13//===----------------------------------------------------------------------===//
14
16#include "PHIEliminationUtils.h"
17#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/Statistic.h"
40#include "llvm/Pass.h"
42#include "llvm/Support/Debug.h"
44#include <cassert>
45#include <iterator>
46#include <utility>
47
48using namespace llvm;
49
50#define DEBUG_TYPE "phi-node-elimination"
51
52static cl::opt<bool>
53 DisableEdgeSplitting("disable-phi-elim-edge-splitting", cl::init(false),
55 cl::desc("Disable critical edge splitting "
56 "during PHI elimination"));
57
58static cl::opt<bool>
59 SplitAllCriticalEdges("phi-elim-split-all-critical-edges", cl::init(false),
61 cl::desc("Split all critical edges during "
62 "PHI elimination"));
63
65 "no-phi-elim-live-out-early-exit", cl::init(false), cl::Hidden,
66 cl::desc("Do not use an early exit if isLiveOutPastPHIs returns true."));
67
68namespace {
69
70class PHIEliminationImpl {
71 MachineRegisterInfo *MRI = nullptr; // Machine register information
72 LiveVariables *LV = nullptr;
73 LiveIntervals *LIS = nullptr;
74 MachineLoopInfo *MLI = nullptr;
75 MachineDominatorTree *MDT = nullptr;
76 MachinePostDominatorTree *PDT = nullptr;
77
78 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
79 /// in predecessor basic blocks.
80 bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
81
82 void LowerPHINode(MachineBasicBlock &MBB,
84 bool AllEdgesCritical);
85
86 /// analyzePHINodes - Gather information about the PHI nodes in
87 /// here. In particular, we want to map the number of uses of a virtual
88 /// register which is used in a PHI node. We map that to the BB the
89 /// vreg is coming from. This is used later to determine when the vreg
90 /// is killed in the BB.
91 void analyzePHINodes(const MachineFunction &MF);
92
93 /// Split critical edges where necessary for good coalescer performance.
94 bool SplitPHIEdges(MachineFunction &MF, MachineBasicBlock &MBB,
95 MachineLoopInfo *MLI,
96 std::vector<SparseBitVector<>> *LiveInSets,
98
99 // These functions are temporary abstractions around LiveVariables and
100 // LiveIntervals, so they can go away when LiveVariables does.
101 bool isLiveIn(Register Reg, const MachineBasicBlock *MBB);
102 bool isLiveOutPastPHIs(Register Reg, const MachineBasicBlock *MBB);
103
104 using BBVRegPair = std::pair<unsigned, Register>;
105 using VRegPHIUse = DenseMap<BBVRegPair, unsigned>;
106
107 // Count the number of non-undef PHI uses of each register in each BB.
108 VRegPHIUse VRegPHIUseCount;
109
110 // Defs of PHI sources which are implicit_def.
112
113 // Map reusable lowered PHI node -> incoming join register.
114 using LoweredPHIMap =
116 LoweredPHIMap LoweredPHIs;
117
118 MachineFunctionPass *P = nullptr;
119 MachineFunctionAnalysisManager *MFAM = nullptr;
120
121public:
122 PHIEliminationImpl(MachineFunctionPass *P) : P(P) {
123 auto *LVWrapper = P->getAnalysisIfAvailable<LiveVariablesWrapperPass>();
124 auto *LISWrapper = P->getAnalysisIfAvailable<LiveIntervalsWrapperPass>();
125 auto *MLIWrapper = P->getAnalysisIfAvailable<MachineLoopInfoWrapperPass>();
126 auto *MDTWrapper =
127 P->getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
128 auto *PDTWrapper =
129 P->getAnalysisIfAvailable<MachinePostDominatorTreeWrapperPass>();
130 LV = LVWrapper ? &LVWrapper->getLV() : nullptr;
131 LIS = LISWrapper ? &LISWrapper->getLIS() : nullptr;
132 MLI = MLIWrapper ? &MLIWrapper->getLI() : nullptr;
133 MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
134 PDT = PDTWrapper ? &PDTWrapper->getPostDomTree() : nullptr;
135 }
136
137 PHIEliminationImpl(MachineFunction &MF, MachineFunctionAnalysisManager &AM)
138 : LV(AM.getCachedResult<LiveVariablesAnalysis>(MF)),
139 LIS(AM.getCachedResult<LiveIntervalsAnalysis>(MF)),
140 MLI(AM.getCachedResult<MachineLoopAnalysis>(MF)),
141 MDT(AM.getCachedResult<MachineDominatorTreeAnalysis>(MF)),
142 PDT(AM.getCachedResult<MachinePostDominatorTreeAnalysis>(MF)),
143 MFAM(&AM) {}
144
145 bool run(MachineFunction &MF);
146};
147
148class PHIElimination : public MachineFunctionPass {
149public:
150 static char ID; // Pass identification, replacement for typeid
151
152 PHIElimination() : MachineFunctionPass(ID) {
154 }
155
156 bool runOnMachineFunction(MachineFunction &MF) override {
157 PHIEliminationImpl Impl(this);
158 return Impl.run(MF);
159 }
160
161 MachineFunctionProperties getSetProperties() const override {
162 return MachineFunctionProperties().setNoPHIs();
163 }
164
165 void getAnalysisUsage(AnalysisUsage &AU) const override;
166};
167
168} // end anonymous namespace
169
173 PHIEliminationImpl Impl(MF, MFAM);
174 bool Changed = Impl.run(MF);
175 if (!Changed)
176 return PreservedAnalyses::all();
178 PA.preserve<LiveIntervalsAnalysis>();
179 PA.preserve<LiveVariablesAnalysis>();
180 PA.preserve<SlotIndexesAnalysis>();
181 PA.preserve<MachineDominatorTreeAnalysis>();
183 PA.preserve<MachineLoopAnalysis>();
184 return PA;
185}
186
187STATISTIC(NumLowered, "Number of phis lowered");
188STATISTIC(NumCriticalEdgesSplit, "Number of critical edges split");
189STATISTIC(NumReused, "Number of reused lowered phis");
190
191char PHIElimination::ID = 0;
192
193char &llvm::PHIEliminationID = PHIElimination::ID;
194
196 "Eliminate PHI nodes for register allocation", false,
197 false)
200 "Eliminate PHI nodes for register allocation", false, false)
201
202void PHIElimination::getAnalysisUsage(AnalysisUsage &AU) const {
203 AU.addUsedIfAvailable<LiveVariablesWrapperPass>();
204 AU.addUsedIfAvailable<MachineLoopInfoWrapperPass>();
205 AU.addPreserved<LiveVariablesWrapperPass>();
206 AU.addPreserved<SlotIndexesWrapperPass>();
207 AU.addPreserved<LiveIntervalsWrapperPass>();
208 AU.addPreserved<MachineDominatorTreeWrapperPass>();
209 AU.addPreserved<MachinePostDominatorTreeWrapperPass>();
210 AU.addPreserved<MachineLoopInfoWrapperPass>();
212}
213
214bool PHIEliminationImpl::run(MachineFunction &MF) {
215 MRI = &MF.getRegInfo();
216
217 MachineDomTreeUpdater MDTU(MDT, PDT,
218 MachineDomTreeUpdater::UpdateStrategy::Lazy);
219
220 bool Changed = false;
221
222 // Split critical edges to help the coalescer.
223 if (!DisableEdgeSplitting && (LV || LIS)) {
224 // A set of live-in regs for each MBB which is used to update LV
225 // efficiently also with large functions.
226 std::vector<SparseBitVector<>> LiveInSets;
227 if (LV) {
228 LiveInSets.resize(MF.size());
229 for (unsigned Index = 0, e = MRI->getNumVirtRegs(); Index != e; ++Index) {
230 // Set the bit for this register for each MBB where it is
231 // live-through or live-in (killed).
232 Register VirtReg = Register::index2VirtReg(Index);
233 MachineInstr *DefMI = MRI->getVRegDef(VirtReg);
234 if (!DefMI)
235 continue;
236 LiveVariables::VarInfo &VI = LV->getVarInfo(VirtReg);
237 SparseBitVector<>::iterator AliveBlockItr = VI.AliveBlocks.begin();
238 SparseBitVector<>::iterator EndItr = VI.AliveBlocks.end();
239 while (AliveBlockItr != EndItr) {
240 unsigned BlockNum = *(AliveBlockItr++);
241 LiveInSets[BlockNum].set(Index);
242 }
243 // The register is live into an MBB in which it is killed but not
244 // defined. See comment for VarInfo in LiveVariables.h.
245 MachineBasicBlock *DefMBB = DefMI->getParent();
246 if (VI.Kills.size() > 1 ||
247 (!VI.Kills.empty() && VI.Kills.front()->getParent() != DefMBB))
248 for (auto *MI : VI.Kills)
249 LiveInSets[MI->getParent()->getNumber()].set(Index);
250 }
251 }
252
253 for (auto &MBB : MF)
254 Changed |=
255 SplitPHIEdges(MF, MBB, MLI, (LV ? &LiveInSets : nullptr), MDTU);
256 }
257
258 // This pass takes the function out of SSA form.
259 MRI->leaveSSA();
260
261 // Populate VRegPHIUseCount
262 if (LV || LIS)
263 analyzePHINodes(MF);
264
265 // Eliminate PHI instructions by inserting copies into predecessor blocks.
266 for (auto &MBB : MF)
267 Changed |= EliminatePHINodes(MF, MBB);
268
269 // Remove dead IMPLICIT_DEF instructions.
270 for (MachineInstr *DefMI : ImpDefs) {
271 Register DefReg = DefMI->getOperand(0).getReg();
272 if (MRI->use_nodbg_empty(DefReg)) {
273 if (LIS)
276 }
277 }
278
279 // Clean up the lowered PHI instructions.
280 for (auto &I : LoweredPHIs) {
281 if (LIS)
282 LIS->RemoveMachineInstrFromMaps(*I.first);
283 MF.deleteMachineInstr(I.first);
284 }
285
286 LoweredPHIs.clear();
287 ImpDefs.clear();
288 VRegPHIUseCount.clear();
289
290 MF.getProperties().setNoPHIs();
291
292 return Changed;
293}
294
295/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
296/// predecessor basic blocks.
297bool PHIEliminationImpl::EliminatePHINodes(MachineFunction &MF,
299 if (MBB.empty() || !MBB.front().isPHI())
300 return false; // Quick exit for basic blocks without PHIs.
301
302 // Get an iterator to the last PHI node.
304 std::prev(MBB.SkipPHIsAndLabels(MBB.begin()));
305
306 // If all incoming edges are critical, we try to deduplicate identical PHIs so
307 // that we generate fewer copies. If at any edge is non-critical, we either
308 // have less than two predecessors (=> no PHIs) or a predecessor has only us
309 // as a successor (=> identical PHI node can't occur in different block).
310 bool AllEdgesCritical = MBB.pred_size() >= 2;
311 for (MachineBasicBlock *Pred : MBB.predecessors()) {
312 if (Pred->succ_size() < 2) {
313 AllEdgesCritical = false;
314 break;
315 }
316 }
317
318 while (MBB.front().isPHI())
319 LowerPHINode(MBB, LastPHIIt, AllEdgesCritical);
320
321 return true;
322}
323
324/// Return true if all defs of VirtReg are implicit-defs.
325/// This includes registers with no defs.
326static bool isImplicitlyDefined(Register VirtReg,
327 const MachineRegisterInfo &MRI) {
328 for (MachineInstr &DI : MRI.def_instructions(VirtReg))
329 if (!DI.isImplicitDef())
330 return false;
331 return true;
332}
333
334/// Return true if all sources of the phi node are implicit_def's, or undef's.
335static bool allPhiOperandsUndefined(const MachineInstr &MPhi,
336 const MachineRegisterInfo &MRI) {
337 for (unsigned I = 1, E = MPhi.getNumOperands(); I != E; I += 2) {
338 const MachineOperand &MO = MPhi.getOperand(I);
339 if (!isImplicitlyDefined(MO.getReg(), MRI) && !MO.isUndef())
340 return false;
341 }
342 return true;
343}
344/// LowerPHINode - Lower the PHI node at the top of the specified block.
345void PHIEliminationImpl::LowerPHINode(MachineBasicBlock &MBB,
347 bool AllEdgesCritical) {
348 ++NumLowered;
349
350 MachineBasicBlock::iterator AfterPHIsIt = std::next(LastPHIIt);
351
352 // Unlink the PHI node from the basic block, but don't delete the PHI yet.
353 MachineInstr *MPhi = MBB.remove(&*MBB.begin());
354
355 unsigned NumSrcs = (MPhi->getNumOperands() - 1) / 2;
356 Register DestReg = MPhi->getOperand(0).getReg();
357 assert(MPhi->getOperand(0).getSubReg() == 0 && "Can't handle sub-reg PHIs");
358 bool isDead = MPhi->getOperand(0).isDead();
359
360 // Create a new register for the incoming PHI arguments.
362 Register IncomingReg;
363 bool EliminateNow = true; // delay elimination of nodes in LoweredPHIs
364 bool reusedIncoming = false; // Is IncomingReg reused from an earlier PHI?
365
366 // Insert a register to register copy at the top of the current block (but
367 // after any remaining phi nodes) which copies the new incoming register
368 // into the phi node destination.
369 MachineInstr *PHICopy = nullptr;
371 if (allPhiOperandsUndefined(*MPhi, *MRI))
372 // If all sources of a PHI node are implicit_def or undef uses, just emit an
373 // implicit_def instead of a copy.
374 PHICopy = BuildMI(MBB, AfterPHIsIt, MPhi->getDebugLoc(),
375 TII->get(TargetOpcode::IMPLICIT_DEF), DestReg);
376 else {
377 // Can we reuse an earlier PHI node? This only happens for critical edges,
378 // typically those created by tail duplication. Typically, an identical PHI
379 // node can't occur, so avoid hashing/storing such PHIs, which is somewhat
380 // expensive.
381 Register *Entry = nullptr;
382 if (AllEdgesCritical)
383 Entry = &LoweredPHIs[MPhi];
384 if (Entry && *Entry) {
385 // An identical PHI node was already lowered. Reuse the incoming register.
386 IncomingReg = *Entry;
387 reusedIncoming = true;
388 ++NumReused;
389 LLVM_DEBUG(dbgs() << "Reusing " << printReg(IncomingReg) << " for "
390 << *MPhi);
391 } else {
392 const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(DestReg);
393 IncomingReg = MF.getRegInfo().createVirtualRegister(RC);
394 if (Entry) {
395 EliminateNow = false;
396 *Entry = IncomingReg;
397 }
398 }
399
400 // Give the target possiblity to handle special cases fallthrough otherwise
401 PHICopy = TII->createPHIDestinationCopy(
402 MBB, AfterPHIsIt, MPhi->getDebugLoc(), IncomingReg, DestReg);
403 }
404
405 if (MPhi->peekDebugInstrNum()) {
406 // If referred to by debug-info, store where this PHI was.
408 unsigned ID = MPhi->peekDebugInstrNum();
409 auto P = MachineFunction::DebugPHIRegallocPos(&MBB, IncomingReg, 0);
410 auto Res = MF->DebugPHIPositions.insert({ID, P});
411 assert(Res.second);
412 (void)Res;
413 }
414
415 // Update live variable information if there is any.
416 if (LV) {
417 if (IncomingReg) {
418 LiveVariables::VarInfo &VI = LV->getVarInfo(IncomingReg);
419
420 MachineInstr *OldKill = nullptr;
421 bool IsPHICopyAfterOldKill = false;
422
423 if (reusedIncoming && (OldKill = VI.findKill(&MBB))) {
424 // Calculate whether the PHICopy is after the OldKill.
425 // In general, the PHICopy is inserted as the first non-phi instruction
426 // by default, so it's before the OldKill. But some Target hooks for
427 // createPHIDestinationCopy() may modify the default insert position of
428 // PHICopy.
429 for (auto I = MBB.SkipPHIsAndLabels(MBB.begin()), E = MBB.end(); I != E;
430 ++I) {
431 if (I == PHICopy)
432 break;
433
434 if (I == OldKill) {
435 IsPHICopyAfterOldKill = true;
436 break;
437 }
438 }
439 }
440
441 // When we are reusing the incoming register and it has been marked killed
442 // by OldKill, if the PHICopy is after the OldKill, we should remove the
443 // killed flag from OldKill.
444 if (IsPHICopyAfterOldKill) {
445 LLVM_DEBUG(dbgs() << "Remove old kill from " << *OldKill);
446 LV->removeVirtualRegisterKilled(IncomingReg, *OldKill);
448 }
449
450 // Add information to LiveVariables to know that the first used incoming
451 // value or the resued incoming value whose PHICopy is after the OldKIll
452 // is killed. Note that because the value is defined in several places
453 // (once each for each incoming block), the "def" block and instruction
454 // fields for the VarInfo is not filled in.
455 if (!OldKill || IsPHICopyAfterOldKill)
456 LV->addVirtualRegisterKilled(IncomingReg, *PHICopy);
457 }
458
459 // Since we are going to be deleting the PHI node, if it is the last use of
460 // any registers, or if the value itself is dead, we need to move this
461 // information over to the new copy we just inserted.
463
464 // If the result is dead, update LV.
465 if (isDead) {
466 LV->addVirtualRegisterDead(DestReg, *PHICopy);
467 LV->removeVirtualRegisterDead(DestReg, *MPhi);
468 }
469 }
470
471 // Update LiveIntervals for the new copy or implicit def.
472 if (LIS) {
473 SlotIndex DestCopyIndex = LIS->InsertMachineInstrInMaps(*PHICopy);
474
475 SlotIndex MBBStartIndex = LIS->getMBBStartIdx(&MBB);
476 if (IncomingReg) {
477 // Add the region from the beginning of MBB to the copy instruction to
478 // IncomingReg's live interval.
479 LiveInterval &IncomingLI = LIS->getOrCreateEmptyInterval(IncomingReg);
480 VNInfo *IncomingVNI = IncomingLI.getVNInfoAt(MBBStartIndex);
481 if (!IncomingVNI)
482 IncomingVNI =
483 IncomingLI.getNextValue(MBBStartIndex, LIS->getVNInfoAllocator());
485 MBBStartIndex, DestCopyIndex.getRegSlot(), IncomingVNI));
486 }
487
488 LiveInterval &DestLI = LIS->getInterval(DestReg);
489 assert(!DestLI.empty() && "PHIs should have non-empty LiveIntervals.");
490
491 SlotIndex NewStart = DestCopyIndex.getRegSlot();
492
493 SmallVector<LiveRange *> ToUpdate({&DestLI});
494 for (auto &SR : DestLI.subranges())
495 ToUpdate.push_back(&SR);
496
497 for (auto LR : ToUpdate) {
498 auto DestSegment = LR->find(MBBStartIndex);
499 assert(DestSegment != LR->end() &&
500 "PHI destination must be live in block");
501
502 if (LR->endIndex().isDead()) {
503 // A dead PHI's live range begins and ends at the start of the MBB, but
504 // the lowered copy, which will still be dead, needs to begin and end at
505 // the copy instruction.
506 VNInfo *OrigDestVNI = LR->getVNInfoAt(DestSegment->start);
507 assert(OrigDestVNI && "PHI destination should be live at block entry.");
508 LR->removeSegment(DestSegment->start, DestSegment->start.getDeadSlot());
509 LR->createDeadDef(NewStart, LIS->getVNInfoAllocator());
510 LR->removeValNo(OrigDestVNI);
511 continue;
512 }
513
514 // Destination copies are not inserted in the same order as the PHI nodes
515 // they replace. Hence the start of the live range may need to be adjusted
516 // to match the actual slot index of the copy.
517 if (DestSegment->start > NewStart) {
518 VNInfo *VNI = LR->getVNInfoAt(DestSegment->start);
519 assert(VNI && "value should be defined for known segment");
520 LR->addSegment(
521 LiveInterval::Segment(NewStart, DestSegment->start, VNI));
522 } else if (DestSegment->start < NewStart) {
523 assert(DestSegment->start >= MBBStartIndex);
524 assert(DestSegment->end >= DestCopyIndex.getRegSlot());
525 LR->removeSegment(DestSegment->start, NewStart);
526 }
527 VNInfo *DestVNI = LR->getVNInfoAt(NewStart);
528 assert(DestVNI && "PHI destination should be live at its definition.");
529 DestVNI->def = NewStart;
530 }
531 }
532
533 // Adjust the VRegPHIUseCount map to account for the removal of this PHI node.
534 if (LV || LIS) {
535 for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2) {
536 if (!MPhi->getOperand(i).isUndef()) {
537 --VRegPHIUseCount[BBVRegPair(
538 MPhi->getOperand(i + 1).getMBB()->getNumber(),
539 MPhi->getOperand(i).getReg())];
540 }
541 }
542 }
543
544 // Now loop over all of the incoming arguments, changing them to copy into the
545 // IncomingReg register in the corresponding predecessor basic block.
547 for (int i = NumSrcs - 1; i >= 0; --i) {
548 Register SrcReg = MPhi->getOperand(i * 2 + 1).getReg();
549 unsigned SrcSubReg = MPhi->getOperand(i * 2 + 1).getSubReg();
550 bool SrcUndef = MPhi->getOperand(i * 2 + 1).isUndef() ||
551 isImplicitlyDefined(SrcReg, *MRI);
552 assert(SrcReg.isVirtual() &&
553 "Machine PHI Operands must all be virtual registers!");
554
555 // Get the MachineBasicBlock equivalent of the BasicBlock that is the source
556 // path the PHI.
557 MachineBasicBlock &opBlock = *MPhi->getOperand(i * 2 + 2).getMBB();
558
559 // Check to make sure we haven't already emitted the copy for this block.
560 // This can happen because PHI nodes may have multiple entries for the same
561 // basic block.
562 if (!MBBsInsertedInto.insert(&opBlock).second)
563 continue; // If the copy has already been emitted, we're done.
564
565 MachineInstr *SrcRegDef = MRI->getVRegDef(SrcReg);
566 if (SrcRegDef && TII->isUnspillableTerminator(SrcRegDef)) {
567 assert(SrcRegDef->getOperand(0).isReg() &&
568 SrcRegDef->getOperand(0).isDef() &&
569 "Expected operand 0 to be a reg def!");
570 // Now that the PHI's use has been removed (as the instruction was
571 // removed) there should be no other uses of the SrcReg.
572 assert(MRI->use_empty(SrcReg) &&
573 "Expected a single use from UnspillableTerminator");
574 SrcRegDef->getOperand(0).setReg(IncomingReg);
575
576 // Update LiveVariables.
577 if (LV) {
578 LiveVariables::VarInfo &SrcVI = LV->getVarInfo(SrcReg);
579 LiveVariables::VarInfo &IncomingVI = LV->getVarInfo(IncomingReg);
580 IncomingVI.AliveBlocks = std::move(SrcVI.AliveBlocks);
581 SrcVI.AliveBlocks.clear();
582 }
583
584 continue;
585 }
586
587 // Find a safe location to insert the copy, this may be the first terminator
588 // in the block (or end()).
590 findPHICopyInsertPoint(&opBlock, &MBB, SrcReg);
591
592 // Insert the copy.
593 MachineInstr *NewSrcInstr = nullptr;
594 if (!reusedIncoming && IncomingReg) {
595 if (SrcUndef) {
596 // The source register is undefined, so there is no need for a real
597 // COPY, but we still need to ensure joint dominance by defs.
598 // Insert an IMPLICIT_DEF instruction.
599 NewSrcInstr =
600 BuildMI(opBlock, InsertPos, MPhi->getDebugLoc(),
601 TII->get(TargetOpcode::IMPLICIT_DEF), IncomingReg);
602
603 // Clean up the old implicit-def, if there even was one.
604 if (MachineInstr *DefMI = MRI->getVRegDef(SrcReg))
605 if (DefMI->isImplicitDef())
606 ImpDefs.insert(DefMI);
607 } else {
608 // Delete the debug location, since the copy is inserted into a
609 // different basic block.
610 NewSrcInstr = TII->createPHISourceCopy(opBlock, InsertPos, nullptr,
611 SrcReg, SrcSubReg, IncomingReg);
612 }
613 }
614
615 // We only need to update the LiveVariables kill of SrcReg if this was the
616 // last PHI use of SrcReg to be lowered on this CFG edge and it is not live
617 // out of the predecessor. We can also ignore undef sources.
618 if (LV && !SrcUndef &&
619 !VRegPHIUseCount[BBVRegPair(opBlock.getNumber(), SrcReg)] &&
620 !LV->isLiveOut(SrcReg, opBlock)) {
621 // We want to be able to insert a kill of the register if this PHI (aka,
622 // the copy we just inserted) is the last use of the source value. Live
623 // variable analysis conservatively handles this by saying that the value
624 // is live until the end of the block the PHI entry lives in. If the value
625 // really is dead at the PHI copy, there will be no successor blocks which
626 // have the value live-in.
627
628 // Okay, if we now know that the value is not live out of the block, we
629 // can add a kill marker in this block saying that it kills the incoming
630 // value!
631
632 // In our final twist, we have to decide which instruction kills the
633 // register. In most cases this is the copy, however, terminator
634 // instructions at the end of the block may also use the value. In this
635 // case, we should mark the last such terminator as being the killing
636 // block, not the copy.
637 MachineBasicBlock::iterator KillInst = opBlock.end();
638 for (MachineBasicBlock::iterator Term = InsertPos; Term != opBlock.end();
639 ++Term) {
640 if (Term->readsRegister(SrcReg, /*TRI=*/nullptr))
641 KillInst = Term;
642 }
643
644 if (KillInst == opBlock.end()) {
645 // No terminator uses the register.
646
647 if (reusedIncoming || !IncomingReg) {
648 // We may have to rewind a bit if we didn't insert a copy this time.
649 KillInst = InsertPos;
650 while (KillInst != opBlock.begin()) {
651 --KillInst;
652 if (KillInst->isDebugInstr())
653 continue;
654 if (KillInst->readsRegister(SrcReg, /*TRI=*/nullptr))
655 break;
656 }
657 } else {
658 // We just inserted this copy.
659 KillInst = NewSrcInstr;
660 }
661 }
662 assert(KillInst->readsRegister(SrcReg, /*TRI=*/nullptr) &&
663 "Cannot find kill instruction");
664
665 // Finally, mark it killed.
666 LV->addVirtualRegisterKilled(SrcReg, *KillInst);
667
668 // This vreg no longer lives all of the way through opBlock.
669 unsigned opBlockNum = opBlock.getNumber();
670 LV->getVarInfo(SrcReg).AliveBlocks.reset(opBlockNum);
671 }
672
673 if (LIS) {
674 if (NewSrcInstr) {
675 LIS->InsertMachineInstrInMaps(*NewSrcInstr);
676 LIS->addSegmentToEndOfBlock(IncomingReg, *NewSrcInstr);
677 }
678
679 if (!SrcUndef &&
680 !VRegPHIUseCount[BBVRegPair(opBlock.getNumber(), SrcReg)]) {
681 LiveInterval &SrcLI = LIS->getInterval(SrcReg);
682
683 bool isLiveOut = false;
684 for (MachineBasicBlock *Succ : opBlock.successors()) {
685 SlotIndex startIdx = LIS->getMBBStartIdx(Succ);
686 VNInfo *VNI = SrcLI.getVNInfoAt(startIdx);
687
688 // Definitions by other PHIs are not truly live-in for our purposes.
689 if (VNI && VNI->def != startIdx) {
690 isLiveOut = true;
691 break;
692 }
693 }
694
695 if (!isLiveOut) {
696 MachineBasicBlock::iterator KillInst = opBlock.end();
697 for (MachineBasicBlock::iterator Term = InsertPos;
698 Term != opBlock.end(); ++Term) {
699 if (Term->readsRegister(SrcReg, /*TRI=*/nullptr))
700 KillInst = Term;
701 }
702
703 if (KillInst == opBlock.end()) {
704 // No terminator uses the register.
705
706 if (reusedIncoming || !IncomingReg) {
707 // We may have to rewind a bit if we didn't just insert a copy.
708 KillInst = InsertPos;
709 while (KillInst != opBlock.begin()) {
710 --KillInst;
711 if (KillInst->isDebugInstr())
712 continue;
713 if (KillInst->readsRegister(SrcReg, /*TRI=*/nullptr))
714 break;
715 }
716 } else {
717 // We just inserted this copy.
718 KillInst = std::prev(InsertPos);
719 }
720 }
721 assert(KillInst->readsRegister(SrcReg, /*TRI=*/nullptr) &&
722 "Cannot find kill instruction");
723
724 SlotIndex LastUseIndex = LIS->getInstructionIndex(*KillInst);
725 SrcLI.removeSegment(LastUseIndex.getRegSlot(),
726 LIS->getMBBEndIdx(&opBlock));
727 for (auto &SR : SrcLI.subranges()) {
728 SR.removeSegment(LastUseIndex.getRegSlot(),
729 LIS->getMBBEndIdx(&opBlock));
730 }
731 }
732 }
733 }
734 }
735
736 // Really delete the PHI instruction now, if it is not in the LoweredPHIs map.
737 if (EliminateNow) {
738 if (LIS)
739 LIS->RemoveMachineInstrFromMaps(*MPhi);
740 MF.deleteMachineInstr(MPhi);
741 }
742}
743
744/// analyzePHINodes - Gather information about the PHI nodes in here. In
745/// particular, we want to map the number of uses of a virtual register which is
746/// used in a PHI node. We map that to the BB the vreg is coming from. This is
747/// used later to determine when the vreg is killed in the BB.
748void PHIEliminationImpl::analyzePHINodes(const MachineFunction &MF) {
749 for (const auto &MBB : MF) {
750 for (const auto &BBI : MBB) {
751 if (!BBI.isPHI())
752 break;
753 for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2) {
754 if (!BBI.getOperand(i).isUndef()) {
755 ++VRegPHIUseCount[BBVRegPair(
756 BBI.getOperand(i + 1).getMBB()->getNumber(),
757 BBI.getOperand(i).getReg())];
758 }
759 }
760 }
761 }
762}
763
764bool PHIEliminationImpl::SplitPHIEdges(
766 std::vector<SparseBitVector<>> *LiveInSets, MachineDomTreeUpdater &MDTU) {
767 if (MBB.empty() || !MBB.front().isPHI() || MBB.isEHPad())
768 return false; // Quick exit for basic blocks without PHIs.
769
770 const MachineLoop *CurLoop = MLI ? MLI->getLoopFor(&MBB) : nullptr;
771 bool IsLoopHeader = CurLoop && &MBB == CurLoop->getHeader();
772
773 bool Changed = false;
774 for (MachineBasicBlock::iterator BBI = MBB.begin(), BBE = MBB.end();
775 BBI != BBE && BBI->isPHI(); ++BBI) {
776 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
777 Register Reg = BBI->getOperand(i).getReg();
778 MachineBasicBlock *PreMBB = BBI->getOperand(i + 1).getMBB();
779 // Is there a critical edge from PreMBB to MBB?
780 if (PreMBB->succ_size() == 1)
781 continue;
782
783 // Avoid splitting backedges of loops. It would introduce small
784 // out-of-line blocks into the loop which is very bad for code placement.
785 if (PreMBB == &MBB && !SplitAllCriticalEdges)
786 continue;
787 const MachineLoop *PreLoop = MLI ? MLI->getLoopFor(PreMBB) : nullptr;
788 if (IsLoopHeader && PreLoop == CurLoop && !SplitAllCriticalEdges)
789 continue;
790
791 // LV doesn't consider a phi use live-out, so isLiveOut only returns true
792 // when the source register is live-out for some other reason than a phi
793 // use. That means the copy we will insert in PreMBB won't be a kill, and
794 // there is a risk it may not be coalesced away.
795 //
796 // If the copy would be a kill, there is no need to split the edge.
797 bool ShouldSplit = isLiveOutPastPHIs(Reg, PreMBB);
798 if (!ShouldSplit && !NoPhiElimLiveOutEarlyExit)
799 continue;
800 if (ShouldSplit) {
801 LLVM_DEBUG(dbgs() << printReg(Reg) << " live-out before critical edge "
802 << printMBBReference(*PreMBB) << " -> "
803 << printMBBReference(MBB) << ": " << *BBI);
804 }
805
806 // If Reg is not live-in to MBB, it means it must be live-in to some
807 // other PreMBB successor, and we can avoid the interference by splitting
808 // the edge.
809 //
810 // If Reg *is* live-in to MBB, the interference is inevitable and a copy
811 // is likely to be left after coalescing. If we are looking at a loop
812 // exiting edge, split it so we won't insert code in the loop, otherwise
813 // don't bother.
814 ShouldSplit = ShouldSplit && !isLiveIn(Reg, &MBB);
815
816 // Check for a loop exiting edge.
817 if (!ShouldSplit && CurLoop != PreLoop) {
818 LLVM_DEBUG({
819 dbgs() << "Split wouldn't help, maybe avoid loop copies?\n";
820 if (PreLoop)
821 dbgs() << "PreLoop: " << *PreLoop;
822 if (CurLoop)
823 dbgs() << "CurLoop: " << *CurLoop;
824 });
825 // This edge could be entering a loop, exiting a loop, or it could be
826 // both: Jumping directly form one loop to the header of a sibling
827 // loop.
828 // Split unless this edge is entering CurLoop from an outer loop.
829 ShouldSplit = PreLoop && !PreLoop->contains(CurLoop);
830 }
831 if (!ShouldSplit && !SplitAllCriticalEdges)
832 continue;
833 if (!(P ? PreMBB->SplitCriticalEdge(&MBB, *P, LiveInSets, &MDTU)
834 : PreMBB->SplitCriticalEdge(&MBB, *MFAM, LiveInSets, &MDTU))) {
835 LLVM_DEBUG(dbgs() << "Failed to split critical edge.\n");
836 continue;
837 }
838 Changed = true;
839 ++NumCriticalEdgesSplit;
840 }
841 }
842 return Changed;
843}
844
845bool PHIEliminationImpl::isLiveIn(Register Reg, const MachineBasicBlock *MBB) {
846 assert((LV || LIS) &&
847 "isLiveIn() requires either LiveVariables or LiveIntervals");
848 if (LIS)
849 return LIS->isLiveInToMBB(LIS->getInterval(Reg), MBB);
850 else
851 return LV->isLiveIn(Reg, *MBB);
852}
853
854bool PHIEliminationImpl::isLiveOutPastPHIs(Register Reg,
855 const MachineBasicBlock *MBB) {
856 assert((LV || LIS) &&
857 "isLiveOutPastPHIs() requires either LiveVariables or LiveIntervals");
858 // LiveVariables considers uses in PHIs to be in the predecessor basic block,
859 // so that a register used only in a PHI is not live out of the block. In
860 // contrast, LiveIntervals considers uses in PHIs to be on the edge rather
861 // than in the predecessor basic block, so that a register used only in a PHI
862 // is live out of the block.
863 if (LIS) {
864 const LiveInterval &LI = LIS->getInterval(Reg);
865 for (const MachineBasicBlock *SI : MBB->successors())
866 if (LI.liveAt(LIS->getMBBStartIdx(SI)))
867 return true;
868 return false;
869 } else {
870 return LV->isLiveOut(Reg, *MBB);
871 }
872}
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const TargetInstrInfo & TII
MachineBasicBlock & MBB
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines the DenseMap class.
#define DEBUG_TYPE
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
#define P(N)
static bool allPhiOperandsUndefined(const MachineInstr &MPhi, const MachineRegisterInfo &MRI)
Return true if all sources of the phi node are implicit_def's, or undef's.
static cl::opt< bool > NoPhiElimLiveOutEarlyExit("no-phi-elim-live-out-early-exit", cl::init(false), cl::Hidden, cl::desc("Do not use an early exit if isLiveOutPastPHIs returns true."))
static bool isImplicitlyDefined(Register VirtReg, const MachineRegisterInfo &MRI)
Return true if all defs of VirtReg are implicit-defs.
static cl::opt< bool > DisableEdgeSplitting("disable-phi-elim-edge-splitting", cl::init(false), cl::Hidden, cl::desc("Disable critical edge splitting " "during PHI elimination"))
static cl::opt< bool > SplitAllCriticalEdges("phi-elim-split-all-critical-edges", cl::init(false), cl::Hidden, cl::desc("Split all critical edges during " "PHI elimination"))
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
static bool isLiveOut(const MachineBasicBlock &MBB, unsigned Reg)
bool isDead(const MachineInstr &MI, const MachineRegisterInfo &MRI)
This file defines the SmallPtrSet class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:114
Represent the analysis usage information of a pass.
LiveInterval - This class represents the liveness of a register, or stack slot.
iterator_range< subrange_iterator > subranges()
SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const
Return the first index in the given basic block.
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
LiveInterval & getOrCreateEmptyInterval(Register Reg)
Return an existing interval for Reg.
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
void RemoveMachineInstrFromMaps(MachineInstr &MI)
VNInfo::Allocator & getVNInfoAllocator()
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Return the last index in the given basic block.
LiveInterval & getInterval(Register Reg)
LLVM_ABI LiveInterval::Segment addSegmentToEndOfBlock(Register Reg, MachineInstr &startInst)
Given a register and an instruction, adds a live segment from that instruction to the end of its MBB.
bool isLiveInToMBB(const LiveRange &LR, const MachineBasicBlock *mbb) const
LLVM_ABI iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
bool liveAt(SlotIndex index) const
bool empty() const
VNInfo * getNextValue(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator)
getNextValue - Create a new value number and return it.
LLVM_ABI void removeSegment(SlotIndex Start, SlotIndex End, bool RemoveDeadValNo=false)
Remove the specified interval from this live range.
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
bool removeVirtualRegisterDead(Register Reg, MachineInstr &MI)
removeVirtualRegisterDead - Remove the specified kill of the virtual register from the live variable ...
bool removeVirtualRegisterKilled(Register Reg, MachineInstr &MI)
removeVirtualRegisterKilled - Remove the specified kill of the virtual register from the live variabl...
LLVM_ABI void removeVirtualRegistersKilled(MachineInstr &MI)
removeVirtualRegistersKilled - Remove all killed info for the specified instruction.
void addVirtualRegisterDead(Register IncomingReg, MachineInstr &MI, bool AddIfNotFound=false)
addVirtualRegisterDead - Add information about the fact that the specified register is dead after bei...
LLVM_ABI bool isLiveOut(Register Reg, const MachineBasicBlock &MBB)
isLiveOut - Determine if Reg is live out from MBB, when not considering PHI nodes.
bool isLiveIn(Register Reg, const MachineBasicBlock &MBB)
void addVirtualRegisterKilled(Register IncomingReg, MachineInstr &MI, bool AddIfNotFound=false)
addVirtualRegisterKilled - Add information about the fact that the specified register is killed after...
LLVM_ABI VarInfo & getVarInfo(Register Reg)
getVarInfo - Return the VarInfo structure for the specified VIRTUAL register.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
BlockT * getHeader() const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode.
Definition MCInstrInfo.h:90
bool isEHPad() const
Returns true if the block is a landing pad.
MachineBasicBlock * SplitCriticalEdge(MachineBasicBlock *Succ, Pass &P, std::vector< SparseBitVector<> > *LiveInSets=nullptr, MachineDomTreeUpdater *MDTU=nullptr)
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
LLVM_ABI iterator SkipPHIsAndLabels(iterator I)
Return the first instruction in MBB after I that is not a PHI or a label.
MachineInstr * remove(MachineInstr *I)
Remove the unbundled instruction from the instruction list without deleting it.
LLVM_ABI void dump() const
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< succ_iterator > successors()
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Location of a PHI instruction that is also a debug-info variable value, for the duration of register ...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
unsigned size() const
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
DenseMap< unsigned, DebugPHIRegallocPos > DebugPHIPositions
Map of debug instruction numbers to the position of their PHI instructions during register allocation...
Representation of each machine instruction.
bool isImplicitDef() const
const MachineBasicBlock * getParent() const
unsigned getNumOperands() const
Retuns the total number of operands.
unsigned peekDebugInstrNum() const
Examine the instruction number of this MachineInstr.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
const MachineOperand & getOperand(unsigned i) const
Analysis pass that exposes the MachineLoopInfo for a machine function.
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() const
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
Register getReg() const
getReg - Returns the register number.
MachinePostDominatorTree - an analysis pass wrapper for DominatorTree used to compute the post-domina...
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition Register.h:20
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition Register.h:72
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:66
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
void reset(unsigned Idx)
SparseBitVectorIterator iterator
TargetInstrInfo - Interface to description of machine instruction set.
bool isUnspillableTerminator(const MachineInstr *MI) const
Return true if the given instruction is terminator that is unspillable, according to isUnspillableTer...
virtual MachineInstr * createPHIDestinationCopy(MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt, const DebugLoc &DL, Register Src, Register Dst) const
During PHI eleimination lets target to make necessary checks and insert the copy to the PHI destinati...
virtual MachineInstr * createPHISourceCopy(MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt, const DebugLoc &DL, Register Src, unsigned SrcSubReg, Register Dst) const
During PHI eleimination lets target to make necessary checks and insert the copy to the PHI destinati...
virtual const TargetInstrInfo * getInstrInfo() const
VNInfo - Value Number Information.
SlotIndex def
The index of the defining instruction.
Changed
@ Entry
Definition COFF.h:862
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
MachineBasicBlock::iterator findPHICopyInsertPoint(MachineBasicBlock *MBB, MachineBasicBlock *SuccMBB, Register SrcReg)
findPHICopyInsertPoint - Find a safe place in MBB to insert a copy from SrcReg when following the CFG...
LLVM_ABI unsigned SplitAllCriticalEdges(Function &F, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
Loop over all of the edges in the CFG, breaking critical edges as they are found.
LLVM_ABI void initializePHIEliminationPass(PassRegistry &)
LLVM_ABI char & PHIEliminationID
PHIElimination - This pass eliminates machine instruction PHI nodes by inserting copy instructions.
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.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
This represents a simple continuous liveness interval for a value.
VarInfo - This represents the regions where a virtual register is live in the program.
SparseBitVector AliveBlocks
AliveBlocks - Set of blocks in which this value is alive completely through.