BranchFolding.cpp 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638
  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. STATISTIC(NumHoist , "Number of times common instructions are hoisted");
  43. static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
  44. cl::init(cl::BOU_UNSET), cl::Hidden);
  45. // Throttle for huge numbers of predecessors (compile speed problems)
  46. static cl::opt<unsigned>
  47. TailMergeThreshold("tail-merge-threshold",
  48. cl::desc("Max number of predecessors to consider tail merging"),
  49. cl::init(150), cl::Hidden);
  50. // Heuristic for tail merging (and, inversely, tail duplication).
  51. // TODO: This should be replaced with a target query.
  52. static cl::opt<unsigned>
  53. TailMergeSize("tail-merge-size",
  54. cl::desc("Min number of instructions to consider tail merging"),
  55. cl::init(3), cl::Hidden);
  56. namespace {
  57. /// BranchFolderPass - Wrap branch folder in a machine function pass.
  58. class BranchFolderPass : public MachineFunctionPass,
  59. public BranchFolder {
  60. public:
  61. static char ID;
  62. explicit BranchFolderPass(bool defaultEnableTailMerge)
  63. : MachineFunctionPass(ID), BranchFolder(defaultEnableTailMerge, true) {}
  64. virtual bool runOnMachineFunction(MachineFunction &MF);
  65. virtual const char *getPassName() const { return "Control Flow Optimizer"; }
  66. };
  67. }
  68. char BranchFolderPass::ID = 0;
  69. FunctionPass *llvm::createBranchFoldingPass(bool DefaultEnableTailMerge) {
  70. return new BranchFolderPass(DefaultEnableTailMerge);
  71. }
  72. bool BranchFolderPass::runOnMachineFunction(MachineFunction &MF) {
  73. return OptimizeFunction(MF,
  74. MF.getTarget().getInstrInfo(),
  75. MF.getTarget().getRegisterInfo(),
  76. getAnalysisIfAvailable<MachineModuleInfo>());
  77. }
  78. BranchFolder::BranchFolder(bool defaultEnableTailMerge, bool CommonHoist) {
  79. switch (FlagEnableTailMerge) {
  80. case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
  81. case cl::BOU_TRUE: EnableTailMerge = true; break;
  82. case cl::BOU_FALSE: EnableTailMerge = false; break;
  83. }
  84. EnableHoistCommonCode = CommonHoist;
  85. }
  86. /// RemoveDeadBlock - Remove the specified dead machine basic block from the
  87. /// function, updating the CFG.
  88. void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
  89. assert(MBB->pred_empty() && "MBB must be dead!");
  90. DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
  91. MachineFunction *MF = MBB->getParent();
  92. // drop all successors.
  93. while (!MBB->succ_empty())
  94. MBB->removeSuccessor(MBB->succ_end()-1);
  95. // Remove the block.
  96. MF->erase(MBB);
  97. }
  98. /// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
  99. /// followed by terminators, and if the implicitly defined registers are not
  100. /// used by the terminators, remove those implicit_def's. e.g.
  101. /// BB1:
  102. /// r0 = implicit_def
  103. /// r1 = implicit_def
  104. /// br
  105. /// This block can be optimized away later if the implicit instructions are
  106. /// removed.
  107. bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock *MBB) {
  108. SmallSet<unsigned, 4> ImpDefRegs;
  109. MachineBasicBlock::iterator I = MBB->begin();
  110. while (I != MBB->end()) {
  111. if (!I->isImplicitDef())
  112. break;
  113. unsigned Reg = I->getOperand(0).getReg();
  114. ImpDefRegs.insert(Reg);
  115. for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
  116. unsigned SubReg = *SubRegs; ++SubRegs)
  117. ImpDefRegs.insert(SubReg);
  118. ++I;
  119. }
  120. if (ImpDefRegs.empty())
  121. return false;
  122. MachineBasicBlock::iterator FirstTerm = I;
  123. while (I != MBB->end()) {
  124. if (!TII->isUnpredicatedTerminator(I))
  125. return false;
  126. // See if it uses any of the implicitly defined registers.
  127. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  128. MachineOperand &MO = I->getOperand(i);
  129. if (!MO.isReg() || !MO.isUse())
  130. continue;
  131. unsigned Reg = MO.getReg();
  132. if (ImpDefRegs.count(Reg))
  133. return false;
  134. }
  135. ++I;
  136. }
  137. I = MBB->begin();
  138. while (I != FirstTerm) {
  139. MachineInstr *ImpDefMI = &*I;
  140. ++I;
  141. MBB->erase(ImpDefMI);
  142. }
  143. return true;
  144. }
  145. /// OptimizeFunction - Perhaps branch folding, tail merging and other
  146. /// CFG optimizations on the given function.
  147. bool BranchFolder::OptimizeFunction(MachineFunction &MF,
  148. const TargetInstrInfo *tii,
  149. const TargetRegisterInfo *tri,
  150. MachineModuleInfo *mmi) {
  151. if (!tii) return false;
  152. TII = tii;
  153. TRI = tri;
  154. MMI = mmi;
  155. RS = TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
  156. // Fix CFG. The later algorithms expect it to be right.
  157. bool MadeChange = false;
  158. for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
  159. MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
  160. SmallVector<MachineOperand, 4> Cond;
  161. if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true))
  162. MadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
  163. MadeChange |= OptimizeImpDefsBlock(MBB);
  164. }
  165. bool MadeChangeThisIteration = true;
  166. while (MadeChangeThisIteration) {
  167. MadeChangeThisIteration = TailMergeBlocks(MF);
  168. MadeChangeThisIteration |= OptimizeBranches(MF);
  169. if (EnableHoistCommonCode)
  170. MadeChangeThisIteration |= HoistCommonCode(MF);
  171. MadeChange |= MadeChangeThisIteration;
  172. }
  173. // See if any jump tables have become dead as the code generator
  174. // did its thing.
  175. MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
  176. if (JTI == 0) {
  177. delete RS;
  178. return MadeChange;
  179. }
  180. // Walk the function to find jump tables that are live.
  181. BitVector JTIsLive(JTI->getJumpTables().size());
  182. for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
  183. BB != E; ++BB) {
  184. for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
  185. I != E; ++I)
  186. for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
  187. MachineOperand &Op = I->getOperand(op);
  188. if (!Op.isJTI()) continue;
  189. // Remember that this JT is live.
  190. JTIsLive.set(Op.getIndex());
  191. }
  192. }
  193. // Finally, remove dead jump tables. This happens when the
  194. // indirect jump was unreachable (and thus deleted).
  195. for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
  196. if (!JTIsLive.test(i)) {
  197. JTI->RemoveJumpTable(i);
  198. MadeChange = true;
  199. }
  200. delete RS;
  201. return MadeChange;
  202. }
  203. //===----------------------------------------------------------------------===//
  204. // Tail Merging of Blocks
  205. //===----------------------------------------------------------------------===//
  206. /// HashMachineInstr - Compute a hash value for MI and its operands.
  207. static unsigned HashMachineInstr(const MachineInstr *MI) {
  208. unsigned Hash = MI->getOpcode();
  209. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  210. const MachineOperand &Op = MI->getOperand(i);
  211. // Merge in bits from the operand if easy.
  212. unsigned OperandHash = 0;
  213. switch (Op.getType()) {
  214. case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
  215. case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
  216. case MachineOperand::MO_MachineBasicBlock:
  217. OperandHash = Op.getMBB()->getNumber();
  218. break;
  219. case MachineOperand::MO_FrameIndex:
  220. case MachineOperand::MO_ConstantPoolIndex:
  221. case MachineOperand::MO_JumpTableIndex:
  222. OperandHash = Op.getIndex();
  223. break;
  224. case MachineOperand::MO_GlobalAddress:
  225. case MachineOperand::MO_ExternalSymbol:
  226. // Global address / external symbol are too hard, don't bother, but do
  227. // pull in the offset.
  228. OperandHash = Op.getOffset();
  229. break;
  230. default: break;
  231. }
  232. Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
  233. }
  234. return Hash;
  235. }
  236. /// HashEndOfMBB - Hash the last instruction in the MBB.
  237. static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
  238. MachineBasicBlock::const_iterator I = MBB->end();
  239. if (I == MBB->begin())
  240. return 0; // Empty MBB.
  241. --I;
  242. // Skip debug info so it will not affect codegen.
  243. while (I->isDebugValue()) {
  244. if (I==MBB->begin())
  245. return 0; // MBB empty except for debug info.
  246. --I;
  247. }
  248. return HashMachineInstr(I);
  249. }
  250. /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
  251. /// of instructions they actually have in common together at their end. Return
  252. /// iterators for the first shared instruction in each block.
  253. static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
  254. MachineBasicBlock *MBB2,
  255. MachineBasicBlock::iterator &I1,
  256. MachineBasicBlock::iterator &I2) {
  257. I1 = MBB1->end();
  258. I2 = MBB2->end();
  259. unsigned TailLen = 0;
  260. while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
  261. --I1; --I2;
  262. // Skip debugging pseudos; necessary to avoid changing the code.
  263. while (I1->isDebugValue()) {
  264. if (I1==MBB1->begin()) {
  265. while (I2->isDebugValue()) {
  266. if (I2==MBB2->begin())
  267. // I1==DBG at begin; I2==DBG at begin
  268. return TailLen;
  269. --I2;
  270. }
  271. ++I2;
  272. // I1==DBG at begin; I2==non-DBG, or first of DBGs not at begin
  273. return TailLen;
  274. }
  275. --I1;
  276. }
  277. // I1==first (untested) non-DBG preceding known match
  278. while (I2->isDebugValue()) {
  279. if (I2==MBB2->begin()) {
  280. ++I1;
  281. // I1==non-DBG, or first of DBGs not at begin; I2==DBG at begin
  282. return TailLen;
  283. }
  284. --I2;
  285. }
  286. // I1, I2==first (untested) non-DBGs preceding known match
  287. if (!I1->isIdenticalTo(I2) ||
  288. // FIXME: This check is dubious. It's used to get around a problem where
  289. // people incorrectly expect inline asm directives to remain in the same
  290. // relative order. This is untenable because normal compiler
  291. // optimizations (like this one) may reorder and/or merge these
  292. // directives.
  293. I1->isInlineAsm()) {
  294. ++I1; ++I2;
  295. break;
  296. }
  297. ++TailLen;
  298. }
  299. // Back past possible debugging pseudos at beginning of block. This matters
  300. // when one block differs from the other only by whether debugging pseudos
  301. // are present at the beginning. (This way, the various checks later for
  302. // I1==MBB1->begin() work as expected.)
  303. if (I1 == MBB1->begin() && I2 != MBB2->begin()) {
  304. --I2;
  305. while (I2->isDebugValue()) {
  306. if (I2 == MBB2->begin()) {
  307. return TailLen;
  308. }
  309. --I2;
  310. }
  311. ++I2;
  312. }
  313. if (I2 == MBB2->begin() && I1 != MBB1->begin()) {
  314. --I1;
  315. while (I1->isDebugValue()) {
  316. if (I1 == MBB1->begin())
  317. return TailLen;
  318. --I1;
  319. }
  320. ++I1;
  321. }
  322. return TailLen;
  323. }
  324. /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
  325. /// after it, replacing it with an unconditional branch to NewDest.
  326. void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
  327. MachineBasicBlock *NewDest) {
  328. TII->ReplaceTailWithBranchTo(OldInst, NewDest);
  329. ++NumTailMerge;
  330. }
  331. /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
  332. /// MBB so that the part before the iterator falls into the part starting at the
  333. /// iterator. This returns the new MBB.
  334. MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
  335. MachineBasicBlock::iterator BBI1) {
  336. if (!TII->isLegalToSplitMBBAt(CurMBB, BBI1))
  337. return 0;
  338. MachineFunction &MF = *CurMBB.getParent();
  339. // Create the fall-through block.
  340. MachineFunction::iterator MBBI = &CurMBB;
  341. MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(CurMBB.getBasicBlock());
  342. CurMBB.getParent()->insert(++MBBI, NewMBB);
  343. // Move all the successors of this block to the specified block.
  344. NewMBB->transferSuccessors(&CurMBB);
  345. // Add an edge from CurMBB to NewMBB for the fall-through.
  346. CurMBB.addSuccessor(NewMBB);
  347. // Splice the code over.
  348. NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
  349. // For targets that use the register scavenger, we must maintain LiveIns.
  350. if (RS) {
  351. RS->enterBasicBlock(&CurMBB);
  352. if (!CurMBB.empty())
  353. RS->forward(prior(CurMBB.end()));
  354. BitVector RegsLiveAtExit(TRI->getNumRegs());
  355. RS->getRegsUsed(RegsLiveAtExit, false);
  356. for (unsigned int i = 0, e = TRI->getNumRegs(); i != e; i++)
  357. if (RegsLiveAtExit[i])
  358. NewMBB->addLiveIn(i);
  359. }
  360. return NewMBB;
  361. }
  362. /// EstimateRuntime - Make a rough estimate for how long it will take to run
  363. /// the specified code.
  364. static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
  365. MachineBasicBlock::iterator E) {
  366. unsigned Time = 0;
  367. for (; I != E; ++I) {
  368. if (I->isDebugValue())
  369. continue;
  370. const TargetInstrDesc &TID = I->getDesc();
  371. if (TID.isCall())
  372. Time += 10;
  373. else if (TID.mayLoad() || TID.mayStore())
  374. Time += 2;
  375. else
  376. ++Time;
  377. }
  378. return Time;
  379. }
  380. // CurMBB needs to add an unconditional branch to SuccMBB (we removed these
  381. // branches temporarily for tail merging). In the case where CurMBB ends
  382. // with a conditional branch to the next block, optimize by reversing the
  383. // test and conditionally branching to SuccMBB instead.
  384. static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB,
  385. const TargetInstrInfo *TII) {
  386. MachineFunction *MF = CurMBB->getParent();
  387. MachineFunction::iterator I = llvm::next(MachineFunction::iterator(CurMBB));
  388. MachineBasicBlock *TBB = 0, *FBB = 0;
  389. SmallVector<MachineOperand, 4> Cond;
  390. DebugLoc dl; // FIXME: this is nowhere
  391. if (I != MF->end() &&
  392. !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
  393. MachineBasicBlock *NextBB = I;
  394. if (TBB == NextBB && !Cond.empty() && !FBB) {
  395. if (!TII->ReverseBranchCondition(Cond)) {
  396. TII->RemoveBranch(*CurMBB);
  397. TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond, dl);
  398. return;
  399. }
  400. }
  401. }
  402. TII->InsertBranch(*CurMBB, SuccBB, NULL,
  403. SmallVector<MachineOperand, 0>(), dl);
  404. }
  405. bool
  406. BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const {
  407. if (getHash() < o.getHash())
  408. return true;
  409. else if (getHash() > o.getHash())
  410. return false;
  411. else if (getBlock()->getNumber() < o.getBlock()->getNumber())
  412. return true;
  413. else if (getBlock()->getNumber() > o.getBlock()->getNumber())
  414. return false;
  415. else {
  416. // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
  417. // an object with itself.
  418. #ifndef _GLIBCXX_DEBUG
  419. llvm_unreachable("Predecessor appears twice");
  420. #endif
  421. return false;
  422. }
  423. }
  424. /// CountTerminators - Count the number of terminators in the given
  425. /// block and set I to the position of the first non-terminator, if there
  426. /// is one, or MBB->end() otherwise.
  427. static unsigned CountTerminators(MachineBasicBlock *MBB,
  428. MachineBasicBlock::iterator &I) {
  429. I = MBB->end();
  430. unsigned NumTerms = 0;
  431. for (;;) {
  432. if (I == MBB->begin()) {
  433. I = MBB->end();
  434. break;
  435. }
  436. --I;
  437. if (!I->getDesc().isTerminator()) break;
  438. ++NumTerms;
  439. }
  440. return NumTerms;
  441. }
  442. /// ProfitableToMerge - Check if two machine basic blocks have a common tail
  443. /// and decide if it would be profitable to merge those tails. Return the
  444. /// length of the common tail and iterators to the first common instruction
  445. /// in each block.
  446. static bool ProfitableToMerge(MachineBasicBlock *MBB1,
  447. MachineBasicBlock *MBB2,
  448. unsigned minCommonTailLength,
  449. unsigned &CommonTailLen,
  450. MachineBasicBlock::iterator &I1,
  451. MachineBasicBlock::iterator &I2,
  452. MachineBasicBlock *SuccBB,
  453. MachineBasicBlock *PredBB) {
  454. CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2);
  455. if (CommonTailLen == 0)
  456. return false;
  457. DEBUG(dbgs() << "Common tail length of BB#" << MBB1->getNumber()
  458. << " and BB#" << MBB2->getNumber() << " is " << CommonTailLen
  459. << '\n');
  460. // It's almost always profitable to merge any number of non-terminator
  461. // instructions with the block that falls through into the common successor.
  462. if (MBB1 == PredBB || MBB2 == PredBB) {
  463. MachineBasicBlock::iterator I;
  464. unsigned NumTerms = CountTerminators(MBB1 == PredBB ? MBB2 : MBB1, I);
  465. if (CommonTailLen > NumTerms)
  466. return true;
  467. }
  468. // If one of the blocks can be completely merged and happens to be in
  469. // a position where the other could fall through into it, merge any number
  470. // of instructions, because it can be done without a branch.
  471. // TODO: If the blocks are not adjacent, move one of them so that they are?
  472. if (MBB1->isLayoutSuccessor(MBB2) && I2 == MBB2->begin())
  473. return true;
  474. if (MBB2->isLayoutSuccessor(MBB1) && I1 == MBB1->begin())
  475. return true;
  476. // If both blocks have an unconditional branch temporarily stripped out,
  477. // count that as an additional common instruction for the following
  478. // heuristics.
  479. unsigned EffectiveTailLen = CommonTailLen;
  480. if (SuccBB && MBB1 != PredBB && MBB2 != PredBB &&
  481. !MBB1->back().getDesc().isBarrier() &&
  482. !MBB2->back().getDesc().isBarrier())
  483. ++EffectiveTailLen;
  484. // Check if the common tail is long enough to be worthwhile.
  485. if (EffectiveTailLen >= minCommonTailLength)
  486. return true;
  487. // If we are optimizing for code size, 2 instructions in common is enough if
  488. // we don't have to split a block. At worst we will be introducing 1 new
  489. // branch instruction, which is likely to be smaller than the 2
  490. // instructions that would be deleted in the merge.
  491. MachineFunction *MF = MBB1->getParent();
  492. if (EffectiveTailLen >= 2 &&
  493. MF->getFunction()->hasFnAttr(Attribute::OptimizeForSize) &&
  494. (I1 == MBB1->begin() || I2 == MBB2->begin()))
  495. return true;
  496. return false;
  497. }
  498. /// ComputeSameTails - Look through all the blocks in MergePotentials that have
  499. /// hash CurHash (guaranteed to match the last element). Build the vector
  500. /// SameTails of all those that have the (same) largest number of instructions
  501. /// in common of any pair of these blocks. SameTails entries contain an
  502. /// iterator into MergePotentials (from which the MachineBasicBlock can be
  503. /// found) and a MachineBasicBlock::iterator into that MBB indicating the
  504. /// instruction where the matching code sequence begins.
  505. /// Order of elements in SameTails is the reverse of the order in which
  506. /// those blocks appear in MergePotentials (where they are not necessarily
  507. /// consecutive).
  508. unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
  509. unsigned minCommonTailLength,
  510. MachineBasicBlock *SuccBB,
  511. MachineBasicBlock *PredBB) {
  512. unsigned maxCommonTailLength = 0U;
  513. SameTails.clear();
  514. MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
  515. MPIterator HighestMPIter = prior(MergePotentials.end());
  516. for (MPIterator CurMPIter = prior(MergePotentials.end()),
  517. B = MergePotentials.begin();
  518. CurMPIter != B && CurMPIter->getHash() == CurHash;
  519. --CurMPIter) {
  520. for (MPIterator I = prior(CurMPIter); I->getHash() == CurHash ; --I) {
  521. unsigned CommonTailLen;
  522. if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(),
  523. minCommonTailLength,
  524. CommonTailLen, TrialBBI1, TrialBBI2,
  525. SuccBB, PredBB)) {
  526. if (CommonTailLen > maxCommonTailLength) {
  527. SameTails.clear();
  528. maxCommonTailLength = CommonTailLen;
  529. HighestMPIter = CurMPIter;
  530. SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1));
  531. }
  532. if (HighestMPIter == CurMPIter &&
  533. CommonTailLen == maxCommonTailLength)
  534. SameTails.push_back(SameTailElt(I, TrialBBI2));
  535. }
  536. if (I == B)
  537. break;
  538. }
  539. }
  540. return maxCommonTailLength;
  541. }
  542. /// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
  543. /// MergePotentials, restoring branches at ends of blocks as appropriate.
  544. void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
  545. MachineBasicBlock *SuccBB,
  546. MachineBasicBlock *PredBB) {
  547. MPIterator CurMPIter, B;
  548. for (CurMPIter = prior(MergePotentials.end()), B = MergePotentials.begin();
  549. CurMPIter->getHash() == CurHash;
  550. --CurMPIter) {
  551. // Put the unconditional branch back, if we need one.
  552. MachineBasicBlock *CurMBB = CurMPIter->getBlock();
  553. if (SuccBB && CurMBB != PredBB)
  554. FixTail(CurMBB, SuccBB, TII);
  555. if (CurMPIter == B)
  556. break;
  557. }
  558. if (CurMPIter->getHash() != CurHash)
  559. CurMPIter++;
  560. MergePotentials.erase(CurMPIter, MergePotentials.end());
  561. }
  562. /// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
  563. /// only of the common tail. Create a block that does by splitting one.
  564. bool BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
  565. unsigned maxCommonTailLength,
  566. unsigned &commonTailIndex) {
  567. commonTailIndex = 0;
  568. unsigned TimeEstimate = ~0U;
  569. for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
  570. // Use PredBB if possible; that doesn't require a new branch.
  571. if (SameTails[i].getBlock() == PredBB) {
  572. commonTailIndex = i;
  573. break;
  574. }
  575. // Otherwise, make a (fairly bogus) choice based on estimate of
  576. // how long it will take the various blocks to execute.
  577. unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(),
  578. SameTails[i].getTailStartPos());
  579. if (t <= TimeEstimate) {
  580. TimeEstimate = t;
  581. commonTailIndex = i;
  582. }
  583. }
  584. MachineBasicBlock::iterator BBI =
  585. SameTails[commonTailIndex].getTailStartPos();
  586. MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
  587. // If the common tail includes any debug info we will take it pretty
  588. // randomly from one of the inputs. Might be better to remove it?
  589. DEBUG(dbgs() << "\nSplitting BB#" << MBB->getNumber() << ", size "
  590. << maxCommonTailLength);
  591. MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI);
  592. if (!newMBB) {
  593. DEBUG(dbgs() << "... failed!");
  594. return false;
  595. }
  596. SameTails[commonTailIndex].setBlock(newMBB);
  597. SameTails[commonTailIndex].setTailStartPos(newMBB->begin());
  598. // If we split PredBB, newMBB is the new predecessor.
  599. if (PredBB == MBB)
  600. PredBB = newMBB;
  601. return true;
  602. }
  603. // See if any of the blocks in MergePotentials (which all have a common single
  604. // successor, or all have no successor) can be tail-merged. If there is a
  605. // successor, any blocks in MergePotentials that are not tail-merged and
  606. // are not immediately before Succ must have an unconditional branch to
  607. // Succ added (but the predecessor/successor lists need no adjustment).
  608. // The lone predecessor of Succ that falls through into Succ,
  609. // if any, is given in PredBB.
  610. bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,
  611. MachineBasicBlock *PredBB) {
  612. bool MadeChange = false;
  613. // Except for the special cases below, tail-merge if there are at least
  614. // this many instructions in common.
  615. unsigned minCommonTailLength = TailMergeSize;
  616. DEBUG(dbgs() << "\nTryTailMergeBlocks: ";
  617. for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
  618. dbgs() << "BB#" << MergePotentials[i].getBlock()->getNumber()
  619. << (i == e-1 ? "" : ", ");
  620. dbgs() << "\n";
  621. if (SuccBB) {
  622. dbgs() << " with successor BB#" << SuccBB->getNumber() << '\n';
  623. if (PredBB)
  624. dbgs() << " which has fall-through from BB#"
  625. << PredBB->getNumber() << "\n";
  626. }
  627. dbgs() << "Looking for common tails of at least "
  628. << minCommonTailLength << " instruction"
  629. << (minCommonTailLength == 1 ? "" : "s") << '\n';
  630. );
  631. // Sort by hash value so that blocks with identical end sequences sort
  632. // together.
  633. std::stable_sort(MergePotentials.begin(), MergePotentials.end());
  634. // Walk through equivalence sets looking for actual exact matches.
  635. while (MergePotentials.size() > 1) {
  636. unsigned CurHash = MergePotentials.back().getHash();
  637. // Build SameTails, identifying the set of blocks with this hash code
  638. // and with the maximum number of instructions in common.
  639. unsigned maxCommonTailLength = ComputeSameTails(CurHash,
  640. minCommonTailLength,
  641. SuccBB, PredBB);
  642. // If we didn't find any pair that has at least minCommonTailLength
  643. // instructions in common, remove all blocks with this hash code and retry.
  644. if (SameTails.empty()) {
  645. RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
  646. continue;
  647. }
  648. // If one of the blocks is the entire common tail (and not the entry
  649. // block, which we can't jump to), we can treat all blocks with this same
  650. // tail at once. Use PredBB if that is one of the possibilities, as that
  651. // will not introduce any extra branches.
  652. MachineBasicBlock *EntryBB = MergePotentials.begin()->getBlock()->
  653. getParent()->begin();
  654. unsigned commonTailIndex = SameTails.size();
  655. // If there are two blocks, check to see if one can be made to fall through
  656. // into the other.
  657. if (SameTails.size() == 2 &&
  658. SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) &&
  659. SameTails[1].tailIsWholeBlock())
  660. commonTailIndex = 1;
  661. else if (SameTails.size() == 2 &&
  662. SameTails[1].getBlock()->isLayoutSuccessor(
  663. SameTails[0].getBlock()) &&
  664. SameTails[0].tailIsWholeBlock())
  665. commonTailIndex = 0;
  666. else {
  667. // Otherwise just pick one, favoring the fall-through predecessor if
  668. // there is one.
  669. for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
  670. MachineBasicBlock *MBB = SameTails[i].getBlock();
  671. if (MBB == EntryBB && SameTails[i].tailIsWholeBlock())
  672. continue;
  673. if (MBB == PredBB) {
  674. commonTailIndex = i;
  675. break;
  676. }
  677. if (SameTails[i].tailIsWholeBlock())
  678. commonTailIndex = i;
  679. }
  680. }
  681. if (commonTailIndex == SameTails.size() ||
  682. (SameTails[commonTailIndex].getBlock() == PredBB &&
  683. !SameTails[commonTailIndex].tailIsWholeBlock())) {
  684. // None of the blocks consist entirely of the common tail.
  685. // Split a block so that one does.
  686. if (!CreateCommonTailOnlyBlock(PredBB,
  687. maxCommonTailLength, commonTailIndex)) {
  688. RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
  689. continue;
  690. }
  691. }
  692. MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
  693. // MBB is common tail. Adjust all other BB's to jump to this one.
  694. // Traversal must be forwards so erases work.
  695. DEBUG(dbgs() << "\nUsing common tail in BB#" << MBB->getNumber()
  696. << " for ");
  697. for (unsigned int i=0, e = SameTails.size(); i != e; ++i) {
  698. if (commonTailIndex == i)
  699. continue;
  700. DEBUG(dbgs() << "BB#" << SameTails[i].getBlock()->getNumber()
  701. << (i == e-1 ? "" : ", "));
  702. // Hack the end off BB i, making it jump to BB commonTailIndex instead.
  703. ReplaceTailWithBranchTo(SameTails[i].getTailStartPos(), MBB);
  704. // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
  705. MergePotentials.erase(SameTails[i].getMPIter());
  706. }
  707. DEBUG(dbgs() << "\n");
  708. // We leave commonTailIndex in the worklist in case there are other blocks
  709. // that match it with a smaller number of instructions.
  710. MadeChange = true;
  711. }
  712. return MadeChange;
  713. }
  714. bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
  715. if (!EnableTailMerge) return false;
  716. bool MadeChange = false;
  717. // First find blocks with no successors.
  718. MergePotentials.clear();
  719. for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
  720. if (I->succ_empty())
  721. MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(I), I));
  722. }
  723. // See if we can do any tail merging on those.
  724. if (MergePotentials.size() < TailMergeThreshold &&
  725. MergePotentials.size() >= 2)
  726. MadeChange |= TryTailMergeBlocks(NULL, NULL);
  727. // Look at blocks (IBB) with multiple predecessors (PBB).
  728. // We change each predecessor to a canonical form, by
  729. // (1) temporarily removing any unconditional branch from the predecessor
  730. // to IBB, and
  731. // (2) alter conditional branches so they branch to the other block
  732. // not IBB; this may require adding back an unconditional branch to IBB
  733. // later, where there wasn't one coming in. E.g.
  734. // Bcc IBB
  735. // fallthrough to QBB
  736. // here becomes
  737. // Bncc QBB
  738. // with a conceptual B to IBB after that, which never actually exists.
  739. // With those changes, we see whether the predecessors' tails match,
  740. // and merge them if so. We change things out of canonical form and
  741. // back to the way they were later in the process. (OptimizeBranches
  742. // would undo some of this, but we can't use it, because we'd get into
  743. // a compile-time infinite loop repeatedly doing and undoing the same
  744. // transformations.)
  745. for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
  746. I != E; ++I) {
  747. if (I->pred_size() >= 2 && I->pred_size() < TailMergeThreshold) {
  748. SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
  749. MachineBasicBlock *IBB = I;
  750. MachineBasicBlock *PredBB = prior(I);
  751. MergePotentials.clear();
  752. for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
  753. E2 = I->pred_end();
  754. P != E2; ++P) {
  755. MachineBasicBlock *PBB = *P;
  756. // Skip blocks that loop to themselves, can't tail merge these.
  757. if (PBB == IBB)
  758. continue;
  759. // Visit each predecessor only once.
  760. if (!UniquePreds.insert(PBB))
  761. continue;
  762. MachineBasicBlock *TBB = 0, *FBB = 0;
  763. SmallVector<MachineOperand, 4> Cond;
  764. if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond, true)) {
  765. // Failing case: IBB is the target of a cbr, and
  766. // we cannot reverse the branch.
  767. SmallVector<MachineOperand, 4> NewCond(Cond);
  768. if (!Cond.empty() && TBB == IBB) {
  769. if (TII->ReverseBranchCondition(NewCond))
  770. continue;
  771. // This is the QBB case described above
  772. if (!FBB)
  773. FBB = llvm::next(MachineFunction::iterator(PBB));
  774. }
  775. // Failing case: the only way IBB can be reached from PBB is via
  776. // exception handling. Happens for landing pads. Would be nice
  777. // to have a bit in the edge so we didn't have to do all this.
  778. if (IBB->isLandingPad()) {
  779. MachineFunction::iterator IP = PBB; IP++;
  780. MachineBasicBlock *PredNextBB = NULL;
  781. if (IP != MF.end())
  782. PredNextBB = IP;
  783. if (TBB == NULL) {
  784. if (IBB != PredNextBB) // fallthrough
  785. continue;
  786. } else if (FBB) {
  787. if (TBB != IBB && FBB != IBB) // cbr then ubr
  788. continue;
  789. } else if (Cond.empty()) {
  790. if (TBB != IBB) // ubr
  791. continue;
  792. } else {
  793. if (TBB != IBB && IBB != PredNextBB) // cbr
  794. continue;
  795. }
  796. }
  797. // Remove the unconditional branch at the end, if any.
  798. if (TBB && (Cond.empty() || FBB)) {
  799. DebugLoc dl; // FIXME: this is nowhere
  800. TII->RemoveBranch(*PBB);
  801. if (!Cond.empty())
  802. // reinsert conditional branch only, for now
  803. TII->InsertBranch(*PBB, (TBB == IBB) ? FBB : TBB, 0, NewCond, dl);
  804. }
  805. MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(PBB), *P));
  806. }
  807. }
  808. if (MergePotentials.size() >= 2)
  809. MadeChange |= TryTailMergeBlocks(IBB, PredBB);
  810. // Reinsert an unconditional branch if needed.
  811. // The 1 below can occur as a result of removing blocks in TryTailMergeBlocks.
  812. PredBB = prior(I); // this may have been changed in TryTailMergeBlocks
  813. if (MergePotentials.size() == 1 &&
  814. MergePotentials.begin()->getBlock() != PredBB)
  815. FixTail(MergePotentials.begin()->getBlock(), IBB, TII);
  816. }
  817. }
  818. return MadeChange;
  819. }
  820. //===----------------------------------------------------------------------===//
  821. // Branch Optimization
  822. //===----------------------------------------------------------------------===//
  823. bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
  824. bool MadeChange = false;
  825. // Make sure blocks are numbered in order
  826. MF.RenumberBlocks();
  827. for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
  828. I != E; ) {
  829. MachineBasicBlock *MBB = I++;
  830. MadeChange |= OptimizeBlock(MBB);
  831. // If it is dead, remove it.
  832. if (MBB->pred_empty()) {
  833. RemoveDeadBlock(MBB);
  834. MadeChange = true;
  835. ++NumDeadBlocks;
  836. }
  837. }
  838. return MadeChange;
  839. }
  840. // Blocks should be considered empty if they contain only debug info;
  841. // else the debug info would affect codegen.
  842. static bool IsEmptyBlock(MachineBasicBlock *MBB) {
  843. if (MBB->empty())
  844. return true;
  845. for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
  846. MBBI!=MBBE; ++MBBI) {
  847. if (!MBBI->isDebugValue())
  848. return false;
  849. }
  850. return true;
  851. }
  852. // Blocks with only debug info and branches should be considered the same
  853. // as blocks with only branches.
  854. static bool IsBranchOnlyBlock(MachineBasicBlock *MBB) {
  855. MachineBasicBlock::iterator MBBI, MBBE;
  856. for (MBBI = MBB->begin(), MBBE = MBB->end(); MBBI!=MBBE; ++MBBI) {
  857. if (!MBBI->isDebugValue())
  858. break;
  859. }
  860. return (MBBI->getDesc().isBranch());
  861. }
  862. /// IsBetterFallthrough - Return true if it would be clearly better to
  863. /// fall-through to MBB1 than to fall through into MBB2. This has to return
  864. /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
  865. /// result in infinite loops.
  866. static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
  867. MachineBasicBlock *MBB2) {
  868. // Right now, we use a simple heuristic. If MBB2 ends with a call, and
  869. // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
  870. // optimize branches that branch to either a return block or an assert block
  871. // into a fallthrough to the return.
  872. if (IsEmptyBlock(MBB1) || IsEmptyBlock(MBB2)) return false;
  873. // If there is a clear successor ordering we make sure that one block
  874. // will fall through to the next
  875. if (MBB1->isSuccessor(MBB2)) return true;
  876. if (MBB2->isSuccessor(MBB1)) return false;
  877. // Neither block consists entirely of debug info (per IsEmptyBlock check),
  878. // so we needn't test for falling off the beginning here.
  879. MachineBasicBlock::iterator MBB1I = --MBB1->end();
  880. while (MBB1I->isDebugValue())
  881. --MBB1I;
  882. MachineBasicBlock::iterator MBB2I = --MBB2->end();
  883. while (MBB2I->isDebugValue())
  884. --MBB2I;
  885. return MBB2I->getDesc().isCall() && !MBB1I->getDesc().isCall();
  886. }
  887. /// OptimizeBlock - Analyze and optimize control flow related to the specified
  888. /// block. This is never called on the entry block.
  889. bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
  890. bool MadeChange = false;
  891. MachineFunction &MF = *MBB->getParent();
  892. DebugLoc dl; // FIXME: this is nowhere
  893. ReoptimizeBlock:
  894. MachineFunction::iterator FallThrough = MBB;
  895. ++FallThrough;
  896. // If this block is empty, make everyone use its fall-through, not the block
  897. // explicitly. Landing pads should not do this since the landing-pad table
  898. // points to this block. Blocks with their addresses taken shouldn't be
  899. // optimized away.
  900. if (IsEmptyBlock(MBB) && !MBB->isLandingPad() && !MBB->hasAddressTaken()) {
  901. // Dead block? Leave for cleanup later.
  902. if (MBB->pred_empty()) return MadeChange;
  903. if (FallThrough == MF.end()) {
  904. // TODO: Simplify preds to not branch here if possible!
  905. } else {
  906. // Rewrite all predecessors of the old block to go to the fallthrough
  907. // instead.
  908. while (!MBB->pred_empty()) {
  909. MachineBasicBlock *Pred = *(MBB->pred_end()-1);
  910. Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
  911. }
  912. // If MBB was the target of a jump table, update jump tables to go to the
  913. // fallthrough instead.
  914. if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
  915. MJTI->ReplaceMBBInJumpTables(MBB, FallThrough);
  916. MadeChange = true;
  917. }
  918. return MadeChange;
  919. }
  920. // Check to see if we can simplify the terminator of the block before this
  921. // one.
  922. MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
  923. MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
  924. SmallVector<MachineOperand, 4> PriorCond;
  925. bool PriorUnAnalyzable =
  926. TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
  927. if (!PriorUnAnalyzable) {
  928. // If the CFG for the prior block has extra edges, remove them.
  929. MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
  930. !PriorCond.empty());
  931. // If the previous branch is conditional and both conditions go to the same
  932. // destination, remove the branch, replacing it with an unconditional one or
  933. // a fall-through.
  934. if (PriorTBB && PriorTBB == PriorFBB) {
  935. TII->RemoveBranch(PrevBB);
  936. PriorCond.clear();
  937. if (PriorTBB != MBB)
  938. TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond, dl);
  939. MadeChange = true;
  940. ++NumBranchOpts;
  941. goto ReoptimizeBlock;
  942. }
  943. // If the previous block unconditionally falls through to this block and
  944. // this block has no other predecessors, move the contents of this block
  945. // into the prior block. This doesn't usually happen when SimplifyCFG
  946. // has been used, but it can happen if tail merging splits a fall-through
  947. // predecessor of a block.
  948. // This has to check PrevBB->succ_size() because EH edges are ignored by
  949. // AnalyzeBranch.
  950. if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 &&
  951. PrevBB.succ_size() == 1 &&
  952. !MBB->hasAddressTaken() && !MBB->isLandingPad()) {
  953. DEBUG(dbgs() << "\nMerging into block: " << PrevBB
  954. << "From MBB: " << *MBB);
  955. if (PrevBB.begin() != PrevBB.end()) {
  956. MachineBasicBlock::iterator PrevBBIter = PrevBB.end();
  957. --PrevBBIter;
  958. MachineBasicBlock::iterator MBBIter = MBB->begin();
  959. while (PrevBBIter != PrevBB.begin() && MBBIter != MBB->end()
  960. && PrevBBIter->isDebugValue() && MBBIter->isDebugValue()) {
  961. if (!MBBIter->isIdenticalTo(PrevBBIter))
  962. break;
  963. MachineInstr *DuplicateDbg = MBBIter;
  964. ++MBBIter; -- PrevBBIter;
  965. DuplicateDbg->eraseFromParent();
  966. }
  967. }
  968. PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end());
  969. PrevBB.removeSuccessor(PrevBB.succ_begin());;
  970. assert(PrevBB.succ_empty());
  971. PrevBB.transferSuccessors(MBB);
  972. MadeChange = true;
  973. return MadeChange;
  974. }
  975. // If the previous branch *only* branches to *this* block (conditional or
  976. // not) remove the branch.
  977. if (PriorTBB == MBB && PriorFBB == 0) {
  978. TII->RemoveBranch(PrevBB);
  979. MadeChange = true;
  980. ++NumBranchOpts;
  981. goto ReoptimizeBlock;
  982. }
  983. // If the prior block branches somewhere else on the condition and here if
  984. // the condition is false, remove the uncond second branch.
  985. if (PriorFBB == MBB) {
  986. TII->RemoveBranch(PrevBB);
  987. TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond, dl);
  988. MadeChange = true;
  989. ++NumBranchOpts;
  990. goto ReoptimizeBlock;
  991. }
  992. // If the prior block branches here on true and somewhere else on false, and
  993. // if the branch condition is reversible, reverse the branch to create a
  994. // fall-through.
  995. if (PriorTBB == MBB) {
  996. SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
  997. if (!TII->ReverseBranchCondition(NewPriorCond)) {
  998. TII->RemoveBranch(PrevBB);
  999. TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond, dl);
  1000. MadeChange = true;
  1001. ++NumBranchOpts;
  1002. goto ReoptimizeBlock;
  1003. }
  1004. }
  1005. // If this block has no successors (e.g. it is a return block or ends with
  1006. // a call to a no-return function like abort or __cxa_throw) and if the pred
  1007. // falls through into this block, and if it would otherwise fall through
  1008. // into the block after this, move this block to the end of the function.
  1009. //
  1010. // We consider it more likely that execution will stay in the function (e.g.
  1011. // due to loops) than it is to exit it. This asserts in loops etc, moving
  1012. // the assert condition out of the loop body.
  1013. if (MBB->succ_empty() && !PriorCond.empty() && PriorFBB == 0 &&
  1014. MachineFunction::iterator(PriorTBB) == FallThrough &&
  1015. !MBB->canFallThrough()) {
  1016. bool DoTransform = true;
  1017. // We have to be careful that the succs of PredBB aren't both no-successor
  1018. // blocks. If neither have successors and if PredBB is the second from
  1019. // last block in the function, we'd just keep swapping the two blocks for
  1020. // last. Only do the swap if one is clearly better to fall through than
  1021. // the other.
  1022. if (FallThrough == --MF.end() &&
  1023. !IsBetterFallthrough(PriorTBB, MBB))
  1024. DoTransform = false;
  1025. if (DoTransform) {
  1026. // Reverse the branch so we will fall through on the previous true cond.
  1027. SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
  1028. if (!TII->ReverseBranchCondition(NewPriorCond)) {
  1029. DEBUG(dbgs() << "\nMoving MBB: " << *MBB
  1030. << "To make fallthrough to: " << *PriorTBB << "\n");
  1031. TII->RemoveBranch(PrevBB);
  1032. TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond, dl);
  1033. // Move this block to the end of the function.
  1034. MBB->moveAfter(--MF.end());
  1035. MadeChange = true;
  1036. ++NumBranchOpts;
  1037. return MadeChange;
  1038. }
  1039. }
  1040. }
  1041. }
  1042. // Analyze the branch in the current block.
  1043. MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
  1044. SmallVector<MachineOperand, 4> CurCond;
  1045. bool CurUnAnalyzable= TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
  1046. if (!CurUnAnalyzable) {
  1047. // If the CFG for the prior block has extra edges, remove them.
  1048. MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
  1049. // If this is a two-way branch, and the FBB branches to this block, reverse
  1050. // the condition so the single-basic-block loop is faster. Instead of:
  1051. // Loop: xxx; jcc Out; jmp Loop
  1052. // we want:
  1053. // Loop: xxx; jncc Loop; jmp Out
  1054. if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
  1055. SmallVector<MachineOperand, 4> NewCond(CurCond);
  1056. if (!TII->ReverseBranchCondition(NewCond)) {
  1057. TII->RemoveBranch(*MBB);
  1058. TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond, dl);
  1059. MadeChange = true;
  1060. ++NumBranchOpts;
  1061. goto ReoptimizeBlock;
  1062. }
  1063. }
  1064. // If this branch is the only thing in its block, see if we can forward
  1065. // other blocks across it.
  1066. if (CurTBB && CurCond.empty() && CurFBB == 0 &&
  1067. IsBranchOnlyBlock(MBB) && CurTBB != MBB &&
  1068. !MBB->hasAddressTaken()) {
  1069. // This block may contain just an unconditional branch. Because there can
  1070. // be 'non-branch terminators' in the block, try removing the branch and
  1071. // then seeing if the block is empty.
  1072. TII->RemoveBranch(*MBB);
  1073. // If the only things remaining in the block are debug info, remove these
  1074. // as well, so this will behave the same as an empty block in non-debug
  1075. // mode.
  1076. if (!MBB->empty()) {
  1077. bool NonDebugInfoFound = false;
  1078. for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
  1079. I != E; ++I) {
  1080. if (!I->isDebugValue()) {
  1081. NonDebugInfoFound = true;
  1082. break;
  1083. }
  1084. }
  1085. if (!NonDebugInfoFound)
  1086. // Make the block empty, losing the debug info (we could probably
  1087. // improve this in some cases.)
  1088. MBB->erase(MBB->begin(), MBB->end());
  1089. }
  1090. // If this block is just an unconditional branch to CurTBB, we can
  1091. // usually completely eliminate the block. The only case we cannot
  1092. // completely eliminate the block is when the block before this one
  1093. // falls through into MBB and we can't understand the prior block's branch
  1094. // condition.
  1095. if (MBB->empty()) {
  1096. bool PredHasNoFallThrough = !PrevBB.canFallThrough();
  1097. if (PredHasNoFallThrough || !PriorUnAnalyzable ||
  1098. !PrevBB.isSuccessor(MBB)) {
  1099. // If the prior block falls through into us, turn it into an
  1100. // explicit branch to us to make updates simpler.
  1101. if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
  1102. PriorTBB != MBB && PriorFBB != MBB) {
  1103. if (PriorTBB == 0) {
  1104. assert(PriorCond.empty() && PriorFBB == 0 &&
  1105. "Bad branch analysis");
  1106. PriorTBB = MBB;
  1107. } else {
  1108. assert(PriorFBB == 0 && "Machine CFG out of date!");
  1109. PriorFBB = MBB;
  1110. }
  1111. TII->RemoveBranch(PrevBB);
  1112. TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, dl);
  1113. }
  1114. // Iterate through all the predecessors, revectoring each in-turn.
  1115. size_t PI = 0;
  1116. bool DidChange = false;
  1117. bool HasBranchToSelf = false;
  1118. while(PI != MBB->pred_size()) {
  1119. MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
  1120. if (PMBB == MBB) {
  1121. // If this block has an uncond branch to itself, leave it.
  1122. ++PI;
  1123. HasBranchToSelf = true;
  1124. } else {
  1125. DidChange = true;
  1126. PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
  1127. // If this change resulted in PMBB ending in a conditional
  1128. // branch where both conditions go to the same destination,
  1129. // change this to an unconditional branch (and fix the CFG).
  1130. MachineBasicBlock *NewCurTBB = 0, *NewCurFBB = 0;
  1131. SmallVector<MachineOperand, 4> NewCurCond;
  1132. bool NewCurUnAnalyzable = TII->AnalyzeBranch(*PMBB, NewCurTBB,
  1133. NewCurFBB, NewCurCond, true);
  1134. if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
  1135. TII->RemoveBranch(*PMBB);
  1136. NewCurCond.clear();
  1137. TII->InsertBranch(*PMBB, NewCurTBB, 0, NewCurCond, dl);
  1138. MadeChange = true;
  1139. ++NumBranchOpts;
  1140. PMBB->CorrectExtraCFGEdges(NewCurTBB, 0, false);
  1141. }
  1142. }
  1143. }
  1144. // Change any jumptables to go to the new MBB.
  1145. if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
  1146. MJTI->ReplaceMBBInJumpTables(MBB, CurTBB);
  1147. if (DidChange) {
  1148. ++NumBranchOpts;
  1149. MadeChange = true;
  1150. if (!HasBranchToSelf) return MadeChange;
  1151. }
  1152. }
  1153. }
  1154. // Add the branch back if the block is more than just an uncond branch.
  1155. TII->InsertBranch(*MBB, CurTBB, 0, CurCond, dl);
  1156. }
  1157. }
  1158. // If the prior block doesn't fall through into this block, and if this
  1159. // block doesn't fall through into some other block, see if we can find a
  1160. // place to move this block where a fall-through will happen.
  1161. if (!PrevBB.canFallThrough()) {
  1162. // Now we know that there was no fall-through into this block, check to
  1163. // see if it has a fall-through into its successor.
  1164. bool CurFallsThru = MBB->canFallThrough();
  1165. if (!MBB->isLandingPad()) {
  1166. // Check all the predecessors of this block. If one of them has no fall
  1167. // throughs, move this block right after it.
  1168. for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
  1169. E = MBB->pred_end(); PI != E; ++PI) {
  1170. // Analyze the branch at the end of the pred.
  1171. MachineBasicBlock *PredBB = *PI;
  1172. MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
  1173. MachineBasicBlock *PredTBB = 0, *PredFBB = 0;
  1174. SmallVector<MachineOperand, 4> PredCond;
  1175. if (PredBB != MBB && !PredBB->canFallThrough() &&
  1176. !TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true)
  1177. && (!CurFallsThru || !CurTBB || !CurFBB)
  1178. && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
  1179. // If the current block doesn't fall through, just move it.
  1180. // If the current block can fall through and does not end with a
  1181. // conditional branch, we need to append an unconditional jump to
  1182. // the (current) next block. To avoid a possible compile-time
  1183. // infinite loop, move blocks only backward in this case.
  1184. // Also, if there are already 2 branches here, we cannot add a third;
  1185. // this means we have the case
  1186. // Bcc next
  1187. // B elsewhere
  1188. // next:
  1189. if (CurFallsThru) {
  1190. MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
  1191. CurCond.clear();
  1192. TII->InsertBranch(*MBB, NextBB, 0, CurCond, dl);
  1193. }
  1194. MBB->moveAfter(PredBB);
  1195. MadeChange = true;
  1196. goto ReoptimizeBlock;
  1197. }
  1198. }
  1199. }
  1200. if (!CurFallsThru) {
  1201. // Check all successors to see if we can move this block before it.
  1202. for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
  1203. E = MBB->succ_end(); SI != E; ++SI) {
  1204. // Analyze the branch at the end of the block before the succ.
  1205. MachineBasicBlock *SuccBB = *SI;
  1206. MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
  1207. // If this block doesn't already fall-through to that successor, and if
  1208. // the succ doesn't already have a block that can fall through into it,
  1209. // and if the successor isn't an EH destination, we can arrange for the
  1210. // fallthrough to happen.
  1211. if (SuccBB != MBB && &*SuccPrev != MBB &&
  1212. !SuccPrev->canFallThrough() && !CurUnAnalyzable &&
  1213. !SuccBB->isLandingPad()) {
  1214. MBB->moveBefore(SuccBB);
  1215. MadeChange = true;
  1216. goto ReoptimizeBlock;
  1217. }
  1218. }
  1219. // Okay, there is no really great place to put this block. If, however,
  1220. // the block before this one would be a fall-through if this block were
  1221. // removed, move this block to the end of the function.
  1222. MachineBasicBlock *PrevTBB = 0, *PrevFBB = 0;
  1223. SmallVector<MachineOperand, 4> PrevCond;
  1224. if (FallThrough != MF.end() &&
  1225. !TII->AnalyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) &&
  1226. PrevBB.isSuccessor(FallThrough)) {
  1227. MBB->moveAfter(--MF.end());
  1228. MadeChange = true;
  1229. return MadeChange;
  1230. }
  1231. }
  1232. }
  1233. return MadeChange;
  1234. }
  1235. //===----------------------------------------------------------------------===//
  1236. // Hoist Common Code
  1237. //===----------------------------------------------------------------------===//
  1238. /// HoistCommonCode - Hoist common instruction sequences at the start of basic
  1239. /// blocks to their common predecessor.
  1240. bool BranchFolder::HoistCommonCode(MachineFunction &MF) {
  1241. bool MadeChange = false;
  1242. for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ) {
  1243. MachineBasicBlock *MBB = I++;
  1244. MadeChange |= HoistCommonCodeInSuccs(MBB);
  1245. }
  1246. return MadeChange;
  1247. }
  1248. /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
  1249. /// its 'true' successor.
  1250. static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
  1251. MachineBasicBlock *TrueBB) {
  1252. for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
  1253. E = BB->succ_end(); SI != E; ++SI) {
  1254. MachineBasicBlock *SuccBB = *SI;
  1255. if (SuccBB != TrueBB)
  1256. return SuccBB;
  1257. }
  1258. return NULL;
  1259. }
  1260. /// findHoistingInsertPosAndDeps - Find the location to move common instructions
  1261. /// in successors to. The location is ususally just before the terminator,
  1262. /// however if the terminator is a conditional branch and its previous
  1263. /// instruction is the flag setting instruction, the previous instruction is
  1264. /// the preferred location. This function also gathers uses and defs of the
  1265. /// instructions from the insertion point to the end of the block. The data is
  1266. /// used by HoistCommonCodeInSuccs to ensure safety.
  1267. static
  1268. MachineBasicBlock::iterator findHoistingInsertPosAndDeps(MachineBasicBlock *MBB,
  1269. const TargetInstrInfo *TII,
  1270. const TargetRegisterInfo *TRI,
  1271. SmallSet<unsigned,4> &Uses,
  1272. SmallSet<unsigned,4> &Defs) {
  1273. MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
  1274. if (!TII->isUnpredicatedTerminator(Loc))
  1275. return MBB->end();
  1276. for (unsigned i = 0, e = Loc->getNumOperands(); i != e; ++i) {
  1277. const MachineOperand &MO = Loc->getOperand(i);
  1278. if (!MO.isReg())
  1279. continue;
  1280. unsigned Reg = MO.getReg();
  1281. if (!Reg)
  1282. continue;
  1283. if (MO.isUse()) {
  1284. Uses.insert(Reg);
  1285. for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
  1286. Uses.insert(*AS);
  1287. } else if (!MO.isDead())
  1288. // Don't try to hoist code in the rare case the terminator defines a
  1289. // register that is later used.
  1290. return MBB->end();
  1291. }
  1292. if (Uses.empty())
  1293. return Loc;
  1294. if (Loc == MBB->begin())
  1295. return MBB->end();
  1296. // The terminator is probably a conditional branch, try not to separate the
  1297. // branch from condition setting instruction.
  1298. MachineBasicBlock::iterator PI = Loc;
  1299. --PI;
  1300. while (PI != MBB->begin() && Loc->isDebugValue())
  1301. --PI;
  1302. bool IsDef = false;
  1303. for (unsigned i = 0, e = PI->getNumOperands(); !IsDef && i != e; ++i) {
  1304. const MachineOperand &MO = PI->getOperand(i);
  1305. if (!MO.isReg() || MO.isUse())
  1306. continue;
  1307. unsigned Reg = MO.getReg();
  1308. if (!Reg)
  1309. continue;
  1310. if (Uses.count(Reg))
  1311. IsDef = true;
  1312. }
  1313. if (!IsDef)
  1314. // The condition setting instruction is not just before the conditional
  1315. // branch.
  1316. return Loc;
  1317. // Be conservative, don't insert instruction above something that may have
  1318. // side-effects. And since it's potentially bad to separate flag setting
  1319. // instruction from the conditional branch, just abort the optimization
  1320. // completely.
  1321. // Also avoid moving code above predicated instruction since it's hard to
  1322. // reason about register liveness with predicated instruction.
  1323. bool DontMoveAcrossStore = true;
  1324. if (!PI->isSafeToMove(TII, 0, DontMoveAcrossStore) ||
  1325. TII->isPredicated(PI))
  1326. return MBB->end();
  1327. // Find out what registers are live. Note this routine is ignoring other live
  1328. // registers which are only used by instructions in successor blocks.
  1329. for (unsigned i = 0, e = PI->getNumOperands(); i != e; ++i) {
  1330. const MachineOperand &MO = PI->getOperand(i);
  1331. if (!MO.isReg())
  1332. continue;
  1333. unsigned Reg = MO.getReg();
  1334. if (!Reg)
  1335. continue;
  1336. if (MO.isUse()) {
  1337. Uses.insert(Reg);
  1338. for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
  1339. Uses.insert(*AS);
  1340. } else {
  1341. if (Uses.count(Reg)) {
  1342. Uses.erase(Reg);
  1343. for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
  1344. Uses.erase(*SR); // Use getSubRegisters to be conservative
  1345. }
  1346. Defs.insert(Reg);
  1347. for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
  1348. Defs.insert(*AS);
  1349. }
  1350. }
  1351. return PI;
  1352. }
  1353. /// HoistCommonCodeInSuccs - If the successors of MBB has common instruction
  1354. /// sequence at the start of the function, move the instructions before MBB
  1355. /// terminator if it's legal.
  1356. bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock *MBB) {
  1357. MachineBasicBlock *TBB = 0, *FBB = 0;
  1358. SmallVector<MachineOperand, 4> Cond;
  1359. if (TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true) || !TBB || Cond.empty())
  1360. return false;
  1361. if (!FBB) FBB = findFalseBlock(MBB, TBB);
  1362. if (!FBB)
  1363. // Malformed bcc? True and false blocks are the same?
  1364. return false;
  1365. // Restrict the optimization to cases where MBB is the only predecessor,
  1366. // it is an obvious win.
  1367. if (TBB->pred_size() > 1 || FBB->pred_size() > 1)
  1368. return false;
  1369. // Find a suitable position to hoist the common instructions to. Also figure
  1370. // out which registers are used or defined by instructions from the insertion
  1371. // point to the end of the block.
  1372. SmallSet<unsigned, 4> Uses, Defs;
  1373. MachineBasicBlock::iterator Loc =
  1374. findHoistingInsertPosAndDeps(MBB, TII, TRI, Uses, Defs);
  1375. if (Loc == MBB->end())
  1376. return false;
  1377. bool HasDups = false;
  1378. SmallVector<unsigned, 4> LocalDefs;
  1379. SmallSet<unsigned, 4> LocalDefsSet;
  1380. MachineBasicBlock::iterator TIB = TBB->begin();
  1381. MachineBasicBlock::iterator FIB = FBB->begin();
  1382. MachineBasicBlock::iterator TIE = TBB->end();
  1383. MachineBasicBlock::iterator FIE = FBB->end();
  1384. while (TIB != TIE && FIB != FIE) {
  1385. // Skip dbg_value instructions. These do not count.
  1386. if (TIB->isDebugValue()) {
  1387. while (TIB != TIE && TIB->isDebugValue())
  1388. ++TIB;
  1389. if (TIB == TIE)
  1390. break;
  1391. }
  1392. if (FIB->isDebugValue()) {
  1393. while (FIB != FIE && FIB->isDebugValue())
  1394. ++FIB;
  1395. if (FIB == FIE)
  1396. break;
  1397. }
  1398. if (!TIB->isIdenticalTo(FIB, MachineInstr::CheckKillDead))
  1399. break;
  1400. if (TII->isPredicated(TIB))
  1401. // Hard to reason about register liveness with predicated instruction.
  1402. break;
  1403. bool IsSafe = true;
  1404. for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) {
  1405. MachineOperand &MO = TIB->getOperand(i);
  1406. if (!MO.isReg())
  1407. continue;
  1408. unsigned Reg = MO.getReg();
  1409. if (!Reg)
  1410. continue;
  1411. if (MO.isDef()) {
  1412. if (Uses.count(Reg)) {
  1413. // Avoid clobbering a register that's used by the instruction at
  1414. // the point of insertion.
  1415. IsSafe = false;
  1416. break;
  1417. }
  1418. if (Defs.count(Reg) && !MO.isDead()) {
  1419. // Don't hoist the instruction if the def would be clobber by the
  1420. // instruction at the point insertion. FIXME: This is overly
  1421. // conservative. It should be possible to hoist the instructions
  1422. // in BB2 in the following example:
  1423. // BB1:
  1424. // r1, eflag = op1 r2, r3
  1425. // brcc eflag
  1426. //
  1427. // BB2:
  1428. // r1 = op2, ...
  1429. // = op3, r1<kill>
  1430. IsSafe = false;
  1431. break;
  1432. }
  1433. } else if (!LocalDefsSet.count(Reg)) {
  1434. if (Defs.count(Reg)) {
  1435. // Use is defined by the instruction at the point of insertion.
  1436. IsSafe = false;
  1437. break;
  1438. }
  1439. }
  1440. }
  1441. if (!IsSafe)
  1442. break;
  1443. bool DontMoveAcrossStore = true;
  1444. if (!TIB->isSafeToMove(TII, 0, DontMoveAcrossStore))
  1445. break;
  1446. // Track local defs so we can update liveins.
  1447. for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) {
  1448. MachineOperand &MO = TIB->getOperand(i);
  1449. if (!MO.isReg())
  1450. continue;
  1451. unsigned Reg = MO.getReg();
  1452. if (!Reg)
  1453. continue;
  1454. if (MO.isDef()) {
  1455. if (!MO.isDead()) {
  1456. LocalDefs.push_back(Reg);
  1457. LocalDefsSet.insert(Reg);
  1458. for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
  1459. LocalDefsSet.insert(*SR);
  1460. }
  1461. } else if (MO.isKill() && LocalDefsSet.count(Reg)) {
  1462. LocalDefsSet.erase(Reg);
  1463. for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
  1464. LocalDefsSet.erase(*SR);
  1465. }
  1466. }
  1467. HasDups = true;;
  1468. ++TIB;
  1469. ++FIB;
  1470. }
  1471. if (!HasDups)
  1472. return false;
  1473. MBB->splice(Loc, TBB, TBB->begin(), TIB);
  1474. FBB->erase(FBB->begin(), FIB);
  1475. // Update livein's.
  1476. for (unsigned i = 0, e = LocalDefs.size(); i != e; ++i) {
  1477. unsigned Def = LocalDefs[i];
  1478. if (LocalDefsSet.count(Def)) {
  1479. TBB->addLiveIn(Def);
  1480. FBB->addLiveIn(Def);
  1481. }
  1482. }
  1483. ++NumHoist;
  1484. return true;
  1485. }