EarlyIfConversion.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  1. //===-- EarlyIfConversion.cpp - If-conversion on SSA form machine code ----===//
  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. // Early if-conversion is for out-of-order CPUs that don't have a lot of
  11. // predicable instructions. The goal is to eliminate conditional branches that
  12. // may mispredict.
  13. //
  14. // Instructions from both sides of the branch are executed specutatively, and a
  15. // cmov instruction selects the result.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "llvm/ADT/BitVector.h"
  19. #include "llvm/ADT/PostOrderIterator.h"
  20. #include "llvm/ADT/SetVector.h"
  21. #include "llvm/ADT/SmallPtrSet.h"
  22. #include "llvm/ADT/SparseSet.h"
  23. #include "llvm/ADT/Statistic.h"
  24. #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
  25. #include "llvm/CodeGen/MachineDominators.h"
  26. #include "llvm/CodeGen/MachineFunction.h"
  27. #include "llvm/CodeGen/MachineFunctionPass.h"
  28. #include "llvm/CodeGen/MachineLoopInfo.h"
  29. #include "llvm/CodeGen/MachineRegisterInfo.h"
  30. #include "llvm/CodeGen/MachineTraceMetrics.h"
  31. #include "llvm/CodeGen/Passes.h"
  32. #include "llvm/Support/CommandLine.h"
  33. #include "llvm/Support/Debug.h"
  34. #include "llvm/Support/raw_ostream.h"
  35. #include "llvm/Target/TargetInstrInfo.h"
  36. #include "llvm/Target/TargetRegisterInfo.h"
  37. #include "llvm/Target/TargetSubtargetInfo.h"
  38. using namespace llvm;
  39. #define DEBUG_TYPE "early-ifcvt"
  40. // Absolute maximum number of instructions allowed per speculated block.
  41. // This bypasses all other heuristics, so it should be set fairly high.
  42. static cl::opt<unsigned>
  43. BlockInstrLimit("early-ifcvt-limit", cl::init(30), cl::Hidden,
  44. cl::desc("Maximum number of instructions per speculated block."));
  45. // Stress testing mode - disable heuristics.
  46. static cl::opt<bool> Stress("stress-early-ifcvt", cl::Hidden,
  47. cl::desc("Turn all knobs to 11"));
  48. STATISTIC(NumDiamondsSeen, "Number of diamonds");
  49. STATISTIC(NumDiamondsConv, "Number of diamonds converted");
  50. STATISTIC(NumTrianglesSeen, "Number of triangles");
  51. STATISTIC(NumTrianglesConv, "Number of triangles converted");
  52. //===----------------------------------------------------------------------===//
  53. // SSAIfConv
  54. //===----------------------------------------------------------------------===//
  55. //
  56. // The SSAIfConv class performs if-conversion on SSA form machine code after
  57. // determining if it is possible. The class contains no heuristics; external
  58. // code should be used to determine when if-conversion is a good idea.
  59. //
  60. // SSAIfConv can convert both triangles and diamonds:
  61. //
  62. // Triangle: Head Diamond: Head
  63. // | \ / \_
  64. // | \ / |
  65. // | [TF]BB FBB TBB
  66. // | / \ /
  67. // | / \ /
  68. // Tail Tail
  69. //
  70. // Instructions in the conditional blocks TBB and/or FBB are spliced into the
  71. // Head block, and phis in the Tail block are converted to select instructions.
  72. //
  73. namespace {
  74. class SSAIfConv {
  75. const TargetInstrInfo *TII;
  76. const TargetRegisterInfo *TRI;
  77. MachineRegisterInfo *MRI;
  78. public:
  79. /// The block containing the conditional branch.
  80. MachineBasicBlock *Head;
  81. /// The block containing phis after the if-then-else.
  82. MachineBasicBlock *Tail;
  83. /// The 'true' conditional block as determined by AnalyzeBranch.
  84. MachineBasicBlock *TBB;
  85. /// The 'false' conditional block as determined by AnalyzeBranch.
  86. MachineBasicBlock *FBB;
  87. /// isTriangle - When there is no 'else' block, either TBB or FBB will be
  88. /// equal to Tail.
  89. bool isTriangle() const { return TBB == Tail || FBB == Tail; }
  90. /// Returns the Tail predecessor for the True side.
  91. MachineBasicBlock *getTPred() const { return TBB == Tail ? Head : TBB; }
  92. /// Returns the Tail predecessor for the False side.
  93. MachineBasicBlock *getFPred() const { return FBB == Tail ? Head : FBB; }
  94. /// Information about each phi in the Tail block.
  95. struct PHIInfo {
  96. MachineInstr *PHI;
  97. unsigned TReg, FReg;
  98. // Latencies from Cond+Branch, TReg, and FReg to DstReg.
  99. int CondCycles, TCycles, FCycles;
  100. PHIInfo(MachineInstr *phi)
  101. : PHI(phi), TReg(0), FReg(0), CondCycles(0), TCycles(0), FCycles(0) {}
  102. };
  103. SmallVector<PHIInfo, 8> PHIs;
  104. private:
  105. /// The branch condition determined by AnalyzeBranch.
  106. SmallVector<MachineOperand, 4> Cond;
  107. /// Instructions in Head that define values used by the conditional blocks.
  108. /// The hoisted instructions must be inserted after these instructions.
  109. SmallPtrSet<MachineInstr*, 8> InsertAfter;
  110. /// Register units clobbered by the conditional blocks.
  111. BitVector ClobberedRegUnits;
  112. // Scratch pad for findInsertionPoint.
  113. SparseSet<unsigned> LiveRegUnits;
  114. /// Insertion point in Head for speculatively executed instructions form TBB
  115. /// and FBB.
  116. MachineBasicBlock::iterator InsertionPoint;
  117. /// Return true if all non-terminator instructions in MBB can be safely
  118. /// speculated.
  119. bool canSpeculateInstrs(MachineBasicBlock *MBB);
  120. /// Find a valid insertion point in Head.
  121. bool findInsertionPoint();
  122. /// Replace PHI instructions in Tail with selects.
  123. void replacePHIInstrs();
  124. /// Insert selects and rewrite PHI operands to use them.
  125. void rewritePHIOperands();
  126. public:
  127. /// runOnMachineFunction - Initialize per-function data structures.
  128. void runOnMachineFunction(MachineFunction &MF) {
  129. TII = MF.getSubtarget().getInstrInfo();
  130. TRI = MF.getSubtarget().getRegisterInfo();
  131. MRI = &MF.getRegInfo();
  132. LiveRegUnits.clear();
  133. LiveRegUnits.setUniverse(TRI->getNumRegUnits());
  134. ClobberedRegUnits.clear();
  135. ClobberedRegUnits.resize(TRI->getNumRegUnits());
  136. }
  137. /// canConvertIf - If the sub-CFG headed by MBB can be if-converted,
  138. /// initialize the internal state, and return true.
  139. bool canConvertIf(MachineBasicBlock *MBB);
  140. /// convertIf - If-convert the last block passed to canConvertIf(), assuming
  141. /// it is possible. Add any erased blocks to RemovedBlocks.
  142. void convertIf(SmallVectorImpl<MachineBasicBlock*> &RemovedBlocks);
  143. };
  144. } // end anonymous namespace
  145. /// canSpeculateInstrs - Returns true if all the instructions in MBB can safely
  146. /// be speculated. The terminators are not considered.
  147. ///
  148. /// If instructions use any values that are defined in the head basic block,
  149. /// the defining instructions are added to InsertAfter.
  150. ///
  151. /// Any clobbered regunits are added to ClobberedRegUnits.
  152. ///
  153. bool SSAIfConv::canSpeculateInstrs(MachineBasicBlock *MBB) {
  154. // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
  155. // get right.
  156. if (!MBB->livein_empty()) {
  157. DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has live-ins.\n");
  158. return false;
  159. }
  160. unsigned InstrCount = 0;
  161. // Check all instructions, except the terminators. It is assumed that
  162. // terminators never have side effects or define any used register values.
  163. for (MachineBasicBlock::iterator I = MBB->begin(),
  164. E = MBB->getFirstTerminator(); I != E; ++I) {
  165. if (I->isDebugValue())
  166. continue;
  167. if (++InstrCount > BlockInstrLimit && !Stress) {
  168. DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has more than "
  169. << BlockInstrLimit << " instructions.\n");
  170. return false;
  171. }
  172. // There shouldn't normally be any phis in a single-predecessor block.
  173. if (I->isPHI()) {
  174. DEBUG(dbgs() << "Can't hoist: " << *I);
  175. return false;
  176. }
  177. // Don't speculate loads. Note that it may be possible and desirable to
  178. // speculate GOT or constant pool loads that are guaranteed not to trap,
  179. // but we don't support that for now.
  180. if (I->mayLoad()) {
  181. DEBUG(dbgs() << "Won't speculate load: " << *I);
  182. return false;
  183. }
  184. // We never speculate stores, so an AA pointer isn't necessary.
  185. bool DontMoveAcrossStore = true;
  186. if (!I->isSafeToMove(nullptr, DontMoveAcrossStore)) {
  187. DEBUG(dbgs() << "Can't speculate: " << *I);
  188. return false;
  189. }
  190. // Check for any dependencies on Head instructions.
  191. for (const MachineOperand &MO : I->operands()) {
  192. if (MO.isRegMask()) {
  193. DEBUG(dbgs() << "Won't speculate regmask: " << *I);
  194. return false;
  195. }
  196. if (!MO.isReg())
  197. continue;
  198. unsigned Reg = MO.getReg();
  199. // Remember clobbered regunits.
  200. if (MO.isDef() && TargetRegisterInfo::isPhysicalRegister(Reg))
  201. for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
  202. ClobberedRegUnits.set(*Units);
  203. if (!MO.readsReg() || !TargetRegisterInfo::isVirtualRegister(Reg))
  204. continue;
  205. MachineInstr *DefMI = MRI->getVRegDef(Reg);
  206. if (!DefMI || DefMI->getParent() != Head)
  207. continue;
  208. if (InsertAfter.insert(DefMI).second)
  209. DEBUG(dbgs() << "BB#" << MBB->getNumber() << " depends on " << *DefMI);
  210. if (DefMI->isTerminator()) {
  211. DEBUG(dbgs() << "Can't insert instructions below terminator.\n");
  212. return false;
  213. }
  214. }
  215. }
  216. return true;
  217. }
  218. /// Find an insertion point in Head for the speculated instructions. The
  219. /// insertion point must be:
  220. ///
  221. /// 1. Before any terminators.
  222. /// 2. After any instructions in InsertAfter.
  223. /// 3. Not have any clobbered regunits live.
  224. ///
  225. /// This function sets InsertionPoint and returns true when successful, it
  226. /// returns false if no valid insertion point could be found.
  227. ///
  228. bool SSAIfConv::findInsertionPoint() {
  229. // Keep track of live regunits before the current position.
  230. // Only track RegUnits that are also in ClobberedRegUnits.
  231. LiveRegUnits.clear();
  232. SmallVector<unsigned, 8> Reads;
  233. MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
  234. MachineBasicBlock::iterator I = Head->end();
  235. MachineBasicBlock::iterator B = Head->begin();
  236. while (I != B) {
  237. --I;
  238. // Some of the conditional code depends in I.
  239. if (InsertAfter.count(I)) {
  240. DEBUG(dbgs() << "Can't insert code after " << *I);
  241. return false;
  242. }
  243. // Update live regunits.
  244. for (const MachineOperand &MO : I->operands()) {
  245. // We're ignoring regmask operands. That is conservatively correct.
  246. if (!MO.isReg())
  247. continue;
  248. unsigned Reg = MO.getReg();
  249. if (!TargetRegisterInfo::isPhysicalRegister(Reg))
  250. continue;
  251. // I clobbers Reg, so it isn't live before I.
  252. if (MO.isDef())
  253. for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
  254. LiveRegUnits.erase(*Units);
  255. // Unless I reads Reg.
  256. if (MO.readsReg())
  257. Reads.push_back(Reg);
  258. }
  259. // Anything read by I is live before I.
  260. while (!Reads.empty())
  261. for (MCRegUnitIterator Units(Reads.pop_back_val(), TRI); Units.isValid();
  262. ++Units)
  263. if (ClobberedRegUnits.test(*Units))
  264. LiveRegUnits.insert(*Units);
  265. // We can't insert before a terminator.
  266. if (I != FirstTerm && I->isTerminator())
  267. continue;
  268. // Some of the clobbered registers are live before I, not a valid insertion
  269. // point.
  270. if (!LiveRegUnits.empty()) {
  271. DEBUG({
  272. dbgs() << "Would clobber";
  273. for (SparseSet<unsigned>::const_iterator
  274. i = LiveRegUnits.begin(), e = LiveRegUnits.end(); i != e; ++i)
  275. dbgs() << ' ' << PrintRegUnit(*i, TRI);
  276. dbgs() << " live before " << *I;
  277. });
  278. continue;
  279. }
  280. // This is a valid insertion point.
  281. InsertionPoint = I;
  282. DEBUG(dbgs() << "Can insert before " << *I);
  283. return true;
  284. }
  285. DEBUG(dbgs() << "No legal insertion point found.\n");
  286. return false;
  287. }
  288. /// canConvertIf - analyze the sub-cfg rooted in MBB, and return true if it is
  289. /// a potential candidate for if-conversion. Fill out the internal state.
  290. ///
  291. bool SSAIfConv::canConvertIf(MachineBasicBlock *MBB) {
  292. Head = MBB;
  293. TBB = FBB = Tail = nullptr;
  294. if (Head->succ_size() != 2)
  295. return false;
  296. MachineBasicBlock *Succ0 = Head->succ_begin()[0];
  297. MachineBasicBlock *Succ1 = Head->succ_begin()[1];
  298. // Canonicalize so Succ0 has MBB as its single predecessor.
  299. if (Succ0->pred_size() != 1)
  300. std::swap(Succ0, Succ1);
  301. if (Succ0->pred_size() != 1 || Succ0->succ_size() != 1)
  302. return false;
  303. Tail = Succ0->succ_begin()[0];
  304. // This is not a triangle.
  305. if (Tail != Succ1) {
  306. // Check for a diamond. We won't deal with any critical edges.
  307. if (Succ1->pred_size() != 1 || Succ1->succ_size() != 1 ||
  308. Succ1->succ_begin()[0] != Tail)
  309. return false;
  310. DEBUG(dbgs() << "\nDiamond: BB#" << Head->getNumber()
  311. << " -> BB#" << Succ0->getNumber()
  312. << "/BB#" << Succ1->getNumber()
  313. << " -> BB#" << Tail->getNumber() << '\n');
  314. // Live-in physregs are tricky to get right when speculating code.
  315. if (!Tail->livein_empty()) {
  316. DEBUG(dbgs() << "Tail has live-ins.\n");
  317. return false;
  318. }
  319. } else {
  320. DEBUG(dbgs() << "\nTriangle: BB#" << Head->getNumber()
  321. << " -> BB#" << Succ0->getNumber()
  322. << " -> BB#" << Tail->getNumber() << '\n');
  323. }
  324. // This is a triangle or a diamond.
  325. // If Tail doesn't have any phis, there must be side effects.
  326. if (Tail->empty() || !Tail->front().isPHI()) {
  327. DEBUG(dbgs() << "No phis in tail.\n");
  328. return false;
  329. }
  330. // The branch we're looking to eliminate must be analyzable.
  331. Cond.clear();
  332. if (TII->AnalyzeBranch(*Head, TBB, FBB, Cond)) {
  333. DEBUG(dbgs() << "Branch not analyzable.\n");
  334. return false;
  335. }
  336. // This is weird, probably some sort of degenerate CFG.
  337. if (!TBB) {
  338. DEBUG(dbgs() << "AnalyzeBranch didn't find conditional branch.\n");
  339. return false;
  340. }
  341. // AnalyzeBranch doesn't set FBB on a fall-through branch.
  342. // Make sure it is always set.
  343. FBB = TBB == Succ0 ? Succ1 : Succ0;
  344. // Any phis in the tail block must be convertible to selects.
  345. PHIs.clear();
  346. MachineBasicBlock *TPred = getTPred();
  347. MachineBasicBlock *FPred = getFPred();
  348. for (MachineBasicBlock::iterator I = Tail->begin(), E = Tail->end();
  349. I != E && I->isPHI(); ++I) {
  350. PHIs.push_back(&*I);
  351. PHIInfo &PI = PHIs.back();
  352. // Find PHI operands corresponding to TPred and FPred.
  353. for (unsigned i = 1; i != PI.PHI->getNumOperands(); i += 2) {
  354. if (PI.PHI->getOperand(i+1).getMBB() == TPred)
  355. PI.TReg = PI.PHI->getOperand(i).getReg();
  356. if (PI.PHI->getOperand(i+1).getMBB() == FPred)
  357. PI.FReg = PI.PHI->getOperand(i).getReg();
  358. }
  359. assert(TargetRegisterInfo::isVirtualRegister(PI.TReg) && "Bad PHI");
  360. assert(TargetRegisterInfo::isVirtualRegister(PI.FReg) && "Bad PHI");
  361. // Get target information.
  362. if (!TII->canInsertSelect(*Head, Cond, PI.TReg, PI.FReg,
  363. PI.CondCycles, PI.TCycles, PI.FCycles)) {
  364. DEBUG(dbgs() << "Can't convert: " << *PI.PHI);
  365. return false;
  366. }
  367. }
  368. // Check that the conditional instructions can be speculated.
  369. InsertAfter.clear();
  370. ClobberedRegUnits.reset();
  371. if (TBB != Tail && !canSpeculateInstrs(TBB))
  372. return false;
  373. if (FBB != Tail && !canSpeculateInstrs(FBB))
  374. return false;
  375. // Try to find a valid insertion point for the speculated instructions in the
  376. // head basic block.
  377. if (!findInsertionPoint())
  378. return false;
  379. if (isTriangle())
  380. ++NumTrianglesSeen;
  381. else
  382. ++NumDiamondsSeen;
  383. return true;
  384. }
  385. /// replacePHIInstrs - Completely replace PHI instructions with selects.
  386. /// This is possible when the only Tail predecessors are the if-converted
  387. /// blocks.
  388. void SSAIfConv::replacePHIInstrs() {
  389. assert(Tail->pred_size() == 2 && "Cannot replace PHIs");
  390. MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
  391. assert(FirstTerm != Head->end() && "No terminators");
  392. DebugLoc HeadDL = FirstTerm->getDebugLoc();
  393. // Convert all PHIs to select instructions inserted before FirstTerm.
  394. for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
  395. PHIInfo &PI = PHIs[i];
  396. DEBUG(dbgs() << "If-converting " << *PI.PHI);
  397. unsigned DstReg = PI.PHI->getOperand(0).getReg();
  398. TII->insertSelect(*Head, FirstTerm, HeadDL, DstReg, Cond, PI.TReg, PI.FReg);
  399. DEBUG(dbgs() << " --> " << *std::prev(FirstTerm));
  400. PI.PHI->eraseFromParent();
  401. PI.PHI = nullptr;
  402. }
  403. }
  404. /// rewritePHIOperands - When there are additional Tail predecessors, insert
  405. /// select instructions in Head and rewrite PHI operands to use the selects.
  406. /// Keep the PHI instructions in Tail to handle the other predecessors.
  407. void SSAIfConv::rewritePHIOperands() {
  408. MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
  409. assert(FirstTerm != Head->end() && "No terminators");
  410. DebugLoc HeadDL = FirstTerm->getDebugLoc();
  411. // Convert all PHIs to select instructions inserted before FirstTerm.
  412. for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
  413. PHIInfo &PI = PHIs[i];
  414. unsigned DstReg = 0;
  415. DEBUG(dbgs() << "If-converting " << *PI.PHI);
  416. if (PI.TReg == PI.FReg) {
  417. // We do not need the select instruction if both incoming values are
  418. // equal.
  419. DstReg = PI.TReg;
  420. } else {
  421. unsigned PHIDst = PI.PHI->getOperand(0).getReg();
  422. DstReg = MRI->createVirtualRegister(MRI->getRegClass(PHIDst));
  423. TII->insertSelect(*Head, FirstTerm, HeadDL,
  424. DstReg, Cond, PI.TReg, PI.FReg);
  425. DEBUG(dbgs() << " --> " << *std::prev(FirstTerm));
  426. }
  427. // Rewrite PHI operands TPred -> (DstReg, Head), remove FPred.
  428. for (unsigned i = PI.PHI->getNumOperands(); i != 1; i -= 2) {
  429. MachineBasicBlock *MBB = PI.PHI->getOperand(i-1).getMBB();
  430. if (MBB == getTPred()) {
  431. PI.PHI->getOperand(i-1).setMBB(Head);
  432. PI.PHI->getOperand(i-2).setReg(DstReg);
  433. } else if (MBB == getFPred()) {
  434. PI.PHI->RemoveOperand(i-1);
  435. PI.PHI->RemoveOperand(i-2);
  436. }
  437. }
  438. DEBUG(dbgs() << " --> " << *PI.PHI);
  439. }
  440. }
  441. /// convertIf - Execute the if conversion after canConvertIf has determined the
  442. /// feasibility.
  443. ///
  444. /// Any basic blocks erased will be added to RemovedBlocks.
  445. ///
  446. void SSAIfConv::convertIf(SmallVectorImpl<MachineBasicBlock*> &RemovedBlocks) {
  447. assert(Head && Tail && TBB && FBB && "Call canConvertIf first.");
  448. // Update statistics.
  449. if (isTriangle())
  450. ++NumTrianglesConv;
  451. else
  452. ++NumDiamondsConv;
  453. // Move all instructions into Head, except for the terminators.
  454. if (TBB != Tail)
  455. Head->splice(InsertionPoint, TBB, TBB->begin(), TBB->getFirstTerminator());
  456. if (FBB != Tail)
  457. Head->splice(InsertionPoint, FBB, FBB->begin(), FBB->getFirstTerminator());
  458. // Are there extra Tail predecessors?
  459. bool ExtraPreds = Tail->pred_size() != 2;
  460. if (ExtraPreds)
  461. rewritePHIOperands();
  462. else
  463. replacePHIInstrs();
  464. // Fix up the CFG, temporarily leave Head without any successors.
  465. Head->removeSuccessor(TBB);
  466. Head->removeSuccessor(FBB);
  467. if (TBB != Tail)
  468. TBB->removeSuccessor(Tail);
  469. if (FBB != Tail)
  470. FBB->removeSuccessor(Tail);
  471. // Fix up Head's terminators.
  472. // It should become a single branch or a fallthrough.
  473. DebugLoc HeadDL = Head->getFirstTerminator()->getDebugLoc();
  474. TII->RemoveBranch(*Head);
  475. // Erase the now empty conditional blocks. It is likely that Head can fall
  476. // through to Tail, and we can join the two blocks.
  477. if (TBB != Tail) {
  478. RemovedBlocks.push_back(TBB);
  479. TBB->eraseFromParent();
  480. }
  481. if (FBB != Tail) {
  482. RemovedBlocks.push_back(FBB);
  483. FBB->eraseFromParent();
  484. }
  485. assert(Head->succ_empty() && "Additional head successors?");
  486. if (!ExtraPreds && Head->isLayoutSuccessor(Tail)) {
  487. // Splice Tail onto the end of Head.
  488. DEBUG(dbgs() << "Joining tail BB#" << Tail->getNumber()
  489. << " into head BB#" << Head->getNumber() << '\n');
  490. Head->splice(Head->end(), Tail,
  491. Tail->begin(), Tail->end());
  492. Head->transferSuccessorsAndUpdatePHIs(Tail);
  493. RemovedBlocks.push_back(Tail);
  494. Tail->eraseFromParent();
  495. } else {
  496. // We need a branch to Tail, let code placement work it out later.
  497. DEBUG(dbgs() << "Converting to unconditional branch.\n");
  498. SmallVector<MachineOperand, 0> EmptyCond;
  499. TII->InsertBranch(*Head, Tail, nullptr, EmptyCond, HeadDL);
  500. Head->addSuccessor(Tail);
  501. }
  502. DEBUG(dbgs() << *Head);
  503. }
  504. //===----------------------------------------------------------------------===//
  505. // EarlyIfConverter Pass
  506. //===----------------------------------------------------------------------===//
  507. namespace {
  508. class EarlyIfConverter : public MachineFunctionPass {
  509. const TargetInstrInfo *TII;
  510. const TargetRegisterInfo *TRI;
  511. MCSchedModel SchedModel;
  512. MachineRegisterInfo *MRI;
  513. MachineDominatorTree *DomTree;
  514. MachineLoopInfo *Loops;
  515. MachineTraceMetrics *Traces;
  516. MachineTraceMetrics::Ensemble *MinInstr;
  517. SSAIfConv IfConv;
  518. public:
  519. static char ID;
  520. EarlyIfConverter() : MachineFunctionPass(ID) {}
  521. void getAnalysisUsage(AnalysisUsage &AU) const override;
  522. bool runOnMachineFunction(MachineFunction &MF) override;
  523. const char *getPassName() const override { return "Early If-Conversion"; }
  524. private:
  525. bool tryConvertIf(MachineBasicBlock*);
  526. void updateDomTree(ArrayRef<MachineBasicBlock*> Removed);
  527. void updateLoops(ArrayRef<MachineBasicBlock*> Removed);
  528. void invalidateTraces();
  529. bool shouldConvertIf();
  530. };
  531. } // end anonymous namespace
  532. char EarlyIfConverter::ID = 0;
  533. char &llvm::EarlyIfConverterID = EarlyIfConverter::ID;
  534. INITIALIZE_PASS_BEGIN(EarlyIfConverter,
  535. "early-ifcvt", "Early If Converter", false, false)
  536. INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
  537. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  538. INITIALIZE_PASS_DEPENDENCY(MachineTraceMetrics)
  539. INITIALIZE_PASS_END(EarlyIfConverter,
  540. "early-ifcvt", "Early If Converter", false, false)
  541. void EarlyIfConverter::getAnalysisUsage(AnalysisUsage &AU) const {
  542. AU.addRequired<MachineBranchProbabilityInfo>();
  543. AU.addRequired<MachineDominatorTree>();
  544. AU.addPreserved<MachineDominatorTree>();
  545. AU.addRequired<MachineLoopInfo>();
  546. AU.addPreserved<MachineLoopInfo>();
  547. AU.addRequired<MachineTraceMetrics>();
  548. AU.addPreserved<MachineTraceMetrics>();
  549. MachineFunctionPass::getAnalysisUsage(AU);
  550. }
  551. /// Update the dominator tree after if-conversion erased some blocks.
  552. void EarlyIfConverter::updateDomTree(ArrayRef<MachineBasicBlock*> Removed) {
  553. // convertIf can remove TBB, FBB, and Tail can be merged into Head.
  554. // TBB and FBB should not dominate any blocks.
  555. // Tail children should be transferred to Head.
  556. MachineDomTreeNode *HeadNode = DomTree->getNode(IfConv.Head);
  557. for (unsigned i = 0, e = Removed.size(); i != e; ++i) {
  558. MachineDomTreeNode *Node = DomTree->getNode(Removed[i]);
  559. assert(Node != HeadNode && "Cannot erase the head node");
  560. while (Node->getNumChildren()) {
  561. assert(Node->getBlock() == IfConv.Tail && "Unexpected children");
  562. DomTree->changeImmediateDominator(Node->getChildren().back(), HeadNode);
  563. }
  564. DomTree->eraseNode(Removed[i]);
  565. }
  566. }
  567. /// Update LoopInfo after if-conversion.
  568. void EarlyIfConverter::updateLoops(ArrayRef<MachineBasicBlock*> Removed) {
  569. if (!Loops)
  570. return;
  571. // If-conversion doesn't change loop structure, and it doesn't mess with back
  572. // edges, so updating LoopInfo is simply removing the dead blocks.
  573. for (unsigned i = 0, e = Removed.size(); i != e; ++i)
  574. Loops->removeBlock(Removed[i]);
  575. }
  576. /// Invalidate MachineTraceMetrics before if-conversion.
  577. void EarlyIfConverter::invalidateTraces() {
  578. Traces->verifyAnalysis();
  579. Traces->invalidate(IfConv.Head);
  580. Traces->invalidate(IfConv.Tail);
  581. Traces->invalidate(IfConv.TBB);
  582. Traces->invalidate(IfConv.FBB);
  583. Traces->verifyAnalysis();
  584. }
  585. // Adjust cycles with downward saturation.
  586. static unsigned adjCycles(unsigned Cyc, int Delta) {
  587. if (Delta < 0 && Cyc + Delta > Cyc)
  588. return 0;
  589. return Cyc + Delta;
  590. }
  591. /// Apply cost model and heuristics to the if-conversion in IfConv.
  592. /// Return true if the conversion is a good idea.
  593. ///
  594. bool EarlyIfConverter::shouldConvertIf() {
  595. // Stress testing mode disables all cost considerations.
  596. if (Stress)
  597. return true;
  598. if (!MinInstr)
  599. MinInstr = Traces->getEnsemble(MachineTraceMetrics::TS_MinInstrCount);
  600. MachineTraceMetrics::Trace TBBTrace = MinInstr->getTrace(IfConv.getTPred());
  601. MachineTraceMetrics::Trace FBBTrace = MinInstr->getTrace(IfConv.getFPred());
  602. DEBUG(dbgs() << "TBB: " << TBBTrace << "FBB: " << FBBTrace);
  603. unsigned MinCrit = std::min(TBBTrace.getCriticalPath(),
  604. FBBTrace.getCriticalPath());
  605. // Set a somewhat arbitrary limit on the critical path extension we accept.
  606. unsigned CritLimit = SchedModel.MispredictPenalty/2;
  607. // If-conversion only makes sense when there is unexploited ILP. Compute the
  608. // maximum-ILP resource length of the trace after if-conversion. Compare it
  609. // to the shortest critical path.
  610. SmallVector<const MachineBasicBlock*, 1> ExtraBlocks;
  611. if (IfConv.TBB != IfConv.Tail)
  612. ExtraBlocks.push_back(IfConv.TBB);
  613. unsigned ResLength = FBBTrace.getResourceLength(ExtraBlocks);
  614. DEBUG(dbgs() << "Resource length " << ResLength
  615. << ", minimal critical path " << MinCrit << '\n');
  616. if (ResLength > MinCrit + CritLimit) {
  617. DEBUG(dbgs() << "Not enough available ILP.\n");
  618. return false;
  619. }
  620. // Assume that the depth of the first head terminator will also be the depth
  621. // of the select instruction inserted, as determined by the flag dependency.
  622. // TBB / FBB data dependencies may delay the select even more.
  623. MachineTraceMetrics::Trace HeadTrace = MinInstr->getTrace(IfConv.Head);
  624. unsigned BranchDepth =
  625. HeadTrace.getInstrCycles(IfConv.Head->getFirstTerminator()).Depth;
  626. DEBUG(dbgs() << "Branch depth: " << BranchDepth << '\n');
  627. // Look at all the tail phis, and compute the critical path extension caused
  628. // by inserting select instructions.
  629. MachineTraceMetrics::Trace TailTrace = MinInstr->getTrace(IfConv.Tail);
  630. for (unsigned i = 0, e = IfConv.PHIs.size(); i != e; ++i) {
  631. SSAIfConv::PHIInfo &PI = IfConv.PHIs[i];
  632. unsigned Slack = TailTrace.getInstrSlack(PI.PHI);
  633. unsigned MaxDepth = Slack + TailTrace.getInstrCycles(PI.PHI).Depth;
  634. DEBUG(dbgs() << "Slack " << Slack << ":\t" << *PI.PHI);
  635. // The condition is pulled into the critical path.
  636. unsigned CondDepth = adjCycles(BranchDepth, PI.CondCycles);
  637. if (CondDepth > MaxDepth) {
  638. unsigned Extra = CondDepth - MaxDepth;
  639. DEBUG(dbgs() << "Condition adds " << Extra << " cycles.\n");
  640. if (Extra > CritLimit) {
  641. DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
  642. return false;
  643. }
  644. }
  645. // The TBB value is pulled into the critical path.
  646. unsigned TDepth = adjCycles(TBBTrace.getPHIDepth(PI.PHI), PI.TCycles);
  647. if (TDepth > MaxDepth) {
  648. unsigned Extra = TDepth - MaxDepth;
  649. DEBUG(dbgs() << "TBB data adds " << Extra << " cycles.\n");
  650. if (Extra > CritLimit) {
  651. DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
  652. return false;
  653. }
  654. }
  655. // The FBB value is pulled into the critical path.
  656. unsigned FDepth = adjCycles(FBBTrace.getPHIDepth(PI.PHI), PI.FCycles);
  657. if (FDepth > MaxDepth) {
  658. unsigned Extra = FDepth - MaxDepth;
  659. DEBUG(dbgs() << "FBB data adds " << Extra << " cycles.\n");
  660. if (Extra > CritLimit) {
  661. DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
  662. return false;
  663. }
  664. }
  665. }
  666. return true;
  667. }
  668. /// Attempt repeated if-conversion on MBB, return true if successful.
  669. ///
  670. bool EarlyIfConverter::tryConvertIf(MachineBasicBlock *MBB) {
  671. bool Changed = false;
  672. while (IfConv.canConvertIf(MBB) && shouldConvertIf()) {
  673. // If-convert MBB and update analyses.
  674. invalidateTraces();
  675. SmallVector<MachineBasicBlock*, 4> RemovedBlocks;
  676. IfConv.convertIf(RemovedBlocks);
  677. Changed = true;
  678. updateDomTree(RemovedBlocks);
  679. updateLoops(RemovedBlocks);
  680. }
  681. return Changed;
  682. }
  683. bool EarlyIfConverter::runOnMachineFunction(MachineFunction &MF) {
  684. DEBUG(dbgs() << "********** EARLY IF-CONVERSION **********\n"
  685. << "********** Function: " << MF.getName() << '\n');
  686. // Only run if conversion if the target wants it.
  687. const TargetSubtargetInfo &STI = MF.getSubtarget();
  688. if (!STI.enableEarlyIfConversion())
  689. return false;
  690. TII = STI.getInstrInfo();
  691. TRI = STI.getRegisterInfo();
  692. SchedModel = STI.getSchedModel();
  693. MRI = &MF.getRegInfo();
  694. DomTree = &getAnalysis<MachineDominatorTree>();
  695. Loops = getAnalysisIfAvailable<MachineLoopInfo>();
  696. Traces = &getAnalysis<MachineTraceMetrics>();
  697. MinInstr = nullptr;
  698. bool Changed = false;
  699. IfConv.runOnMachineFunction(MF);
  700. // Visit blocks in dominator tree post-order. The post-order enables nested
  701. // if-conversion in a single pass. The tryConvertIf() function may erase
  702. // blocks, but only blocks dominated by the head block. This makes it safe to
  703. // update the dominator tree while the post-order iterator is still active.
  704. for (auto DomNode : post_order(DomTree))
  705. if (tryConvertIf(DomNode->getBlock()))
  706. Changed = true;
  707. return Changed;
  708. }