BranchFolding.cpp 77 KB

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