BranchFolding.cpp 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033
  1. //===- BranchFolding.cpp - Fold machine code branch instructions ----------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This pass forwards branches to unconditional branches to make them branch
  10. // directly to the target block. This pass often results in dead MBB's, which
  11. // it then removes.
  12. //
  13. // Note that this pass must be run after register allocation, it cannot handle
  14. // SSA form. It also must handle virtual registers for targets that emit virtual
  15. // ISA (e.g. NVPTX).
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "BranchFolding.h"
  19. #include "llvm/ADT/BitVector.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/ADT/SmallSet.h"
  22. #include "llvm/ADT/SmallVector.h"
  23. #include "llvm/ADT/Statistic.h"
  24. #include "llvm/Analysis/ProfileSummaryInfo.h"
  25. #include "llvm/CodeGen/Analysis.h"
  26. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  27. #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
  28. #include "llvm/CodeGen/MachineFunction.h"
  29. #include "llvm/CodeGen/MachineFunctionPass.h"
  30. #include "llvm/CodeGen/MachineInstr.h"
  31. #include "llvm/CodeGen/MachineInstrBuilder.h"
  32. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  33. #include "llvm/CodeGen/MachineLoopInfo.h"
  34. #include "llvm/CodeGen/MachineModuleInfo.h"
  35. #include "llvm/CodeGen/MachineOperand.h"
  36. #include "llvm/CodeGen/MachineRegisterInfo.h"
  37. #include "llvm/CodeGen/MachineSizeOpts.h"
  38. #include "llvm/CodeGen/MBFIWrapper.h"
  39. #include "llvm/CodeGen/TargetInstrInfo.h"
  40. #include "llvm/CodeGen/TargetOpcodes.h"
  41. #include "llvm/CodeGen/TargetPassConfig.h"
  42. #include "llvm/CodeGen/TargetRegisterInfo.h"
  43. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  44. #include "llvm/IR/DebugInfoMetadata.h"
  45. #include "llvm/IR/DebugLoc.h"
  46. #include "llvm/IR/Function.h"
  47. #include "llvm/InitializePasses.h"
  48. #include "llvm/MC/LaneBitmask.h"
  49. #include "llvm/MC/MCRegisterInfo.h"
  50. #include "llvm/Pass.h"
  51. #include "llvm/Support/BlockFrequency.h"
  52. #include "llvm/Support/BranchProbability.h"
  53. #include "llvm/Support/CommandLine.h"
  54. #include "llvm/Support/Debug.h"
  55. #include "llvm/Support/ErrorHandling.h"
  56. #include "llvm/Support/raw_ostream.h"
  57. #include "llvm/Target/TargetMachine.h"
  58. #include <cassert>
  59. #include <cstddef>
  60. #include <iterator>
  61. #include <numeric>
  62. using namespace llvm;
  63. #define DEBUG_TYPE "branch-folder"
  64. STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
  65. STATISTIC(NumBranchOpts, "Number of branches optimized");
  66. STATISTIC(NumTailMerge , "Number of block tails merged");
  67. STATISTIC(NumHoist , "Number of times common instructions are hoisted");
  68. STATISTIC(NumTailCalls, "Number of tail calls optimized");
  69. static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
  70. cl::init(cl::BOU_UNSET), cl::Hidden);
  71. // Throttle for huge numbers of predecessors (compile speed problems)
  72. static cl::opt<unsigned>
  73. TailMergeThreshold("tail-merge-threshold",
  74. cl::desc("Max number of predecessors to consider tail merging"),
  75. cl::init(150), cl::Hidden);
  76. // Heuristic for tail merging (and, inversely, tail duplication).
  77. // TODO: This should be replaced with a target query.
  78. static cl::opt<unsigned>
  79. TailMergeSize("tail-merge-size",
  80. cl::desc("Min number of instructions to consider tail merging"),
  81. cl::init(3), cl::Hidden);
  82. namespace {
  83. /// BranchFolderPass - Wrap branch folder in a machine function pass.
  84. class BranchFolderPass : public MachineFunctionPass {
  85. public:
  86. static char ID;
  87. explicit BranchFolderPass(): MachineFunctionPass(ID) {}
  88. bool runOnMachineFunction(MachineFunction &MF) override;
  89. void getAnalysisUsage(AnalysisUsage &AU) const override {
  90. AU.addRequired<MachineBlockFrequencyInfo>();
  91. AU.addRequired<MachineBranchProbabilityInfo>();
  92. AU.addRequired<ProfileSummaryInfoWrapperPass>();
  93. AU.addRequired<TargetPassConfig>();
  94. MachineFunctionPass::getAnalysisUsage(AU);
  95. }
  96. };
  97. } // end anonymous namespace
  98. char BranchFolderPass::ID = 0;
  99. char &llvm::BranchFolderPassID = BranchFolderPass::ID;
  100. INITIALIZE_PASS(BranchFolderPass, DEBUG_TYPE,
  101. "Control Flow Optimizer", false, false)
  102. bool BranchFolderPass::runOnMachineFunction(MachineFunction &MF) {
  103. if (skipFunction(MF.getFunction()))
  104. return false;
  105. TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
  106. // TailMerge can create jump into if branches that make CFG irreducible for
  107. // HW that requires structurized CFG.
  108. bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
  109. PassConfig->getEnableTailMerge();
  110. MBFIWrapper MBBFreqInfo(
  111. getAnalysis<MachineBlockFrequencyInfo>());
  112. BranchFolder Folder(EnableTailMerge, /*CommonHoist=*/true, MBBFreqInfo,
  113. getAnalysis<MachineBranchProbabilityInfo>(),
  114. &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI());
  115. return Folder.OptimizeFunction(MF, MF.getSubtarget().getInstrInfo(),
  116. MF.getSubtarget().getRegisterInfo());
  117. }
  118. BranchFolder::BranchFolder(bool DefaultEnableTailMerge, bool CommonHoist,
  119. MBFIWrapper &FreqInfo,
  120. const MachineBranchProbabilityInfo &ProbInfo,
  121. ProfileSummaryInfo *PSI, unsigned MinTailLength)
  122. : EnableHoistCommonCode(CommonHoist), MinCommonTailLength(MinTailLength),
  123. MBBFreqInfo(FreqInfo), MBPI(ProbInfo), PSI(PSI) {
  124. if (MinCommonTailLength == 0)
  125. MinCommonTailLength = TailMergeSize;
  126. switch (FlagEnableTailMerge) {
  127. case cl::BOU_UNSET:
  128. EnableTailMerge = DefaultEnableTailMerge;
  129. break;
  130. case cl::BOU_TRUE: EnableTailMerge = true; break;
  131. case cl::BOU_FALSE: EnableTailMerge = false; break;
  132. }
  133. }
  134. void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
  135. assert(MBB->pred_empty() && "MBB must be dead!");
  136. LLVM_DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
  137. MachineFunction *MF = MBB->getParent();
  138. // drop all successors.
  139. while (!MBB->succ_empty())
  140. MBB->removeSuccessor(MBB->succ_end()-1);
  141. // Avoid matching if this pointer gets reused.
  142. TriedMerging.erase(MBB);
  143. // Update call site info.
  144. for (const MachineInstr &MI : *MBB)
  145. if (MI.shouldUpdateCallSiteInfo())
  146. MF->eraseCallSiteInfo(&MI);
  147. // Remove the block.
  148. MF->erase(MBB);
  149. EHScopeMembership.erase(MBB);
  150. if (MLI)
  151. MLI->removeBlock(MBB);
  152. }
  153. bool BranchFolder::OptimizeFunction(MachineFunction &MF,
  154. const TargetInstrInfo *tii,
  155. const TargetRegisterInfo *tri,
  156. MachineLoopInfo *mli, bool AfterPlacement) {
  157. if (!tii) return false;
  158. TriedMerging.clear();
  159. MachineRegisterInfo &MRI = MF.getRegInfo();
  160. AfterBlockPlacement = AfterPlacement;
  161. TII = tii;
  162. TRI = tri;
  163. MLI = mli;
  164. this->MRI = &MRI;
  165. UpdateLiveIns = MRI.tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF);
  166. if (!UpdateLiveIns)
  167. MRI.invalidateLiveness();
  168. bool MadeChange = false;
  169. // Recalculate EH scope membership.
  170. EHScopeMembership = getEHScopeMembership(MF);
  171. bool MadeChangeThisIteration = true;
  172. while (MadeChangeThisIteration) {
  173. MadeChangeThisIteration = TailMergeBlocks(MF);
  174. // No need to clean up if tail merging does not change anything after the
  175. // block placement.
  176. if (!AfterBlockPlacement || MadeChangeThisIteration)
  177. MadeChangeThisIteration |= OptimizeBranches(MF);
  178. if (EnableHoistCommonCode)
  179. MadeChangeThisIteration |= HoistCommonCode(MF);
  180. MadeChange |= MadeChangeThisIteration;
  181. }
  182. // See if any jump tables have become dead as the code generator
  183. // did its thing.
  184. MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
  185. if (!JTI)
  186. return MadeChange;
  187. // Walk the function to find jump tables that are live.
  188. BitVector JTIsLive(JTI->getJumpTables().size());
  189. for (const MachineBasicBlock &BB : MF) {
  190. for (const MachineInstr &I : BB)
  191. for (const MachineOperand &Op : I.operands()) {
  192. if (!Op.isJTI()) continue;
  193. // Remember that this JT is live.
  194. JTIsLive.set(Op.getIndex());
  195. }
  196. }
  197. // Finally, remove dead jump tables. This happens when the
  198. // indirect jump was unreachable (and thus deleted).
  199. for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
  200. if (!JTIsLive.test(i)) {
  201. JTI->RemoveJumpTable(i);
  202. MadeChange = true;
  203. }
  204. return MadeChange;
  205. }
  206. //===----------------------------------------------------------------------===//
  207. // Tail Merging of Blocks
  208. //===----------------------------------------------------------------------===//
  209. /// HashMachineInstr - Compute a hash value for MI and its operands.
  210. static unsigned HashMachineInstr(const MachineInstr &MI) {
  211. unsigned Hash = MI.getOpcode();
  212. for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
  213. const MachineOperand &Op = MI.getOperand(i);
  214. // Merge in bits from the operand if easy. We can't use MachineOperand's
  215. // hash_code here because it's not deterministic and we sort by hash value
  216. // later.
  217. unsigned OperandHash = 0;
  218. switch (Op.getType()) {
  219. case MachineOperand::MO_Register:
  220. OperandHash = Op.getReg();
  221. break;
  222. case MachineOperand::MO_Immediate:
  223. OperandHash = Op.getImm();
  224. break;
  225. case MachineOperand::MO_MachineBasicBlock:
  226. OperandHash = Op.getMBB()->getNumber();
  227. break;
  228. case MachineOperand::MO_FrameIndex:
  229. case MachineOperand::MO_ConstantPoolIndex:
  230. case MachineOperand::MO_JumpTableIndex:
  231. OperandHash = Op.getIndex();
  232. break;
  233. case MachineOperand::MO_GlobalAddress:
  234. case MachineOperand::MO_ExternalSymbol:
  235. // Global address / external symbol are too hard, don't bother, but do
  236. // pull in the offset.
  237. OperandHash = Op.getOffset();
  238. break;
  239. default:
  240. break;
  241. }
  242. Hash += ((OperandHash << 3) | Op.getType()) << (i & 31);
  243. }
  244. return Hash;
  245. }
  246. /// HashEndOfMBB - Hash the last instruction in the MBB.
  247. static unsigned HashEndOfMBB(const MachineBasicBlock &MBB) {
  248. MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr(false);
  249. if (I == MBB.end())
  250. return 0;
  251. return HashMachineInstr(*I);
  252. }
  253. /// Whether MI should be counted as an instruction when calculating common tail.
  254. static bool countsAsInstruction(const MachineInstr &MI) {
  255. return !(MI.isDebugInstr() || MI.isCFIInstruction());
  256. }
  257. /// Iterate backwards from the given iterator \p I, towards the beginning of the
  258. /// block. If a MI satisfying 'countsAsInstruction' is found, return an iterator
  259. /// pointing to that MI. If no such MI is found, return the end iterator.
  260. static MachineBasicBlock::iterator
  261. skipBackwardPastNonInstructions(MachineBasicBlock::iterator I,
  262. MachineBasicBlock *MBB) {
  263. while (I != MBB->begin()) {
  264. --I;
  265. if (countsAsInstruction(*I))
  266. return I;
  267. }
  268. return MBB->end();
  269. }
  270. /// Given two machine basic blocks, return the number of instructions they
  271. /// actually have in common together at their end. If a common tail is found (at
  272. /// least by one instruction), then iterators for the first shared instruction
  273. /// in each block are returned as well.
  274. ///
  275. /// Non-instructions according to countsAsInstruction are ignored.
  276. static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
  277. MachineBasicBlock *MBB2,
  278. MachineBasicBlock::iterator &I1,
  279. MachineBasicBlock::iterator &I2) {
  280. MachineBasicBlock::iterator MBBI1 = MBB1->end();
  281. MachineBasicBlock::iterator MBBI2 = MBB2->end();
  282. unsigned TailLen = 0;
  283. while (true) {
  284. MBBI1 = skipBackwardPastNonInstructions(MBBI1, MBB1);
  285. MBBI2 = skipBackwardPastNonInstructions(MBBI2, MBB2);
  286. if (MBBI1 == MBB1->end() || MBBI2 == MBB2->end())
  287. break;
  288. if (!MBBI1->isIdenticalTo(*MBBI2) ||
  289. // FIXME: This check is dubious. It's used to get around a problem where
  290. // people incorrectly expect inline asm directives to remain in the same
  291. // relative order. This is untenable because normal compiler
  292. // optimizations (like this one) may reorder and/or merge these
  293. // directives.
  294. MBBI1->isInlineAsm()) {
  295. break;
  296. }
  297. if (MBBI1->getFlag(MachineInstr::NoMerge) ||
  298. MBBI2->getFlag(MachineInstr::NoMerge))
  299. break;
  300. ++TailLen;
  301. I1 = MBBI1;
  302. I2 = MBBI2;
  303. }
  304. return TailLen;
  305. }
  306. void BranchFolder::replaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
  307. MachineBasicBlock &NewDest) {
  308. if (UpdateLiveIns) {
  309. // OldInst should always point to an instruction.
  310. MachineBasicBlock &OldMBB = *OldInst->getParent();
  311. LiveRegs.clear();
  312. LiveRegs.addLiveOuts(OldMBB);
  313. // Move backward to the place where will insert the jump.
  314. MachineBasicBlock::iterator I = OldMBB.end();
  315. do {
  316. --I;
  317. LiveRegs.stepBackward(*I);
  318. } while (I != OldInst);
  319. // Merging the tails may have switched some undef operand to non-undef ones.
  320. // Add IMPLICIT_DEFS into OldMBB as necessary to have a definition of the
  321. // register.
  322. for (MachineBasicBlock::RegisterMaskPair P : NewDest.liveins()) {
  323. // We computed the liveins with computeLiveIn earlier and should only see
  324. // full registers:
  325. assert(P.LaneMask == LaneBitmask::getAll() &&
  326. "Can only handle full register.");
  327. MCPhysReg Reg = P.PhysReg;
  328. if (!LiveRegs.available(*MRI, Reg))
  329. continue;
  330. DebugLoc DL;
  331. BuildMI(OldMBB, OldInst, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Reg);
  332. }
  333. }
  334. TII->ReplaceTailWithBranchTo(OldInst, &NewDest);
  335. ++NumTailMerge;
  336. }
  337. MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
  338. MachineBasicBlock::iterator BBI1,
  339. const BasicBlock *BB) {
  340. if (!TII->isLegalToSplitMBBAt(CurMBB, BBI1))
  341. return nullptr;
  342. MachineFunction &MF = *CurMBB.getParent();
  343. // Create the fall-through block.
  344. MachineFunction::iterator MBBI = CurMBB.getIterator();
  345. MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(BB);
  346. CurMBB.getParent()->insert(++MBBI, NewMBB);
  347. // Move all the successors of this block to the specified block.
  348. NewMBB->transferSuccessors(&CurMBB);
  349. // Add an edge from CurMBB to NewMBB for the fall-through.
  350. CurMBB.addSuccessor(NewMBB);
  351. // Splice the code over.
  352. NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
  353. // NewMBB belongs to the same loop as CurMBB.
  354. if (MLI)
  355. if (MachineLoop *ML = MLI->getLoopFor(&CurMBB))
  356. ML->addBasicBlockToLoop(NewMBB, MLI->getBase());
  357. // NewMBB inherits CurMBB's block frequency.
  358. MBBFreqInfo.setBlockFreq(NewMBB, MBBFreqInfo.getBlockFreq(&CurMBB));
  359. if (UpdateLiveIns)
  360. computeAndAddLiveIns(LiveRegs, *NewMBB);
  361. // Add the new block to the EH scope.
  362. const auto &EHScopeI = EHScopeMembership.find(&CurMBB);
  363. if (EHScopeI != EHScopeMembership.end()) {
  364. auto n = EHScopeI->second;
  365. EHScopeMembership[NewMBB] = n;
  366. }
  367. return NewMBB;
  368. }
  369. /// EstimateRuntime - Make a rough estimate for how long it will take to run
  370. /// the specified code.
  371. static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
  372. MachineBasicBlock::iterator E) {
  373. unsigned Time = 0;
  374. for (; I != E; ++I) {
  375. if (!countsAsInstruction(*I))
  376. continue;
  377. if (I->isCall())
  378. Time += 10;
  379. else if (I->mayLoadOrStore())
  380. Time += 2;
  381. else
  382. ++Time;
  383. }
  384. return Time;
  385. }
  386. // CurMBB needs to add an unconditional branch to SuccMBB (we removed these
  387. // branches temporarily for tail merging). In the case where CurMBB ends
  388. // with a conditional branch to the next block, optimize by reversing the
  389. // test and conditionally branching to SuccMBB instead.
  390. static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB,
  391. const TargetInstrInfo *TII) {
  392. MachineFunction *MF = CurMBB->getParent();
  393. MachineFunction::iterator I = std::next(MachineFunction::iterator(CurMBB));
  394. MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
  395. SmallVector<MachineOperand, 4> Cond;
  396. DebugLoc dl = CurMBB->findBranchDebugLoc();
  397. if (I != MF->end() && !TII->analyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
  398. MachineBasicBlock *NextBB = &*I;
  399. if (TBB == NextBB && !Cond.empty() && !FBB) {
  400. if (!TII->reverseBranchCondition(Cond)) {
  401. TII->removeBranch(*CurMBB);
  402. TII->insertBranch(*CurMBB, SuccBB, nullptr, Cond, dl);
  403. return;
  404. }
  405. }
  406. }
  407. TII->insertBranch(*CurMBB, SuccBB, nullptr,
  408. SmallVector<MachineOperand, 0>(), dl);
  409. }
  410. bool
  411. BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const {
  412. if (getHash() < o.getHash())
  413. return true;
  414. if (getHash() > o.getHash())
  415. return false;
  416. if (getBlock()->getNumber() < o.getBlock()->getNumber())
  417. return true;
  418. if (getBlock()->getNumber() > o.getBlock()->getNumber())
  419. return false;
  420. // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
  421. // an object with itself.
  422. #ifndef _GLIBCXX_DEBUG
  423. llvm_unreachable("Predecessor appears twice");
  424. #else
  425. return false;
  426. #endif
  427. }
  428. /// CountTerminators - Count the number of terminators in the given
  429. /// block and set I to the position of the first non-terminator, if there
  430. /// is one, or MBB->end() otherwise.
  431. static unsigned CountTerminators(MachineBasicBlock *MBB,
  432. MachineBasicBlock::iterator &I) {
  433. I = MBB->end();
  434. unsigned NumTerms = 0;
  435. while (true) {
  436. if (I == MBB->begin()) {
  437. I = MBB->end();
  438. break;
  439. }
  440. --I;
  441. if (!I->isTerminator()) break;
  442. ++NumTerms;
  443. }
  444. return NumTerms;
  445. }
  446. /// A no successor, non-return block probably ends in unreachable and is cold.
  447. /// Also consider a block that ends in an indirect branch to be a return block,
  448. /// since many targets use plain indirect branches to return.
  449. static bool blockEndsInUnreachable(const MachineBasicBlock *MBB) {
  450. if (!MBB->succ_empty())
  451. return false;
  452. if (MBB->empty())
  453. return true;
  454. return !(MBB->back().isReturn() || MBB->back().isIndirectBranch());
  455. }
  456. /// ProfitableToMerge - Check if two machine basic blocks have a common tail
  457. /// and decide if it would be profitable to merge those tails. Return the
  458. /// length of the common tail and iterators to the first common instruction
  459. /// in each block.
  460. /// MBB1, MBB2 The blocks to check
  461. /// MinCommonTailLength Minimum size of tail block to be merged.
  462. /// CommonTailLen Out parameter to record the size of the shared tail between
  463. /// MBB1 and MBB2
  464. /// I1, I2 Iterator references that will be changed to point to the first
  465. /// instruction in the common tail shared by MBB1,MBB2
  466. /// SuccBB A common successor of MBB1, MBB2 which are in a canonical form
  467. /// relative to SuccBB
  468. /// PredBB The layout predecessor of SuccBB, if any.
  469. /// EHScopeMembership map from block to EH scope #.
  470. /// AfterPlacement True if we are merging blocks after layout. Stricter
  471. /// thresholds apply to prevent undoing tail-duplication.
  472. static bool
  473. ProfitableToMerge(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2,
  474. unsigned MinCommonTailLength, unsigned &CommonTailLen,
  475. MachineBasicBlock::iterator &I1,
  476. MachineBasicBlock::iterator &I2, MachineBasicBlock *SuccBB,
  477. MachineBasicBlock *PredBB,
  478. DenseMap<const MachineBasicBlock *, int> &EHScopeMembership,
  479. bool AfterPlacement,
  480. MBFIWrapper &MBBFreqInfo,
  481. ProfileSummaryInfo *PSI) {
  482. // It is never profitable to tail-merge blocks from two different EH scopes.
  483. if (!EHScopeMembership.empty()) {
  484. auto EHScope1 = EHScopeMembership.find(MBB1);
  485. assert(EHScope1 != EHScopeMembership.end());
  486. auto EHScope2 = EHScopeMembership.find(MBB2);
  487. assert(EHScope2 != EHScopeMembership.end());
  488. if (EHScope1->second != EHScope2->second)
  489. return false;
  490. }
  491. CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2);
  492. if (CommonTailLen == 0)
  493. return false;
  494. LLVM_DEBUG(dbgs() << "Common tail length of " << printMBBReference(*MBB1)
  495. << " and " << printMBBReference(*MBB2) << " is "
  496. << CommonTailLen << '\n');
  497. // Move the iterators to the beginning of the MBB if we only got debug
  498. // instructions before the tail. This is to avoid splitting a block when we
  499. // only got debug instructions before the tail (to be invariant on -g).
  500. if (skipDebugInstructionsForward(MBB1->begin(), MBB1->end(), false) == I1)
  501. I1 = MBB1->begin();
  502. if (skipDebugInstructionsForward(MBB2->begin(), MBB2->end(), false) == I2)
  503. I2 = MBB2->begin();
  504. bool FullBlockTail1 = I1 == MBB1->begin();
  505. bool FullBlockTail2 = I2 == MBB2->begin();
  506. // It's almost always profitable to merge any number of non-terminator
  507. // instructions with the block that falls through into the common successor.
  508. // This is true only for a single successor. For multiple successors, we are
  509. // trading a conditional branch for an unconditional one.
  510. // TODO: Re-visit successor size for non-layout tail merging.
  511. if ((MBB1 == PredBB || MBB2 == PredBB) &&
  512. (!AfterPlacement || MBB1->succ_size() == 1)) {
  513. MachineBasicBlock::iterator I;
  514. unsigned NumTerms = CountTerminators(MBB1 == PredBB ? MBB2 : MBB1, I);
  515. if (CommonTailLen > NumTerms)
  516. return true;
  517. }
  518. // If these are identical non-return blocks with no successors, merge them.
  519. // Such blocks are typically cold calls to noreturn functions like abort, and
  520. // are unlikely to become a fallthrough target after machine block placement.
  521. // Tail merging these blocks is unlikely to create additional unconditional
  522. // branches, and will reduce the size of this cold code.
  523. if (FullBlockTail1 && FullBlockTail2 &&
  524. blockEndsInUnreachable(MBB1) && blockEndsInUnreachable(MBB2))
  525. return true;
  526. // If one of the blocks can be completely merged and happens to be in
  527. // a position where the other could fall through into it, merge any number
  528. // of instructions, because it can be done without a branch.
  529. // TODO: If the blocks are not adjacent, move one of them so that they are?
  530. if (MBB1->isLayoutSuccessor(MBB2) && FullBlockTail2)
  531. return true;
  532. if (MBB2->isLayoutSuccessor(MBB1) && FullBlockTail1)
  533. return true;
  534. // If both blocks are identical and end in a branch, merge them unless they
  535. // both have a fallthrough predecessor and successor.
  536. // We can only do this after block placement because it depends on whether
  537. // there are fallthroughs, and we don't know until after layout.
  538. if (AfterPlacement && FullBlockTail1 && FullBlockTail2) {
  539. auto BothFallThrough = [](MachineBasicBlock *MBB) {
  540. if (!MBB->succ_empty() && !MBB->canFallThrough())
  541. return false;
  542. MachineFunction::iterator I(MBB);
  543. MachineFunction *MF = MBB->getParent();
  544. return (MBB != &*MF->begin()) && std::prev(I)->canFallThrough();
  545. };
  546. if (!BothFallThrough(MBB1) || !BothFallThrough(MBB2))
  547. return true;
  548. }
  549. // If both blocks have an unconditional branch temporarily stripped out,
  550. // count that as an additional common instruction for the following
  551. // heuristics. This heuristic is only accurate for single-succ blocks, so to
  552. // make sure that during layout merging and duplicating don't crash, we check
  553. // for that when merging during layout.
  554. unsigned EffectiveTailLen = CommonTailLen;
  555. if (SuccBB && MBB1 != PredBB && MBB2 != PredBB &&
  556. (MBB1->succ_size() == 1 || !AfterPlacement) &&
  557. !MBB1->back().isBarrier() &&
  558. !MBB2->back().isBarrier())
  559. ++EffectiveTailLen;
  560. // Check if the common tail is long enough to be worthwhile.
  561. if (EffectiveTailLen >= MinCommonTailLength)
  562. return true;
  563. // If we are optimizing for code size, 2 instructions in common is enough if
  564. // we don't have to split a block. At worst we will be introducing 1 new
  565. // branch instruction, which is likely to be smaller than the 2
  566. // instructions that would be deleted in the merge.
  567. MachineFunction *MF = MBB1->getParent();
  568. bool OptForSize =
  569. MF->getFunction().hasOptSize() ||
  570. (llvm::shouldOptimizeForSize(MBB1, PSI, &MBBFreqInfo) &&
  571. llvm::shouldOptimizeForSize(MBB2, PSI, &MBBFreqInfo));
  572. return EffectiveTailLen >= 2 && OptForSize &&
  573. (FullBlockTail1 || FullBlockTail2);
  574. }
  575. unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
  576. unsigned MinCommonTailLength,
  577. MachineBasicBlock *SuccBB,
  578. MachineBasicBlock *PredBB) {
  579. unsigned maxCommonTailLength = 0U;
  580. SameTails.clear();
  581. MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
  582. MPIterator HighestMPIter = std::prev(MergePotentials.end());
  583. for (MPIterator CurMPIter = std::prev(MergePotentials.end()),
  584. B = MergePotentials.begin();
  585. CurMPIter != B && CurMPIter->getHash() == CurHash; --CurMPIter) {
  586. for (MPIterator I = std::prev(CurMPIter); I->getHash() == CurHash; --I) {
  587. unsigned CommonTailLen;
  588. if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(),
  589. MinCommonTailLength,
  590. CommonTailLen, TrialBBI1, TrialBBI2,
  591. SuccBB, PredBB,
  592. EHScopeMembership,
  593. AfterBlockPlacement, MBBFreqInfo, PSI)) {
  594. if (CommonTailLen > maxCommonTailLength) {
  595. SameTails.clear();
  596. maxCommonTailLength = CommonTailLen;
  597. HighestMPIter = CurMPIter;
  598. SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1));
  599. }
  600. if (HighestMPIter == CurMPIter &&
  601. CommonTailLen == maxCommonTailLength)
  602. SameTails.push_back(SameTailElt(I, TrialBBI2));
  603. }
  604. if (I == B)
  605. break;
  606. }
  607. }
  608. return maxCommonTailLength;
  609. }
  610. void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
  611. MachineBasicBlock *SuccBB,
  612. MachineBasicBlock *PredBB) {
  613. MPIterator CurMPIter, B;
  614. for (CurMPIter = std::prev(MergePotentials.end()),
  615. B = MergePotentials.begin();
  616. CurMPIter->getHash() == CurHash; --CurMPIter) {
  617. // Put the unconditional branch back, if we need one.
  618. MachineBasicBlock *CurMBB = CurMPIter->getBlock();
  619. if (SuccBB && CurMBB != PredBB)
  620. FixTail(CurMBB, SuccBB, TII);
  621. if (CurMPIter == B)
  622. break;
  623. }
  624. if (CurMPIter->getHash() != CurHash)
  625. CurMPIter++;
  626. MergePotentials.erase(CurMPIter, MergePotentials.end());
  627. }
  628. bool BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
  629. MachineBasicBlock *SuccBB,
  630. unsigned maxCommonTailLength,
  631. unsigned &commonTailIndex) {
  632. commonTailIndex = 0;
  633. unsigned TimeEstimate = ~0U;
  634. for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
  635. // Use PredBB if possible; that doesn't require a new branch.
  636. if (SameTails[i].getBlock() == PredBB) {
  637. commonTailIndex = i;
  638. break;
  639. }
  640. // Otherwise, make a (fairly bogus) choice based on estimate of
  641. // how long it will take the various blocks to execute.
  642. unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(),
  643. SameTails[i].getTailStartPos());
  644. if (t <= TimeEstimate) {
  645. TimeEstimate = t;
  646. commonTailIndex = i;
  647. }
  648. }
  649. MachineBasicBlock::iterator BBI =
  650. SameTails[commonTailIndex].getTailStartPos();
  651. MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
  652. LLVM_DEBUG(dbgs() << "\nSplitting " << printMBBReference(*MBB) << ", size "
  653. << maxCommonTailLength);
  654. // If the split block unconditionally falls-thru to SuccBB, it will be
  655. // merged. In control flow terms it should then take SuccBB's name. e.g. If
  656. // SuccBB is an inner loop, the common tail is still part of the inner loop.
  657. const BasicBlock *BB = (SuccBB && MBB->succ_size() == 1) ?
  658. SuccBB->getBasicBlock() : MBB->getBasicBlock();
  659. MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI, BB);
  660. if (!newMBB) {
  661. LLVM_DEBUG(dbgs() << "... failed!");
  662. return false;
  663. }
  664. SameTails[commonTailIndex].setBlock(newMBB);
  665. SameTails[commonTailIndex].setTailStartPos(newMBB->begin());
  666. // If we split PredBB, newMBB is the new predecessor.
  667. if (PredBB == MBB)
  668. PredBB = newMBB;
  669. return true;
  670. }
  671. static void
  672. mergeOperations(MachineBasicBlock::iterator MBBIStartPos,
  673. MachineBasicBlock &MBBCommon) {
  674. MachineBasicBlock *MBB = MBBIStartPos->getParent();
  675. // Note CommonTailLen does not necessarily matches the size of
  676. // the common BB nor all its instructions because of debug
  677. // instructions differences.
  678. unsigned CommonTailLen = 0;
  679. for (auto E = MBB->end(); MBBIStartPos != E; ++MBBIStartPos)
  680. ++CommonTailLen;
  681. MachineBasicBlock::reverse_iterator MBBI = MBB->rbegin();
  682. MachineBasicBlock::reverse_iterator MBBIE = MBB->rend();
  683. MachineBasicBlock::reverse_iterator MBBICommon = MBBCommon.rbegin();
  684. MachineBasicBlock::reverse_iterator MBBIECommon = MBBCommon.rend();
  685. while (CommonTailLen--) {
  686. assert(MBBI != MBBIE && "Reached BB end within common tail length!");
  687. (void)MBBIE;
  688. if (!countsAsInstruction(*MBBI)) {
  689. ++MBBI;
  690. continue;
  691. }
  692. while ((MBBICommon != MBBIECommon) && !countsAsInstruction(*MBBICommon))
  693. ++MBBICommon;
  694. assert(MBBICommon != MBBIECommon &&
  695. "Reached BB end within common tail length!");
  696. assert(MBBICommon->isIdenticalTo(*MBBI) && "Expected matching MIIs!");
  697. // Merge MMOs from memory operations in the common block.
  698. if (MBBICommon->mayLoadOrStore())
  699. MBBICommon->cloneMergedMemRefs(*MBB->getParent(), {&*MBBICommon, &*MBBI});
  700. // Drop undef flags if they aren't present in all merged instructions.
  701. for (unsigned I = 0, E = MBBICommon->getNumOperands(); I != E; ++I) {
  702. MachineOperand &MO = MBBICommon->getOperand(I);
  703. if (MO.isReg() && MO.isUndef()) {
  704. const MachineOperand &OtherMO = MBBI->getOperand(I);
  705. if (!OtherMO.isUndef())
  706. MO.setIsUndef(false);
  707. }
  708. }
  709. ++MBBI;
  710. ++MBBICommon;
  711. }
  712. }
  713. void BranchFolder::mergeCommonTails(unsigned commonTailIndex) {
  714. MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
  715. std::vector<MachineBasicBlock::iterator> NextCommonInsts(SameTails.size());
  716. for (unsigned int i = 0 ; i != SameTails.size() ; ++i) {
  717. if (i != commonTailIndex) {
  718. NextCommonInsts[i] = SameTails[i].getTailStartPos();
  719. mergeOperations(SameTails[i].getTailStartPos(), *MBB);
  720. } else {
  721. assert(SameTails[i].getTailStartPos() == MBB->begin() &&
  722. "MBB is not a common tail only block");
  723. }
  724. }
  725. for (auto &MI : *MBB) {
  726. if (!countsAsInstruction(MI))
  727. continue;
  728. DebugLoc DL = MI.getDebugLoc();
  729. for (unsigned int i = 0 ; i < NextCommonInsts.size() ; i++) {
  730. if (i == commonTailIndex)
  731. continue;
  732. auto &Pos = NextCommonInsts[i];
  733. assert(Pos != SameTails[i].getBlock()->end() &&
  734. "Reached BB end within common tail");
  735. while (!countsAsInstruction(*Pos)) {
  736. ++Pos;
  737. assert(Pos != SameTails[i].getBlock()->end() &&
  738. "Reached BB end within common tail");
  739. }
  740. assert(MI.isIdenticalTo(*Pos) && "Expected matching MIIs!");
  741. DL = DILocation::getMergedLocation(DL, Pos->getDebugLoc());
  742. NextCommonInsts[i] = ++Pos;
  743. }
  744. MI.setDebugLoc(DL);
  745. }
  746. if (UpdateLiveIns) {
  747. LivePhysRegs NewLiveIns(*TRI);
  748. computeLiveIns(NewLiveIns, *MBB);
  749. LiveRegs.init(*TRI);
  750. // The flag merging may lead to some register uses no longer using the
  751. // <undef> flag, add IMPLICIT_DEFs in the predecessors as necessary.
  752. for (MachineBasicBlock *Pred : MBB->predecessors()) {
  753. LiveRegs.clear();
  754. LiveRegs.addLiveOuts(*Pred);
  755. MachineBasicBlock::iterator InsertBefore = Pred->getFirstTerminator();
  756. for (Register Reg : NewLiveIns) {
  757. if (!LiveRegs.available(*MRI, Reg))
  758. continue;
  759. DebugLoc DL;
  760. BuildMI(*Pred, InsertBefore, DL, TII->get(TargetOpcode::IMPLICIT_DEF),
  761. Reg);
  762. }
  763. }
  764. MBB->clearLiveIns();
  765. addLiveIns(*MBB, NewLiveIns);
  766. }
  767. }
  768. // See if any of the blocks in MergePotentials (which all have SuccBB as a
  769. // successor, or all have no successor if it is null) can be tail-merged.
  770. // If there is a successor, any blocks in MergePotentials that are not
  771. // tail-merged and are not immediately before Succ must have an unconditional
  772. // branch to Succ added (but the predecessor/successor lists need no
  773. // adjustment). The lone predecessor of Succ that falls through into Succ,
  774. // if any, is given in PredBB.
  775. // MinCommonTailLength - Except for the special cases below, tail-merge if
  776. // there are at least this many instructions in common.
  777. bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,
  778. MachineBasicBlock *PredBB,
  779. unsigned MinCommonTailLength) {
  780. bool MadeChange = false;
  781. LLVM_DEBUG(
  782. dbgs() << "\nTryTailMergeBlocks: ";
  783. for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i) dbgs()
  784. << printMBBReference(*MergePotentials[i].getBlock())
  785. << (i == e - 1 ? "" : ", ");
  786. dbgs() << "\n"; if (SuccBB) {
  787. dbgs() << " with successor " << printMBBReference(*SuccBB) << '\n';
  788. if (PredBB)
  789. dbgs() << " which has fall-through from "
  790. << printMBBReference(*PredBB) << "\n";
  791. } dbgs() << "Looking for common tails of at least "
  792. << MinCommonTailLength << " instruction"
  793. << (MinCommonTailLength == 1 ? "" : "s") << '\n';);
  794. // Sort by hash value so that blocks with identical end sequences sort
  795. // together.
  796. array_pod_sort(MergePotentials.begin(), MergePotentials.end());
  797. // Walk through equivalence sets looking for actual exact matches.
  798. while (MergePotentials.size() > 1) {
  799. unsigned CurHash = MergePotentials.back().getHash();
  800. // Build SameTails, identifying the set of blocks with this hash code
  801. // and with the maximum number of instructions in common.
  802. unsigned maxCommonTailLength = ComputeSameTails(CurHash,
  803. MinCommonTailLength,
  804. SuccBB, PredBB);
  805. // If we didn't find any pair that has at least MinCommonTailLength
  806. // instructions in common, remove all blocks with this hash code and retry.
  807. if (SameTails.empty()) {
  808. RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
  809. continue;
  810. }
  811. // If one of the blocks is the entire common tail (and is not the entry
  812. // block/an EH pad, which we can't jump to), we can treat all blocks with
  813. // this same tail at once. Use PredBB if that is one of the possibilities,
  814. // as that will not introduce any extra branches.
  815. MachineBasicBlock *EntryBB =
  816. &MergePotentials.front().getBlock()->getParent()->front();
  817. unsigned commonTailIndex = SameTails.size();
  818. // If there are two blocks, check to see if one can be made to fall through
  819. // into the other.
  820. if (SameTails.size() == 2 &&
  821. SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) &&
  822. SameTails[1].tailIsWholeBlock() && !SameTails[1].getBlock()->isEHPad())
  823. commonTailIndex = 1;
  824. else if (SameTails.size() == 2 &&
  825. SameTails[1].getBlock()->isLayoutSuccessor(
  826. SameTails[0].getBlock()) &&
  827. SameTails[0].tailIsWholeBlock() &&
  828. !SameTails[0].getBlock()->isEHPad())
  829. commonTailIndex = 0;
  830. else {
  831. // Otherwise just pick one, favoring the fall-through predecessor if
  832. // there is one.
  833. for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
  834. MachineBasicBlock *MBB = SameTails[i].getBlock();
  835. if ((MBB == EntryBB || MBB->isEHPad()) &&
  836. SameTails[i].tailIsWholeBlock())
  837. continue;
  838. if (MBB == PredBB) {
  839. commonTailIndex = i;
  840. break;
  841. }
  842. if (SameTails[i].tailIsWholeBlock())
  843. commonTailIndex = i;
  844. }
  845. }
  846. if (commonTailIndex == SameTails.size() ||
  847. (SameTails[commonTailIndex].getBlock() == PredBB &&
  848. !SameTails[commonTailIndex].tailIsWholeBlock())) {
  849. // None of the blocks consist entirely of the common tail.
  850. // Split a block so that one does.
  851. if (!CreateCommonTailOnlyBlock(PredBB, SuccBB,
  852. maxCommonTailLength, commonTailIndex)) {
  853. RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
  854. continue;
  855. }
  856. }
  857. MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
  858. // Recompute common tail MBB's edge weights and block frequency.
  859. setCommonTailEdgeWeights(*MBB);
  860. // Merge debug locations, MMOs and undef flags across identical instructions
  861. // for common tail.
  862. mergeCommonTails(commonTailIndex);
  863. // MBB is common tail. Adjust all other BB's to jump to this one.
  864. // Traversal must be forwards so erases work.
  865. LLVM_DEBUG(dbgs() << "\nUsing common tail in " << printMBBReference(*MBB)
  866. << " for ");
  867. for (unsigned int i=0, e = SameTails.size(); i != e; ++i) {
  868. if (commonTailIndex == i)
  869. continue;
  870. LLVM_DEBUG(dbgs() << printMBBReference(*SameTails[i].getBlock())
  871. << (i == e - 1 ? "" : ", "));
  872. // Hack the end off BB i, making it jump to BB commonTailIndex instead.
  873. replaceTailWithBranchTo(SameTails[i].getTailStartPos(), *MBB);
  874. // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
  875. MergePotentials.erase(SameTails[i].getMPIter());
  876. }
  877. LLVM_DEBUG(dbgs() << "\n");
  878. // We leave commonTailIndex in the worklist in case there are other blocks
  879. // that match it with a smaller number of instructions.
  880. MadeChange = true;
  881. }
  882. return MadeChange;
  883. }
  884. bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
  885. bool MadeChange = false;
  886. if (!EnableTailMerge)
  887. return MadeChange;
  888. // First find blocks with no successors.
  889. // Block placement may create new tail merging opportunities for these blocks.
  890. MergePotentials.clear();
  891. for (MachineBasicBlock &MBB : MF) {
  892. if (MergePotentials.size() == TailMergeThreshold)
  893. break;
  894. if (!TriedMerging.count(&MBB) && MBB.succ_empty())
  895. MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(MBB), &MBB));
  896. }
  897. // If this is a large problem, avoid visiting the same basic blocks
  898. // multiple times.
  899. if (MergePotentials.size() == TailMergeThreshold)
  900. for (const MergePotentialsElt &Elt : MergePotentials)
  901. TriedMerging.insert(Elt.getBlock());
  902. // See if we can do any tail merging on those.
  903. if (MergePotentials.size() >= 2)
  904. MadeChange |= TryTailMergeBlocks(nullptr, nullptr, MinCommonTailLength);
  905. // Look at blocks (IBB) with multiple predecessors (PBB).
  906. // We change each predecessor to a canonical form, by
  907. // (1) temporarily removing any unconditional branch from the predecessor
  908. // to IBB, and
  909. // (2) alter conditional branches so they branch to the other block
  910. // not IBB; this may require adding back an unconditional branch to IBB
  911. // later, where there wasn't one coming in. E.g.
  912. // Bcc IBB
  913. // fallthrough to QBB
  914. // here becomes
  915. // Bncc QBB
  916. // with a conceptual B to IBB after that, which never actually exists.
  917. // With those changes, we see whether the predecessors' tails match,
  918. // and merge them if so. We change things out of canonical form and
  919. // back to the way they were later in the process. (OptimizeBranches
  920. // would undo some of this, but we can't use it, because we'd get into
  921. // a compile-time infinite loop repeatedly doing and undoing the same
  922. // transformations.)
  923. for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
  924. I != E; ++I) {
  925. if (I->pred_size() < 2) continue;
  926. SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
  927. MachineBasicBlock *IBB = &*I;
  928. MachineBasicBlock *PredBB = &*std::prev(I);
  929. MergePotentials.clear();
  930. MachineLoop *ML;
  931. // Bail if merging after placement and IBB is the loop header because
  932. // -- If merging predecessors that belong to the same loop as IBB, the
  933. // common tail of merged predecessors may become the loop top if block
  934. // placement is called again and the predecessors may branch to this common
  935. // tail and require more branches. This can be relaxed if
  936. // MachineBlockPlacement::findBestLoopTop is more flexible.
  937. // --If merging predecessors that do not belong to the same loop as IBB, the
  938. // loop info of IBB's loop and the other loops may be affected. Calling the
  939. // block placement again may make big change to the layout and eliminate the
  940. // reason to do tail merging here.
  941. if (AfterBlockPlacement && MLI) {
  942. ML = MLI->getLoopFor(IBB);
  943. if (ML && IBB == ML->getHeader())
  944. continue;
  945. }
  946. for (MachineBasicBlock *PBB : I->predecessors()) {
  947. if (MergePotentials.size() == TailMergeThreshold)
  948. break;
  949. if (TriedMerging.count(PBB))
  950. continue;
  951. // Skip blocks that loop to themselves, can't tail merge these.
  952. if (PBB == IBB)
  953. continue;
  954. // Visit each predecessor only once.
  955. if (!UniquePreds.insert(PBB).second)
  956. continue;
  957. // Skip blocks which may jump to a landing pad or jump from an asm blob.
  958. // Can't tail merge these.
  959. if (PBB->hasEHPadSuccessor() || PBB->mayHaveInlineAsmBr())
  960. continue;
  961. // After block placement, only consider predecessors that belong to the
  962. // same loop as IBB. The reason is the same as above when skipping loop
  963. // header.
  964. if (AfterBlockPlacement && MLI)
  965. if (ML != MLI->getLoopFor(PBB))
  966. continue;
  967. MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
  968. SmallVector<MachineOperand, 4> Cond;
  969. if (!TII->analyzeBranch(*PBB, TBB, FBB, Cond, true)) {
  970. // Failing case: IBB is the target of a cbr, and we cannot reverse the
  971. // branch.
  972. SmallVector<MachineOperand, 4> NewCond(Cond);
  973. if (!Cond.empty() && TBB == IBB) {
  974. if (TII->reverseBranchCondition(NewCond))
  975. continue;
  976. // This is the QBB case described above
  977. if (!FBB) {
  978. auto Next = ++PBB->getIterator();
  979. if (Next != MF.end())
  980. FBB = &*Next;
  981. }
  982. }
  983. // Remove the unconditional branch at the end, if any.
  984. if (TBB && (Cond.empty() || FBB)) {
  985. DebugLoc dl = PBB->findBranchDebugLoc();
  986. TII->removeBranch(*PBB);
  987. if (!Cond.empty())
  988. // reinsert conditional branch only, for now
  989. TII->insertBranch(*PBB, (TBB == IBB) ? FBB : TBB, nullptr,
  990. NewCond, dl);
  991. }
  992. MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(*PBB), PBB));
  993. }
  994. }
  995. // If this is a large problem, avoid visiting the same basic blocks multiple
  996. // times.
  997. if (MergePotentials.size() == TailMergeThreshold)
  998. for (MergePotentialsElt &Elt : MergePotentials)
  999. TriedMerging.insert(Elt.getBlock());
  1000. if (MergePotentials.size() >= 2)
  1001. MadeChange |= TryTailMergeBlocks(IBB, PredBB, MinCommonTailLength);
  1002. // Reinsert an unconditional branch if needed. The 1 below can occur as a
  1003. // result of removing blocks in TryTailMergeBlocks.
  1004. PredBB = &*std::prev(I); // this may have been changed in TryTailMergeBlocks
  1005. if (MergePotentials.size() == 1 &&
  1006. MergePotentials.begin()->getBlock() != PredBB)
  1007. FixTail(MergePotentials.begin()->getBlock(), IBB, TII);
  1008. }
  1009. return MadeChange;
  1010. }
  1011. void BranchFolder::setCommonTailEdgeWeights(MachineBasicBlock &TailMBB) {
  1012. SmallVector<BlockFrequency, 2> EdgeFreqLs(TailMBB.succ_size());
  1013. BlockFrequency AccumulatedMBBFreq;
  1014. // Aggregate edge frequency of successor edge j:
  1015. // edgeFreq(j) = sum (freq(bb) * edgeProb(bb, j)),
  1016. // where bb is a basic block that is in SameTails.
  1017. for (const auto &Src : SameTails) {
  1018. const MachineBasicBlock *SrcMBB = Src.getBlock();
  1019. BlockFrequency BlockFreq = MBBFreqInfo.getBlockFreq(SrcMBB);
  1020. AccumulatedMBBFreq += BlockFreq;
  1021. // It is not necessary to recompute edge weights if TailBB has less than two
  1022. // successors.
  1023. if (TailMBB.succ_size() <= 1)
  1024. continue;
  1025. auto EdgeFreq = EdgeFreqLs.begin();
  1026. for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
  1027. SuccI != SuccE; ++SuccI, ++EdgeFreq)
  1028. *EdgeFreq += BlockFreq * MBPI.getEdgeProbability(SrcMBB, *SuccI);
  1029. }
  1030. MBBFreqInfo.setBlockFreq(&TailMBB, AccumulatedMBBFreq);
  1031. if (TailMBB.succ_size() <= 1)
  1032. return;
  1033. auto SumEdgeFreq =
  1034. std::accumulate(EdgeFreqLs.begin(), EdgeFreqLs.end(), BlockFrequency(0))
  1035. .getFrequency();
  1036. auto EdgeFreq = EdgeFreqLs.begin();
  1037. if (SumEdgeFreq > 0) {
  1038. for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
  1039. SuccI != SuccE; ++SuccI, ++EdgeFreq) {
  1040. auto Prob = BranchProbability::getBranchProbability(
  1041. EdgeFreq->getFrequency(), SumEdgeFreq);
  1042. TailMBB.setSuccProbability(SuccI, Prob);
  1043. }
  1044. }
  1045. }
  1046. //===----------------------------------------------------------------------===//
  1047. // Branch Optimization
  1048. //===----------------------------------------------------------------------===//
  1049. bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
  1050. bool MadeChange = false;
  1051. // Make sure blocks are numbered in order
  1052. MF.RenumberBlocks();
  1053. // Renumbering blocks alters EH scope membership, recalculate it.
  1054. EHScopeMembership = getEHScopeMembership(MF);
  1055. for (MachineBasicBlock &MBB :
  1056. llvm::make_early_inc_range(llvm::drop_begin(MF))) {
  1057. MadeChange |= OptimizeBlock(&MBB);
  1058. // If it is dead, remove it.
  1059. if (MBB.pred_empty()) {
  1060. RemoveDeadBlock(&MBB);
  1061. MadeChange = true;
  1062. ++NumDeadBlocks;
  1063. }
  1064. }
  1065. return MadeChange;
  1066. }
  1067. // Blocks should be considered empty if they contain only debug info;
  1068. // else the debug info would affect codegen.
  1069. static bool IsEmptyBlock(MachineBasicBlock *MBB) {
  1070. return MBB->getFirstNonDebugInstr(true) == MBB->end();
  1071. }
  1072. // Blocks with only debug info and branches should be considered the same
  1073. // as blocks with only branches.
  1074. static bool IsBranchOnlyBlock(MachineBasicBlock *MBB) {
  1075. MachineBasicBlock::iterator I = MBB->getFirstNonDebugInstr();
  1076. assert(I != MBB->end() && "empty block!");
  1077. return I->isBranch();
  1078. }
  1079. /// IsBetterFallthrough - Return true if it would be clearly better to
  1080. /// fall-through to MBB1 than to fall through into MBB2. This has to return
  1081. /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
  1082. /// result in infinite loops.
  1083. static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
  1084. MachineBasicBlock *MBB2) {
  1085. assert(MBB1 && MBB2 && "Unknown MachineBasicBlock");
  1086. // Right now, we use a simple heuristic. If MBB2 ends with a call, and
  1087. // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
  1088. // optimize branches that branch to either a return block or an assert block
  1089. // into a fallthrough to the return.
  1090. MachineBasicBlock::iterator MBB1I = MBB1->getLastNonDebugInstr();
  1091. MachineBasicBlock::iterator MBB2I = MBB2->getLastNonDebugInstr();
  1092. if (MBB1I == MBB1->end() || MBB2I == MBB2->end())
  1093. return false;
  1094. // If there is a clear successor ordering we make sure that one block
  1095. // will fall through to the next
  1096. if (MBB1->isSuccessor(MBB2)) return true;
  1097. if (MBB2->isSuccessor(MBB1)) return false;
  1098. return MBB2I->isCall() && !MBB1I->isCall();
  1099. }
  1100. /// getBranchDebugLoc - Find and return, if any, the DebugLoc of the branch
  1101. /// instructions on the block.
  1102. static DebugLoc getBranchDebugLoc(MachineBasicBlock &MBB) {
  1103. MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
  1104. if (I != MBB.end() && I->isBranch())
  1105. return I->getDebugLoc();
  1106. return DebugLoc();
  1107. }
  1108. static void copyDebugInfoToPredecessor(const TargetInstrInfo *TII,
  1109. MachineBasicBlock &MBB,
  1110. MachineBasicBlock &PredMBB) {
  1111. auto InsertBefore = PredMBB.getFirstTerminator();
  1112. for (MachineInstr &MI : MBB.instrs())
  1113. if (MI.isDebugInstr()) {
  1114. TII->duplicate(PredMBB, InsertBefore, MI);
  1115. LLVM_DEBUG(dbgs() << "Copied debug entity from empty block to pred: "
  1116. << MI);
  1117. }
  1118. }
  1119. static void copyDebugInfoToSuccessor(const TargetInstrInfo *TII,
  1120. MachineBasicBlock &MBB,
  1121. MachineBasicBlock &SuccMBB) {
  1122. auto InsertBefore = SuccMBB.SkipPHIsAndLabels(SuccMBB.begin());
  1123. for (MachineInstr &MI : MBB.instrs())
  1124. if (MI.isDebugInstr()) {
  1125. TII->duplicate(SuccMBB, InsertBefore, MI);
  1126. LLVM_DEBUG(dbgs() << "Copied debug entity from empty block to succ: "
  1127. << MI);
  1128. }
  1129. }
  1130. // Try to salvage DBG_VALUE instructions from an otherwise empty block. If such
  1131. // a basic block is removed we would lose the debug information unless we have
  1132. // copied the information to a predecessor/successor.
  1133. //
  1134. // TODO: This function only handles some simple cases. An alternative would be
  1135. // to run a heavier analysis, such as the LiveDebugValues pass, before we do
  1136. // branch folding.
  1137. static void salvageDebugInfoFromEmptyBlock(const TargetInstrInfo *TII,
  1138. MachineBasicBlock &MBB) {
  1139. assert(IsEmptyBlock(&MBB) && "Expected an empty block (except debug info).");
  1140. // If this MBB is the only predecessor of a successor it is legal to copy
  1141. // DBG_VALUE instructions to the beginning of the successor.
  1142. for (MachineBasicBlock *SuccBB : MBB.successors())
  1143. if (SuccBB->pred_size() == 1)
  1144. copyDebugInfoToSuccessor(TII, MBB, *SuccBB);
  1145. // If this MBB is the only successor of a predecessor it is legal to copy the
  1146. // DBG_VALUE instructions to the end of the predecessor (just before the
  1147. // terminators, assuming that the terminator isn't affecting the DBG_VALUE).
  1148. for (MachineBasicBlock *PredBB : MBB.predecessors())
  1149. if (PredBB->succ_size() == 1)
  1150. copyDebugInfoToPredecessor(TII, MBB, *PredBB);
  1151. }
  1152. bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
  1153. bool MadeChange = false;
  1154. MachineFunction &MF = *MBB->getParent();
  1155. ReoptimizeBlock:
  1156. MachineFunction::iterator FallThrough = MBB->getIterator();
  1157. ++FallThrough;
  1158. // Make sure MBB and FallThrough belong to the same EH scope.
  1159. bool SameEHScope = true;
  1160. if (!EHScopeMembership.empty() && FallThrough != MF.end()) {
  1161. auto MBBEHScope = EHScopeMembership.find(MBB);
  1162. assert(MBBEHScope != EHScopeMembership.end());
  1163. auto FallThroughEHScope = EHScopeMembership.find(&*FallThrough);
  1164. assert(FallThroughEHScope != EHScopeMembership.end());
  1165. SameEHScope = MBBEHScope->second == FallThroughEHScope->second;
  1166. }
  1167. // Analyze the branch in the current block. As a side-effect, this may cause
  1168. // the block to become empty.
  1169. MachineBasicBlock *CurTBB = nullptr, *CurFBB = nullptr;
  1170. SmallVector<MachineOperand, 4> CurCond;
  1171. bool CurUnAnalyzable =
  1172. TII->analyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
  1173. // If this block is empty, make everyone use its fall-through, not the block
  1174. // explicitly. Landing pads should not do this since the landing-pad table
  1175. // points to this block. Blocks with their addresses taken shouldn't be
  1176. // optimized away.
  1177. if (IsEmptyBlock(MBB) && !MBB->isEHPad() && !MBB->hasAddressTaken() &&
  1178. SameEHScope) {
  1179. salvageDebugInfoFromEmptyBlock(TII, *MBB);
  1180. // Dead block? Leave for cleanup later.
  1181. if (MBB->pred_empty()) return MadeChange;
  1182. if (FallThrough == MF.end()) {
  1183. // TODO: Simplify preds to not branch here if possible!
  1184. } else if (FallThrough->isEHPad()) {
  1185. // Don't rewrite to a landing pad fallthough. That could lead to the case
  1186. // where a BB jumps to more than one landing pad.
  1187. // TODO: Is it ever worth rewriting predecessors which don't already
  1188. // jump to a landing pad, and so can safely jump to the fallthrough?
  1189. } else if (MBB->isSuccessor(&*FallThrough)) {
  1190. // Rewrite all predecessors of the old block to go to the fallthrough
  1191. // instead.
  1192. while (!MBB->pred_empty()) {
  1193. MachineBasicBlock *Pred = *(MBB->pred_end()-1);
  1194. Pred->ReplaceUsesOfBlockWith(MBB, &*FallThrough);
  1195. }
  1196. // If MBB was the target of a jump table, update jump tables to go to the
  1197. // fallthrough instead.
  1198. if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
  1199. MJTI->ReplaceMBBInJumpTables(MBB, &*FallThrough);
  1200. MadeChange = true;
  1201. }
  1202. return MadeChange;
  1203. }
  1204. // Check to see if we can simplify the terminator of the block before this
  1205. // one.
  1206. MachineBasicBlock &PrevBB = *std::prev(MachineFunction::iterator(MBB));
  1207. MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
  1208. SmallVector<MachineOperand, 4> PriorCond;
  1209. bool PriorUnAnalyzable =
  1210. TII->analyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
  1211. if (!PriorUnAnalyzable) {
  1212. // If the previous branch is conditional and both conditions go to the same
  1213. // destination, remove the branch, replacing it with an unconditional one or
  1214. // a fall-through.
  1215. if (PriorTBB && PriorTBB == PriorFBB) {
  1216. DebugLoc dl = getBranchDebugLoc(PrevBB);
  1217. TII->removeBranch(PrevBB);
  1218. PriorCond.clear();
  1219. if (PriorTBB != MBB)
  1220. TII->insertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
  1221. MadeChange = true;
  1222. ++NumBranchOpts;
  1223. goto ReoptimizeBlock;
  1224. }
  1225. // If the previous block unconditionally falls through to this block and
  1226. // this block has no other predecessors, move the contents of this block
  1227. // into the prior block. This doesn't usually happen when SimplifyCFG
  1228. // has been used, but it can happen if tail merging splits a fall-through
  1229. // predecessor of a block.
  1230. // This has to check PrevBB->succ_size() because EH edges are ignored by
  1231. // analyzeBranch.
  1232. if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 &&
  1233. PrevBB.succ_size() == 1 &&
  1234. !MBB->hasAddressTaken() && !MBB->isEHPad()) {
  1235. LLVM_DEBUG(dbgs() << "\nMerging into block: " << PrevBB
  1236. << "From MBB: " << *MBB);
  1237. // Remove redundant DBG_VALUEs first.
  1238. if (!PrevBB.empty()) {
  1239. MachineBasicBlock::iterator PrevBBIter = PrevBB.end();
  1240. --PrevBBIter;
  1241. MachineBasicBlock::iterator MBBIter = MBB->begin();
  1242. // Check if DBG_VALUE at the end of PrevBB is identical to the
  1243. // DBG_VALUE at the beginning of MBB.
  1244. while (PrevBBIter != PrevBB.begin() && MBBIter != MBB->end()
  1245. && PrevBBIter->isDebugInstr() && MBBIter->isDebugInstr()) {
  1246. if (!MBBIter->isIdenticalTo(*PrevBBIter))
  1247. break;
  1248. MachineInstr &DuplicateDbg = *MBBIter;
  1249. ++MBBIter; -- PrevBBIter;
  1250. DuplicateDbg.eraseFromParent();
  1251. }
  1252. }
  1253. PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end());
  1254. PrevBB.removeSuccessor(PrevBB.succ_begin());
  1255. assert(PrevBB.succ_empty());
  1256. PrevBB.transferSuccessors(MBB);
  1257. MadeChange = true;
  1258. return MadeChange;
  1259. }
  1260. // If the previous branch *only* branches to *this* block (conditional or
  1261. // not) remove the branch.
  1262. if (PriorTBB == MBB && !PriorFBB) {
  1263. TII->removeBranch(PrevBB);
  1264. MadeChange = true;
  1265. ++NumBranchOpts;
  1266. goto ReoptimizeBlock;
  1267. }
  1268. // If the prior block branches somewhere else on the condition and here if
  1269. // the condition is false, remove the uncond second branch.
  1270. if (PriorFBB == MBB) {
  1271. DebugLoc dl = getBranchDebugLoc(PrevBB);
  1272. TII->removeBranch(PrevBB);
  1273. TII->insertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
  1274. MadeChange = true;
  1275. ++NumBranchOpts;
  1276. goto ReoptimizeBlock;
  1277. }
  1278. // If the prior block branches here on true and somewhere else on false, and
  1279. // if the branch condition is reversible, reverse the branch to create a
  1280. // fall-through.
  1281. if (PriorTBB == MBB) {
  1282. SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
  1283. if (!TII->reverseBranchCondition(NewPriorCond)) {
  1284. DebugLoc dl = getBranchDebugLoc(PrevBB);
  1285. TII->removeBranch(PrevBB);
  1286. TII->insertBranch(PrevBB, PriorFBB, nullptr, NewPriorCond, dl);
  1287. MadeChange = true;
  1288. ++NumBranchOpts;
  1289. goto ReoptimizeBlock;
  1290. }
  1291. }
  1292. // If this block has no successors (e.g. it is a return block or ends with
  1293. // a call to a no-return function like abort or __cxa_throw) and if the pred
  1294. // falls through into this block, and if it would otherwise fall through
  1295. // into the block after this, move this block to the end of the function.
  1296. //
  1297. // We consider it more likely that execution will stay in the function (e.g.
  1298. // due to loops) than it is to exit it. This asserts in loops etc, moving
  1299. // the assert condition out of the loop body.
  1300. if (MBB->succ_empty() && !PriorCond.empty() && !PriorFBB &&
  1301. MachineFunction::iterator(PriorTBB) == FallThrough &&
  1302. !MBB->canFallThrough()) {
  1303. bool DoTransform = true;
  1304. // We have to be careful that the succs of PredBB aren't both no-successor
  1305. // blocks. If neither have successors and if PredBB is the second from
  1306. // last block in the function, we'd just keep swapping the two blocks for
  1307. // last. Only do the swap if one is clearly better to fall through than
  1308. // the other.
  1309. if (FallThrough == --MF.end() &&
  1310. !IsBetterFallthrough(PriorTBB, MBB))
  1311. DoTransform = false;
  1312. if (DoTransform) {
  1313. // Reverse the branch so we will fall through on the previous true cond.
  1314. SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
  1315. if (!TII->reverseBranchCondition(NewPriorCond)) {
  1316. LLVM_DEBUG(dbgs() << "\nMoving MBB: " << *MBB
  1317. << "To make fallthrough to: " << *PriorTBB << "\n");
  1318. DebugLoc dl = getBranchDebugLoc(PrevBB);
  1319. TII->removeBranch(PrevBB);
  1320. TII->insertBranch(PrevBB, MBB, nullptr, NewPriorCond, dl);
  1321. // Move this block to the end of the function.
  1322. MBB->moveAfter(&MF.back());
  1323. MadeChange = true;
  1324. ++NumBranchOpts;
  1325. return MadeChange;
  1326. }
  1327. }
  1328. }
  1329. }
  1330. bool OptForSize =
  1331. MF.getFunction().hasOptSize() ||
  1332. llvm::shouldOptimizeForSize(MBB, PSI, &MBBFreqInfo);
  1333. if (!IsEmptyBlock(MBB) && MBB->pred_size() == 1 && OptForSize) {
  1334. // Changing "Jcc foo; foo: jmp bar;" into "Jcc bar;" might change the branch
  1335. // direction, thereby defeating careful block placement and regressing
  1336. // performance. Therefore, only consider this for optsize functions.
  1337. MachineInstr &TailCall = *MBB->getFirstNonDebugInstr();
  1338. if (TII->isUnconditionalTailCall(TailCall)) {
  1339. MachineBasicBlock *Pred = *MBB->pred_begin();
  1340. MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
  1341. SmallVector<MachineOperand, 4> PredCond;
  1342. bool PredAnalyzable =
  1343. !TII->analyzeBranch(*Pred, PredTBB, PredFBB, PredCond, true);
  1344. if (PredAnalyzable && !PredCond.empty() && PredTBB == MBB &&
  1345. PredTBB != PredFBB) {
  1346. // The predecessor has a conditional branch to this block which consists
  1347. // of only a tail call. Try to fold the tail call into the conditional
  1348. // branch.
  1349. if (TII->canMakeTailCallConditional(PredCond, TailCall)) {
  1350. // TODO: It would be nice if analyzeBranch() could provide a pointer
  1351. // to the branch instruction so replaceBranchWithTailCall() doesn't
  1352. // have to search for it.
  1353. TII->replaceBranchWithTailCall(*Pred, PredCond, TailCall);
  1354. ++NumTailCalls;
  1355. Pred->removeSuccessor(MBB);
  1356. MadeChange = true;
  1357. return MadeChange;
  1358. }
  1359. }
  1360. // If the predecessor is falling through to this block, we could reverse
  1361. // the branch condition and fold the tail call into that. However, after
  1362. // that we might have to re-arrange the CFG to fall through to the other
  1363. // block and there is a high risk of regressing code size rather than
  1364. // improving it.
  1365. }
  1366. }
  1367. if (!CurUnAnalyzable) {
  1368. // If this is a two-way branch, and the FBB branches to this block, reverse
  1369. // the condition so the single-basic-block loop is faster. Instead of:
  1370. // Loop: xxx; jcc Out; jmp Loop
  1371. // we want:
  1372. // Loop: xxx; jncc Loop; jmp Out
  1373. if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
  1374. SmallVector<MachineOperand, 4> NewCond(CurCond);
  1375. if (!TII->reverseBranchCondition(NewCond)) {
  1376. DebugLoc dl = getBranchDebugLoc(*MBB);
  1377. TII->removeBranch(*MBB);
  1378. TII->insertBranch(*MBB, CurFBB, CurTBB, NewCond, dl);
  1379. MadeChange = true;
  1380. ++NumBranchOpts;
  1381. goto ReoptimizeBlock;
  1382. }
  1383. }
  1384. // If this branch is the only thing in its block, see if we can forward
  1385. // other blocks across it.
  1386. if (CurTBB && CurCond.empty() && !CurFBB &&
  1387. IsBranchOnlyBlock(MBB) && CurTBB != MBB &&
  1388. !MBB->hasAddressTaken() && !MBB->isEHPad()) {
  1389. DebugLoc dl = getBranchDebugLoc(*MBB);
  1390. // This block may contain just an unconditional branch. Because there can
  1391. // be 'non-branch terminators' in the block, try removing the branch and
  1392. // then seeing if the block is empty.
  1393. TII->removeBranch(*MBB);
  1394. // If the only things remaining in the block are debug info, remove these
  1395. // as well, so this will behave the same as an empty block in non-debug
  1396. // mode.
  1397. if (IsEmptyBlock(MBB)) {
  1398. // Make the block empty, losing the debug info (we could probably
  1399. // improve this in some cases.)
  1400. MBB->erase(MBB->begin(), MBB->end());
  1401. }
  1402. // If this block is just an unconditional branch to CurTBB, we can
  1403. // usually completely eliminate the block. The only case we cannot
  1404. // completely eliminate the block is when the block before this one
  1405. // falls through into MBB and we can't understand the prior block's branch
  1406. // condition.
  1407. if (MBB->empty()) {
  1408. bool PredHasNoFallThrough = !PrevBB.canFallThrough();
  1409. if (PredHasNoFallThrough || !PriorUnAnalyzable ||
  1410. !PrevBB.isSuccessor(MBB)) {
  1411. // If the prior block falls through into us, turn it into an
  1412. // explicit branch to us to make updates simpler.
  1413. if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
  1414. PriorTBB != MBB && PriorFBB != MBB) {
  1415. if (!PriorTBB) {
  1416. assert(PriorCond.empty() && !PriorFBB &&
  1417. "Bad branch analysis");
  1418. PriorTBB = MBB;
  1419. } else {
  1420. assert(!PriorFBB && "Machine CFG out of date!");
  1421. PriorFBB = MBB;
  1422. }
  1423. DebugLoc pdl = getBranchDebugLoc(PrevBB);
  1424. TII->removeBranch(PrevBB);
  1425. TII->insertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, pdl);
  1426. }
  1427. // Iterate through all the predecessors, revectoring each in-turn.
  1428. size_t PI = 0;
  1429. bool DidChange = false;
  1430. bool HasBranchToSelf = false;
  1431. while(PI != MBB->pred_size()) {
  1432. MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
  1433. if (PMBB == MBB) {
  1434. // If this block has an uncond branch to itself, leave it.
  1435. ++PI;
  1436. HasBranchToSelf = true;
  1437. } else {
  1438. DidChange = true;
  1439. PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
  1440. // If this change resulted in PMBB ending in a conditional
  1441. // branch where both conditions go to the same destination,
  1442. // change this to an unconditional branch.
  1443. MachineBasicBlock *NewCurTBB = nullptr, *NewCurFBB = nullptr;
  1444. SmallVector<MachineOperand, 4> NewCurCond;
  1445. bool NewCurUnAnalyzable = TII->analyzeBranch(
  1446. *PMBB, NewCurTBB, NewCurFBB, NewCurCond, true);
  1447. if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
  1448. DebugLoc pdl = getBranchDebugLoc(*PMBB);
  1449. TII->removeBranch(*PMBB);
  1450. NewCurCond.clear();
  1451. TII->insertBranch(*PMBB, NewCurTBB, nullptr, NewCurCond, pdl);
  1452. MadeChange = true;
  1453. ++NumBranchOpts;
  1454. }
  1455. }
  1456. }
  1457. // Change any jumptables to go to the new MBB.
  1458. if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
  1459. MJTI->ReplaceMBBInJumpTables(MBB, CurTBB);
  1460. if (DidChange) {
  1461. ++NumBranchOpts;
  1462. MadeChange = true;
  1463. if (!HasBranchToSelf) return MadeChange;
  1464. }
  1465. }
  1466. }
  1467. // Add the branch back if the block is more than just an uncond branch.
  1468. TII->insertBranch(*MBB, CurTBB, nullptr, CurCond, dl);
  1469. }
  1470. }
  1471. // If the prior block doesn't fall through into this block, and if this
  1472. // block doesn't fall through into some other block, see if we can find a
  1473. // place to move this block where a fall-through will happen.
  1474. if (!PrevBB.canFallThrough()) {
  1475. // Now we know that there was no fall-through into this block, check to
  1476. // see if it has a fall-through into its successor.
  1477. bool CurFallsThru = MBB->canFallThrough();
  1478. if (!MBB->isEHPad()) {
  1479. // Check all the predecessors of this block. If one of them has no fall
  1480. // throughs, and analyzeBranch thinks it _could_ fallthrough to this
  1481. // block, move this block right after it.
  1482. for (MachineBasicBlock *PredBB : MBB->predecessors()) {
  1483. // Analyze the branch at the end of the pred.
  1484. MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
  1485. SmallVector<MachineOperand, 4> PredCond;
  1486. if (PredBB != MBB && !PredBB->canFallThrough() &&
  1487. !TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true) &&
  1488. (PredTBB == MBB || PredFBB == MBB) &&
  1489. (!CurFallsThru || !CurTBB || !CurFBB) &&
  1490. (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
  1491. // If the current block doesn't fall through, just move it.
  1492. // If the current block can fall through and does not end with a
  1493. // conditional branch, we need to append an unconditional jump to
  1494. // the (current) next block. To avoid a possible compile-time
  1495. // infinite loop, move blocks only backward in this case.
  1496. // Also, if there are already 2 branches here, we cannot add a third;
  1497. // this means we have the case
  1498. // Bcc next
  1499. // B elsewhere
  1500. // next:
  1501. if (CurFallsThru) {
  1502. MachineBasicBlock *NextBB = &*std::next(MBB->getIterator());
  1503. CurCond.clear();
  1504. TII->insertBranch(*MBB, NextBB, nullptr, CurCond, DebugLoc());
  1505. }
  1506. MBB->moveAfter(PredBB);
  1507. MadeChange = true;
  1508. goto ReoptimizeBlock;
  1509. }
  1510. }
  1511. }
  1512. if (!CurFallsThru) {
  1513. // Check analyzable branch-successors to see if we can move this block
  1514. // before one.
  1515. if (!CurUnAnalyzable) {
  1516. for (MachineBasicBlock *SuccBB : {CurFBB, CurTBB}) {
  1517. if (!SuccBB)
  1518. continue;
  1519. // Analyze the branch at the end of the block before the succ.
  1520. MachineFunction::iterator SuccPrev = --SuccBB->getIterator();
  1521. // If this block doesn't already fall-through to that successor, and
  1522. // if the succ doesn't already have a block that can fall through into
  1523. // it, we can arrange for the fallthrough to happen.
  1524. if (SuccBB != MBB && &*SuccPrev != MBB &&
  1525. !SuccPrev->canFallThrough()) {
  1526. MBB->moveBefore(SuccBB);
  1527. MadeChange = true;
  1528. goto ReoptimizeBlock;
  1529. }
  1530. }
  1531. }
  1532. // Okay, there is no really great place to put this block. If, however,
  1533. // the block before this one would be a fall-through if this block were
  1534. // removed, move this block to the end of the function. There is no real
  1535. // advantage in "falling through" to an EH block, so we don't want to
  1536. // perform this transformation for that case.
  1537. //
  1538. // Also, Windows EH introduced the possibility of an arbitrary number of
  1539. // successors to a given block. The analyzeBranch call does not consider
  1540. // exception handling and so we can get in a state where a block
  1541. // containing a call is followed by multiple EH blocks that would be
  1542. // rotated infinitely at the end of the function if the transformation
  1543. // below were performed for EH "FallThrough" blocks. Therefore, even if
  1544. // that appears not to be happening anymore, we should assume that it is
  1545. // possible and not remove the "!FallThrough()->isEHPad" condition below.
  1546. MachineBasicBlock *PrevTBB = nullptr, *PrevFBB = nullptr;
  1547. SmallVector<MachineOperand, 4> PrevCond;
  1548. if (FallThrough != MF.end() &&
  1549. !FallThrough->isEHPad() &&
  1550. !TII->analyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) &&
  1551. PrevBB.isSuccessor(&*FallThrough)) {
  1552. MBB->moveAfter(&MF.back());
  1553. MadeChange = true;
  1554. return MadeChange;
  1555. }
  1556. }
  1557. }
  1558. return MadeChange;
  1559. }
  1560. //===----------------------------------------------------------------------===//
  1561. // Hoist Common Code
  1562. //===----------------------------------------------------------------------===//
  1563. bool BranchFolder::HoistCommonCode(MachineFunction &MF) {
  1564. bool MadeChange = false;
  1565. for (MachineBasicBlock &MBB : llvm::make_early_inc_range(MF))
  1566. MadeChange |= HoistCommonCodeInSuccs(&MBB);
  1567. return MadeChange;
  1568. }
  1569. /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
  1570. /// its 'true' successor.
  1571. static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
  1572. MachineBasicBlock *TrueBB) {
  1573. for (MachineBasicBlock *SuccBB : BB->successors())
  1574. if (SuccBB != TrueBB)
  1575. return SuccBB;
  1576. return nullptr;
  1577. }
  1578. template <class Container>
  1579. static void addRegAndItsAliases(Register Reg, const TargetRegisterInfo *TRI,
  1580. Container &Set) {
  1581. if (Reg.isPhysical()) {
  1582. for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
  1583. Set.insert(*AI);
  1584. } else {
  1585. Set.insert(Reg);
  1586. }
  1587. }
  1588. /// findHoistingInsertPosAndDeps - Find the location to move common instructions
  1589. /// in successors to. The location is usually just before the terminator,
  1590. /// however if the terminator is a conditional branch and its previous
  1591. /// instruction is the flag setting instruction, the previous instruction is
  1592. /// the preferred location. This function also gathers uses and defs of the
  1593. /// instructions from the insertion point to the end of the block. The data is
  1594. /// used by HoistCommonCodeInSuccs to ensure safety.
  1595. static
  1596. MachineBasicBlock::iterator findHoistingInsertPosAndDeps(MachineBasicBlock *MBB,
  1597. const TargetInstrInfo *TII,
  1598. const TargetRegisterInfo *TRI,
  1599. SmallSet<Register, 4> &Uses,
  1600. SmallSet<Register, 4> &Defs) {
  1601. MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
  1602. if (!TII->isUnpredicatedTerminator(*Loc))
  1603. return MBB->end();
  1604. for (const MachineOperand &MO : Loc->operands()) {
  1605. if (!MO.isReg())
  1606. continue;
  1607. Register Reg = MO.getReg();
  1608. if (!Reg)
  1609. continue;
  1610. if (MO.isUse()) {
  1611. addRegAndItsAliases(Reg, TRI, Uses);
  1612. } else {
  1613. if (!MO.isDead())
  1614. // Don't try to hoist code in the rare case the terminator defines a
  1615. // register that is later used.
  1616. return MBB->end();
  1617. // If the terminator defines a register, make sure we don't hoist
  1618. // the instruction whose def might be clobbered by the terminator.
  1619. addRegAndItsAliases(Reg, TRI, Defs);
  1620. }
  1621. }
  1622. if (Uses.empty())
  1623. return Loc;
  1624. // If the terminator is the only instruction in the block and Uses is not
  1625. // empty (or we would have returned above), we can still safely hoist
  1626. // instructions just before the terminator as long as the Defs/Uses are not
  1627. // violated (which is checked in HoistCommonCodeInSuccs).
  1628. if (Loc == MBB->begin())
  1629. return Loc;
  1630. // The terminator is probably a conditional branch, try not to separate the
  1631. // branch from condition setting instruction.
  1632. MachineBasicBlock::iterator PI = prev_nodbg(Loc, MBB->begin());
  1633. bool IsDef = false;
  1634. for (const MachineOperand &MO : PI->operands()) {
  1635. // If PI has a regmask operand, it is probably a call. Separate away.
  1636. if (MO.isRegMask())
  1637. return Loc;
  1638. if (!MO.isReg() || MO.isUse())
  1639. continue;
  1640. Register Reg = MO.getReg();
  1641. if (!Reg)
  1642. continue;
  1643. if (Uses.count(Reg)) {
  1644. IsDef = true;
  1645. break;
  1646. }
  1647. }
  1648. if (!IsDef)
  1649. // The condition setting instruction is not just before the conditional
  1650. // branch.
  1651. return Loc;
  1652. // Be conservative, don't insert instruction above something that may have
  1653. // side-effects. And since it's potentially bad to separate flag setting
  1654. // instruction from the conditional branch, just abort the optimization
  1655. // completely.
  1656. // Also avoid moving code above predicated instruction since it's hard to
  1657. // reason about register liveness with predicated instruction.
  1658. bool DontMoveAcrossStore = true;
  1659. if (!PI->isSafeToMove(nullptr, DontMoveAcrossStore) || TII->isPredicated(*PI))
  1660. return MBB->end();
  1661. // Find out what registers are live. Note this routine is ignoring other live
  1662. // registers which are only used by instructions in successor blocks.
  1663. for (const MachineOperand &MO : PI->operands()) {
  1664. if (!MO.isReg())
  1665. continue;
  1666. Register Reg = MO.getReg();
  1667. if (!Reg)
  1668. continue;
  1669. if (MO.isUse()) {
  1670. addRegAndItsAliases(Reg, TRI, Uses);
  1671. } else {
  1672. if (Uses.erase(Reg)) {
  1673. if (Register::isPhysicalRegister(Reg)) {
  1674. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
  1675. Uses.erase(*SubRegs); // Use sub-registers to be conservative
  1676. }
  1677. }
  1678. addRegAndItsAliases(Reg, TRI, Defs);
  1679. }
  1680. }
  1681. return PI;
  1682. }
  1683. bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock *MBB) {
  1684. MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
  1685. SmallVector<MachineOperand, 4> Cond;
  1686. if (TII->analyzeBranch(*MBB, TBB, FBB, Cond, true) || !TBB || Cond.empty())
  1687. return false;
  1688. if (!FBB) FBB = findFalseBlock(MBB, TBB);
  1689. if (!FBB)
  1690. // Malformed bcc? True and false blocks are the same?
  1691. return false;
  1692. // Restrict the optimization to cases where MBB is the only predecessor,
  1693. // it is an obvious win.
  1694. if (TBB->pred_size() > 1 || FBB->pred_size() > 1)
  1695. return false;
  1696. // Find a suitable position to hoist the common instructions to. Also figure
  1697. // out which registers are used or defined by instructions from the insertion
  1698. // point to the end of the block.
  1699. SmallSet<Register, 4> Uses, Defs;
  1700. MachineBasicBlock::iterator Loc =
  1701. findHoistingInsertPosAndDeps(MBB, TII, TRI, Uses, Defs);
  1702. if (Loc == MBB->end())
  1703. return false;
  1704. bool HasDups = false;
  1705. SmallSet<Register, 4> ActiveDefsSet, AllDefsSet;
  1706. MachineBasicBlock::iterator TIB = TBB->begin();
  1707. MachineBasicBlock::iterator FIB = FBB->begin();
  1708. MachineBasicBlock::iterator TIE = TBB->end();
  1709. MachineBasicBlock::iterator FIE = FBB->end();
  1710. while (TIB != TIE && FIB != FIE) {
  1711. // Skip dbg_value instructions. These do not count.
  1712. TIB = skipDebugInstructionsForward(TIB, TIE, false);
  1713. FIB = skipDebugInstructionsForward(FIB, FIE, false);
  1714. if (TIB == TIE || FIB == FIE)
  1715. break;
  1716. if (!TIB->isIdenticalTo(*FIB, MachineInstr::CheckKillDead))
  1717. break;
  1718. if (TII->isPredicated(*TIB))
  1719. // Hard to reason about register liveness with predicated instruction.
  1720. break;
  1721. bool IsSafe = true;
  1722. for (MachineOperand &MO : TIB->operands()) {
  1723. // Don't attempt to hoist instructions with register masks.
  1724. if (MO.isRegMask()) {
  1725. IsSafe = false;
  1726. break;
  1727. }
  1728. if (!MO.isReg())
  1729. continue;
  1730. Register Reg = MO.getReg();
  1731. if (!Reg)
  1732. continue;
  1733. if (MO.isDef()) {
  1734. if (Uses.count(Reg)) {
  1735. // Avoid clobbering a register that's used by the instruction at
  1736. // the point of insertion.
  1737. IsSafe = false;
  1738. break;
  1739. }
  1740. if (Defs.count(Reg) && !MO.isDead()) {
  1741. // Don't hoist the instruction if the def would be clobber by the
  1742. // instruction at the point insertion. FIXME: This is overly
  1743. // conservative. It should be possible to hoist the instructions
  1744. // in BB2 in the following example:
  1745. // BB1:
  1746. // r1, eflag = op1 r2, r3
  1747. // brcc eflag
  1748. //
  1749. // BB2:
  1750. // r1 = op2, ...
  1751. // = op3, killed r1
  1752. IsSafe = false;
  1753. break;
  1754. }
  1755. } else if (!ActiveDefsSet.count(Reg)) {
  1756. if (Defs.count(Reg)) {
  1757. // Use is defined by the instruction at the point of insertion.
  1758. IsSafe = false;
  1759. break;
  1760. }
  1761. if (MO.isKill() && Uses.count(Reg))
  1762. // Kills a register that's read by the instruction at the point of
  1763. // insertion. Remove the kill marker.
  1764. MO.setIsKill(false);
  1765. }
  1766. }
  1767. if (!IsSafe)
  1768. break;
  1769. bool DontMoveAcrossStore = true;
  1770. if (!TIB->isSafeToMove(nullptr, DontMoveAcrossStore))
  1771. break;
  1772. // Remove kills from ActiveDefsSet, these registers had short live ranges.
  1773. for (const MachineOperand &MO : TIB->operands()) {
  1774. if (!MO.isReg() || !MO.isUse() || !MO.isKill())
  1775. continue;
  1776. Register Reg = MO.getReg();
  1777. if (!Reg)
  1778. continue;
  1779. if (!AllDefsSet.count(Reg)) {
  1780. continue;
  1781. }
  1782. if (Reg.isPhysical()) {
  1783. for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
  1784. ActiveDefsSet.erase(*AI);
  1785. } else {
  1786. ActiveDefsSet.erase(Reg);
  1787. }
  1788. }
  1789. // Track local defs so we can update liveins.
  1790. for (const MachineOperand &MO : TIB->operands()) {
  1791. if (!MO.isReg() || !MO.isDef() || MO.isDead())
  1792. continue;
  1793. Register Reg = MO.getReg();
  1794. if (!Reg || Reg.isVirtual())
  1795. continue;
  1796. addRegAndItsAliases(Reg, TRI, ActiveDefsSet);
  1797. addRegAndItsAliases(Reg, TRI, AllDefsSet);
  1798. }
  1799. HasDups = true;
  1800. ++TIB;
  1801. ++FIB;
  1802. }
  1803. if (!HasDups)
  1804. return false;
  1805. MBB->splice(Loc, TBB, TBB->begin(), TIB);
  1806. FBB->erase(FBB->begin(), FIB);
  1807. if (UpdateLiveIns) {
  1808. recomputeLiveIns(*TBB);
  1809. recomputeLiveIns(*FBB);
  1810. }
  1811. ++NumHoist;
  1812. return true;
  1813. }