BranchFolding.cpp 78 KB

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