2
0

PHIElimination.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. //===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This pass eliminates machine instruction PHI nodes by inserting copy
  11. // instructions. This destroys SSA information, but is the desired input for
  12. // some register allocators.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/CodeGen/Passes.h"
  16. #include "PHIEliminationUtils.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/SmallPtrSet.h"
  19. #include "llvm/ADT/Statistic.h"
  20. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  21. #include "llvm/CodeGen/LiveVariables.h"
  22. #include "llvm/CodeGen/MachineDominators.h"
  23. #include "llvm/CodeGen/MachineInstr.h"
  24. #include "llvm/CodeGen/MachineInstrBuilder.h"
  25. #include "llvm/CodeGen/MachineLoopInfo.h"
  26. #include "llvm/CodeGen/MachineRegisterInfo.h"
  27. #include "llvm/IR/Function.h"
  28. #include "llvm/Support/CommandLine.h"
  29. #include "llvm/Support/Compiler.h"
  30. #include "llvm/Support/Debug.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #include "llvm/Target/TargetInstrInfo.h"
  33. #include "llvm/Target/TargetSubtargetInfo.h"
  34. #include <algorithm>
  35. using namespace llvm;
  36. #define DEBUG_TYPE "phielim"
  37. static cl::opt<bool>
  38. DisableEdgeSplitting("disable-phi-elim-edge-splitting", cl::init(false),
  39. cl::Hidden, cl::desc("Disable critical edge splitting "
  40. "during PHI elimination"));
  41. static cl::opt<bool>
  42. SplitAllCriticalEdges("phi-elim-split-all-critical-edges", cl::init(false),
  43. cl::Hidden, cl::desc("Split all critical edges during "
  44. "PHI elimination"));
  45. static cl::opt<bool> NoPhiElimLiveOutEarlyExit(
  46. "no-phi-elim-live-out-early-exit", cl::init(false), cl::Hidden,
  47. cl::desc("Do not use an early exit if isLiveOutPastPHIs returns true."));
  48. namespace {
  49. class PHIElimination : public MachineFunctionPass {
  50. MachineRegisterInfo *MRI; // Machine register information
  51. LiveVariables *LV;
  52. LiveIntervals *LIS;
  53. public:
  54. static char ID; // Pass identification, replacement for typeid
  55. PHIElimination() : MachineFunctionPass(ID) {
  56. initializePHIEliminationPass(*PassRegistry::getPassRegistry());
  57. }
  58. bool runOnMachineFunction(MachineFunction &Fn) override;
  59. void getAnalysisUsage(AnalysisUsage &AU) const override;
  60. private:
  61. /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
  62. /// in predecessor basic blocks.
  63. ///
  64. bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
  65. void LowerPHINode(MachineBasicBlock &MBB,
  66. MachineBasicBlock::iterator LastPHIIt);
  67. /// analyzePHINodes - Gather information about the PHI nodes in
  68. /// here. In particular, we want to map the number of uses of a virtual
  69. /// register which is used in a PHI node. We map that to the BB the
  70. /// vreg is coming from. This is used later to determine when the vreg
  71. /// is killed in the BB.
  72. ///
  73. void analyzePHINodes(const MachineFunction& Fn);
  74. /// Split critical edges where necessary for good coalescer performance.
  75. bool SplitPHIEdges(MachineFunction &MF, MachineBasicBlock &MBB,
  76. MachineLoopInfo *MLI);
  77. // These functions are temporary abstractions around LiveVariables and
  78. // LiveIntervals, so they can go away when LiveVariables does.
  79. bool isLiveIn(unsigned Reg, const MachineBasicBlock *MBB);
  80. bool isLiveOutPastPHIs(unsigned Reg, const MachineBasicBlock *MBB);
  81. typedef std::pair<unsigned, unsigned> BBVRegPair;
  82. typedef DenseMap<BBVRegPair, unsigned> VRegPHIUse;
  83. VRegPHIUse VRegPHIUseCount;
  84. // Defs of PHI sources which are implicit_def.
  85. SmallPtrSet<MachineInstr*, 4> ImpDefs;
  86. // Map reusable lowered PHI node -> incoming join register.
  87. typedef DenseMap<MachineInstr*, unsigned,
  88. MachineInstrExpressionTrait> LoweredPHIMap;
  89. LoweredPHIMap LoweredPHIs;
  90. };
  91. }
  92. STATISTIC(NumLowered, "Number of phis lowered");
  93. STATISTIC(NumCriticalEdgesSplit, "Number of critical edges split");
  94. STATISTIC(NumReused, "Number of reused lowered phis");
  95. char PHIElimination::ID = 0;
  96. char& llvm::PHIEliminationID = PHIElimination::ID;
  97. INITIALIZE_PASS_BEGIN(PHIElimination, "phi-node-elimination",
  98. "Eliminate PHI nodes for register allocation",
  99. false, false)
  100. INITIALIZE_PASS_DEPENDENCY(LiveVariables)
  101. INITIALIZE_PASS_END(PHIElimination, "phi-node-elimination",
  102. "Eliminate PHI nodes for register allocation", false, false)
  103. void PHIElimination::getAnalysisUsage(AnalysisUsage &AU) const {
  104. AU.addPreserved<LiveVariables>();
  105. AU.addPreserved<SlotIndexes>();
  106. AU.addPreserved<LiveIntervals>();
  107. AU.addPreserved<MachineDominatorTree>();
  108. AU.addPreserved<MachineLoopInfo>();
  109. MachineFunctionPass::getAnalysisUsage(AU);
  110. }
  111. bool PHIElimination::runOnMachineFunction(MachineFunction &MF) {
  112. MRI = &MF.getRegInfo();
  113. LV = getAnalysisIfAvailable<LiveVariables>();
  114. LIS = getAnalysisIfAvailable<LiveIntervals>();
  115. bool Changed = false;
  116. // This pass takes the function out of SSA form.
  117. MRI->leaveSSA();
  118. // Split critical edges to help the coalescer. This does not yet support
  119. // updating LiveIntervals, so we disable it.
  120. if (!DisableEdgeSplitting && (LV || LIS)) {
  121. MachineLoopInfo *MLI = getAnalysisIfAvailable<MachineLoopInfo>();
  122. for (auto &MBB : MF)
  123. Changed |= SplitPHIEdges(MF, MBB, MLI);
  124. }
  125. // Populate VRegPHIUseCount
  126. analyzePHINodes(MF);
  127. // Eliminate PHI instructions by inserting copies into predecessor blocks.
  128. for (auto &MBB : MF)
  129. Changed |= EliminatePHINodes(MF, MBB);
  130. // Remove dead IMPLICIT_DEF instructions.
  131. for (MachineInstr *DefMI : ImpDefs) {
  132. unsigned DefReg = DefMI->getOperand(0).getReg();
  133. if (MRI->use_nodbg_empty(DefReg)) {
  134. if (LIS)
  135. LIS->RemoveMachineInstrFromMaps(DefMI);
  136. DefMI->eraseFromParent();
  137. }
  138. }
  139. // Clean up the lowered PHI instructions.
  140. for (LoweredPHIMap::iterator I = LoweredPHIs.begin(), E = LoweredPHIs.end();
  141. I != E; ++I) {
  142. if (LIS)
  143. LIS->RemoveMachineInstrFromMaps(I->first);
  144. MF.DeleteMachineInstr(I->first);
  145. }
  146. LoweredPHIs.clear();
  147. ImpDefs.clear();
  148. VRegPHIUseCount.clear();
  149. return Changed;
  150. }
  151. /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
  152. /// predecessor basic blocks.
  153. ///
  154. bool PHIElimination::EliminatePHINodes(MachineFunction &MF,
  155. MachineBasicBlock &MBB) {
  156. if (MBB.empty() || !MBB.front().isPHI())
  157. return false; // Quick exit for basic blocks without PHIs.
  158. // Get an iterator to the first instruction after the last PHI node (this may
  159. // also be the end of the basic block).
  160. MachineBasicBlock::iterator LastPHIIt =
  161. std::prev(MBB.SkipPHIsAndLabels(MBB.begin()));
  162. while (MBB.front().isPHI())
  163. LowerPHINode(MBB, LastPHIIt);
  164. return true;
  165. }
  166. /// isImplicitlyDefined - Return true if all defs of VirtReg are implicit-defs.
  167. /// This includes registers with no defs.
  168. static bool isImplicitlyDefined(unsigned VirtReg,
  169. const MachineRegisterInfo *MRI) {
  170. for (MachineInstr &DI : MRI->def_instructions(VirtReg))
  171. if (!DI.isImplicitDef())
  172. return false;
  173. return true;
  174. }
  175. /// isSourceDefinedByImplicitDef - Return true if all sources of the phi node
  176. /// are implicit_def's.
  177. static bool isSourceDefinedByImplicitDef(const MachineInstr *MPhi,
  178. const MachineRegisterInfo *MRI) {
  179. for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
  180. if (!isImplicitlyDefined(MPhi->getOperand(i).getReg(), MRI))
  181. return false;
  182. return true;
  183. }
  184. /// LowerPHINode - Lower the PHI node at the top of the specified block,
  185. ///
  186. void PHIElimination::LowerPHINode(MachineBasicBlock &MBB,
  187. MachineBasicBlock::iterator LastPHIIt) {
  188. ++NumLowered;
  189. MachineBasicBlock::iterator AfterPHIsIt = std::next(LastPHIIt);
  190. // Unlink the PHI node from the basic block, but don't delete the PHI yet.
  191. MachineInstr *MPhi = MBB.remove(MBB.begin());
  192. unsigned NumSrcs = (MPhi->getNumOperands() - 1) / 2;
  193. unsigned DestReg = MPhi->getOperand(0).getReg();
  194. assert(MPhi->getOperand(0).getSubReg() == 0 && "Can't handle sub-reg PHIs");
  195. bool isDead = MPhi->getOperand(0).isDead();
  196. // Create a new register for the incoming PHI arguments.
  197. MachineFunction &MF = *MBB.getParent();
  198. unsigned IncomingReg = 0;
  199. bool reusedIncoming = false; // Is IncomingReg reused from an earlier PHI?
  200. // Insert a register to register copy at the top of the current block (but
  201. // after any remaining phi nodes) which copies the new incoming register
  202. // into the phi node destination.
  203. const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
  204. if (isSourceDefinedByImplicitDef(MPhi, MRI))
  205. // If all sources of a PHI node are implicit_def, just emit an
  206. // implicit_def instead of a copy.
  207. BuildMI(MBB, AfterPHIsIt, MPhi->getDebugLoc(),
  208. TII->get(TargetOpcode::IMPLICIT_DEF), DestReg);
  209. else {
  210. // Can we reuse an earlier PHI node? This only happens for critical edges,
  211. // typically those created by tail duplication.
  212. unsigned &entry = LoweredPHIs[MPhi];
  213. if (entry) {
  214. // An identical PHI node was already lowered. Reuse the incoming register.
  215. IncomingReg = entry;
  216. reusedIncoming = true;
  217. ++NumReused;
  218. DEBUG(dbgs() << "Reusing " << PrintReg(IncomingReg) << " for " << *MPhi);
  219. } else {
  220. const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(DestReg);
  221. entry = IncomingReg = MF.getRegInfo().createVirtualRegister(RC);
  222. }
  223. BuildMI(MBB, AfterPHIsIt, MPhi->getDebugLoc(),
  224. TII->get(TargetOpcode::COPY), DestReg)
  225. .addReg(IncomingReg);
  226. }
  227. // Update live variable information if there is any.
  228. if (LV) {
  229. MachineInstr *PHICopy = std::prev(AfterPHIsIt);
  230. if (IncomingReg) {
  231. LiveVariables::VarInfo &VI = LV->getVarInfo(IncomingReg);
  232. // Increment use count of the newly created virtual register.
  233. LV->setPHIJoin(IncomingReg);
  234. // When we are reusing the incoming register, it may already have been
  235. // killed in this block. The old kill will also have been inserted at
  236. // AfterPHIsIt, so it appears before the current PHICopy.
  237. if (reusedIncoming)
  238. if (MachineInstr *OldKill = VI.findKill(&MBB)) {
  239. DEBUG(dbgs() << "Remove old kill from " << *OldKill);
  240. LV->removeVirtualRegisterKilled(IncomingReg, OldKill);
  241. DEBUG(MBB.dump());
  242. }
  243. // Add information to LiveVariables to know that the incoming value is
  244. // killed. Note that because the value is defined in several places (once
  245. // each for each incoming block), the "def" block and instruction fields
  246. // for the VarInfo is not filled in.
  247. LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
  248. }
  249. // Since we are going to be deleting the PHI node, if it is the last use of
  250. // any registers, or if the value itself is dead, we need to move this
  251. // information over to the new copy we just inserted.
  252. LV->removeVirtualRegistersKilled(MPhi);
  253. // If the result is dead, update LV.
  254. if (isDead) {
  255. LV->addVirtualRegisterDead(DestReg, PHICopy);
  256. LV->removeVirtualRegisterDead(DestReg, MPhi);
  257. }
  258. }
  259. // Update LiveIntervals for the new copy or implicit def.
  260. if (LIS) {
  261. MachineInstr *NewInstr = std::prev(AfterPHIsIt);
  262. SlotIndex DestCopyIndex = LIS->InsertMachineInstrInMaps(NewInstr);
  263. SlotIndex MBBStartIndex = LIS->getMBBStartIdx(&MBB);
  264. if (IncomingReg) {
  265. // Add the region from the beginning of MBB to the copy instruction to
  266. // IncomingReg's live interval.
  267. LiveInterval &IncomingLI = LIS->createEmptyInterval(IncomingReg);
  268. VNInfo *IncomingVNI = IncomingLI.getVNInfoAt(MBBStartIndex);
  269. if (!IncomingVNI)
  270. IncomingVNI = IncomingLI.getNextValue(MBBStartIndex,
  271. LIS->getVNInfoAllocator());
  272. IncomingLI.addSegment(LiveInterval::Segment(MBBStartIndex,
  273. DestCopyIndex.getRegSlot(),
  274. IncomingVNI));
  275. }
  276. LiveInterval &DestLI = LIS->getInterval(DestReg);
  277. assert(DestLI.begin() != DestLI.end() &&
  278. "PHIs should have nonempty LiveIntervals.");
  279. if (DestLI.endIndex().isDead()) {
  280. // A dead PHI's live range begins and ends at the start of the MBB, but
  281. // the lowered copy, which will still be dead, needs to begin and end at
  282. // the copy instruction.
  283. VNInfo *OrigDestVNI = DestLI.getVNInfoAt(MBBStartIndex);
  284. assert(OrigDestVNI && "PHI destination should be live at block entry.");
  285. DestLI.removeSegment(MBBStartIndex, MBBStartIndex.getDeadSlot());
  286. DestLI.createDeadDef(DestCopyIndex.getRegSlot(),
  287. LIS->getVNInfoAllocator());
  288. DestLI.removeValNo(OrigDestVNI);
  289. } else {
  290. // Otherwise, remove the region from the beginning of MBB to the copy
  291. // instruction from DestReg's live interval.
  292. DestLI.removeSegment(MBBStartIndex, DestCopyIndex.getRegSlot());
  293. VNInfo *DestVNI = DestLI.getVNInfoAt(DestCopyIndex.getRegSlot());
  294. assert(DestVNI && "PHI destination should be live at its definition.");
  295. DestVNI->def = DestCopyIndex.getRegSlot();
  296. }
  297. }
  298. // Adjust the VRegPHIUseCount map to account for the removal of this PHI node.
  299. for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
  300. --VRegPHIUseCount[BBVRegPair(MPhi->getOperand(i+1).getMBB()->getNumber(),
  301. MPhi->getOperand(i).getReg())];
  302. // Now loop over all of the incoming arguments, changing them to copy into the
  303. // IncomingReg register in the corresponding predecessor basic block.
  304. SmallPtrSet<MachineBasicBlock*, 8> MBBsInsertedInto;
  305. for (int i = NumSrcs - 1; i >= 0; --i) {
  306. unsigned SrcReg = MPhi->getOperand(i*2+1).getReg();
  307. unsigned SrcSubReg = MPhi->getOperand(i*2+1).getSubReg();
  308. bool SrcUndef = MPhi->getOperand(i*2+1).isUndef() ||
  309. isImplicitlyDefined(SrcReg, MRI);
  310. assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
  311. "Machine PHI Operands must all be virtual registers!");
  312. // Get the MachineBasicBlock equivalent of the BasicBlock that is the source
  313. // path the PHI.
  314. MachineBasicBlock &opBlock = *MPhi->getOperand(i*2+2).getMBB();
  315. // Check to make sure we haven't already emitted the copy for this block.
  316. // This can happen because PHI nodes may have multiple entries for the same
  317. // basic block.
  318. if (!MBBsInsertedInto.insert(&opBlock).second)
  319. continue; // If the copy has already been emitted, we're done.
  320. // Find a safe location to insert the copy, this may be the first terminator
  321. // in the block (or end()).
  322. MachineBasicBlock::iterator InsertPos =
  323. findPHICopyInsertPoint(&opBlock, &MBB, SrcReg);
  324. // Insert the copy.
  325. MachineInstr *NewSrcInstr = nullptr;
  326. if (!reusedIncoming && IncomingReg) {
  327. if (SrcUndef) {
  328. // The source register is undefined, so there is no need for a real
  329. // COPY, but we still need to ensure joint dominance by defs.
  330. // Insert an IMPLICIT_DEF instruction.
  331. NewSrcInstr = BuildMI(opBlock, InsertPos, MPhi->getDebugLoc(),
  332. TII->get(TargetOpcode::IMPLICIT_DEF),
  333. IncomingReg);
  334. // Clean up the old implicit-def, if there even was one.
  335. if (MachineInstr *DefMI = MRI->getVRegDef(SrcReg))
  336. if (DefMI->isImplicitDef())
  337. ImpDefs.insert(DefMI);
  338. } else {
  339. NewSrcInstr = BuildMI(opBlock, InsertPos, MPhi->getDebugLoc(),
  340. TII->get(TargetOpcode::COPY), IncomingReg)
  341. .addReg(SrcReg, 0, SrcSubReg);
  342. }
  343. }
  344. // We only need to update the LiveVariables kill of SrcReg if this was the
  345. // last PHI use of SrcReg to be lowered on this CFG edge and it is not live
  346. // out of the predecessor. We can also ignore undef sources.
  347. if (LV && !SrcUndef &&
  348. !VRegPHIUseCount[BBVRegPair(opBlock.getNumber(), SrcReg)] &&
  349. !LV->isLiveOut(SrcReg, opBlock)) {
  350. // We want to be able to insert a kill of the register if this PHI (aka,
  351. // the copy we just inserted) is the last use of the source value. Live
  352. // variable analysis conservatively handles this by saying that the value
  353. // is live until the end of the block the PHI entry lives in. If the value
  354. // really is dead at the PHI copy, there will be no successor blocks which
  355. // have the value live-in.
  356. // Okay, if we now know that the value is not live out of the block, we
  357. // can add a kill marker in this block saying that it kills the incoming
  358. // value!
  359. // In our final twist, we have to decide which instruction kills the
  360. // register. In most cases this is the copy, however, terminator
  361. // instructions at the end of the block may also use the value. In this
  362. // case, we should mark the last such terminator as being the killing
  363. // block, not the copy.
  364. MachineBasicBlock::iterator KillInst = opBlock.end();
  365. MachineBasicBlock::iterator FirstTerm = opBlock.getFirstTerminator();
  366. for (MachineBasicBlock::iterator Term = FirstTerm;
  367. Term != opBlock.end(); ++Term) {
  368. if (Term->readsRegister(SrcReg))
  369. KillInst = Term;
  370. }
  371. if (KillInst == opBlock.end()) {
  372. // No terminator uses the register.
  373. if (reusedIncoming || !IncomingReg) {
  374. // We may have to rewind a bit if we didn't insert a copy this time.
  375. KillInst = FirstTerm;
  376. while (KillInst != opBlock.begin()) {
  377. --KillInst;
  378. if (KillInst->isDebugValue())
  379. continue;
  380. if (KillInst->readsRegister(SrcReg))
  381. break;
  382. }
  383. } else {
  384. // We just inserted this copy.
  385. KillInst = std::prev(InsertPos);
  386. }
  387. }
  388. assert(KillInst->readsRegister(SrcReg) && "Cannot find kill instruction");
  389. // Finally, mark it killed.
  390. LV->addVirtualRegisterKilled(SrcReg, KillInst);
  391. // This vreg no longer lives all of the way through opBlock.
  392. unsigned opBlockNum = opBlock.getNumber();
  393. LV->getVarInfo(SrcReg).AliveBlocks.reset(opBlockNum);
  394. }
  395. if (LIS) {
  396. if (NewSrcInstr) {
  397. LIS->InsertMachineInstrInMaps(NewSrcInstr);
  398. LIS->addSegmentToEndOfBlock(IncomingReg, NewSrcInstr);
  399. }
  400. if (!SrcUndef &&
  401. !VRegPHIUseCount[BBVRegPair(opBlock.getNumber(), SrcReg)]) {
  402. LiveInterval &SrcLI = LIS->getInterval(SrcReg);
  403. bool isLiveOut = false;
  404. for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),
  405. SE = opBlock.succ_end(); SI != SE; ++SI) {
  406. SlotIndex startIdx = LIS->getMBBStartIdx(*SI);
  407. VNInfo *VNI = SrcLI.getVNInfoAt(startIdx);
  408. // Definitions by other PHIs are not truly live-in for our purposes.
  409. if (VNI && VNI->def != startIdx) {
  410. isLiveOut = true;
  411. break;
  412. }
  413. }
  414. if (!isLiveOut) {
  415. MachineBasicBlock::iterator KillInst = opBlock.end();
  416. MachineBasicBlock::iterator FirstTerm = opBlock.getFirstTerminator();
  417. for (MachineBasicBlock::iterator Term = FirstTerm;
  418. Term != opBlock.end(); ++Term) {
  419. if (Term->readsRegister(SrcReg))
  420. KillInst = Term;
  421. }
  422. if (KillInst == opBlock.end()) {
  423. // No terminator uses the register.
  424. if (reusedIncoming || !IncomingReg) {
  425. // We may have to rewind a bit if we didn't just insert a copy.
  426. KillInst = FirstTerm;
  427. while (KillInst != opBlock.begin()) {
  428. --KillInst;
  429. if (KillInst->isDebugValue())
  430. continue;
  431. if (KillInst->readsRegister(SrcReg))
  432. break;
  433. }
  434. } else {
  435. // We just inserted this copy.
  436. KillInst = std::prev(InsertPos);
  437. }
  438. }
  439. assert(KillInst->readsRegister(SrcReg) &&
  440. "Cannot find kill instruction");
  441. SlotIndex LastUseIndex = LIS->getInstructionIndex(KillInst);
  442. SrcLI.removeSegment(LastUseIndex.getRegSlot(),
  443. LIS->getMBBEndIdx(&opBlock));
  444. }
  445. }
  446. }
  447. }
  448. // Really delete the PHI instruction now, if it is not in the LoweredPHIs map.
  449. if (reusedIncoming || !IncomingReg) {
  450. if (LIS)
  451. LIS->RemoveMachineInstrFromMaps(MPhi);
  452. MF.DeleteMachineInstr(MPhi);
  453. }
  454. }
  455. /// analyzePHINodes - Gather information about the PHI nodes in here. In
  456. /// particular, we want to map the number of uses of a virtual register which is
  457. /// used in a PHI node. We map that to the BB the vreg is coming from. This is
  458. /// used later to determine when the vreg is killed in the BB.
  459. ///
  460. void PHIElimination::analyzePHINodes(const MachineFunction& MF) {
  461. for (const auto &MBB : MF)
  462. for (const auto &BBI : MBB) {
  463. if (!BBI.isPHI())
  464. break;
  465. for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2)
  466. ++VRegPHIUseCount[BBVRegPair(BBI.getOperand(i+1).getMBB()->getNumber(),
  467. BBI.getOperand(i).getReg())];
  468. }
  469. }
  470. bool PHIElimination::SplitPHIEdges(MachineFunction &MF,
  471. MachineBasicBlock &MBB,
  472. MachineLoopInfo *MLI) {
  473. if (MBB.empty() || !MBB.front().isPHI() || MBB.isLandingPad())
  474. return false; // Quick exit for basic blocks without PHIs.
  475. const MachineLoop *CurLoop = MLI ? MLI->getLoopFor(&MBB) : nullptr;
  476. bool IsLoopHeader = CurLoop && &MBB == CurLoop->getHeader();
  477. bool Changed = false;
  478. for (MachineBasicBlock::iterator BBI = MBB.begin(), BBE = MBB.end();
  479. BBI != BBE && BBI->isPHI(); ++BBI) {
  480. for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
  481. unsigned Reg = BBI->getOperand(i).getReg();
  482. MachineBasicBlock *PreMBB = BBI->getOperand(i+1).getMBB();
  483. // Is there a critical edge from PreMBB to MBB?
  484. if (PreMBB->succ_size() == 1)
  485. continue;
  486. // Avoid splitting backedges of loops. It would introduce small
  487. // out-of-line blocks into the loop which is very bad for code placement.
  488. if (PreMBB == &MBB && !SplitAllCriticalEdges)
  489. continue;
  490. const MachineLoop *PreLoop = MLI ? MLI->getLoopFor(PreMBB) : nullptr;
  491. if (IsLoopHeader && PreLoop == CurLoop && !SplitAllCriticalEdges)
  492. continue;
  493. // LV doesn't consider a phi use live-out, so isLiveOut only returns true
  494. // when the source register is live-out for some other reason than a phi
  495. // use. That means the copy we will insert in PreMBB won't be a kill, and
  496. // there is a risk it may not be coalesced away.
  497. //
  498. // If the copy would be a kill, there is no need to split the edge.
  499. bool ShouldSplit = isLiveOutPastPHIs(Reg, PreMBB);
  500. if (!ShouldSplit && !NoPhiElimLiveOutEarlyExit)
  501. continue;
  502. if (ShouldSplit) {
  503. DEBUG(dbgs() << PrintReg(Reg) << " live-out before critical edge BB#"
  504. << PreMBB->getNumber() << " -> BB#" << MBB.getNumber()
  505. << ": " << *BBI);
  506. }
  507. // If Reg is not live-in to MBB, it means it must be live-in to some
  508. // other PreMBB successor, and we can avoid the interference by splitting
  509. // the edge.
  510. //
  511. // If Reg *is* live-in to MBB, the interference is inevitable and a copy
  512. // is likely to be left after coalescing. If we are looking at a loop
  513. // exiting edge, split it so we won't insert code in the loop, otherwise
  514. // don't bother.
  515. ShouldSplit = ShouldSplit && !isLiveIn(Reg, &MBB);
  516. // Check for a loop exiting edge.
  517. if (!ShouldSplit && CurLoop != PreLoop) {
  518. DEBUG({
  519. dbgs() << "Split wouldn't help, maybe avoid loop copies?\n";
  520. if (PreLoop) dbgs() << "PreLoop: " << *PreLoop;
  521. if (CurLoop) dbgs() << "CurLoop: " << *CurLoop;
  522. });
  523. // This edge could be entering a loop, exiting a loop, or it could be
  524. // both: Jumping directly form one loop to the header of a sibling
  525. // loop.
  526. // Split unless this edge is entering CurLoop from an outer loop.
  527. ShouldSplit = PreLoop && !PreLoop->contains(CurLoop);
  528. }
  529. if (!ShouldSplit && !SplitAllCriticalEdges)
  530. continue;
  531. if (!PreMBB->SplitCriticalEdge(&MBB, this)) {
  532. DEBUG(dbgs() << "Failed to split critical edge.\n");
  533. continue;
  534. }
  535. Changed = true;
  536. ++NumCriticalEdgesSplit;
  537. }
  538. }
  539. return Changed;
  540. }
  541. bool PHIElimination::isLiveIn(unsigned Reg, const MachineBasicBlock *MBB) {
  542. assert((LV || LIS) &&
  543. "isLiveIn() requires either LiveVariables or LiveIntervals");
  544. if (LIS)
  545. return LIS->isLiveInToMBB(LIS->getInterval(Reg), MBB);
  546. else
  547. return LV->isLiveIn(Reg, *MBB);
  548. }
  549. bool PHIElimination::isLiveOutPastPHIs(unsigned Reg,
  550. const MachineBasicBlock *MBB) {
  551. assert((LV || LIS) &&
  552. "isLiveOutPastPHIs() requires either LiveVariables or LiveIntervals");
  553. // LiveVariables considers uses in PHIs to be in the predecessor basic block,
  554. // so that a register used only in a PHI is not live out of the block. In
  555. // contrast, LiveIntervals considers uses in PHIs to be on the edge rather than
  556. // in the predecessor basic block, so that a register used only in a PHI is live
  557. // out of the block.
  558. if (LIS) {
  559. const LiveInterval &LI = LIS->getInterval(Reg);
  560. for (const MachineBasicBlock *SI : MBB->successors())
  561. if (LI.liveAt(LIS->getMBBStartIdx(SI)))
  562. return true;
  563. return false;
  564. } else {
  565. return LV->isLiveOut(Reg, *MBB);
  566. }
  567. }