BranchFolding.cpp 69 KB

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