BranchFolding.cpp 64 KB

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