TailDuplicator.cpp 37 KB

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