BranchFolding.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  1. //===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
  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 forwards branches to unconditional branches to make them branch
  11. // directly to the target block. This pass often results in dead MBB's, which
  12. // it then removes.
  13. //
  14. // Note that this pass must be run after register allocation, it cannot handle
  15. // SSA form.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #define DEBUG_TYPE "branchfolding"
  19. #include "BranchFolding.h"
  20. #include "llvm/Function.h"
  21. #include "llvm/CodeGen/Passes.h"
  22. #include "llvm/CodeGen/MachineModuleInfo.h"
  23. #include "llvm/CodeGen/MachineFunctionPass.h"
  24. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  25. #include "llvm/CodeGen/RegisterScavenging.h"
  26. #include "llvm/Target/TargetInstrInfo.h"
  27. #include "llvm/Target/TargetMachine.h"
  28. #include "llvm/Target/TargetRegisterInfo.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/ADT/SmallSet.h"
  34. #include "llvm/ADT/SetVector.h"
  35. #include "llvm/ADT/Statistic.h"
  36. #include "llvm/ADT/STLExtras.h"
  37. #include <algorithm>
  38. using namespace llvm;
  39. STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
  40. STATISTIC(NumBranchOpts, "Number of branches optimized");
  41. STATISTIC(NumTailMerge , "Number of block tails merged");
  42. static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
  43. cl::init(cl::BOU_UNSET), cl::Hidden);
  44. // Throttle for huge numbers of predecessors (compile speed problems)
  45. static cl::opt<unsigned>
  46. TailMergeThreshold("tail-merge-threshold",
  47. cl::desc("Max number of predecessors to consider tail merging"),
  48. cl::init(150), cl::Hidden);
  49. // Heuristic for tail merging (and, inversely, tail duplication).
  50. // TODO: This should be replaced with a target query.
  51. static cl::opt<unsigned>
  52. TailMergeSize("tail-merge-size",
  53. cl::desc("Min number of instructions to consider tail merging"),
  54. cl::init(3), cl::Hidden);
  55. namespace {
  56. /// BranchFolderPass - Wrap branch folder in a machine function pass.
  57. class BranchFolderPass : public MachineFunctionPass,
  58. public BranchFolder {
  59. public:
  60. static char ID;
  61. explicit BranchFolderPass(bool defaultEnableTailMerge)
  62. : MachineFunctionPass(&ID), BranchFolder(defaultEnableTailMerge) {}
  63. virtual bool runOnMachineFunction(MachineFunction &MF);
  64. virtual const char *getPassName() const { return "Control Flow Optimizer"; }
  65. };
  66. }
  67. char BranchFolderPass::ID = 0;
  68. FunctionPass *llvm::createBranchFoldingPass(bool DefaultEnableTailMerge) {
  69. return new BranchFolderPass(DefaultEnableTailMerge);
  70. }
  71. bool BranchFolderPass::runOnMachineFunction(MachineFunction &MF) {
  72. return OptimizeFunction(MF,
  73. MF.getTarget().getInstrInfo(),
  74. MF.getTarget().getRegisterInfo(),
  75. getAnalysisIfAvailable<MachineModuleInfo>());
  76. }
  77. BranchFolder::BranchFolder(bool defaultEnableTailMerge) {
  78. switch (FlagEnableTailMerge) {
  79. case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
  80. case cl::BOU_TRUE: EnableTailMerge = true; break;
  81. case cl::BOU_FALSE: EnableTailMerge = false; break;
  82. }
  83. }
  84. /// RemoveDeadBlock - Remove the specified dead machine basic block from the
  85. /// function, updating the CFG.
  86. void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
  87. assert(MBB->pred_empty() && "MBB must be dead!");
  88. DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
  89. MachineFunction *MF = MBB->getParent();
  90. // drop all successors.
  91. while (!MBB->succ_empty())
  92. MBB->removeSuccessor(MBB->succ_end()-1);
  93. // If there are any labels in the basic block, unregister them from
  94. // MachineModuleInfo.
  95. if (MMI && !MBB->empty()) {
  96. for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
  97. I != E; ++I) {
  98. if (I->isLabel())
  99. // The label ID # is always operand #0, an immediate.
  100. MMI->InvalidateLabel(I->getOperand(0).getImm());
  101. }
  102. }
  103. // Remove the block.
  104. MF->erase(MBB);
  105. }
  106. /// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
  107. /// followed by terminators, and if the implicitly defined registers are not
  108. /// used by the terminators, remove those implicit_def's. e.g.
  109. /// BB1:
  110. /// r0 = implicit_def
  111. /// r1 = implicit_def
  112. /// br
  113. /// This block can be optimized away later if the implicit instructions are
  114. /// removed.
  115. bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock *MBB) {
  116. SmallSet<unsigned, 4> ImpDefRegs;
  117. MachineBasicBlock::iterator I = MBB->begin();
  118. while (I != MBB->end()) {
  119. if (!I->isImplicitDef())
  120. break;
  121. unsigned Reg = I->getOperand(0).getReg();
  122. ImpDefRegs.insert(Reg);
  123. for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
  124. unsigned SubReg = *SubRegs; ++SubRegs)
  125. ImpDefRegs.insert(SubReg);
  126. ++I;
  127. }
  128. if (ImpDefRegs.empty())
  129. return false;
  130. MachineBasicBlock::iterator FirstTerm = I;
  131. while (I != MBB->end()) {
  132. if (!TII->isUnpredicatedTerminator(I))
  133. return false;
  134. // See if it uses any of the implicitly defined registers.
  135. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  136. MachineOperand &MO = I->getOperand(i);
  137. if (!MO.isReg() || !MO.isUse())
  138. continue;
  139. unsigned Reg = MO.getReg();
  140. if (ImpDefRegs.count(Reg))
  141. return false;
  142. }
  143. ++I;
  144. }
  145. I = MBB->begin();
  146. while (I != FirstTerm) {
  147. MachineInstr *ImpDefMI = &*I;
  148. ++I;
  149. MBB->erase(ImpDefMI);
  150. }
  151. return true;
  152. }
  153. /// OptimizeFunction - Perhaps branch folding, tail merging and other
  154. /// CFG optimizations on the given function.
  155. bool BranchFolder::OptimizeFunction(MachineFunction &MF,
  156. const TargetInstrInfo *tii,
  157. const TargetRegisterInfo *tri,
  158. MachineModuleInfo *mmi) {
  159. if (!tii) return false;
  160. TII = tii;
  161. TRI = tri;
  162. MMI = mmi;
  163. RS = TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
  164. // Fix CFG. The later algorithms expect it to be right.
  165. bool MadeChange = false;
  166. for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
  167. MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
  168. SmallVector<MachineOperand, 4> Cond;
  169. if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true))
  170. MadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
  171. MadeChange |= OptimizeImpDefsBlock(MBB);
  172. }
  173. bool MadeChangeThisIteration = true;
  174. while (MadeChangeThisIteration) {
  175. MadeChangeThisIteration = false;
  176. MadeChangeThisIteration |= TailMergeBlocks(MF);
  177. MadeChangeThisIteration |= OptimizeBranches(MF);
  178. MadeChange |= MadeChangeThisIteration;
  179. }
  180. // See if any jump tables have become mergable or dead as the code generator
  181. // did its thing.
  182. MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
  183. if (JTI == 0) {
  184. delete RS;
  185. return MadeChange;
  186. }
  187. const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
  188. // Figure out how these jump tables should be merged.
  189. std::vector<unsigned> JTMapping;
  190. JTMapping.reserve(JTs.size());
  191. // We always keep the 0th jump table.
  192. JTMapping.push_back(0);
  193. // Scan the jump tables, seeing if there are any duplicates. Note that this
  194. // is N^2, which should be fixed someday.
  195. for (unsigned i = 1, e = JTs.size(); i != e; ++i) {
  196. if (JTs[i].MBBs.empty())
  197. JTMapping.push_back(i);
  198. else
  199. JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
  200. }
  201. // If a jump table was merge with another one, walk the function rewriting
  202. // references to jump tables to reference the new JT ID's. Keep track of
  203. // whether we see a jump table idx, if not, we can delete the JT.
  204. BitVector JTIsLive(JTs.size());
  205. for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
  206. BB != E; ++BB) {
  207. for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
  208. I != E; ++I)
  209. for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
  210. MachineOperand &Op = I->getOperand(op);
  211. if (!Op.isJTI()) continue;
  212. unsigned NewIdx = JTMapping[Op.getIndex()];
  213. Op.setIndex(NewIdx);
  214. // Remember that this JT is live.
  215. JTIsLive.set(NewIdx);
  216. }
  217. }
  218. // Finally, remove dead jump tables. This happens either because the
  219. // indirect jump was unreachable (and thus deleted) or because the jump
  220. // table was merged with some other one.
  221. for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
  222. if (!JTIsLive.test(i)) {
  223. JTI->RemoveJumpTable(i);
  224. MadeChange = true;
  225. }
  226. delete RS;
  227. return MadeChange;
  228. }
  229. //===----------------------------------------------------------------------===//
  230. // Tail Merging of Blocks
  231. //===----------------------------------------------------------------------===//
  232. /// HashMachineInstr - Compute a hash value for MI and its operands.
  233. static unsigned HashMachineInstr(const MachineInstr *MI) {
  234. unsigned Hash = MI->getOpcode();
  235. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  236. const MachineOperand &Op = MI->getOperand(i);
  237. // Merge in bits from the operand if easy.
  238. unsigned OperandHash = 0;
  239. switch (Op.getType()) {
  240. case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
  241. case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
  242. case MachineOperand::MO_MachineBasicBlock:
  243. OperandHash = Op.getMBB()->getNumber();
  244. break;
  245. case MachineOperand::MO_FrameIndex:
  246. case MachineOperand::MO_ConstantPoolIndex:
  247. case MachineOperand::MO_JumpTableIndex:
  248. OperandHash = Op.getIndex();
  249. break;
  250. case MachineOperand::MO_GlobalAddress:
  251. case MachineOperand::MO_ExternalSymbol:
  252. // Global address / external symbol are too hard, don't bother, but do
  253. // pull in the offset.
  254. OperandHash = Op.getOffset();
  255. break;
  256. default: break;
  257. }
  258. Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
  259. }
  260. return Hash;
  261. }
  262. /// HashEndOfMBB - Hash the last few instructions in the MBB. For blocks
  263. /// with no successors, we hash two instructions, because cross-jumping
  264. /// only saves code when at least two instructions are removed (since a
  265. /// branch must be inserted). For blocks with a successor, one of the
  266. /// two blocks to be tail-merged will end with a branch already, so
  267. /// it gains to cross-jump even for one instruction.
  268. static unsigned HashEndOfMBB(const MachineBasicBlock *MBB,
  269. unsigned minCommonTailLength) {
  270. MachineBasicBlock::const_iterator I = MBB->end();
  271. if (I == MBB->begin())
  272. return 0; // Empty MBB.
  273. --I;
  274. unsigned Hash = HashMachineInstr(I);
  275. if (I == MBB->begin() || minCommonTailLength == 1)
  276. return Hash; // Single instr MBB.
  277. --I;
  278. // Hash in the second-to-last instruction.
  279. Hash ^= HashMachineInstr(I) << 2;
  280. return Hash;
  281. }
  282. /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
  283. /// of instructions they actually have in common together at their end. Return
  284. /// iterators for the first shared instruction in each block.
  285. static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
  286. MachineBasicBlock *MBB2,
  287. MachineBasicBlock::iterator &I1,
  288. MachineBasicBlock::iterator &I2) {
  289. I1 = MBB1->end();
  290. I2 = MBB2->end();
  291. unsigned TailLen = 0;
  292. while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
  293. --I1; --I2;
  294. if (!I1->isIdenticalTo(I2) ||
  295. // FIXME: This check is dubious. It's used to get around a problem where
  296. // people incorrectly expect inline asm directives to remain in the same
  297. // relative order. This is untenable because normal compiler
  298. // optimizations (like this one) may reorder and/or merge these
  299. // directives.
  300. I1->isInlineAsm()) {
  301. ++I1; ++I2;
  302. break;
  303. }
  304. ++TailLen;
  305. }
  306. return TailLen;
  307. }
  308. /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
  309. /// after it, replacing it with an unconditional branch to NewDest. This
  310. /// returns true if OldInst's block is modified, false if NewDest is modified.
  311. void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
  312. MachineBasicBlock *NewDest) {
  313. MachineBasicBlock *OldBB = OldInst->getParent();
  314. // Remove all the old successors of OldBB from the CFG.
  315. while (!OldBB->succ_empty())
  316. OldBB->removeSuccessor(OldBB->succ_begin());
  317. // Remove all the dead instructions from the end of OldBB.
  318. OldBB->erase(OldInst, OldBB->end());
  319. // If OldBB isn't immediately before OldBB, insert a branch to it.
  320. if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
  321. TII->InsertBranch(*OldBB, NewDest, 0, SmallVector<MachineOperand, 0>());
  322. OldBB->addSuccessor(NewDest);
  323. ++NumTailMerge;
  324. }
  325. /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
  326. /// MBB so that the part before the iterator falls into the part starting at the
  327. /// iterator. This returns the new MBB.
  328. MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
  329. MachineBasicBlock::iterator BBI1) {
  330. MachineFunction &MF = *CurMBB.getParent();
  331. // Create the fall-through block.
  332. MachineFunction::iterator MBBI = &CurMBB;
  333. MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(CurMBB.getBasicBlock());
  334. CurMBB.getParent()->insert(++MBBI, NewMBB);
  335. // Move all the successors of this block to the specified block.
  336. NewMBB->transferSuccessors(&CurMBB);
  337. // Add an edge from CurMBB to NewMBB for the fall-through.
  338. CurMBB.addSuccessor(NewMBB);
  339. // Splice the code over.
  340. NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
  341. // For targets that use the register scavenger, we must maintain LiveIns.
  342. if (RS) {
  343. RS->enterBasicBlock(&CurMBB);
  344. if (!CurMBB.empty())
  345. RS->forward(prior(CurMBB.end()));
  346. BitVector RegsLiveAtExit(TRI->getNumRegs());
  347. RS->getRegsUsed(RegsLiveAtExit, false);
  348. for (unsigned int i = 0, e = TRI->getNumRegs(); i != e; i++)
  349. if (RegsLiveAtExit[i])
  350. NewMBB->addLiveIn(i);
  351. }
  352. return NewMBB;
  353. }
  354. /// EstimateRuntime - Make a rough estimate for how long it will take to run
  355. /// the specified code.
  356. static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
  357. MachineBasicBlock::iterator E) {
  358. unsigned Time = 0;
  359. for (; I != E; ++I) {
  360. const TargetInstrDesc &TID = I->getDesc();
  361. if (TID.isCall())
  362. Time += 10;
  363. else if (TID.mayLoad() || TID.mayStore())
  364. Time += 2;
  365. else
  366. ++Time;
  367. }
  368. return Time;
  369. }
  370. // CurMBB needs to add an unconditional branch to SuccMBB (we removed these
  371. // branches temporarily for tail merging). In the case where CurMBB ends
  372. // with a conditional branch to the next block, optimize by reversing the
  373. // test and conditionally branching to SuccMBB instead.
  374. static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB,
  375. const TargetInstrInfo *TII) {
  376. MachineFunction *MF = CurMBB->getParent();
  377. MachineFunction::iterator I = llvm::next(MachineFunction::iterator(CurMBB));
  378. MachineBasicBlock *TBB = 0, *FBB = 0;
  379. SmallVector<MachineOperand, 4> Cond;
  380. if (I != MF->end() &&
  381. !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
  382. MachineBasicBlock *NextBB = I;
  383. if (TBB == NextBB && !Cond.empty() && !FBB) {
  384. if (!TII->ReverseBranchCondition(Cond)) {
  385. TII->RemoveBranch(*CurMBB);
  386. TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
  387. return;
  388. }
  389. }
  390. }
  391. TII->InsertBranch(*CurMBB, SuccBB, NULL, SmallVector<MachineOperand, 0>());
  392. }
  393. bool
  394. BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const {
  395. if (getHash() < o.getHash())
  396. return true;
  397. else if (getHash() > o.getHash())
  398. return false;
  399. else if (getBlock()->getNumber() < o.getBlock()->getNumber())
  400. return true;
  401. else if (getBlock()->getNumber() > o.getBlock()->getNumber())
  402. return false;
  403. else {
  404. // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
  405. // an object with itself.
  406. #ifndef _GLIBCXX_DEBUG
  407. llvm_unreachable("Predecessor appears twice");
  408. #endif
  409. return false;
  410. }
  411. }
  412. /// CountTerminators - Count the number of terminators in the given
  413. /// block and set I to the position of the first non-terminator, if there
  414. /// is one, or MBB->end() otherwise.
  415. static unsigned CountTerminators(MachineBasicBlock *MBB,
  416. MachineBasicBlock::iterator &I) {
  417. I = MBB->end();
  418. unsigned NumTerms = 0;
  419. for (;;) {
  420. if (I == MBB->begin()) {
  421. I = MBB->end();
  422. break;
  423. }
  424. --I;
  425. if (!I->getDesc().isTerminator()) break;
  426. ++NumTerms;
  427. }
  428. return NumTerms;
  429. }
  430. /// ProfitableToMerge - Check if two machine basic blocks have a common tail
  431. /// and decide if it would be profitable to merge those tails. Return the
  432. /// length of the common tail and iterators to the first common instruction
  433. /// in each block.
  434. static bool ProfitableToMerge(MachineBasicBlock *MBB1,
  435. MachineBasicBlock *MBB2,
  436. unsigned minCommonTailLength,
  437. unsigned &CommonTailLen,
  438. MachineBasicBlock::iterator &I1,
  439. MachineBasicBlock::iterator &I2,
  440. MachineBasicBlock *SuccBB,
  441. MachineBasicBlock *PredBB) {
  442. CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2);
  443. MachineFunction *MF = MBB1->getParent();
  444. if (CommonTailLen == 0)
  445. return false;
  446. // It's almost always profitable to merge any number of non-terminator
  447. // instructions with the block that falls through into the common successor.
  448. if (MBB1 == PredBB || MBB2 == PredBB) {
  449. MachineBasicBlock::iterator I;
  450. unsigned NumTerms = CountTerminators(MBB1 == PredBB ? MBB2 : MBB1, I);
  451. if (CommonTailLen > NumTerms)
  452. return true;
  453. }
  454. // If one of the blocks can be completely merged and happens to be in
  455. // a position where the other could fall through into it, merge any number
  456. // of instructions, because it can be done without a branch.
  457. // TODO: If the blocks are not adjacent, move one of them so that they are?
  458. if (MBB1->isLayoutSuccessor(MBB2) && I2 == MBB2->begin())
  459. return true;
  460. if (MBB2->isLayoutSuccessor(MBB1) && I1 == MBB1->begin())
  461. return true;
  462. // If both blocks have an unconditional branch temporarily stripped out,
  463. // count that as an additional common instruction for the following
  464. // heuristics.
  465. unsigned EffectiveTailLen = CommonTailLen;
  466. if (SuccBB && MBB1 != PredBB && MBB2 != PredBB &&
  467. !MBB1->back().getDesc().isBarrier() &&
  468. !MBB2->back().getDesc().isBarrier())
  469. ++EffectiveTailLen;
  470. // Check if the common tail is long enough to be worthwhile.
  471. if (EffectiveTailLen >= minCommonTailLength)
  472. return true;
  473. // If we are optimizing for code size, 2 instructions in common is enough if
  474. // we don't have to split a block. At worst we will be introducing 1 new
  475. // branch instruction, which is likely to be smaller than the 2
  476. // instructions that would be deleted in the merge.
  477. if (EffectiveTailLen >= 2 &&
  478. MF->getFunction()->hasFnAttr(Attribute::OptimizeForSize) &&
  479. (I1 == MBB1->begin() || I2 == MBB2->begin()))
  480. return true;
  481. return false;
  482. }
  483. /// ComputeSameTails - Look through all the blocks in MergePotentials that have
  484. /// hash CurHash (guaranteed to match the last element). Build the vector
  485. /// SameTails of all those that have the (same) largest number of instructions
  486. /// in common of any pair of these blocks. SameTails entries contain an
  487. /// iterator into MergePotentials (from which the MachineBasicBlock can be
  488. /// found) and a MachineBasicBlock::iterator into that MBB indicating the
  489. /// instruction where the matching code sequence begins.
  490. /// Order of elements in SameTails is the reverse of the order in which
  491. /// those blocks appear in MergePotentials (where they are not necessarily
  492. /// consecutive).
  493. unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
  494. unsigned minCommonTailLength,
  495. MachineBasicBlock *SuccBB,
  496. MachineBasicBlock *PredBB) {
  497. unsigned maxCommonTailLength = 0U;
  498. SameTails.clear();
  499. MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
  500. MPIterator HighestMPIter = prior(MergePotentials.end());
  501. for (MPIterator CurMPIter = prior(MergePotentials.end()),
  502. B = MergePotentials.begin();
  503. CurMPIter != B && CurMPIter->getHash() == CurHash;
  504. --CurMPIter) {
  505. for (MPIterator I = prior(CurMPIter); I->getHash() == CurHash ; --I) {
  506. unsigned CommonTailLen;
  507. if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(),
  508. minCommonTailLength,
  509. CommonTailLen, TrialBBI1, TrialBBI2,
  510. SuccBB, PredBB)) {
  511. if (CommonTailLen > maxCommonTailLength) {
  512. SameTails.clear();
  513. maxCommonTailLength = CommonTailLen;
  514. HighestMPIter = CurMPIter;
  515. SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1));
  516. }
  517. if (HighestMPIter == CurMPIter &&
  518. CommonTailLen == maxCommonTailLength)
  519. SameTails.push_back(SameTailElt(I, TrialBBI2));
  520. }
  521. if (I == B)
  522. break;
  523. }
  524. }
  525. return maxCommonTailLength;
  526. }
  527. /// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
  528. /// MergePotentials, restoring branches at ends of blocks as appropriate.
  529. void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
  530. MachineBasicBlock *SuccBB,
  531. MachineBasicBlock *PredBB) {
  532. MPIterator CurMPIter, B;
  533. for (CurMPIter = prior(MergePotentials.end()), B = MergePotentials.begin();
  534. CurMPIter->getHash() == CurHash;
  535. --CurMPIter) {
  536. // Put the unconditional branch back, if we need one.
  537. MachineBasicBlock *CurMBB = CurMPIter->getBlock();
  538. if (SuccBB && CurMBB != PredBB)
  539. FixTail(CurMBB, SuccBB, TII);
  540. if (CurMPIter == B)
  541. break;
  542. }
  543. if (CurMPIter->getHash() != CurHash)
  544. CurMPIter++;
  545. MergePotentials.erase(CurMPIter, MergePotentials.end());
  546. }
  547. /// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
  548. /// only of the common tail. Create a block that does by splitting one.
  549. unsigned BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
  550. unsigned maxCommonTailLength) {
  551. unsigned commonTailIndex = 0;
  552. unsigned TimeEstimate = ~0U;
  553. for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
  554. // Use PredBB if possible; that doesn't require a new branch.
  555. if (SameTails[i].getBlock() == PredBB) {
  556. commonTailIndex = i;
  557. break;
  558. }
  559. // Otherwise, make a (fairly bogus) choice based on estimate of
  560. // how long it will take the various blocks to execute.
  561. unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(),
  562. SameTails[i].getTailStartPos());
  563. if (t <= TimeEstimate) {
  564. TimeEstimate = t;
  565. commonTailIndex = i;
  566. }
  567. }
  568. MachineBasicBlock::iterator BBI =
  569. SameTails[commonTailIndex].getTailStartPos();
  570. MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
  571. DEBUG(dbgs() << "\nSplitting BB#" << MBB->getNumber() << ", size "
  572. << maxCommonTailLength);
  573. MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI);
  574. SameTails[commonTailIndex].setBlock(newMBB);
  575. SameTails[commonTailIndex].setTailStartPos(newMBB->begin());
  576. // If we split PredBB, newMBB is the new predecessor.
  577. if (PredBB == MBB)
  578. PredBB = newMBB;
  579. return commonTailIndex;
  580. }
  581. // See if any of the blocks in MergePotentials (which all have a common single
  582. // successor, or all have no successor) can be tail-merged. If there is a
  583. // successor, any blocks in MergePotentials that are not tail-merged and
  584. // are not immediately before Succ must have an unconditional branch to
  585. // Succ added (but the predecessor/successor lists need no adjustment).
  586. // The lone predecessor of Succ that falls through into Succ,
  587. // if any, is given in PredBB.
  588. bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,
  589. MachineBasicBlock *PredBB) {
  590. bool MadeChange = false;
  591. // Except for the special cases below, tail-merge if there are at least
  592. // this many instructions in common.
  593. unsigned minCommonTailLength = TailMergeSize;
  594. DEBUG(dbgs() << "\nTryTailMergeBlocks: ";
  595. for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
  596. dbgs() << "BB#" << MergePotentials[i].getBlock()->getNumber()
  597. << (i == e-1 ? "" : ", ");
  598. dbgs() << "\n";
  599. if (SuccBB) {
  600. dbgs() << " with successor BB#" << SuccBB->getNumber() << '\n';
  601. if (PredBB)
  602. dbgs() << " which has fall-through from BB#"
  603. << PredBB->getNumber() << "\n";
  604. }
  605. dbgs() << "Looking for common tails of at least "
  606. << minCommonTailLength << " instruction"
  607. << (minCommonTailLength == 1 ? "" : "s") << '\n';
  608. );
  609. // Sort by hash value so that blocks with identical end sequences sort
  610. // together.
  611. std::stable_sort(MergePotentials.begin(), MergePotentials.end());
  612. // Walk through equivalence sets looking for actual exact matches.
  613. while (MergePotentials.size() > 1) {
  614. unsigned CurHash = MergePotentials.back().getHash();
  615. // Build SameTails, identifying the set of blocks with this hash code
  616. // and with the maximum number of instructions in common.
  617. unsigned maxCommonTailLength = ComputeSameTails(CurHash,
  618. minCommonTailLength,
  619. SuccBB, PredBB);
  620. // If we didn't find any pair that has at least minCommonTailLength
  621. // instructions in common, remove all blocks with this hash code and retry.
  622. if (SameTails.empty()) {
  623. RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
  624. continue;
  625. }
  626. // If one of the blocks is the entire common tail (and not the entry
  627. // block, which we can't jump to), we can treat all blocks with this same
  628. // tail at once. Use PredBB if that is one of the possibilities, as that
  629. // will not introduce any extra branches.
  630. MachineBasicBlock *EntryBB = MergePotentials.begin()->getBlock()->
  631. getParent()->begin();
  632. unsigned commonTailIndex = SameTails.size();
  633. // If there are two blocks, check to see if one can be made to fall through
  634. // into the other.
  635. if (SameTails.size() == 2 &&
  636. SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) &&
  637. SameTails[1].tailIsWholeBlock())
  638. commonTailIndex = 1;
  639. else if (SameTails.size() == 2 &&
  640. SameTails[1].getBlock()->isLayoutSuccessor(
  641. SameTails[0].getBlock()) &&
  642. SameTails[0].tailIsWholeBlock())
  643. commonTailIndex = 0;
  644. else {
  645. // Otherwise just pick one, favoring the fall-through predecessor if
  646. // there is one.
  647. for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
  648. MachineBasicBlock *MBB = SameTails[i].getBlock();
  649. if (MBB == EntryBB && SameTails[i].tailIsWholeBlock())
  650. continue;
  651. if (MBB == PredBB) {
  652. commonTailIndex = i;
  653. break;
  654. }
  655. if (SameTails[i].tailIsWholeBlock())
  656. commonTailIndex = i;
  657. }
  658. }
  659. if (commonTailIndex == SameTails.size() ||
  660. (SameTails[commonTailIndex].getBlock() == PredBB &&
  661. !SameTails[commonTailIndex].tailIsWholeBlock())) {
  662. // None of the blocks consist entirely of the common tail.
  663. // Split a block so that one does.
  664. commonTailIndex = CreateCommonTailOnlyBlock(PredBB, maxCommonTailLength);
  665. }
  666. MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
  667. // MBB is common tail. Adjust all other BB's to jump to this one.
  668. // Traversal must be forwards so erases work.
  669. DEBUG(dbgs() << "\nUsing common tail in BB#" << MBB->getNumber()
  670. << " for ");
  671. for (unsigned int i=0, e = SameTails.size(); i != e; ++i) {
  672. if (commonTailIndex == i)
  673. continue;
  674. DEBUG(dbgs() << "BB#" << SameTails[i].getBlock()->getNumber()
  675. << (i == e-1 ? "" : ", "));
  676. // Hack the end off BB i, making it jump to BB commonTailIndex instead.
  677. ReplaceTailWithBranchTo(SameTails[i].getTailStartPos(), MBB);
  678. // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
  679. MergePotentials.erase(SameTails[i].getMPIter());
  680. }
  681. DEBUG(dbgs() << "\n");
  682. // We leave commonTailIndex in the worklist in case there are other blocks
  683. // that match it with a smaller number of instructions.
  684. MadeChange = true;
  685. }
  686. return MadeChange;
  687. }
  688. bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
  689. if (!EnableTailMerge) return false;
  690. bool MadeChange = false;
  691. // First find blocks with no successors.
  692. MergePotentials.clear();
  693. for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
  694. if (I->succ_empty())
  695. MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(I, 2U), I));
  696. }
  697. // See if we can do any tail merging on those.
  698. if (MergePotentials.size() < TailMergeThreshold &&
  699. MergePotentials.size() >= 2)
  700. MadeChange |= TryTailMergeBlocks(NULL, NULL);
  701. // Look at blocks (IBB) with multiple predecessors (PBB).
  702. // We change each predecessor to a canonical form, by
  703. // (1) temporarily removing any unconditional branch from the predecessor
  704. // to IBB, and
  705. // (2) alter conditional branches so they branch to the other block
  706. // not IBB; this may require adding back an unconditional branch to IBB
  707. // later, where there wasn't one coming in. E.g.
  708. // Bcc IBB
  709. // fallthrough to QBB
  710. // here becomes
  711. // Bncc QBB
  712. // with a conceptual B to IBB after that, which never actually exists.
  713. // With those changes, we see whether the predecessors' tails match,
  714. // and merge them if so. We change things out of canonical form and
  715. // back to the way they were later in the process. (OptimizeBranches
  716. // would undo some of this, but we can't use it, because we'd get into
  717. // a compile-time infinite loop repeatedly doing and undoing the same
  718. // transformations.)
  719. for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
  720. I != E; ++I) {
  721. if (I->pred_size() >= 2 && I->pred_size() < TailMergeThreshold) {
  722. SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
  723. MachineBasicBlock *IBB = I;
  724. MachineBasicBlock *PredBB = prior(I);
  725. MergePotentials.clear();
  726. for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
  727. E2 = I->pred_end();
  728. P != E2; ++P) {
  729. MachineBasicBlock *PBB = *P;
  730. // Skip blocks that loop to themselves, can't tail merge these.
  731. if (PBB == IBB)
  732. continue;
  733. // Visit each predecessor only once.
  734. if (!UniquePreds.insert(PBB))
  735. continue;
  736. MachineBasicBlock *TBB = 0, *FBB = 0;
  737. SmallVector<MachineOperand, 4> Cond;
  738. if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond, true)) {
  739. // Failing case: IBB is the target of a cbr, and
  740. // we cannot reverse the branch.
  741. SmallVector<MachineOperand, 4> NewCond(Cond);
  742. if (!Cond.empty() && TBB == IBB) {
  743. if (TII->ReverseBranchCondition(NewCond))
  744. continue;
  745. // This is the QBB case described above
  746. if (!FBB)
  747. FBB = llvm::next(MachineFunction::iterator(PBB));
  748. }
  749. // Failing case: the only way IBB can be reached from PBB is via
  750. // exception handling. Happens for landing pads. Would be nice
  751. // to have a bit in the edge so we didn't have to do all this.
  752. if (IBB->isLandingPad()) {
  753. MachineFunction::iterator IP = PBB; IP++;
  754. MachineBasicBlock *PredNextBB = NULL;
  755. if (IP != MF.end())
  756. PredNextBB = IP;
  757. if (TBB == NULL) {
  758. if (IBB != PredNextBB) // fallthrough
  759. continue;
  760. } else if (FBB) {
  761. if (TBB != IBB && FBB != IBB) // cbr then ubr
  762. continue;
  763. } else if (Cond.empty()) {
  764. if (TBB != IBB) // ubr
  765. continue;
  766. } else {
  767. if (TBB != IBB && IBB != PredNextBB) // cbr
  768. continue;
  769. }
  770. }
  771. // Remove the unconditional branch at the end, if any.
  772. if (TBB && (Cond.empty() || FBB)) {
  773. TII->RemoveBranch(*PBB);
  774. if (!Cond.empty())
  775. // reinsert conditional branch only, for now
  776. TII->InsertBranch(*PBB, (TBB == IBB) ? FBB : TBB, 0, NewCond);
  777. }
  778. MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(PBB, 1U),
  779. *P));
  780. }
  781. }
  782. if (MergePotentials.size() >= 2)
  783. MadeChange |= TryTailMergeBlocks(IBB, PredBB);
  784. // Reinsert an unconditional branch if needed.
  785. // The 1 below can occur as a result of removing blocks in TryTailMergeBlocks.
  786. PredBB = prior(I); // this may have been changed in TryTailMergeBlocks
  787. if (MergePotentials.size() == 1 &&
  788. MergePotentials.begin()->getBlock() != PredBB)
  789. FixTail(MergePotentials.begin()->getBlock(), IBB, TII);
  790. }
  791. }
  792. return MadeChange;
  793. }
  794. //===----------------------------------------------------------------------===//
  795. // Branch Optimization
  796. //===----------------------------------------------------------------------===//
  797. bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
  798. bool MadeChange = false;
  799. // Make sure blocks are numbered in order
  800. MF.RenumberBlocks();
  801. for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
  802. MachineBasicBlock *MBB = I++;
  803. MadeChange |= OptimizeBlock(MBB);
  804. // If it is dead, remove it.
  805. if (MBB->pred_empty()) {
  806. RemoveDeadBlock(MBB);
  807. MadeChange = true;
  808. ++NumDeadBlocks;
  809. }
  810. }
  811. return MadeChange;
  812. }
  813. /// IsBetterFallthrough - Return true if it would be clearly better to
  814. /// fall-through to MBB1 than to fall through into MBB2. This has to return
  815. /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
  816. /// result in infinite loops.
  817. static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
  818. MachineBasicBlock *MBB2) {
  819. // Right now, we use a simple heuristic. If MBB2 ends with a call, and
  820. // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
  821. // optimize branches that branch to either a return block or an assert block
  822. // into a fallthrough to the return.
  823. if (MBB1->empty() || MBB2->empty()) return false;
  824. // If there is a clear successor ordering we make sure that one block
  825. // will fall through to the next
  826. if (MBB1->isSuccessor(MBB2)) return true;
  827. if (MBB2->isSuccessor(MBB1)) return false;
  828. MachineInstr *MBB1I = --MBB1->end();
  829. MachineInstr *MBB2I = --MBB2->end();
  830. return MBB2I->getDesc().isCall() && !MBB1I->getDesc().isCall();
  831. }
  832. /// OptimizeBlock - Analyze and optimize control flow related to the specified
  833. /// block. This is never called on the entry block.
  834. bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
  835. bool MadeChange = false;
  836. MachineFunction &MF = *MBB->getParent();
  837. ReoptimizeBlock:
  838. MachineFunction::iterator FallThrough = MBB;
  839. ++FallThrough;
  840. // If this block is empty, make everyone use its fall-through, not the block
  841. // explicitly. Landing pads should not do this since the landing-pad table
  842. // points to this block. Blocks with their addresses taken shouldn't be
  843. // optimized away.
  844. if (MBB->empty() && !MBB->isLandingPad() && !MBB->hasAddressTaken()) {
  845. // Dead block? Leave for cleanup later.
  846. if (MBB->pred_empty()) return MadeChange;
  847. if (FallThrough == MF.end()) {
  848. // TODO: Simplify preds to not branch here if possible!
  849. } else {
  850. // Rewrite all predecessors of the old block to go to the fallthrough
  851. // instead.
  852. while (!MBB->pred_empty()) {
  853. MachineBasicBlock *Pred = *(MBB->pred_end()-1);
  854. Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
  855. }
  856. // If MBB was the target of a jump table, update jump tables to go to the
  857. // fallthrough instead.
  858. if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
  859. MJTI->ReplaceMBBInJumpTables(MBB, FallThrough);
  860. MadeChange = true;
  861. }
  862. return MadeChange;
  863. }
  864. // Check to see if we can simplify the terminator of the block before this
  865. // one.
  866. MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
  867. MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
  868. SmallVector<MachineOperand, 4> PriorCond;
  869. bool PriorUnAnalyzable =
  870. TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
  871. if (!PriorUnAnalyzable) {
  872. // If the CFG for the prior block has extra edges, remove them.
  873. MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
  874. !PriorCond.empty());
  875. // If the previous branch is conditional and both conditions go to the same
  876. // destination, remove the branch, replacing it with an unconditional one or
  877. // a fall-through.
  878. if (PriorTBB && PriorTBB == PriorFBB) {
  879. TII->RemoveBranch(PrevBB);
  880. PriorCond.clear();
  881. if (PriorTBB != MBB)
  882. TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
  883. MadeChange = true;
  884. ++NumBranchOpts;
  885. goto ReoptimizeBlock;
  886. }
  887. // If the previous block unconditionally falls through to this block and
  888. // this block has no other predecessors, move the contents of this block
  889. // into the prior block. This doesn't usually happen when SimplifyCFG
  890. // has been used, but it can happen if tail merging splits a fall-through
  891. // predecessor of a block.
  892. // This has to check PrevBB->succ_size() because EH edges are ignored by
  893. // AnalyzeBranch.
  894. if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 &&
  895. PrevBB.succ_size() == 1 &&
  896. !MBB->hasAddressTaken()) {
  897. DEBUG(dbgs() << "\nMerging into block: " << PrevBB
  898. << "From MBB: " << *MBB);
  899. PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end());
  900. PrevBB.removeSuccessor(PrevBB.succ_begin());;
  901. assert(PrevBB.succ_empty());
  902. PrevBB.transferSuccessors(MBB);
  903. MadeChange = true;
  904. return MadeChange;
  905. }
  906. // If the previous branch *only* branches to *this* block (conditional or
  907. // not) remove the branch.
  908. if (PriorTBB == MBB && PriorFBB == 0) {
  909. TII->RemoveBranch(PrevBB);
  910. MadeChange = true;
  911. ++NumBranchOpts;
  912. goto ReoptimizeBlock;
  913. }
  914. // If the prior block branches somewhere else on the condition and here if
  915. // the condition is false, remove the uncond second branch.
  916. if (PriorFBB == MBB) {
  917. TII->RemoveBranch(PrevBB);
  918. TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
  919. MadeChange = true;
  920. ++NumBranchOpts;
  921. goto ReoptimizeBlock;
  922. }
  923. // If the prior block branches here on true and somewhere else on false, and
  924. // if the branch condition is reversible, reverse the branch to create a
  925. // fall-through.
  926. if (PriorTBB == MBB) {
  927. SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
  928. if (!TII->ReverseBranchCondition(NewPriorCond)) {
  929. TII->RemoveBranch(PrevBB);
  930. TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
  931. MadeChange = true;
  932. ++NumBranchOpts;
  933. goto ReoptimizeBlock;
  934. }
  935. }
  936. // If this block has no successors (e.g. it is a return block or ends with
  937. // a call to a no-return function like abort or __cxa_throw) and if the pred
  938. // falls through into this block, and if it would otherwise fall through
  939. // into the block after this, move this block to the end of the function.
  940. //
  941. // We consider it more likely that execution will stay in the function (e.g.
  942. // due to loops) than it is to exit it. This asserts in loops etc, moving
  943. // the assert condition out of the loop body.
  944. if (MBB->succ_empty() && !PriorCond.empty() && PriorFBB == 0 &&
  945. MachineFunction::iterator(PriorTBB) == FallThrough &&
  946. !MBB->canFallThrough()) {
  947. bool DoTransform = true;
  948. // We have to be careful that the succs of PredBB aren't both no-successor
  949. // blocks. If neither have successors and if PredBB is the second from
  950. // last block in the function, we'd just keep swapping the two blocks for
  951. // last. Only do the swap if one is clearly better to fall through than
  952. // the other.
  953. if (FallThrough == --MF.end() &&
  954. !IsBetterFallthrough(PriorTBB, MBB))
  955. DoTransform = false;
  956. // We don't want to do this transformation if we have control flow like:
  957. // br cond BB2
  958. // BB1:
  959. // ..
  960. // jmp BBX
  961. // BB2:
  962. // ..
  963. // ret
  964. //
  965. // In this case, we could actually be moving the return block *into* a
  966. // loop!
  967. if (DoTransform && !MBB->succ_empty() &&
  968. (!PriorTBB->canFallThrough() || PriorTBB->empty()))
  969. DoTransform = false;
  970. if (DoTransform) {
  971. // Reverse the branch so we will fall through on the previous true cond.
  972. SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
  973. if (!TII->ReverseBranchCondition(NewPriorCond)) {
  974. DEBUG(dbgs() << "\nMoving MBB: " << *MBB
  975. << "To make fallthrough to: " << *PriorTBB << "\n");
  976. TII->RemoveBranch(PrevBB);
  977. TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
  978. // Move this block to the end of the function.
  979. MBB->moveAfter(--MF.end());
  980. MadeChange = true;
  981. ++NumBranchOpts;
  982. return MadeChange;
  983. }
  984. }
  985. }
  986. }
  987. // Analyze the branch in the current block.
  988. MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
  989. SmallVector<MachineOperand, 4> CurCond;
  990. bool CurUnAnalyzable= TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
  991. if (!CurUnAnalyzable) {
  992. // If the CFG for the prior block has extra edges, remove them.
  993. MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
  994. // If this is a two-way branch, and the FBB branches to this block, reverse
  995. // the condition so the single-basic-block loop is faster. Instead of:
  996. // Loop: xxx; jcc Out; jmp Loop
  997. // we want:
  998. // Loop: xxx; jncc Loop; jmp Out
  999. if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
  1000. SmallVector<MachineOperand, 4> NewCond(CurCond);
  1001. if (!TII->ReverseBranchCondition(NewCond)) {
  1002. TII->RemoveBranch(*MBB);
  1003. TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
  1004. MadeChange = true;
  1005. ++NumBranchOpts;
  1006. goto ReoptimizeBlock;
  1007. }
  1008. }
  1009. // If this branch is the only thing in its block, see if we can forward
  1010. // other blocks across it.
  1011. if (CurTBB && CurCond.empty() && CurFBB == 0 &&
  1012. MBB->begin()->getDesc().isBranch() && CurTBB != MBB &&
  1013. !MBB->hasAddressTaken()) {
  1014. // This block may contain just an unconditional branch. Because there can
  1015. // be 'non-branch terminators' in the block, try removing the branch and
  1016. // then seeing if the block is empty.
  1017. TII->RemoveBranch(*MBB);
  1018. // If this block is just an unconditional branch to CurTBB, we can
  1019. // usually completely eliminate the block. The only case we cannot
  1020. // completely eliminate the block is when the block before this one
  1021. // falls through into MBB and we can't understand the prior block's branch
  1022. // condition.
  1023. if (MBB->empty()) {
  1024. bool PredHasNoFallThrough = !PrevBB.canFallThrough();
  1025. if (PredHasNoFallThrough || !PriorUnAnalyzable ||
  1026. !PrevBB.isSuccessor(MBB)) {
  1027. // If the prior block falls through into us, turn it into an
  1028. // explicit branch to us to make updates simpler.
  1029. if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
  1030. PriorTBB != MBB && PriorFBB != MBB) {
  1031. if (PriorTBB == 0) {
  1032. assert(PriorCond.empty() && PriorFBB == 0 &&
  1033. "Bad branch analysis");
  1034. PriorTBB = MBB;
  1035. } else {
  1036. assert(PriorFBB == 0 && "Machine CFG out of date!");
  1037. PriorFBB = MBB;
  1038. }
  1039. TII->RemoveBranch(PrevBB);
  1040. TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
  1041. }
  1042. // Iterate through all the predecessors, revectoring each in-turn.
  1043. size_t PI = 0;
  1044. bool DidChange = false;
  1045. bool HasBranchToSelf = false;
  1046. while(PI != MBB->pred_size()) {
  1047. MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
  1048. if (PMBB == MBB) {
  1049. // If this block has an uncond branch to itself, leave it.
  1050. ++PI;
  1051. HasBranchToSelf = true;
  1052. } else {
  1053. DidChange = true;
  1054. PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
  1055. // If this change resulted in PMBB ending in a conditional
  1056. // branch where both conditions go to the same destination,
  1057. // change this to an unconditional branch (and fix the CFG).
  1058. MachineBasicBlock *NewCurTBB = 0, *NewCurFBB = 0;
  1059. SmallVector<MachineOperand, 4> NewCurCond;
  1060. bool NewCurUnAnalyzable = TII->AnalyzeBranch(*PMBB, NewCurTBB,
  1061. NewCurFBB, NewCurCond, true);
  1062. if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
  1063. TII->RemoveBranch(*PMBB);
  1064. NewCurCond.clear();
  1065. TII->InsertBranch(*PMBB, NewCurTBB, 0, NewCurCond);
  1066. MadeChange = true;
  1067. ++NumBranchOpts;
  1068. PMBB->CorrectExtraCFGEdges(NewCurTBB, 0, false);
  1069. }
  1070. }
  1071. }
  1072. // Change any jumptables to go to the new MBB.
  1073. if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
  1074. MJTI->ReplaceMBBInJumpTables(MBB, CurTBB);
  1075. if (DidChange) {
  1076. ++NumBranchOpts;
  1077. MadeChange = true;
  1078. if (!HasBranchToSelf) return MadeChange;
  1079. }
  1080. }
  1081. }
  1082. // Add the branch back if the block is more than just an uncond branch.
  1083. TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
  1084. }
  1085. }
  1086. // If the prior block doesn't fall through into this block, and if this
  1087. // block doesn't fall through into some other block, see if we can find a
  1088. // place to move this block where a fall-through will happen.
  1089. if (!PrevBB.canFallThrough()) {
  1090. // Now we know that there was no fall-through into this block, check to
  1091. // see if it has a fall-through into its successor.
  1092. bool CurFallsThru = MBB->canFallThrough();
  1093. if (!MBB->isLandingPad()) {
  1094. // Check all the predecessors of this block. If one of them has no fall
  1095. // throughs, move this block right after it.
  1096. for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
  1097. E = MBB->pred_end(); PI != E; ++PI) {
  1098. // Analyze the branch at the end of the pred.
  1099. MachineBasicBlock *PredBB = *PI;
  1100. MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
  1101. MachineBasicBlock *PredTBB = 0, *PredFBB = 0;
  1102. SmallVector<MachineOperand, 4> PredCond;
  1103. if (PredBB != MBB && !PredBB->canFallThrough() &&
  1104. !TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true)
  1105. && (!CurFallsThru || !CurTBB || !CurFBB)
  1106. && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
  1107. // If the current block doesn't fall through, just move it.
  1108. // If the current block can fall through and does not end with a
  1109. // conditional branch, we need to append an unconditional jump to
  1110. // the (current) next block. To avoid a possible compile-time
  1111. // infinite loop, move blocks only backward in this case.
  1112. // Also, if there are already 2 branches here, we cannot add a third;
  1113. // this means we have the case
  1114. // Bcc next
  1115. // B elsewhere
  1116. // next:
  1117. if (CurFallsThru) {
  1118. MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
  1119. CurCond.clear();
  1120. TII->InsertBranch(*MBB, NextBB, 0, CurCond);
  1121. }
  1122. MBB->moveAfter(PredBB);
  1123. MadeChange = true;
  1124. goto ReoptimizeBlock;
  1125. }
  1126. }
  1127. }
  1128. if (!CurFallsThru) {
  1129. // Check all successors to see if we can move this block before it.
  1130. for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
  1131. E = MBB->succ_end(); SI != E; ++SI) {
  1132. // Analyze the branch at the end of the block before the succ.
  1133. MachineBasicBlock *SuccBB = *SI;
  1134. MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
  1135. // If this block doesn't already fall-through to that successor, and if
  1136. // the succ doesn't already have a block that can fall through into it,
  1137. // and if the successor isn't an EH destination, we can arrange for the
  1138. // fallthrough to happen.
  1139. if (SuccBB != MBB && &*SuccPrev != MBB &&
  1140. !SuccPrev->canFallThrough() && !CurUnAnalyzable &&
  1141. !SuccBB->isLandingPad()) {
  1142. MBB->moveBefore(SuccBB);
  1143. MadeChange = true;
  1144. goto ReoptimizeBlock;
  1145. }
  1146. }
  1147. // Okay, there is no really great place to put this block. If, however,
  1148. // the block before this one would be a fall-through if this block were
  1149. // removed, move this block to the end of the function.
  1150. MachineBasicBlock *PrevTBB = 0, *PrevFBB = 0;
  1151. SmallVector<MachineOperand, 4> PrevCond;
  1152. if (FallThrough != MF.end() &&
  1153. !TII->AnalyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) &&
  1154. PrevBB.isSuccessor(FallThrough)) {
  1155. MBB->moveAfter(--MF.end());
  1156. MadeChange = true;
  1157. return MadeChange;
  1158. }
  1159. }
  1160. }
  1161. return MadeChange;
  1162. }