BranchFolding.cpp 64 KB

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