TailDuplication.cpp 35 KB

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