BranchFolding.cpp 69 KB

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