TailDuplicator.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070
  1. //===- TailDuplicator.cpp - Duplicate blocks into predecessors' tails -----===//
  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 utility class duplicates basic blocks ending in unconditional branches
  10. // into the tails of their predecessors.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/TailDuplicator.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/DenseSet.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SetVector.h"
  18. #include "llvm/ADT/SmallPtrSet.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/Statistic.h"
  21. #include "llvm/CodeGen/MachineBasicBlock.h"
  22. #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
  23. #include "llvm/CodeGen/MachineFunction.h"
  24. #include "llvm/CodeGen/MachineInstr.h"
  25. #include "llvm/CodeGen/MachineInstrBuilder.h"
  26. #include "llvm/CodeGen/MachineOperand.h"
  27. #include "llvm/CodeGen/MachineRegisterInfo.h"
  28. #include "llvm/CodeGen/MachineSSAUpdater.h"
  29. #include "llvm/CodeGen/MachineSizeOpts.h"
  30. #include "llvm/CodeGen/TargetInstrInfo.h"
  31. #include "llvm/CodeGen/TargetRegisterInfo.h"
  32. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  33. #include "llvm/IR/DebugLoc.h"
  34. #include "llvm/IR/Function.h"
  35. #include "llvm/Support/CommandLine.h"
  36. #include "llvm/Support/Debug.h"
  37. #include "llvm/Support/ErrorHandling.h"
  38. #include "llvm/Support/raw_ostream.h"
  39. #include "llvm/Target/TargetMachine.h"
  40. #include <algorithm>
  41. #include <cassert>
  42. #include <iterator>
  43. #include <utility>
  44. using namespace llvm;
  45. #define DEBUG_TYPE "tailduplication"
  46. STATISTIC(NumTails, "Number of tails duplicated");
  47. STATISTIC(NumTailDups, "Number of tail duplicated blocks");
  48. STATISTIC(NumTailDupAdded,
  49. "Number of instructions added due to tail duplication");
  50. STATISTIC(NumTailDupRemoved,
  51. "Number of instructions removed due to tail duplication");
  52. STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
  53. STATISTIC(NumAddedPHIs, "Number of phis added");
  54. // Heuristic for tail duplication.
  55. static cl::opt<unsigned> TailDuplicateSize(
  56. "tail-dup-size",
  57. cl::desc("Maximum instructions to consider tail duplicating"), cl::init(2),
  58. cl::Hidden);
  59. static cl::opt<unsigned> TailDupIndirectBranchSize(
  60. "tail-dup-indirect-size",
  61. cl::desc("Maximum instructions to consider tail duplicating blocks that "
  62. "end with indirect branches."), cl::init(20),
  63. cl::Hidden);
  64. static cl::opt<bool>
  65. TailDupVerify("tail-dup-verify",
  66. cl::desc("Verify sanity of PHI instructions during taildup"),
  67. cl::init(false), cl::Hidden);
  68. static cl::opt<unsigned> TailDupLimit("tail-dup-limit", cl::init(~0U),
  69. cl::Hidden);
  70. void TailDuplicator::initMF(MachineFunction &MFin, bool PreRegAlloc,
  71. const MachineBranchProbabilityInfo *MBPIin,
  72. MBFIWrapper *MBFIin,
  73. ProfileSummaryInfo *PSIin,
  74. bool LayoutModeIn, unsigned TailDupSizeIn) {
  75. MF = &MFin;
  76. TII = MF->getSubtarget().getInstrInfo();
  77. TRI = MF->getSubtarget().getRegisterInfo();
  78. MRI = &MF->getRegInfo();
  79. MMI = &MF->getMMI();
  80. MBPI = MBPIin;
  81. MBFI = MBFIin;
  82. PSI = PSIin;
  83. TailDupSize = TailDupSizeIn;
  84. assert(MBPI != nullptr && "Machine Branch Probability Info required");
  85. LayoutMode = LayoutModeIn;
  86. this->PreRegAlloc = PreRegAlloc;
  87. }
  88. static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
  89. for (MachineBasicBlock &MBB : llvm::drop_begin(MF)) {
  90. SmallSetVector<MachineBasicBlock *, 8> Preds(MBB.pred_begin(),
  91. MBB.pred_end());
  92. MachineBasicBlock::iterator MI = MBB.begin();
  93. while (MI != MBB.end()) {
  94. if (!MI->isPHI())
  95. break;
  96. for (MachineBasicBlock *PredBB : Preds) {
  97. bool Found = false;
  98. for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
  99. MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
  100. if (PHIBB == PredBB) {
  101. Found = true;
  102. break;
  103. }
  104. }
  105. if (!Found) {
  106. dbgs() << "Malformed PHI in " << printMBBReference(MBB) << ": "
  107. << *MI;
  108. dbgs() << " missing input from predecessor "
  109. << printMBBReference(*PredBB) << '\n';
  110. llvm_unreachable(nullptr);
  111. }
  112. }
  113. for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
  114. MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
  115. if (CheckExtra && !Preds.count(PHIBB)) {
  116. dbgs() << "Warning: malformed PHI in " << printMBBReference(MBB)
  117. << ": " << *MI;
  118. dbgs() << " extra input from predecessor "
  119. << printMBBReference(*PHIBB) << '\n';
  120. llvm_unreachable(nullptr);
  121. }
  122. if (PHIBB->getNumber() < 0) {
  123. dbgs() << "Malformed PHI in " << printMBBReference(MBB) << ": "
  124. << *MI;
  125. dbgs() << " non-existing " << printMBBReference(*PHIBB) << '\n';
  126. llvm_unreachable(nullptr);
  127. }
  128. }
  129. ++MI;
  130. }
  131. }
  132. }
  133. /// Tail duplicate the block and cleanup.
  134. /// \p IsSimple - return value of isSimpleBB
  135. /// \p MBB - block to be duplicated
  136. /// \p ForcedLayoutPred - If non-null, treat this block as the layout
  137. /// predecessor, instead of using the ordering in MF
  138. /// \p DuplicatedPreds - if non-null, \p DuplicatedPreds will contain a list of
  139. /// all Preds that received a copy of \p MBB.
  140. /// \p RemovalCallback - if non-null, called just before MBB is deleted.
  141. bool TailDuplicator::tailDuplicateAndUpdate(
  142. bool IsSimple, MachineBasicBlock *MBB,
  143. MachineBasicBlock *ForcedLayoutPred,
  144. SmallVectorImpl<MachineBasicBlock*> *DuplicatedPreds,
  145. function_ref<void(MachineBasicBlock *)> *RemovalCallback,
  146. SmallVectorImpl<MachineBasicBlock *> *CandidatePtr) {
  147. // Save the successors list.
  148. SmallSetVector<MachineBasicBlock *, 8> Succs(MBB->succ_begin(),
  149. MBB->succ_end());
  150. SmallVector<MachineBasicBlock *, 8> TDBBs;
  151. SmallVector<MachineInstr *, 16> Copies;
  152. if (!tailDuplicate(IsSimple, MBB, ForcedLayoutPred,
  153. TDBBs, Copies, CandidatePtr))
  154. return false;
  155. ++NumTails;
  156. SmallVector<MachineInstr *, 8> NewPHIs;
  157. MachineSSAUpdater SSAUpdate(*MF, &NewPHIs);
  158. // TailBB's immediate successors are now successors of those predecessors
  159. // which duplicated TailBB. Add the predecessors as sources to the PHI
  160. // instructions.
  161. bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
  162. if (PreRegAlloc)
  163. updateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
  164. // If it is dead, remove it.
  165. if (isDead) {
  166. NumTailDupRemoved += MBB->size();
  167. removeDeadBlock(MBB, RemovalCallback);
  168. ++NumDeadBlocks;
  169. }
  170. // Update SSA form.
  171. if (!SSAUpdateVRs.empty()) {
  172. for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
  173. unsigned VReg = SSAUpdateVRs[i];
  174. SSAUpdate.Initialize(VReg);
  175. // If the original definition is still around, add it as an available
  176. // value.
  177. MachineInstr *DefMI = MRI->getVRegDef(VReg);
  178. MachineBasicBlock *DefBB = nullptr;
  179. if (DefMI) {
  180. DefBB = DefMI->getParent();
  181. SSAUpdate.AddAvailableValue(DefBB, VReg);
  182. }
  183. // Add the new vregs as available values.
  184. DenseMap<Register, AvailableValsTy>::iterator LI =
  185. SSAUpdateVals.find(VReg);
  186. for (std::pair<MachineBasicBlock *, Register> &J : LI->second) {
  187. MachineBasicBlock *SrcBB = J.first;
  188. Register SrcReg = J.second;
  189. SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
  190. }
  191. SmallVector<MachineOperand *> DebugUses;
  192. // Rewrite uses that are outside of the original def's block.
  193. for (MachineOperand &UseMO :
  194. llvm::make_early_inc_range(MRI->use_operands(VReg))) {
  195. MachineInstr *UseMI = UseMO.getParent();
  196. // Rewrite debug uses last so that they can take advantage of any
  197. // register mappings introduced by other users in its BB, since we
  198. // cannot create new register definitions specifically for the debug
  199. // instruction (as debug instructions should not affect CodeGen).
  200. if (UseMI->isDebugValue()) {
  201. DebugUses.push_back(&UseMO);
  202. continue;
  203. }
  204. if (UseMI->getParent() == DefBB && !UseMI->isPHI())
  205. continue;
  206. SSAUpdate.RewriteUse(UseMO);
  207. }
  208. for (auto *UseMO : DebugUses) {
  209. MachineInstr *UseMI = UseMO->getParent();
  210. UseMO->setReg(
  211. SSAUpdate.GetValueInMiddleOfBlock(UseMI->getParent(), true));
  212. }
  213. }
  214. SSAUpdateVRs.clear();
  215. SSAUpdateVals.clear();
  216. }
  217. // Eliminate some of the copies inserted by tail duplication to maintain
  218. // SSA form.
  219. for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
  220. MachineInstr *Copy = Copies[i];
  221. if (!Copy->isCopy())
  222. continue;
  223. Register Dst = Copy->getOperand(0).getReg();
  224. Register Src = Copy->getOperand(1).getReg();
  225. if (MRI->hasOneNonDBGUse(Src) &&
  226. MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
  227. // Copy is the only use. Do trivial copy propagation here.
  228. MRI->replaceRegWith(Dst, Src);
  229. Copy->eraseFromParent();
  230. }
  231. }
  232. if (NewPHIs.size())
  233. NumAddedPHIs += NewPHIs.size();
  234. if (DuplicatedPreds)
  235. *DuplicatedPreds = std::move(TDBBs);
  236. return true;
  237. }
  238. /// Look for small blocks that are unconditionally branched to and do not fall
  239. /// through. Tail-duplicate their instructions into their predecessors to
  240. /// eliminate (dynamic) branches.
  241. bool TailDuplicator::tailDuplicateBlocks() {
  242. bool MadeChange = false;
  243. if (PreRegAlloc && TailDupVerify) {
  244. LLVM_DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
  245. VerifyPHIs(*MF, true);
  246. }
  247. for (MachineBasicBlock &MBB :
  248. llvm::make_early_inc_range(llvm::drop_begin(*MF))) {
  249. if (NumTails == TailDupLimit)
  250. break;
  251. bool IsSimple = isSimpleBB(&MBB);
  252. if (!shouldTailDuplicate(IsSimple, MBB))
  253. continue;
  254. MadeChange |= tailDuplicateAndUpdate(IsSimple, &MBB, nullptr);
  255. }
  256. if (PreRegAlloc && TailDupVerify)
  257. VerifyPHIs(*MF, false);
  258. return MadeChange;
  259. }
  260. static bool isDefLiveOut(Register Reg, MachineBasicBlock *BB,
  261. const MachineRegisterInfo *MRI) {
  262. for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
  263. if (UseMI.isDebugValue())
  264. continue;
  265. if (UseMI.getParent() != BB)
  266. return true;
  267. }
  268. return false;
  269. }
  270. static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
  271. for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
  272. if (MI->getOperand(i + 1).getMBB() == SrcBB)
  273. return i;
  274. return 0;
  275. }
  276. // Remember which registers are used by phis in this block. This is
  277. // used to determine which registers are liveout while modifying the
  278. // block (which is why we need to copy the information).
  279. static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
  280. DenseSet<Register> *UsedByPhi) {
  281. for (const auto &MI : BB) {
  282. if (!MI.isPHI())
  283. break;
  284. for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
  285. Register SrcReg = MI.getOperand(i).getReg();
  286. UsedByPhi->insert(SrcReg);
  287. }
  288. }
  289. }
  290. /// Add a definition and source virtual registers pair for SSA update.
  291. void TailDuplicator::addSSAUpdateEntry(Register OrigReg, Register NewReg,
  292. MachineBasicBlock *BB) {
  293. DenseMap<Register, AvailableValsTy>::iterator LI =
  294. SSAUpdateVals.find(OrigReg);
  295. if (LI != SSAUpdateVals.end())
  296. LI->second.push_back(std::make_pair(BB, NewReg));
  297. else {
  298. AvailableValsTy Vals;
  299. Vals.push_back(std::make_pair(BB, NewReg));
  300. SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
  301. SSAUpdateVRs.push_back(OrigReg);
  302. }
  303. }
  304. /// Process PHI node in TailBB by turning it into a copy in PredBB. Remember the
  305. /// source register that's contributed by PredBB and update SSA update map.
  306. void TailDuplicator::processPHI(
  307. MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
  308. DenseMap<Register, RegSubRegPair> &LocalVRMap,
  309. SmallVectorImpl<std::pair<Register, RegSubRegPair>> &Copies,
  310. const DenseSet<Register> &RegsUsedByPhi, bool Remove) {
  311. Register DefReg = MI->getOperand(0).getReg();
  312. unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
  313. assert(SrcOpIdx && "Unable to find matching PHI source?");
  314. Register SrcReg = MI->getOperand(SrcOpIdx).getReg();
  315. unsigned SrcSubReg = MI->getOperand(SrcOpIdx).getSubReg();
  316. const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
  317. LocalVRMap.insert(std::make_pair(DefReg, RegSubRegPair(SrcReg, SrcSubReg)));
  318. // Insert a copy from source to the end of the block. The def register is the
  319. // available value liveout of the block.
  320. Register NewDef = MRI->createVirtualRegister(RC);
  321. Copies.push_back(std::make_pair(NewDef, RegSubRegPair(SrcReg, SrcSubReg)));
  322. if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
  323. addSSAUpdateEntry(DefReg, NewDef, PredBB);
  324. if (!Remove)
  325. return;
  326. // Remove PredBB from the PHI node.
  327. MI->removeOperand(SrcOpIdx + 1);
  328. MI->removeOperand(SrcOpIdx);
  329. if (MI->getNumOperands() == 1 && !TailBB->hasAddressTaken())
  330. MI->eraseFromParent();
  331. else if (MI->getNumOperands() == 1)
  332. MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
  333. }
  334. /// Duplicate a TailBB instruction to PredBB and update
  335. /// the source operands due to earlier PHI translation.
  336. void TailDuplicator::duplicateInstruction(
  337. MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
  338. DenseMap<Register, RegSubRegPair> &LocalVRMap,
  339. const DenseSet<Register> &UsedByPhi) {
  340. // Allow duplication of CFI instructions.
  341. if (MI->isCFIInstruction()) {
  342. BuildMI(*PredBB, PredBB->end(), PredBB->findDebugLoc(PredBB->begin()),
  343. TII->get(TargetOpcode::CFI_INSTRUCTION))
  344. .addCFIIndex(MI->getOperand(0).getCFIIndex())
  345. .setMIFlags(MI->getFlags());
  346. return;
  347. }
  348. MachineInstr &NewMI = TII->duplicate(*PredBB, PredBB->end(), *MI);
  349. if (PreRegAlloc) {
  350. for (unsigned i = 0, e = NewMI.getNumOperands(); i != e; ++i) {
  351. MachineOperand &MO = NewMI.getOperand(i);
  352. if (!MO.isReg())
  353. continue;
  354. Register Reg = MO.getReg();
  355. if (!Reg.isVirtual())
  356. continue;
  357. if (MO.isDef()) {
  358. const TargetRegisterClass *RC = MRI->getRegClass(Reg);
  359. Register NewReg = MRI->createVirtualRegister(RC);
  360. MO.setReg(NewReg);
  361. LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
  362. if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
  363. addSSAUpdateEntry(Reg, NewReg, PredBB);
  364. } else {
  365. auto VI = LocalVRMap.find(Reg);
  366. if (VI != LocalVRMap.end()) {
  367. // Need to make sure that the register class of the mapped register
  368. // will satisfy the constraints of the class of the register being
  369. // replaced.
  370. auto *OrigRC = MRI->getRegClass(Reg);
  371. auto *MappedRC = MRI->getRegClass(VI->second.Reg);
  372. const TargetRegisterClass *ConstrRC;
  373. if (VI->second.SubReg != 0) {
  374. ConstrRC = TRI->getMatchingSuperRegClass(MappedRC, OrigRC,
  375. VI->second.SubReg);
  376. if (ConstrRC) {
  377. // The actual constraining (as in "find appropriate new class")
  378. // is done by getMatchingSuperRegClass, so now we only need to
  379. // change the class of the mapped register.
  380. MRI->setRegClass(VI->second.Reg, ConstrRC);
  381. }
  382. } else {
  383. // For mapped registers that do not have sub-registers, simply
  384. // restrict their class to match the original one.
  385. ConstrRC = MRI->constrainRegClass(VI->second.Reg, OrigRC);
  386. }
  387. if (ConstrRC) {
  388. // If the class constraining succeeded, we can simply replace
  389. // the old register with the mapped one.
  390. MO.setReg(VI->second.Reg);
  391. // We have Reg -> VI.Reg:VI.SubReg, so if Reg is used with a
  392. // sub-register, we need to compose the sub-register indices.
  393. MO.setSubReg(TRI->composeSubRegIndices(MO.getSubReg(),
  394. VI->second.SubReg));
  395. } else {
  396. // The direct replacement is not possible, due to failing register
  397. // class constraints. An explicit COPY is necessary. Create one
  398. // that can be reused
  399. auto *NewRC = MI->getRegClassConstraint(i, TII, TRI);
  400. if (NewRC == nullptr)
  401. NewRC = OrigRC;
  402. Register NewReg = MRI->createVirtualRegister(NewRC);
  403. BuildMI(*PredBB, NewMI, NewMI.getDebugLoc(),
  404. TII->get(TargetOpcode::COPY), NewReg)
  405. .addReg(VI->second.Reg, 0, VI->second.SubReg);
  406. LocalVRMap.erase(VI);
  407. LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
  408. MO.setReg(NewReg);
  409. // The composed VI.Reg:VI.SubReg is replaced with NewReg, which
  410. // is equivalent to the whole register Reg. Hence, Reg:subreg
  411. // is same as NewReg:subreg, so keep the sub-register index
  412. // unchanged.
  413. }
  414. // Clear any kill flags from this operand. The new register could
  415. // have uses after this one, so kills are not valid here.
  416. MO.setIsKill(false);
  417. }
  418. }
  419. }
  420. }
  421. }
  422. /// After FromBB is tail duplicated into its predecessor blocks, the successors
  423. /// have gained new predecessors. Update the PHI instructions in them
  424. /// accordingly.
  425. void TailDuplicator::updateSuccessorsPHIs(
  426. MachineBasicBlock *FromBB, bool isDead,
  427. SmallVectorImpl<MachineBasicBlock *> &TDBBs,
  428. SmallSetVector<MachineBasicBlock *, 8> &Succs) {
  429. for (MachineBasicBlock *SuccBB : Succs) {
  430. for (MachineInstr &MI : *SuccBB) {
  431. if (!MI.isPHI())
  432. break;
  433. MachineInstrBuilder MIB(*FromBB->getParent(), MI);
  434. unsigned Idx = 0;
  435. for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
  436. MachineOperand &MO = MI.getOperand(i + 1);
  437. if (MO.getMBB() == FromBB) {
  438. Idx = i;
  439. break;
  440. }
  441. }
  442. assert(Idx != 0);
  443. MachineOperand &MO0 = MI.getOperand(Idx);
  444. Register Reg = MO0.getReg();
  445. if (isDead) {
  446. // Folded into the previous BB.
  447. // There could be duplicate phi source entries. FIXME: Should sdisel
  448. // or earlier pass fixed this?
  449. for (unsigned i = MI.getNumOperands() - 2; i != Idx; i -= 2) {
  450. MachineOperand &MO = MI.getOperand(i + 1);
  451. if (MO.getMBB() == FromBB) {
  452. MI.removeOperand(i + 1);
  453. MI.removeOperand(i);
  454. }
  455. }
  456. } else
  457. Idx = 0;
  458. // If Idx is set, the operands at Idx and Idx+1 must be removed.
  459. // We reuse the location to avoid expensive removeOperand calls.
  460. DenseMap<Register, AvailableValsTy>::iterator LI =
  461. SSAUpdateVals.find(Reg);
  462. if (LI != SSAUpdateVals.end()) {
  463. // This register is defined in the tail block.
  464. for (const std::pair<MachineBasicBlock *, Register> &J : LI->second) {
  465. MachineBasicBlock *SrcBB = J.first;
  466. // If we didn't duplicate a bb into a particular predecessor, we
  467. // might still have added an entry to SSAUpdateVals to correcly
  468. // recompute SSA. If that case, avoid adding a dummy extra argument
  469. // this PHI.
  470. if (!SrcBB->isSuccessor(SuccBB))
  471. continue;
  472. Register SrcReg = J.second;
  473. if (Idx != 0) {
  474. MI.getOperand(Idx).setReg(SrcReg);
  475. MI.getOperand(Idx + 1).setMBB(SrcBB);
  476. Idx = 0;
  477. } else {
  478. MIB.addReg(SrcReg).addMBB(SrcBB);
  479. }
  480. }
  481. } else {
  482. // Live in tail block, must also be live in predecessors.
  483. for (MachineBasicBlock *SrcBB : TDBBs) {
  484. if (Idx != 0) {
  485. MI.getOperand(Idx).setReg(Reg);
  486. MI.getOperand(Idx + 1).setMBB(SrcBB);
  487. Idx = 0;
  488. } else {
  489. MIB.addReg(Reg).addMBB(SrcBB);
  490. }
  491. }
  492. }
  493. if (Idx != 0) {
  494. MI.removeOperand(Idx + 1);
  495. MI.removeOperand(Idx);
  496. }
  497. }
  498. }
  499. }
  500. /// Determine if it is profitable to duplicate this block.
  501. bool TailDuplicator::shouldTailDuplicate(bool IsSimple,
  502. MachineBasicBlock &TailBB) {
  503. // When doing tail-duplication during layout, the block ordering is in flux,
  504. // so canFallThrough returns a result based on incorrect information and
  505. // should just be ignored.
  506. if (!LayoutMode && TailBB.canFallThrough())
  507. return false;
  508. // Don't try to tail-duplicate single-block loops.
  509. if (TailBB.isSuccessor(&TailBB))
  510. return false;
  511. // Set the limit on the cost to duplicate. When optimizing for size,
  512. // duplicate only one, because one branch instruction can be eliminated to
  513. // compensate for the duplication.
  514. unsigned MaxDuplicateCount;
  515. bool OptForSize = MF->getFunction().hasOptSize() ||
  516. llvm::shouldOptimizeForSize(&TailBB, PSI, MBFI);
  517. if (TailDupSize == 0)
  518. MaxDuplicateCount = TailDuplicateSize;
  519. else
  520. MaxDuplicateCount = TailDupSize;
  521. if (OptForSize)
  522. MaxDuplicateCount = 1;
  523. // If the block to be duplicated ends in an unanalyzable fallthrough, don't
  524. // duplicate it.
  525. // A similar check is necessary in MachineBlockPlacement to make sure pairs of
  526. // blocks with unanalyzable fallthrough get layed out contiguously.
  527. MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
  528. SmallVector<MachineOperand, 4> PredCond;
  529. if (TII->analyzeBranch(TailBB, PredTBB, PredFBB, PredCond) &&
  530. TailBB.canFallThrough())
  531. return false;
  532. // If the target has hardware branch prediction that can handle indirect
  533. // branches, duplicating them can often make them predictable when there
  534. // are common paths through the code. The limit needs to be high enough
  535. // to allow undoing the effects of tail merging and other optimizations
  536. // that rearrange the predecessors of the indirect branch.
  537. bool HasIndirectbr = false;
  538. if (!TailBB.empty())
  539. HasIndirectbr = TailBB.back().isIndirectBranch();
  540. if (HasIndirectbr && PreRegAlloc)
  541. MaxDuplicateCount = TailDupIndirectBranchSize;
  542. // Check the instructions in the block to determine whether tail-duplication
  543. // is invalid or unlikely to be profitable.
  544. unsigned InstrCount = 0;
  545. for (MachineInstr &MI : TailBB) {
  546. // Non-duplicable things shouldn't be tail-duplicated.
  547. // CFI instructions are marked as non-duplicable, because Darwin compact
  548. // unwind info emission can't handle multiple prologue setups. In case of
  549. // DWARF, allow them be duplicated, so that their existence doesn't prevent
  550. // tail duplication of some basic blocks, that would be duplicated otherwise.
  551. if (MI.isNotDuplicable() &&
  552. (TailBB.getParent()->getTarget().getTargetTriple().isOSDarwin() ||
  553. !MI.isCFIInstruction()))
  554. return false;
  555. // Convergent instructions can be duplicated only if doing so doesn't add
  556. // new control dependencies, which is what we're going to do here.
  557. if (MI.isConvergent())
  558. return false;
  559. // Do not duplicate 'return' instructions if this is a pre-regalloc run.
  560. // A return may expand into a lot more instructions (e.g. reload of callee
  561. // saved registers) after PEI.
  562. if (PreRegAlloc && MI.isReturn())
  563. return false;
  564. // Avoid duplicating calls before register allocation. Calls presents a
  565. // barrier to register allocation so duplicating them may end up increasing
  566. // spills.
  567. if (PreRegAlloc && MI.isCall())
  568. return false;
  569. // TailDuplicator::appendCopies will erroneously place COPYs after
  570. // INLINEASM_BR instructions after 4b0aa5724fea, which demonstrates the same
  571. // bug that was fixed in f7a53d82c090.
  572. // FIXME: Use findPHICopyInsertPoint() to find the correct insertion point
  573. // for the COPY when replacing PHIs.
  574. if (MI.getOpcode() == TargetOpcode::INLINEASM_BR)
  575. return false;
  576. if (MI.isBundle())
  577. InstrCount += MI.getBundleSize();
  578. else if (!MI.isPHI() && !MI.isMetaInstruction())
  579. InstrCount += 1;
  580. if (InstrCount > MaxDuplicateCount)
  581. return false;
  582. }
  583. // Check if any of the successors of TailBB has a PHI node in which the
  584. // value corresponding to TailBB uses a subregister.
  585. // If a phi node uses a register paired with a subregister, the actual
  586. // "value type" of the phi may differ from the type of the register without
  587. // any subregisters. Due to a bug, tail duplication may add a new operand
  588. // without a necessary subregister, producing an invalid code. This is
  589. // demonstrated by test/CodeGen/Hexagon/tail-dup-subreg-abort.ll.
  590. // Disable tail duplication for this case for now, until the problem is
  591. // fixed.
  592. for (auto *SB : TailBB.successors()) {
  593. for (auto &I : *SB) {
  594. if (!I.isPHI())
  595. break;
  596. unsigned Idx = getPHISrcRegOpIdx(&I, &TailBB);
  597. assert(Idx != 0);
  598. MachineOperand &PU = I.getOperand(Idx);
  599. if (PU.getSubReg() != 0)
  600. return false;
  601. }
  602. }
  603. if (HasIndirectbr && PreRegAlloc)
  604. return true;
  605. if (IsSimple)
  606. return true;
  607. if (!PreRegAlloc)
  608. return true;
  609. return canCompletelyDuplicateBB(TailBB);
  610. }
  611. /// True if this BB has only one unconditional jump.
  612. bool TailDuplicator::isSimpleBB(MachineBasicBlock *TailBB) {
  613. if (TailBB->succ_size() != 1)
  614. return false;
  615. if (TailBB->pred_empty())
  616. return false;
  617. MachineBasicBlock::iterator I = TailBB->getFirstNonDebugInstr(true);
  618. if (I == TailBB->end())
  619. return true;
  620. return I->isUnconditionalBranch();
  621. }
  622. static bool bothUsedInPHI(const MachineBasicBlock &A,
  623. const SmallPtrSet<MachineBasicBlock *, 8> &SuccsB) {
  624. for (MachineBasicBlock *BB : A.successors())
  625. if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
  626. return true;
  627. return false;
  628. }
  629. bool TailDuplicator::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
  630. for (MachineBasicBlock *PredBB : BB.predecessors()) {
  631. if (PredBB->succ_size() > 1)
  632. return false;
  633. MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
  634. SmallVector<MachineOperand, 4> PredCond;
  635. if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
  636. return false;
  637. if (!PredCond.empty())
  638. return false;
  639. }
  640. return true;
  641. }
  642. bool TailDuplicator::duplicateSimpleBB(
  643. MachineBasicBlock *TailBB, SmallVectorImpl<MachineBasicBlock *> &TDBBs,
  644. const DenseSet<Register> &UsedByPhi) {
  645. SmallPtrSet<MachineBasicBlock *, 8> Succs(TailBB->succ_begin(),
  646. TailBB->succ_end());
  647. SmallVector<MachineBasicBlock *, 8> Preds(TailBB->predecessors());
  648. bool Changed = false;
  649. for (MachineBasicBlock *PredBB : Preds) {
  650. if (PredBB->hasEHPadSuccessor() || PredBB->mayHaveInlineAsmBr())
  651. continue;
  652. if (bothUsedInPHI(*PredBB, Succs))
  653. continue;
  654. MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
  655. SmallVector<MachineOperand, 4> PredCond;
  656. if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
  657. continue;
  658. Changed = true;
  659. LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
  660. << "From simple Succ: " << *TailBB);
  661. MachineBasicBlock *NewTarget = *TailBB->succ_begin();
  662. MachineBasicBlock *NextBB = PredBB->getNextNode();
  663. // Make PredFBB explicit.
  664. if (PredCond.empty())
  665. PredFBB = PredTBB;
  666. // Make fall through explicit.
  667. if (!PredTBB)
  668. PredTBB = NextBB;
  669. if (!PredFBB)
  670. PredFBB = NextBB;
  671. // Redirect
  672. if (PredFBB == TailBB)
  673. PredFBB = NewTarget;
  674. if (PredTBB == TailBB)
  675. PredTBB = NewTarget;
  676. // Make the branch unconditional if possible
  677. if (PredTBB == PredFBB) {
  678. PredCond.clear();
  679. PredFBB = nullptr;
  680. }
  681. // Avoid adding fall through branches.
  682. if (PredFBB == NextBB)
  683. PredFBB = nullptr;
  684. if (PredTBB == NextBB && PredFBB == nullptr)
  685. PredTBB = nullptr;
  686. auto DL = PredBB->findBranchDebugLoc();
  687. TII->removeBranch(*PredBB);
  688. if (!PredBB->isSuccessor(NewTarget))
  689. PredBB->replaceSuccessor(TailBB, NewTarget);
  690. else {
  691. PredBB->removeSuccessor(TailBB, true);
  692. assert(PredBB->succ_size() <= 1);
  693. }
  694. if (PredTBB)
  695. TII->insertBranch(*PredBB, PredTBB, PredFBB, PredCond, DL);
  696. TDBBs.push_back(PredBB);
  697. }
  698. return Changed;
  699. }
  700. bool TailDuplicator::canTailDuplicate(MachineBasicBlock *TailBB,
  701. MachineBasicBlock *PredBB) {
  702. // EH edges are ignored by analyzeBranch.
  703. if (PredBB->succ_size() > 1)
  704. return false;
  705. MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
  706. SmallVector<MachineOperand, 4> PredCond;
  707. if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
  708. return false;
  709. if (!PredCond.empty())
  710. return false;
  711. // FIXME: This is overly conservative; it may be ok to relax this in the
  712. // future under more specific conditions. If TailBB is an INLINEASM_BR
  713. // indirect target, we need to see if the edge from PredBB to TailBB is from
  714. // an INLINEASM_BR in PredBB, and then also if that edge was from the
  715. // indirect target list, fallthrough/default target, or potentially both. If
  716. // it's both, TailDuplicator::tailDuplicate will remove the edge, corrupting
  717. // the successor list in PredBB and predecessor list in TailBB.
  718. if (TailBB->isInlineAsmBrIndirectTarget())
  719. return false;
  720. return true;
  721. }
  722. /// If it is profitable, duplicate TailBB's contents in each
  723. /// of its predecessors.
  724. /// \p IsSimple result of isSimpleBB
  725. /// \p TailBB Block to be duplicated.
  726. /// \p ForcedLayoutPred When non-null, use this block as the layout predecessor
  727. /// instead of the previous block in MF's order.
  728. /// \p TDBBs A vector to keep track of all blocks tail-duplicated
  729. /// into.
  730. /// \p Copies A vector of copy instructions inserted. Used later to
  731. /// walk all the inserted copies and remove redundant ones.
  732. bool TailDuplicator::tailDuplicate(bool IsSimple, MachineBasicBlock *TailBB,
  733. MachineBasicBlock *ForcedLayoutPred,
  734. SmallVectorImpl<MachineBasicBlock *> &TDBBs,
  735. SmallVectorImpl<MachineInstr *> &Copies,
  736. SmallVectorImpl<MachineBasicBlock *> *CandidatePtr) {
  737. LLVM_DEBUG(dbgs() << "\n*** Tail-duplicating " << printMBBReference(*TailBB)
  738. << '\n');
  739. bool ShouldUpdateTerminators = TailBB->canFallThrough();
  740. DenseSet<Register> UsedByPhi;
  741. getRegsUsedByPHIs(*TailBB, &UsedByPhi);
  742. if (IsSimple)
  743. return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi);
  744. // Iterate through all the unique predecessors and tail-duplicate this
  745. // block into them, if possible. Copying the list ahead of time also
  746. // avoids trouble with the predecessor list reallocating.
  747. bool Changed = false;
  748. SmallSetVector<MachineBasicBlock *, 8> Preds;
  749. if (CandidatePtr)
  750. Preds.insert(CandidatePtr->begin(), CandidatePtr->end());
  751. else
  752. Preds.insert(TailBB->pred_begin(), TailBB->pred_end());
  753. for (MachineBasicBlock *PredBB : Preds) {
  754. assert(TailBB != PredBB &&
  755. "Single-block loop should have been rejected earlier!");
  756. if (!canTailDuplicate(TailBB, PredBB))
  757. continue;
  758. // Don't duplicate into a fall-through predecessor (at least for now).
  759. // If profile is available, findDuplicateCandidates can choose better
  760. // fall-through predecessor.
  761. if (!(MF->getFunction().hasProfileData() && LayoutMode)) {
  762. bool IsLayoutSuccessor = false;
  763. if (ForcedLayoutPred)
  764. IsLayoutSuccessor = (ForcedLayoutPred == PredBB);
  765. else if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
  766. IsLayoutSuccessor = true;
  767. if (IsLayoutSuccessor)
  768. continue;
  769. }
  770. LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
  771. << "From Succ: " << *TailBB);
  772. TDBBs.push_back(PredBB);
  773. // Remove PredBB's unconditional branch.
  774. TII->removeBranch(*PredBB);
  775. // Clone the contents of TailBB into PredBB.
  776. DenseMap<Register, RegSubRegPair> LocalVRMap;
  777. SmallVector<std::pair<Register, RegSubRegPair>, 4> CopyInfos;
  778. for (MachineInstr &MI : llvm::make_early_inc_range(*TailBB)) {
  779. if (MI.isPHI()) {
  780. // Replace the uses of the def of the PHI with the register coming
  781. // from PredBB.
  782. processPHI(&MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
  783. } else {
  784. // Replace def of virtual registers with new registers, and update
  785. // uses with PHI source register or the new registers.
  786. duplicateInstruction(&MI, TailBB, PredBB, LocalVRMap, UsedByPhi);
  787. }
  788. }
  789. appendCopies(PredBB, CopyInfos, Copies);
  790. NumTailDupAdded += TailBB->size() - 1; // subtract one for removed branch
  791. // Update the CFG.
  792. PredBB->removeSuccessor(PredBB->succ_begin());
  793. assert(PredBB->succ_empty() &&
  794. "TailDuplicate called on block with multiple successors!");
  795. for (MachineBasicBlock *Succ : TailBB->successors())
  796. PredBB->addSuccessor(Succ, MBPI->getEdgeProbability(TailBB, Succ));
  797. // Update branches in pred to jump to tail's layout successor if needed.
  798. if (ShouldUpdateTerminators)
  799. PredBB->updateTerminator(TailBB->getNextNode());
  800. Changed = true;
  801. ++NumTailDups;
  802. }
  803. // If TailBB was duplicated into all its predecessors except for the prior
  804. // block, which falls through unconditionally, move the contents of this
  805. // block into the prior block.
  806. MachineBasicBlock *PrevBB = ForcedLayoutPred;
  807. if (!PrevBB)
  808. PrevBB = &*std::prev(TailBB->getIterator());
  809. MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
  810. SmallVector<MachineOperand, 4> PriorCond;
  811. // This has to check PrevBB->succ_size() because EH edges are ignored by
  812. // analyzeBranch.
  813. if (PrevBB->succ_size() == 1 &&
  814. // Layout preds are not always CFG preds. Check.
  815. *PrevBB->succ_begin() == TailBB &&
  816. !TII->analyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond) &&
  817. PriorCond.empty() &&
  818. (!PriorTBB || PriorTBB == TailBB) &&
  819. TailBB->pred_size() == 1 &&
  820. !TailBB->hasAddressTaken()) {
  821. LLVM_DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
  822. << "From MBB: " << *TailBB);
  823. // There may be a branch to the layout successor. This is unlikely but it
  824. // happens. The correct thing to do is to remove the branch before
  825. // duplicating the instructions in all cases.
  826. bool RemovedBranches = TII->removeBranch(*PrevBB) != 0;
  827. // If there are still tail instructions, abort the merge
  828. if (PrevBB->getFirstTerminator() == PrevBB->end()) {
  829. if (PreRegAlloc) {
  830. DenseMap<Register, RegSubRegPair> LocalVRMap;
  831. SmallVector<std::pair<Register, RegSubRegPair>, 4> CopyInfos;
  832. MachineBasicBlock::iterator I = TailBB->begin();
  833. // Process PHI instructions first.
  834. while (I != TailBB->end() && I->isPHI()) {
  835. // Replace the uses of the def of the PHI with the register coming
  836. // from PredBB.
  837. MachineInstr *MI = &*I++;
  838. processPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi,
  839. true);
  840. }
  841. // Now copy the non-PHI instructions.
  842. while (I != TailBB->end()) {
  843. // Replace def of virtual registers with new registers, and update
  844. // uses with PHI source register or the new registers.
  845. MachineInstr *MI = &*I++;
  846. assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
  847. duplicateInstruction(MI, TailBB, PrevBB, LocalVRMap, UsedByPhi);
  848. MI->eraseFromParent();
  849. }
  850. appendCopies(PrevBB, CopyInfos, Copies);
  851. } else {
  852. TII->removeBranch(*PrevBB);
  853. // No PHIs to worry about, just splice the instructions over.
  854. PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
  855. }
  856. PrevBB->removeSuccessor(PrevBB->succ_begin());
  857. assert(PrevBB->succ_empty());
  858. PrevBB->transferSuccessors(TailBB);
  859. // Update branches in PrevBB based on Tail's layout successor.
  860. if (ShouldUpdateTerminators)
  861. PrevBB->updateTerminator(TailBB->getNextNode());
  862. TDBBs.push_back(PrevBB);
  863. Changed = true;
  864. } else {
  865. LLVM_DEBUG(dbgs() << "Abort merging blocks, the predecessor still "
  866. "contains terminator instructions");
  867. // Return early if no changes were made
  868. if (!Changed)
  869. return RemovedBranches;
  870. }
  871. Changed |= RemovedBranches;
  872. }
  873. // If this is after register allocation, there are no phis to fix.
  874. if (!PreRegAlloc)
  875. return Changed;
  876. // If we made no changes so far, we are safe.
  877. if (!Changed)
  878. return Changed;
  879. // Handle the nasty case in that we duplicated a block that is part of a loop
  880. // into some but not all of its predecessors. For example:
  881. // 1 -> 2 <-> 3 |
  882. // \ |
  883. // \---> rest |
  884. // if we duplicate 2 into 1 but not into 3, we end up with
  885. // 12 -> 3 <-> 2 -> rest |
  886. // \ / |
  887. // \----->-----/ |
  888. // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
  889. // with a phi in 3 (which now dominates 2).
  890. // What we do here is introduce a copy in 3 of the register defined by the
  891. // phi, just like when we are duplicating 2 into 3, but we don't copy any
  892. // real instructions or remove the 3 -> 2 edge from the phi in 2.
  893. for (MachineBasicBlock *PredBB : Preds) {
  894. if (is_contained(TDBBs, PredBB))
  895. continue;
  896. // EH edges
  897. if (PredBB->succ_size() != 1)
  898. continue;
  899. DenseMap<Register, RegSubRegPair> LocalVRMap;
  900. SmallVector<std::pair<Register, RegSubRegPair>, 4> CopyInfos;
  901. MachineBasicBlock::iterator I = TailBB->begin();
  902. // Process PHI instructions first.
  903. while (I != TailBB->end() && I->isPHI()) {
  904. // Replace the uses of the def of the PHI with the register coming
  905. // from PredBB.
  906. MachineInstr *MI = &*I++;
  907. processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
  908. }
  909. appendCopies(PredBB, CopyInfos, Copies);
  910. }
  911. return Changed;
  912. }
  913. /// At the end of the block \p MBB generate COPY instructions between registers
  914. /// described by \p CopyInfos. Append resulting instructions to \p Copies.
  915. void TailDuplicator::appendCopies(MachineBasicBlock *MBB,
  916. SmallVectorImpl<std::pair<Register, RegSubRegPair>> &CopyInfos,
  917. SmallVectorImpl<MachineInstr*> &Copies) {
  918. MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
  919. const MCInstrDesc &CopyD = TII->get(TargetOpcode::COPY);
  920. for (auto &CI : CopyInfos) {
  921. auto C = BuildMI(*MBB, Loc, DebugLoc(), CopyD, CI.first)
  922. .addReg(CI.second.Reg, 0, CI.second.SubReg);
  923. Copies.push_back(C);
  924. }
  925. }
  926. /// Remove the specified dead machine basic block from the function, updating
  927. /// the CFG.
  928. void TailDuplicator::removeDeadBlock(
  929. MachineBasicBlock *MBB,
  930. function_ref<void(MachineBasicBlock *)> *RemovalCallback) {
  931. assert(MBB->pred_empty() && "MBB must be dead!");
  932. LLVM_DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
  933. MachineFunction *MF = MBB->getParent();
  934. // Update the call site info.
  935. for (const MachineInstr &MI : *MBB)
  936. if (MI.shouldUpdateCallSiteInfo())
  937. MF->eraseCallSiteInfo(&MI);
  938. if (RemovalCallback)
  939. (*RemovalCallback)(MBB);
  940. // Remove all successors.
  941. while (!MBB->succ_empty())
  942. MBB->removeSuccessor(MBB->succ_end() - 1);
  943. // Remove the block.
  944. MBB->eraseFromParent();
  945. }