TailDuplication.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  1. //===-- TailDuplication.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 pass duplicates basic blocks ending in unconditional branches into
  11. // the tails of their predecessors.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/CodeGen/Passes.h"
  15. #include "llvm/ADT/DenseSet.h"
  16. #include "llvm/ADT/SetVector.h"
  17. #include "llvm/ADT/SmallSet.h"
  18. #include "llvm/ADT/Statistic.h"
  19. #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
  20. #include "llvm/CodeGen/MachineFunctionPass.h"
  21. #include "llvm/CodeGen/MachineInstrBuilder.h"
  22. #include "llvm/CodeGen/MachineModuleInfo.h"
  23. #include "llvm/CodeGen/MachineRegisterInfo.h"
  24. #include "llvm/CodeGen/MachineSSAUpdater.h"
  25. #include "llvm/CodeGen/RegisterScavenging.h"
  26. #include "llvm/IR/Function.h"
  27. #include "llvm/Support/CommandLine.h"
  28. #include "llvm/Support/Debug.h"
  29. #include "llvm/Support/ErrorHandling.h"
  30. #include "llvm/Support/raw_ostream.h"
  31. #include "llvm/Target/TargetInstrInfo.h"
  32. #include "llvm/Target/TargetRegisterInfo.h"
  33. #include "llvm/Target/TargetSubtargetInfo.h"
  34. using namespace llvm;
  35. #define DEBUG_TYPE "tailduplication"
  36. STATISTIC(NumTails , "Number of tails duplicated");
  37. STATISTIC(NumTailDups , "Number of tail duplicated blocks");
  38. STATISTIC(NumInstrDups , "Additional instructions due to tail duplication");
  39. STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
  40. STATISTIC(NumAddedPHIs , "Number of phis added");
  41. // Heuristic for tail duplication.
  42. static cl::opt<unsigned>
  43. TailDuplicateSize("tail-dup-size",
  44. cl::desc("Maximum instructions to consider tail duplicating"),
  45. cl::init(2), cl::Hidden);
  46. static cl::opt<bool>
  47. TailDupVerify("tail-dup-verify",
  48. cl::desc("Verify sanity of PHI instructions during taildup"),
  49. cl::init(false), cl::Hidden);
  50. static cl::opt<unsigned>
  51. TailDupLimit("tail-dup-limit", cl::init(~0U), cl::Hidden);
  52. typedef std::vector<std::pair<MachineBasicBlock*,unsigned> > AvailableValsTy;
  53. namespace {
  54. /// TailDuplicatePass - Perform tail duplication.
  55. class TailDuplicatePass : public MachineFunctionPass {
  56. const TargetInstrInfo *TII;
  57. const TargetRegisterInfo *TRI;
  58. const MachineBranchProbabilityInfo *MBPI;
  59. MachineModuleInfo *MMI;
  60. MachineRegisterInfo *MRI;
  61. std::unique_ptr<RegScavenger> RS;
  62. bool PreRegAlloc;
  63. // SSAUpdateVRs - A list of virtual registers for which to update SSA form.
  64. SmallVector<unsigned, 16> SSAUpdateVRs;
  65. // SSAUpdateVals - For each virtual register in SSAUpdateVals keep a list of
  66. // source virtual registers.
  67. DenseMap<unsigned, AvailableValsTy> SSAUpdateVals;
  68. public:
  69. static char ID;
  70. explicit TailDuplicatePass() :
  71. MachineFunctionPass(ID), PreRegAlloc(false) {}
  72. bool runOnMachineFunction(MachineFunction &MF) override;
  73. void getAnalysisUsage(AnalysisUsage &AU) const override;
  74. private:
  75. void AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
  76. MachineBasicBlock *BB);
  77. void ProcessPHI(MachineInstr *MI, MachineBasicBlock *TailBB,
  78. MachineBasicBlock *PredBB,
  79. DenseMap<unsigned, unsigned> &LocalVRMap,
  80. SmallVectorImpl<std::pair<unsigned,unsigned> > &Copies,
  81. const DenseSet<unsigned> &UsedByPhi,
  82. bool Remove);
  83. void DuplicateInstruction(MachineInstr *MI,
  84. MachineBasicBlock *TailBB,
  85. MachineBasicBlock *PredBB,
  86. MachineFunction &MF,
  87. DenseMap<unsigned, unsigned> &LocalVRMap,
  88. const DenseSet<unsigned> &UsedByPhi);
  89. void UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
  90. SmallVectorImpl<MachineBasicBlock *> &TDBBs,
  91. SmallSetVector<MachineBasicBlock*, 8> &Succs);
  92. bool TailDuplicateBlocks(MachineFunction &MF);
  93. bool shouldTailDuplicate(const MachineFunction &MF,
  94. bool IsSimple, MachineBasicBlock &TailBB);
  95. bool isSimpleBB(MachineBasicBlock *TailBB);
  96. bool canCompletelyDuplicateBB(MachineBasicBlock &BB);
  97. bool duplicateSimpleBB(MachineBasicBlock *TailBB,
  98. SmallVectorImpl<MachineBasicBlock *> &TDBBs,
  99. const DenseSet<unsigned> &RegsUsedByPhi,
  100. SmallVectorImpl<MachineInstr *> &Copies);
  101. bool TailDuplicate(MachineBasicBlock *TailBB,
  102. bool IsSimple,
  103. MachineFunction &MF,
  104. SmallVectorImpl<MachineBasicBlock *> &TDBBs,
  105. SmallVectorImpl<MachineInstr *> &Copies);
  106. bool TailDuplicateAndUpdate(MachineBasicBlock *MBB,
  107. bool IsSimple,
  108. MachineFunction &MF);
  109. void RemoveDeadBlock(MachineBasicBlock *MBB);
  110. };
  111. char TailDuplicatePass::ID = 0;
  112. }
  113. char &llvm::TailDuplicateID = TailDuplicatePass::ID;
  114. INITIALIZE_PASS(TailDuplicatePass, "tailduplication", "Tail Duplication",
  115. false, false)
  116. bool TailDuplicatePass::runOnMachineFunction(MachineFunction &MF) {
  117. if (skipOptnoneFunction(*MF.getFunction()))
  118. return false;
  119. TII = MF.getSubtarget().getInstrInfo();
  120. TRI = MF.getSubtarget().getRegisterInfo();
  121. MRI = &MF.getRegInfo();
  122. MMI = getAnalysisIfAvailable<MachineModuleInfo>();
  123. MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
  124. PreRegAlloc = MRI->isSSA();
  125. RS.reset();
  126. if (MRI->tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF))
  127. RS.reset(new RegScavenger());
  128. bool MadeChange = false;
  129. while (TailDuplicateBlocks(MF))
  130. MadeChange = true;
  131. return MadeChange;
  132. }
  133. void TailDuplicatePass::getAnalysisUsage(AnalysisUsage &AU) const {
  134. AU.addRequired<MachineBranchProbabilityInfo>();
  135. MachineFunctionPass::getAnalysisUsage(AU);
  136. }
  137. static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
  138. for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
  139. MachineBasicBlock *MBB = I;
  140. SmallSetVector<MachineBasicBlock*, 8> Preds(MBB->pred_begin(),
  141. MBB->pred_end());
  142. MachineBasicBlock::iterator MI = MBB->begin();
  143. while (MI != MBB->end()) {
  144. if (!MI->isPHI())
  145. break;
  146. for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
  147. PE = Preds.end(); PI != PE; ++PI) {
  148. MachineBasicBlock *PredBB = *PI;
  149. bool Found = false;
  150. for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
  151. MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
  152. if (PHIBB == PredBB) {
  153. Found = true;
  154. break;
  155. }
  156. }
  157. if (!Found) {
  158. dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
  159. dbgs() << " missing input from predecessor BB#"
  160. << PredBB->getNumber() << '\n';
  161. llvm_unreachable(nullptr);
  162. }
  163. }
  164. for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
  165. MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
  166. if (CheckExtra && !Preds.count(PHIBB)) {
  167. dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber()
  168. << ": " << *MI;
  169. dbgs() << " extra input from predecessor BB#"
  170. << PHIBB->getNumber() << '\n';
  171. llvm_unreachable(nullptr);
  172. }
  173. if (PHIBB->getNumber() < 0) {
  174. dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
  175. dbgs() << " non-existing BB#" << PHIBB->getNumber() << '\n';
  176. llvm_unreachable(nullptr);
  177. }
  178. }
  179. ++MI;
  180. }
  181. }
  182. }
  183. /// TailDuplicateAndUpdate - Tail duplicate the block and cleanup.
  184. bool
  185. TailDuplicatePass::TailDuplicateAndUpdate(MachineBasicBlock *MBB,
  186. bool IsSimple,
  187. MachineFunction &MF) {
  188. // Save the successors list.
  189. SmallSetVector<MachineBasicBlock*, 8> Succs(MBB->succ_begin(),
  190. MBB->succ_end());
  191. SmallVector<MachineBasicBlock*, 8> TDBBs;
  192. SmallVector<MachineInstr*, 16> Copies;
  193. if (!TailDuplicate(MBB, IsSimple, MF, TDBBs, Copies))
  194. return false;
  195. ++NumTails;
  196. SmallVector<MachineInstr*, 8> NewPHIs;
  197. MachineSSAUpdater SSAUpdate(MF, &NewPHIs);
  198. // TailBB's immediate successors are now successors of those predecessors
  199. // which duplicated TailBB. Add the predecessors as sources to the PHI
  200. // instructions.
  201. bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
  202. if (PreRegAlloc)
  203. UpdateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
  204. // If it is dead, remove it.
  205. if (isDead) {
  206. NumInstrDups -= MBB->size();
  207. RemoveDeadBlock(MBB);
  208. ++NumDeadBlocks;
  209. }
  210. // Update SSA form.
  211. if (!SSAUpdateVRs.empty()) {
  212. for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
  213. unsigned VReg = SSAUpdateVRs[i];
  214. SSAUpdate.Initialize(VReg);
  215. // If the original definition is still around, add it as an available
  216. // value.
  217. MachineInstr *DefMI = MRI->getVRegDef(VReg);
  218. MachineBasicBlock *DefBB = nullptr;
  219. if (DefMI) {
  220. DefBB = DefMI->getParent();
  221. SSAUpdate.AddAvailableValue(DefBB, VReg);
  222. }
  223. // Add the new vregs as available values.
  224. DenseMap<unsigned, AvailableValsTy>::iterator LI =
  225. SSAUpdateVals.find(VReg);
  226. for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
  227. MachineBasicBlock *SrcBB = LI->second[j].first;
  228. unsigned SrcReg = LI->second[j].second;
  229. SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
  230. }
  231. // Rewrite uses that are outside of the original def's block.
  232. MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
  233. while (UI != MRI->use_end()) {
  234. MachineOperand &UseMO = *UI;
  235. MachineInstr *UseMI = UseMO.getParent();
  236. ++UI;
  237. if (UseMI->isDebugValue()) {
  238. // SSAUpdate can replace the use with an undef. That creates
  239. // a debug instruction that is a kill.
  240. // FIXME: Should it SSAUpdate job to delete debug instructions
  241. // instead of replacing the use with undef?
  242. UseMI->eraseFromParent();
  243. continue;
  244. }
  245. if (UseMI->getParent() == DefBB && !UseMI->isPHI())
  246. continue;
  247. SSAUpdate.RewriteUse(UseMO);
  248. }
  249. }
  250. SSAUpdateVRs.clear();
  251. SSAUpdateVals.clear();
  252. }
  253. // Eliminate some of the copies inserted by tail duplication to maintain
  254. // SSA form.
  255. for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
  256. MachineInstr *Copy = Copies[i];
  257. if (!Copy->isCopy())
  258. continue;
  259. unsigned Dst = Copy->getOperand(0).getReg();
  260. unsigned Src = Copy->getOperand(1).getReg();
  261. if (MRI->hasOneNonDBGUse(Src) &&
  262. MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
  263. // Copy is the only use. Do trivial copy propagation here.
  264. MRI->replaceRegWith(Dst, Src);
  265. Copy->eraseFromParent();
  266. }
  267. }
  268. if (NewPHIs.size())
  269. NumAddedPHIs += NewPHIs.size();
  270. return true;
  271. }
  272. /// TailDuplicateBlocks - Look for small blocks that are unconditionally
  273. /// branched to and do not fall through. Tail-duplicate their instructions
  274. /// into their predecessors to eliminate (dynamic) branches.
  275. bool TailDuplicatePass::TailDuplicateBlocks(MachineFunction &MF) {
  276. bool MadeChange = false;
  277. if (PreRegAlloc && TailDupVerify) {
  278. DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
  279. VerifyPHIs(MF, true);
  280. }
  281. for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
  282. MachineBasicBlock *MBB = I++;
  283. if (NumTails == TailDupLimit)
  284. break;
  285. bool IsSimple = isSimpleBB(MBB);
  286. if (!shouldTailDuplicate(MF, IsSimple, *MBB))
  287. continue;
  288. MadeChange |= TailDuplicateAndUpdate(MBB, IsSimple, MF);
  289. }
  290. if (PreRegAlloc && TailDupVerify)
  291. VerifyPHIs(MF, false);
  292. return MadeChange;
  293. }
  294. static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
  295. const MachineRegisterInfo *MRI) {
  296. for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
  297. if (UseMI.isDebugValue())
  298. continue;
  299. if (UseMI.getParent() != BB)
  300. return true;
  301. }
  302. return false;
  303. }
  304. static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
  305. for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
  306. if (MI->getOperand(i+1).getMBB() == SrcBB)
  307. return i;
  308. return 0;
  309. }
  310. // Remember which registers are used by phis in this block. This is
  311. // used to determine which registers are liveout while modifying the
  312. // block (which is why we need to copy the information).
  313. static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
  314. DenseSet<unsigned> *UsedByPhi) {
  315. for (const auto &MI : BB) {
  316. if (!MI.isPHI())
  317. break;
  318. for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
  319. unsigned SrcReg = MI.getOperand(i).getReg();
  320. UsedByPhi->insert(SrcReg);
  321. }
  322. }
  323. }
  324. /// AddSSAUpdateEntry - Add a definition and source virtual registers pair for
  325. /// SSA update.
  326. void TailDuplicatePass::AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
  327. MachineBasicBlock *BB) {
  328. DenseMap<unsigned, AvailableValsTy>::iterator LI= SSAUpdateVals.find(OrigReg);
  329. if (LI != SSAUpdateVals.end())
  330. LI->second.push_back(std::make_pair(BB, NewReg));
  331. else {
  332. AvailableValsTy Vals;
  333. Vals.push_back(std::make_pair(BB, NewReg));
  334. SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
  335. SSAUpdateVRs.push_back(OrigReg);
  336. }
  337. }
  338. /// ProcessPHI - Process PHI node in TailBB by turning it into a copy in PredBB.
  339. /// Remember the source register that's contributed by PredBB and update SSA
  340. /// update map.
  341. void TailDuplicatePass::ProcessPHI(
  342. MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
  343. DenseMap<unsigned, unsigned> &LocalVRMap,
  344. SmallVectorImpl<std::pair<unsigned, unsigned> > &Copies,
  345. const DenseSet<unsigned> &RegsUsedByPhi, bool Remove) {
  346. unsigned DefReg = MI->getOperand(0).getReg();
  347. unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
  348. assert(SrcOpIdx && "Unable to find matching PHI source?");
  349. unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
  350. const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
  351. LocalVRMap.insert(std::make_pair(DefReg, SrcReg));
  352. // Insert a copy from source to the end of the block. The def register is the
  353. // available value liveout of the block.
  354. unsigned NewDef = MRI->createVirtualRegister(RC);
  355. Copies.push_back(std::make_pair(NewDef, SrcReg));
  356. if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
  357. AddSSAUpdateEntry(DefReg, NewDef, PredBB);
  358. if (!Remove)
  359. return;
  360. // Remove PredBB from the PHI node.
  361. MI->RemoveOperand(SrcOpIdx+1);
  362. MI->RemoveOperand(SrcOpIdx);
  363. if (MI->getNumOperands() == 1)
  364. MI->eraseFromParent();
  365. }
  366. /// DuplicateInstruction - Duplicate a TailBB instruction to PredBB and update
  367. /// the source operands due to earlier PHI translation.
  368. void TailDuplicatePass::DuplicateInstruction(MachineInstr *MI,
  369. MachineBasicBlock *TailBB,
  370. MachineBasicBlock *PredBB,
  371. MachineFunction &MF,
  372. DenseMap<unsigned, unsigned> &LocalVRMap,
  373. const DenseSet<unsigned> &UsedByPhi) {
  374. MachineInstr *NewMI = TII->duplicate(MI, MF);
  375. for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
  376. MachineOperand &MO = NewMI->getOperand(i);
  377. if (!MO.isReg())
  378. continue;
  379. unsigned Reg = MO.getReg();
  380. if (!TargetRegisterInfo::isVirtualRegister(Reg))
  381. continue;
  382. if (MO.isDef()) {
  383. const TargetRegisterClass *RC = MRI->getRegClass(Reg);
  384. unsigned NewReg = MRI->createVirtualRegister(RC);
  385. MO.setReg(NewReg);
  386. LocalVRMap.insert(std::make_pair(Reg, NewReg));
  387. if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
  388. AddSSAUpdateEntry(Reg, NewReg, PredBB);
  389. } else {
  390. DenseMap<unsigned, unsigned>::iterator VI = LocalVRMap.find(Reg);
  391. if (VI != LocalVRMap.end()) {
  392. MO.setReg(VI->second);
  393. // Clear any kill flags from this operand. The new register could have
  394. // uses after this one, so kills are not valid here.
  395. MO.setIsKill(false);
  396. MRI->constrainRegClass(VI->second, MRI->getRegClass(Reg));
  397. }
  398. }
  399. }
  400. PredBB->insert(PredBB->instr_end(), NewMI);
  401. }
  402. /// UpdateSuccessorsPHIs - After FromBB is tail duplicated into its predecessor
  403. /// blocks, the successors have gained new predecessors. Update the PHI
  404. /// instructions in them accordingly.
  405. void
  406. TailDuplicatePass::UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
  407. SmallVectorImpl<MachineBasicBlock *> &TDBBs,
  408. SmallSetVector<MachineBasicBlock*,8> &Succs) {
  409. for (SmallSetVector<MachineBasicBlock*, 8>::iterator SI = Succs.begin(),
  410. SE = Succs.end(); SI != SE; ++SI) {
  411. MachineBasicBlock *SuccBB = *SI;
  412. for (MachineBasicBlock::iterator II = SuccBB->begin(), EE = SuccBB->end();
  413. II != EE; ++II) {
  414. if (!II->isPHI())
  415. break;
  416. MachineInstrBuilder MIB(*FromBB->getParent(), II);
  417. unsigned Idx = 0;
  418. for (unsigned i = 1, e = II->getNumOperands(); i != e; i += 2) {
  419. MachineOperand &MO = II->getOperand(i+1);
  420. if (MO.getMBB() == FromBB) {
  421. Idx = i;
  422. break;
  423. }
  424. }
  425. assert(Idx != 0);
  426. MachineOperand &MO0 = II->getOperand(Idx);
  427. unsigned Reg = MO0.getReg();
  428. if (isDead) {
  429. // Folded into the previous BB.
  430. // There could be duplicate phi source entries. FIXME: Should sdisel
  431. // or earlier pass fixed this?
  432. for (unsigned i = II->getNumOperands()-2; i != Idx; i -= 2) {
  433. MachineOperand &MO = II->getOperand(i+1);
  434. if (MO.getMBB() == FromBB) {
  435. II->RemoveOperand(i+1);
  436. II->RemoveOperand(i);
  437. }
  438. }
  439. } else
  440. Idx = 0;
  441. // If Idx is set, the operands at Idx and Idx+1 must be removed.
  442. // We reuse the location to avoid expensive RemoveOperand calls.
  443. DenseMap<unsigned,AvailableValsTy>::iterator LI=SSAUpdateVals.find(Reg);
  444. if (LI != SSAUpdateVals.end()) {
  445. // This register is defined in the tail block.
  446. for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
  447. MachineBasicBlock *SrcBB = LI->second[j].first;
  448. // If we didn't duplicate a bb into a particular predecessor, we
  449. // might still have added an entry to SSAUpdateVals to correcly
  450. // recompute SSA. If that case, avoid adding a dummy extra argument
  451. // this PHI.
  452. if (!SrcBB->isSuccessor(SuccBB))
  453. continue;
  454. unsigned SrcReg = LI->second[j].second;
  455. if (Idx != 0) {
  456. II->getOperand(Idx).setReg(SrcReg);
  457. II->getOperand(Idx+1).setMBB(SrcBB);
  458. Idx = 0;
  459. } else {
  460. MIB.addReg(SrcReg).addMBB(SrcBB);
  461. }
  462. }
  463. } else {
  464. // Live in tail block, must also be live in predecessors.
  465. for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
  466. MachineBasicBlock *SrcBB = TDBBs[j];
  467. if (Idx != 0) {
  468. II->getOperand(Idx).setReg(Reg);
  469. II->getOperand(Idx+1).setMBB(SrcBB);
  470. Idx = 0;
  471. } else {
  472. MIB.addReg(Reg).addMBB(SrcBB);
  473. }
  474. }
  475. }
  476. if (Idx != 0) {
  477. II->RemoveOperand(Idx+1);
  478. II->RemoveOperand(Idx);
  479. }
  480. }
  481. }
  482. }
  483. /// shouldTailDuplicate - Determine if it is profitable to duplicate this block.
  484. bool
  485. TailDuplicatePass::shouldTailDuplicate(const MachineFunction &MF,
  486. bool IsSimple,
  487. MachineBasicBlock &TailBB) {
  488. // Only duplicate blocks that end with unconditional branches.
  489. if (TailBB.canFallThrough())
  490. return false;
  491. // Don't try to tail-duplicate single-block loops.
  492. if (TailBB.isSuccessor(&TailBB))
  493. return false;
  494. // Set the limit on the cost to duplicate. When optimizing for size,
  495. // duplicate only one, because one branch instruction can be eliminated to
  496. // compensate for the duplication.
  497. unsigned MaxDuplicateCount;
  498. if (TailDuplicateSize.getNumOccurrences() == 0 &&
  499. MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize))
  500. MaxDuplicateCount = 1;
  501. else
  502. MaxDuplicateCount = TailDuplicateSize;
  503. // If the target has hardware branch prediction that can handle indirect
  504. // branches, duplicating them can often make them predictable when there
  505. // are common paths through the code. The limit needs to be high enough
  506. // to allow undoing the effects of tail merging and other optimizations
  507. // that rearrange the predecessors of the indirect branch.
  508. bool HasIndirectbr = false;
  509. if (!TailBB.empty())
  510. HasIndirectbr = TailBB.back().isIndirectBranch();
  511. if (HasIndirectbr && PreRegAlloc)
  512. MaxDuplicateCount = 20;
  513. // Check the instructions in the block to determine whether tail-duplication
  514. // is invalid or unlikely to be profitable.
  515. unsigned InstrCount = 0;
  516. for (MachineBasicBlock::iterator I = TailBB.begin(); I != TailBB.end(); ++I) {
  517. // Non-duplicable things shouldn't be tail-duplicated.
  518. if (I->isNotDuplicable())
  519. return false;
  520. // Do not duplicate 'return' instructions if this is a pre-regalloc run.
  521. // A return may expand into a lot more instructions (e.g. reload of callee
  522. // saved registers) after PEI.
  523. if (PreRegAlloc && I->isReturn())
  524. return false;
  525. // Avoid duplicating calls before register allocation. Calls presents a
  526. // barrier to register allocation so duplicating them may end up increasing
  527. // spills.
  528. if (PreRegAlloc && I->isCall())
  529. return false;
  530. if (!I->isPHI() && !I->isDebugValue())
  531. InstrCount += 1;
  532. if (InstrCount > MaxDuplicateCount)
  533. return false;
  534. }
  535. if (HasIndirectbr && PreRegAlloc)
  536. return true;
  537. if (IsSimple)
  538. return true;
  539. if (!PreRegAlloc)
  540. return true;
  541. return canCompletelyDuplicateBB(TailBB);
  542. }
  543. /// isSimpleBB - True if this BB has only one unconditional jump.
  544. bool
  545. TailDuplicatePass::isSimpleBB(MachineBasicBlock *TailBB) {
  546. if (TailBB->succ_size() != 1)
  547. return false;
  548. if (TailBB->pred_empty())
  549. return false;
  550. MachineBasicBlock::iterator I = TailBB->getFirstNonDebugInstr();
  551. if (I == TailBB->end())
  552. return true;
  553. return I->isUnconditionalBranch();
  554. }
  555. static bool
  556. bothUsedInPHI(const MachineBasicBlock &A,
  557. SmallPtrSet<MachineBasicBlock*, 8> SuccsB) {
  558. for (MachineBasicBlock::const_succ_iterator SI = A.succ_begin(),
  559. SE = A.succ_end(); SI != SE; ++SI) {
  560. MachineBasicBlock *BB = *SI;
  561. if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
  562. return true;
  563. }
  564. return false;
  565. }
  566. bool
  567. TailDuplicatePass::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
  568. for (MachineBasicBlock::pred_iterator PI = BB.pred_begin(),
  569. PE = BB.pred_end(); PI != PE; ++PI) {
  570. MachineBasicBlock *PredBB = *PI;
  571. if (PredBB->succ_size() > 1)
  572. return false;
  573. MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
  574. SmallVector<MachineOperand, 4> PredCond;
  575. if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
  576. return false;
  577. if (!PredCond.empty())
  578. return false;
  579. }
  580. return true;
  581. }
  582. bool
  583. TailDuplicatePass::duplicateSimpleBB(MachineBasicBlock *TailBB,
  584. SmallVectorImpl<MachineBasicBlock *> &TDBBs,
  585. const DenseSet<unsigned> &UsedByPhi,
  586. SmallVectorImpl<MachineInstr *> &Copies) {
  587. SmallPtrSet<MachineBasicBlock*, 8> Succs(TailBB->succ_begin(),
  588. TailBB->succ_end());
  589. SmallVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
  590. TailBB->pred_end());
  591. bool Changed = false;
  592. for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
  593. PE = Preds.end(); PI != PE; ++PI) {
  594. MachineBasicBlock *PredBB = *PI;
  595. if (PredBB->getLandingPadSuccessor())
  596. continue;
  597. if (bothUsedInPHI(*PredBB, Succs))
  598. continue;
  599. MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
  600. SmallVector<MachineOperand, 4> PredCond;
  601. if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
  602. continue;
  603. Changed = true;
  604. DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
  605. << "From simple Succ: " << *TailBB);
  606. MachineBasicBlock *NewTarget = *TailBB->succ_begin();
  607. MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(PredBB));
  608. // Make PredFBB explicit.
  609. if (PredCond.empty())
  610. PredFBB = PredTBB;
  611. // Make fall through explicit.
  612. if (!PredTBB)
  613. PredTBB = NextBB;
  614. if (!PredFBB)
  615. PredFBB = NextBB;
  616. // Redirect
  617. if (PredFBB == TailBB)
  618. PredFBB = NewTarget;
  619. if (PredTBB == TailBB)
  620. PredTBB = NewTarget;
  621. // Make the branch unconditional if possible
  622. if (PredTBB == PredFBB) {
  623. PredCond.clear();
  624. PredFBB = nullptr;
  625. }
  626. // Avoid adding fall through branches.
  627. if (PredFBB == NextBB)
  628. PredFBB = nullptr;
  629. if (PredTBB == NextBB && PredFBB == nullptr)
  630. PredTBB = nullptr;
  631. TII->RemoveBranch(*PredBB);
  632. if (PredTBB)
  633. TII->InsertBranch(*PredBB, PredTBB, PredFBB, PredCond, DebugLoc());
  634. uint32_t Weight = MBPI->getEdgeWeight(PredBB, TailBB);
  635. PredBB->removeSuccessor(TailBB);
  636. unsigned NumSuccessors = PredBB->succ_size();
  637. assert(NumSuccessors <= 1);
  638. if (NumSuccessors == 0 || *PredBB->succ_begin() != NewTarget)
  639. PredBB->addSuccessor(NewTarget, Weight);
  640. TDBBs.push_back(PredBB);
  641. }
  642. return Changed;
  643. }
  644. /// TailDuplicate - If it is profitable, duplicate TailBB's contents in each
  645. /// of its predecessors.
  646. bool
  647. TailDuplicatePass::TailDuplicate(MachineBasicBlock *TailBB,
  648. bool IsSimple,
  649. MachineFunction &MF,
  650. SmallVectorImpl<MachineBasicBlock *> &TDBBs,
  651. SmallVectorImpl<MachineInstr *> &Copies) {
  652. DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n');
  653. DenseSet<unsigned> UsedByPhi;
  654. getRegsUsedByPHIs(*TailBB, &UsedByPhi);
  655. if (IsSimple)
  656. return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
  657. // Iterate through all the unique predecessors and tail-duplicate this
  658. // block into them, if possible. Copying the list ahead of time also
  659. // avoids trouble with the predecessor list reallocating.
  660. bool Changed = false;
  661. SmallSetVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
  662. TailBB->pred_end());
  663. for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
  664. PE = Preds.end(); PI != PE; ++PI) {
  665. MachineBasicBlock *PredBB = *PI;
  666. assert(TailBB != PredBB &&
  667. "Single-block loop should have been rejected earlier!");
  668. // EH edges are ignored by AnalyzeBranch.
  669. if (PredBB->succ_size() > 1)
  670. continue;
  671. MachineBasicBlock *PredTBB, *PredFBB;
  672. SmallVector<MachineOperand, 4> PredCond;
  673. if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
  674. continue;
  675. if (!PredCond.empty())
  676. continue;
  677. // Don't duplicate into a fall-through predecessor (at least for now).
  678. if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
  679. continue;
  680. DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
  681. << "From Succ: " << *TailBB);
  682. TDBBs.push_back(PredBB);
  683. // Remove PredBB's unconditional branch.
  684. TII->RemoveBranch(*PredBB);
  685. if (RS && !TailBB->livein_empty()) {
  686. // Update PredBB livein.
  687. RS->enterBasicBlock(PredBB);
  688. if (!PredBB->empty())
  689. RS->forward(std::prev(PredBB->end()));
  690. for (MachineBasicBlock::livein_iterator I = TailBB->livein_begin(),
  691. E = TailBB->livein_end(); I != E; ++I) {
  692. if (!RS->isRegUsed(*I, false))
  693. // If a register is previously livein to the tail but it's not live
  694. // at the end of predecessor BB, then it should be added to its
  695. // livein list.
  696. PredBB->addLiveIn(*I);
  697. }
  698. }
  699. // Clone the contents of TailBB into PredBB.
  700. DenseMap<unsigned, unsigned> LocalVRMap;
  701. SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
  702. // Use instr_iterator here to properly handle bundles, e.g.
  703. // ARM Thumb2 IT block.
  704. MachineBasicBlock::instr_iterator I = TailBB->instr_begin();
  705. while (I != TailBB->instr_end()) {
  706. MachineInstr *MI = &*I;
  707. ++I;
  708. if (MI->isPHI()) {
  709. // Replace the uses of the def of the PHI with the register coming
  710. // from PredBB.
  711. ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
  712. } else {
  713. // Replace def of virtual registers with new registers, and update
  714. // uses with PHI source register or the new registers.
  715. DuplicateInstruction(MI, TailBB, PredBB, MF, LocalVRMap, UsedByPhi);
  716. }
  717. }
  718. MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
  719. for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
  720. Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
  721. TII->get(TargetOpcode::COPY),
  722. CopyInfos[i].first).addReg(CopyInfos[i].second));
  723. }
  724. // Simplify
  725. TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true);
  726. NumInstrDups += TailBB->size() - 1; // subtract one for removed branch
  727. // Update the CFG.
  728. PredBB->removeSuccessor(PredBB->succ_begin());
  729. assert(PredBB->succ_empty() &&
  730. "TailDuplicate called on block with multiple successors!");
  731. for (MachineBasicBlock::succ_iterator I = TailBB->succ_begin(),
  732. E = TailBB->succ_end(); I != E; ++I)
  733. PredBB->addSuccessor(*I, MBPI->getEdgeWeight(TailBB, I));
  734. Changed = true;
  735. ++NumTailDups;
  736. }
  737. // If TailBB was duplicated into all its predecessors except for the prior
  738. // block, which falls through unconditionally, move the contents of this
  739. // block into the prior block.
  740. MachineBasicBlock *PrevBB = std::prev(MachineFunction::iterator(TailBB));
  741. MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
  742. SmallVector<MachineOperand, 4> PriorCond;
  743. // This has to check PrevBB->succ_size() because EH edges are ignored by
  744. // AnalyzeBranch.
  745. if (PrevBB->succ_size() == 1 &&
  746. !TII->AnalyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true) &&
  747. PriorCond.empty() && !PriorTBB && TailBB->pred_size() == 1 &&
  748. !TailBB->hasAddressTaken()) {
  749. DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
  750. << "From MBB: " << *TailBB);
  751. if (PreRegAlloc) {
  752. DenseMap<unsigned, unsigned> LocalVRMap;
  753. SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
  754. MachineBasicBlock::iterator I = TailBB->begin();
  755. // Process PHI instructions first.
  756. while (I != TailBB->end() && I->isPHI()) {
  757. // Replace the uses of the def of the PHI with the register coming
  758. // from PredBB.
  759. MachineInstr *MI = &*I++;
  760. ProcessPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
  761. if (MI->getParent())
  762. MI->eraseFromParent();
  763. }
  764. // Now copy the non-PHI instructions.
  765. while (I != TailBB->end()) {
  766. // Replace def of virtual registers with new registers, and update
  767. // uses with PHI source register or the new registers.
  768. MachineInstr *MI = &*I++;
  769. assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
  770. DuplicateInstruction(MI, TailBB, PrevBB, MF, LocalVRMap, UsedByPhi);
  771. MI->eraseFromParent();
  772. }
  773. MachineBasicBlock::iterator Loc = PrevBB->getFirstTerminator();
  774. for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
  775. Copies.push_back(BuildMI(*PrevBB, Loc, DebugLoc(),
  776. TII->get(TargetOpcode::COPY),
  777. CopyInfos[i].first)
  778. .addReg(CopyInfos[i].second));
  779. }
  780. } else {
  781. // No PHIs to worry about, just splice the instructions over.
  782. PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
  783. }
  784. PrevBB->removeSuccessor(PrevBB->succ_begin());
  785. assert(PrevBB->succ_empty());
  786. PrevBB->transferSuccessors(TailBB);
  787. TDBBs.push_back(PrevBB);
  788. Changed = true;
  789. }
  790. // If this is after register allocation, there are no phis to fix.
  791. if (!PreRegAlloc)
  792. return Changed;
  793. // If we made no changes so far, we are safe.
  794. if (!Changed)
  795. return Changed;
  796. // Handle the nasty case in that we duplicated a block that is part of a loop
  797. // into some but not all of its predecessors. For example:
  798. // 1 -> 2 <-> 3 |
  799. // \ |
  800. // \---> rest |
  801. // if we duplicate 2 into 1 but not into 3, we end up with
  802. // 12 -> 3 <-> 2 -> rest |
  803. // \ / |
  804. // \----->-----/ |
  805. // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
  806. // with a phi in 3 (which now dominates 2).
  807. // What we do here is introduce a copy in 3 of the register defined by the
  808. // phi, just like when we are duplicating 2 into 3, but we don't copy any
  809. // real instructions or remove the 3 -> 2 edge from the phi in 2.
  810. for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
  811. PE = Preds.end(); PI != PE; ++PI) {
  812. MachineBasicBlock *PredBB = *PI;
  813. if (std::find(TDBBs.begin(), TDBBs.end(), PredBB) != TDBBs.end())
  814. continue;
  815. // EH edges
  816. if (PredBB->succ_size() != 1)
  817. continue;
  818. DenseMap<unsigned, unsigned> LocalVRMap;
  819. SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
  820. MachineBasicBlock::iterator I = TailBB->begin();
  821. // Process PHI instructions first.
  822. while (I != TailBB->end() && I->isPHI()) {
  823. // Replace the uses of the def of the PHI with the register coming
  824. // from PredBB.
  825. MachineInstr *MI = &*I++;
  826. ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
  827. }
  828. MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
  829. for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
  830. Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
  831. TII->get(TargetOpcode::COPY),
  832. CopyInfos[i].first).addReg(CopyInfos[i].second));
  833. }
  834. }
  835. return Changed;
  836. }
  837. /// RemoveDeadBlock - Remove the specified dead machine basic block from the
  838. /// function, updating the CFG.
  839. void TailDuplicatePass::RemoveDeadBlock(MachineBasicBlock *MBB) {
  840. assert(MBB->pred_empty() && "MBB must be dead!");
  841. DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
  842. // Remove all successors.
  843. while (!MBB->succ_empty())
  844. MBB->removeSuccessor(MBB->succ_end()-1);
  845. // Remove the block.
  846. MBB->eraseFromParent();
  847. }