BranchFolding.cpp 64 KB

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