BranchFolding.cpp 75 KB

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