TwoAddressInstructionPass.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  1. //===-- TwoAddressInstructionPass.cpp - Two-Address instruction pass ------===//
  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 file implements the TwoAddress instruction pass which is used
  11. // by most register allocators. Two-Address instructions are rewritten
  12. // from:
  13. //
  14. // A = B op C
  15. //
  16. // to:
  17. //
  18. // A = B
  19. // A op= C
  20. //
  21. // Note that if a register allocator chooses to use this pass, that it
  22. // has to be capable of handling the non-SSA nature of these rewritten
  23. // virtual registers.
  24. //
  25. // It is also worth noting that the duplicate operand of the two
  26. // address instruction is removed.
  27. //
  28. //===----------------------------------------------------------------------===//
  29. #define DEBUG_TYPE "twoaddrinstr"
  30. #include "llvm/CodeGen/Passes.h"
  31. #include "llvm/Function.h"
  32. #include "llvm/CodeGen/LiveVariables.h"
  33. #include "llvm/CodeGen/MachineFunctionPass.h"
  34. #include "llvm/CodeGen/MachineInstr.h"
  35. #include "llvm/CodeGen/MachineRegisterInfo.h"
  36. #include "llvm/Analysis/AliasAnalysis.h"
  37. #include "llvm/Target/TargetRegisterInfo.h"
  38. #include "llvm/Target/TargetInstrInfo.h"
  39. #include "llvm/Target/TargetMachine.h"
  40. #include "llvm/Target/TargetOptions.h"
  41. #include "llvm/Support/Debug.h"
  42. #include "llvm/ADT/BitVector.h"
  43. #include "llvm/ADT/DenseMap.h"
  44. #include "llvm/ADT/SmallSet.h"
  45. #include "llvm/ADT/Statistic.h"
  46. #include "llvm/ADT/STLExtras.h"
  47. using namespace llvm;
  48. STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
  49. STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
  50. STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
  51. STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
  52. STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
  53. STATISTIC(NumReMats, "Number of instructions re-materialized");
  54. STATISTIC(NumDeletes, "Number of dead instructions deleted");
  55. namespace {
  56. class TwoAddressInstructionPass : public MachineFunctionPass {
  57. const TargetInstrInfo *TII;
  58. const TargetRegisterInfo *TRI;
  59. MachineRegisterInfo *MRI;
  60. LiveVariables *LV;
  61. AliasAnalysis *AA;
  62. // DistanceMap - Keep track the distance of a MI from the start of the
  63. // current basic block.
  64. DenseMap<MachineInstr*, unsigned> DistanceMap;
  65. // SrcRegMap - A map from virtual registers to physical registers which
  66. // are likely targets to be coalesced to due to copies from physical
  67. // registers to virtual registers. e.g. v1024 = move r0.
  68. DenseMap<unsigned, unsigned> SrcRegMap;
  69. // DstRegMap - A map from virtual registers to physical registers which
  70. // are likely targets to be coalesced to due to copies to physical
  71. // registers from virtual registers. e.g. r1 = move v1024.
  72. DenseMap<unsigned, unsigned> DstRegMap;
  73. bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
  74. unsigned Reg,
  75. MachineBasicBlock::iterator OldPos);
  76. bool isProfitableToReMat(unsigned Reg, const TargetRegisterClass *RC,
  77. MachineInstr *MI, MachineInstr *DefMI,
  78. MachineBasicBlock *MBB, unsigned Loc);
  79. bool NoUseAfterLastDef(unsigned Reg, MachineBasicBlock *MBB, unsigned Dist,
  80. unsigned &LastDef);
  81. MachineInstr *FindLastUseInMBB(unsigned Reg, MachineBasicBlock *MBB,
  82. unsigned Dist);
  83. bool isProfitableToCommute(unsigned regB, unsigned regC,
  84. MachineInstr *MI, MachineBasicBlock *MBB,
  85. unsigned Dist);
  86. bool CommuteInstruction(MachineBasicBlock::iterator &mi,
  87. MachineFunction::iterator &mbbi,
  88. unsigned RegB, unsigned RegC, unsigned Dist);
  89. bool isProfitableToConv3Addr(unsigned RegA);
  90. bool ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
  91. MachineBasicBlock::iterator &nmi,
  92. MachineFunction::iterator &mbbi,
  93. unsigned RegB, unsigned Dist);
  94. typedef std::pair<std::pair<unsigned, bool>, MachineInstr*> NewKill;
  95. bool canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
  96. SmallVector<NewKill, 4> &NewKills,
  97. MachineBasicBlock *MBB, unsigned Dist);
  98. bool DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
  99. MachineBasicBlock::iterator &nmi,
  100. MachineFunction::iterator &mbbi,
  101. unsigned regB, unsigned regBIdx, unsigned Dist);
  102. bool TryInstructionTransform(MachineBasicBlock::iterator &mi,
  103. MachineBasicBlock::iterator &nmi,
  104. MachineFunction::iterator &mbbi,
  105. unsigned SrcIdx, unsigned DstIdx,
  106. unsigned Dist);
  107. void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
  108. SmallPtrSet<MachineInstr*, 8> &Processed);
  109. public:
  110. static char ID; // Pass identification, replacement for typeid
  111. TwoAddressInstructionPass() : MachineFunctionPass(&ID) {}
  112. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  113. AU.setPreservesCFG();
  114. AU.addRequired<AliasAnalysis>();
  115. AU.addPreserved<LiveVariables>();
  116. AU.addPreservedID(MachineLoopInfoID);
  117. AU.addPreservedID(MachineDominatorsID);
  118. if (StrongPHIElim)
  119. AU.addPreservedID(StrongPHIEliminationID);
  120. else
  121. AU.addPreservedID(PHIEliminationID);
  122. MachineFunctionPass::getAnalysisUsage(AU);
  123. }
  124. /// runOnMachineFunction - Pass entry point.
  125. bool runOnMachineFunction(MachineFunction&);
  126. };
  127. }
  128. char TwoAddressInstructionPass::ID = 0;
  129. static RegisterPass<TwoAddressInstructionPass>
  130. X("twoaddressinstruction", "Two-Address instruction pass");
  131. const PassInfo *const llvm::TwoAddressInstructionPassID = &X;
  132. /// Sink3AddrInstruction - A two-address instruction has been converted to a
  133. /// three-address instruction to avoid clobbering a register. Try to sink it
  134. /// past the instruction that would kill the above mentioned register to reduce
  135. /// register pressure.
  136. bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
  137. MachineInstr *MI, unsigned SavedReg,
  138. MachineBasicBlock::iterator OldPos) {
  139. // Check if it's safe to move this instruction.
  140. bool SeenStore = true; // Be conservative.
  141. if (!MI->isSafeToMove(TII, SeenStore, AA))
  142. return false;
  143. unsigned DefReg = 0;
  144. SmallSet<unsigned, 4> UseRegs;
  145. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  146. const MachineOperand &MO = MI->getOperand(i);
  147. if (!MO.isReg())
  148. continue;
  149. unsigned MOReg = MO.getReg();
  150. if (!MOReg)
  151. continue;
  152. if (MO.isUse() && MOReg != SavedReg)
  153. UseRegs.insert(MO.getReg());
  154. if (!MO.isDef())
  155. continue;
  156. if (MO.isImplicit())
  157. // Don't try to move it if it implicitly defines a register.
  158. return false;
  159. if (DefReg)
  160. // For now, don't move any instructions that define multiple registers.
  161. return false;
  162. DefReg = MO.getReg();
  163. }
  164. // Find the instruction that kills SavedReg.
  165. MachineInstr *KillMI = NULL;
  166. for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SavedReg),
  167. UE = MRI->use_end(); UI != UE; ++UI) {
  168. MachineOperand &UseMO = UI.getOperand();
  169. if (!UseMO.isKill())
  170. continue;
  171. KillMI = UseMO.getParent();
  172. break;
  173. }
  174. if (!KillMI || KillMI->getParent() != MBB || KillMI == MI)
  175. return false;
  176. // If any of the definitions are used by another instruction between the
  177. // position and the kill use, then it's not safe to sink it.
  178. //
  179. // FIXME: This can be sped up if there is an easy way to query whether an
  180. // instruction is before or after another instruction. Then we can use
  181. // MachineRegisterInfo def / use instead.
  182. MachineOperand *KillMO = NULL;
  183. MachineBasicBlock::iterator KillPos = KillMI;
  184. ++KillPos;
  185. unsigned NumVisited = 0;
  186. for (MachineBasicBlock::iterator I = next(OldPos); I != KillPos; ++I) {
  187. MachineInstr *OtherMI = I;
  188. if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
  189. return false;
  190. ++NumVisited;
  191. for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
  192. MachineOperand &MO = OtherMI->getOperand(i);
  193. if (!MO.isReg())
  194. continue;
  195. unsigned MOReg = MO.getReg();
  196. if (!MOReg)
  197. continue;
  198. if (DefReg == MOReg)
  199. return false;
  200. if (MO.isKill()) {
  201. if (OtherMI == KillMI && MOReg == SavedReg)
  202. // Save the operand that kills the register. We want to unset the kill
  203. // marker if we can sink MI past it.
  204. KillMO = &MO;
  205. else if (UseRegs.count(MOReg))
  206. // One of the uses is killed before the destination.
  207. return false;
  208. }
  209. }
  210. }
  211. // Update kill and LV information.
  212. KillMO->setIsKill(false);
  213. KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
  214. KillMO->setIsKill(true);
  215. if (LV)
  216. LV->replaceKillInstruction(SavedReg, KillMI, MI);
  217. // Move instruction to its destination.
  218. MBB->remove(MI);
  219. MBB->insert(KillPos, MI);
  220. ++Num3AddrSunk;
  221. return true;
  222. }
  223. /// isTwoAddrUse - Return true if the specified MI is using the specified
  224. /// register as a two-address operand.
  225. static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) {
  226. const TargetInstrDesc &TID = UseMI->getDesc();
  227. for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
  228. MachineOperand &MO = UseMI->getOperand(i);
  229. if (MO.isReg() && MO.getReg() == Reg &&
  230. (MO.isDef() || UseMI->isRegTiedToDefOperand(i)))
  231. // Earlier use is a two-address one.
  232. return true;
  233. }
  234. return false;
  235. }
  236. /// isProfitableToReMat - Return true if the heuristics determines it is likely
  237. /// to be profitable to re-materialize the definition of Reg rather than copy
  238. /// the register.
  239. bool
  240. TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg,
  241. const TargetRegisterClass *RC,
  242. MachineInstr *MI, MachineInstr *DefMI,
  243. MachineBasicBlock *MBB, unsigned Loc) {
  244. bool OtherUse = false;
  245. for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
  246. UE = MRI->use_end(); UI != UE; ++UI) {
  247. MachineOperand &UseMO = UI.getOperand();
  248. MachineInstr *UseMI = UseMO.getParent();
  249. MachineBasicBlock *UseMBB = UseMI->getParent();
  250. if (UseMBB == MBB) {
  251. DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
  252. if (DI != DistanceMap.end() && DI->second == Loc)
  253. continue; // Current use.
  254. OtherUse = true;
  255. // There is at least one other use in the MBB that will clobber the
  256. // register.
  257. if (isTwoAddrUse(UseMI, Reg))
  258. return true;
  259. }
  260. }
  261. // If other uses in MBB are not two-address uses, then don't remat.
  262. if (OtherUse)
  263. return false;
  264. // No other uses in the same block, remat if it's defined in the same
  265. // block so it does not unnecessarily extend the live range.
  266. return MBB == DefMI->getParent();
  267. }
  268. /// NoUseAfterLastDef - Return true if there are no intervening uses between the
  269. /// last instruction in the MBB that defines the specified register and the
  270. /// two-address instruction which is being processed. It also returns the last
  271. /// def location by reference
  272. bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
  273. MachineBasicBlock *MBB, unsigned Dist,
  274. unsigned &LastDef) {
  275. LastDef = 0;
  276. unsigned LastUse = Dist;
  277. for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
  278. E = MRI->reg_end(); I != E; ++I) {
  279. MachineOperand &MO = I.getOperand();
  280. MachineInstr *MI = MO.getParent();
  281. if (MI->getParent() != MBB)
  282. continue;
  283. DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
  284. if (DI == DistanceMap.end())
  285. continue;
  286. if (MO.isUse() && DI->second < LastUse)
  287. LastUse = DI->second;
  288. if (MO.isDef() && DI->second > LastDef)
  289. LastDef = DI->second;
  290. }
  291. return !(LastUse > LastDef && LastUse < Dist);
  292. }
  293. MachineInstr *TwoAddressInstructionPass::FindLastUseInMBB(unsigned Reg,
  294. MachineBasicBlock *MBB,
  295. unsigned Dist) {
  296. unsigned LastUseDist = 0;
  297. MachineInstr *LastUse = 0;
  298. for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
  299. E = MRI->reg_end(); I != E; ++I) {
  300. MachineOperand &MO = I.getOperand();
  301. MachineInstr *MI = MO.getParent();
  302. if (MI->getParent() != MBB)
  303. continue;
  304. DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
  305. if (DI == DistanceMap.end())
  306. continue;
  307. if (DI->second >= Dist)
  308. continue;
  309. if (MO.isUse() && DI->second > LastUseDist) {
  310. LastUse = DI->first;
  311. LastUseDist = DI->second;
  312. }
  313. }
  314. return LastUse;
  315. }
  316. /// isCopyToReg - Return true if the specified MI is a copy instruction or
  317. /// a extract_subreg instruction. It also returns the source and destination
  318. /// registers and whether they are physical registers by reference.
  319. static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
  320. unsigned &SrcReg, unsigned &DstReg,
  321. bool &IsSrcPhys, bool &IsDstPhys) {
  322. SrcReg = 0;
  323. DstReg = 0;
  324. unsigned SrcSubIdx, DstSubIdx;
  325. if (!TII->isMoveInstr(MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
  326. if (MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
  327. DstReg = MI.getOperand(0).getReg();
  328. SrcReg = MI.getOperand(1).getReg();
  329. } else if (MI.getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
  330. DstReg = MI.getOperand(0).getReg();
  331. SrcReg = MI.getOperand(2).getReg();
  332. } else if (MI.getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
  333. DstReg = MI.getOperand(0).getReg();
  334. SrcReg = MI.getOperand(2).getReg();
  335. }
  336. }
  337. if (DstReg) {
  338. IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
  339. IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
  340. return true;
  341. }
  342. return false;
  343. }
  344. /// isKilled - Test if the given register value, which is used by the given
  345. /// instruction, is killed by the given instruction. This looks through
  346. /// coalescable copies to see if the original value is potentially not killed.
  347. ///
  348. /// For example, in this code:
  349. ///
  350. /// %reg1034 = copy %reg1024
  351. /// %reg1035 = copy %reg1025<kill>
  352. /// %reg1036 = add %reg1034<kill>, %reg1035<kill>
  353. ///
  354. /// %reg1034 is not considered to be killed, since it is copied from a
  355. /// register which is not killed. Treating it as not killed lets the
  356. /// normal heuristics commute the (two-address) add, which lets
  357. /// coalescing eliminate the extra copy.
  358. ///
  359. static bool isKilled(MachineInstr &MI, unsigned Reg,
  360. const MachineRegisterInfo *MRI,
  361. const TargetInstrInfo *TII) {
  362. MachineInstr *DefMI = &MI;
  363. for (;;) {
  364. if (!DefMI->killsRegister(Reg))
  365. return false;
  366. if (TargetRegisterInfo::isPhysicalRegister(Reg))
  367. return true;
  368. MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
  369. // If there are multiple defs, we can't do a simple analysis, so just
  370. // go with what the kill flag says.
  371. if (next(Begin) != MRI->def_end())
  372. return true;
  373. DefMI = &*Begin;
  374. bool IsSrcPhys, IsDstPhys;
  375. unsigned SrcReg, DstReg;
  376. // If the def is something other than a copy, then it isn't going to
  377. // be coalesced, so follow the kill flag.
  378. if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
  379. return true;
  380. Reg = SrcReg;
  381. }
  382. }
  383. /// isTwoAddrUse - Return true if the specified MI uses the specified register
  384. /// as a two-address use. If so, return the destination register by reference.
  385. static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
  386. const TargetInstrDesc &TID = MI.getDesc();
  387. unsigned NumOps = (MI.getOpcode() == TargetInstrInfo::INLINEASM)
  388. ? MI.getNumOperands() : TID.getNumOperands();
  389. for (unsigned i = 0; i != NumOps; ++i) {
  390. const MachineOperand &MO = MI.getOperand(i);
  391. if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
  392. continue;
  393. unsigned ti;
  394. if (MI.isRegTiedToDefOperand(i, &ti)) {
  395. DstReg = MI.getOperand(ti).getReg();
  396. return true;
  397. }
  398. }
  399. return false;
  400. }
  401. /// findOnlyInterestingUse - Given a register, if has a single in-basic block
  402. /// use, return the use instruction if it's a copy or a two-address use.
  403. static
  404. MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
  405. MachineRegisterInfo *MRI,
  406. const TargetInstrInfo *TII,
  407. bool &IsCopy,
  408. unsigned &DstReg, bool &IsDstPhys) {
  409. MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg);
  410. if (UI == MRI->use_end())
  411. return 0;
  412. MachineInstr &UseMI = *UI;
  413. if (++UI != MRI->use_end())
  414. // More than one use.
  415. return 0;
  416. if (UseMI.getParent() != MBB)
  417. return 0;
  418. unsigned SrcReg;
  419. bool IsSrcPhys;
  420. if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
  421. IsCopy = true;
  422. return &UseMI;
  423. }
  424. IsDstPhys = false;
  425. if (isTwoAddrUse(UseMI, Reg, DstReg)) {
  426. IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
  427. return &UseMI;
  428. }
  429. return 0;
  430. }
  431. /// getMappedReg - Return the physical register the specified virtual register
  432. /// might be mapped to.
  433. static unsigned
  434. getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
  435. while (TargetRegisterInfo::isVirtualRegister(Reg)) {
  436. DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
  437. if (SI == RegMap.end())
  438. return 0;
  439. Reg = SI->second;
  440. }
  441. if (TargetRegisterInfo::isPhysicalRegister(Reg))
  442. return Reg;
  443. return 0;
  444. }
  445. /// regsAreCompatible - Return true if the two registers are equal or aliased.
  446. ///
  447. static bool
  448. regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
  449. if (RegA == RegB)
  450. return true;
  451. if (!RegA || !RegB)
  452. return false;
  453. return TRI->regsOverlap(RegA, RegB);
  454. }
  455. /// isProfitableToReMat - Return true if it's potentially profitable to commute
  456. /// the two-address instruction that's being processed.
  457. bool
  458. TwoAddressInstructionPass::isProfitableToCommute(unsigned regB, unsigned regC,
  459. MachineInstr *MI, MachineBasicBlock *MBB,
  460. unsigned Dist) {
  461. // Determine if it's profitable to commute this two address instruction. In
  462. // general, we want no uses between this instruction and the definition of
  463. // the two-address register.
  464. // e.g.
  465. // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
  466. // %reg1029<def> = MOV8rr %reg1028
  467. // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
  468. // insert => %reg1030<def> = MOV8rr %reg1028
  469. // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
  470. // In this case, it might not be possible to coalesce the second MOV8rr
  471. // instruction if the first one is coalesced. So it would be profitable to
  472. // commute it:
  473. // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
  474. // %reg1029<def> = MOV8rr %reg1028
  475. // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
  476. // insert => %reg1030<def> = MOV8rr %reg1029
  477. // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
  478. if (!MI->killsRegister(regC))
  479. return false;
  480. // Ok, we have something like:
  481. // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
  482. // let's see if it's worth commuting it.
  483. // Look for situations like this:
  484. // %reg1024<def> = MOV r1
  485. // %reg1025<def> = MOV r0
  486. // %reg1026<def> = ADD %reg1024, %reg1025
  487. // r0 = MOV %reg1026
  488. // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
  489. unsigned FromRegB = getMappedReg(regB, SrcRegMap);
  490. unsigned FromRegC = getMappedReg(regC, SrcRegMap);
  491. unsigned ToRegB = getMappedReg(regB, DstRegMap);
  492. unsigned ToRegC = getMappedReg(regC, DstRegMap);
  493. if (!regsAreCompatible(FromRegB, ToRegB, TRI) &&
  494. (regsAreCompatible(FromRegB, ToRegC, TRI) ||
  495. regsAreCompatible(FromRegC, ToRegB, TRI)))
  496. return true;
  497. // If there is a use of regC between its last def (could be livein) and this
  498. // instruction, then bail.
  499. unsigned LastDefC = 0;
  500. if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
  501. return false;
  502. // If there is a use of regB between its last def (could be livein) and this
  503. // instruction, then go ahead and make this transformation.
  504. unsigned LastDefB = 0;
  505. if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
  506. return true;
  507. // Since there are no intervening uses for both registers, then commute
  508. // if the def of regC is closer. Its live interval is shorter.
  509. return LastDefB && LastDefC && LastDefC > LastDefB;
  510. }
  511. /// CommuteInstruction - Commute a two-address instruction and update the basic
  512. /// block, distance map, and live variables if needed. Return true if it is
  513. /// successful.
  514. bool
  515. TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
  516. MachineFunction::iterator &mbbi,
  517. unsigned RegB, unsigned RegC, unsigned Dist) {
  518. MachineInstr *MI = mi;
  519. DEBUG(errs() << "2addr: COMMUTING : " << *MI);
  520. MachineInstr *NewMI = TII->commuteInstruction(MI);
  521. if (NewMI == 0) {
  522. DEBUG(errs() << "2addr: COMMUTING FAILED!\n");
  523. return false;
  524. }
  525. DEBUG(errs() << "2addr: COMMUTED TO: " << *NewMI);
  526. // If the instruction changed to commute it, update livevar.
  527. if (NewMI != MI) {
  528. if (LV)
  529. // Update live variables
  530. LV->replaceKillInstruction(RegC, MI, NewMI);
  531. mbbi->insert(mi, NewMI); // Insert the new inst
  532. mbbi->erase(mi); // Nuke the old inst.
  533. mi = NewMI;
  534. DistanceMap.insert(std::make_pair(NewMI, Dist));
  535. }
  536. // Update source register map.
  537. unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
  538. if (FromRegC) {
  539. unsigned RegA = MI->getOperand(0).getReg();
  540. SrcRegMap[RegA] = FromRegC;
  541. }
  542. return true;
  543. }
  544. /// isProfitableToConv3Addr - Return true if it is profitable to convert the
  545. /// given 2-address instruction to a 3-address one.
  546. bool
  547. TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA) {
  548. // Look for situations like this:
  549. // %reg1024<def> = MOV r1
  550. // %reg1025<def> = MOV r0
  551. // %reg1026<def> = ADD %reg1024, %reg1025
  552. // r2 = MOV %reg1026
  553. // Turn ADD into a 3-address instruction to avoid a copy.
  554. unsigned FromRegA = getMappedReg(RegA, SrcRegMap);
  555. unsigned ToRegA = getMappedReg(RegA, DstRegMap);
  556. return (FromRegA && ToRegA && !regsAreCompatible(FromRegA, ToRegA, TRI));
  557. }
  558. /// ConvertInstTo3Addr - Convert the specified two-address instruction into a
  559. /// three address one. Return true if this transformation was successful.
  560. bool
  561. TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
  562. MachineBasicBlock::iterator &nmi,
  563. MachineFunction::iterator &mbbi,
  564. unsigned RegB, unsigned Dist) {
  565. MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
  566. if (NewMI) {
  567. DEBUG(errs() << "2addr: CONVERTING 2-ADDR: " << *mi);
  568. DEBUG(errs() << "2addr: TO 3-ADDR: " << *NewMI);
  569. bool Sunk = false;
  570. if (NewMI->findRegisterUseOperand(RegB, false, TRI))
  571. // FIXME: Temporary workaround. If the new instruction doesn't
  572. // uses RegB, convertToThreeAddress must have created more
  573. // then one instruction.
  574. Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
  575. mbbi->erase(mi); // Nuke the old inst.
  576. if (!Sunk) {
  577. DistanceMap.insert(std::make_pair(NewMI, Dist));
  578. mi = NewMI;
  579. nmi = next(mi);
  580. }
  581. return true;
  582. }
  583. return false;
  584. }
  585. /// ProcessCopy - If the specified instruction is not yet processed, process it
  586. /// if it's a copy. For a copy instruction, we find the physical registers the
  587. /// source and destination registers might be mapped to. These are kept in
  588. /// point-to maps used to determine future optimizations. e.g.
  589. /// v1024 = mov r0
  590. /// v1025 = mov r1
  591. /// v1026 = add v1024, v1025
  592. /// r1 = mov r1026
  593. /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
  594. /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
  595. /// potentially joined with r1 on the output side. It's worthwhile to commute
  596. /// 'add' to eliminate a copy.
  597. void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
  598. MachineBasicBlock *MBB,
  599. SmallPtrSet<MachineInstr*, 8> &Processed) {
  600. if (Processed.count(MI))
  601. return;
  602. bool IsSrcPhys, IsDstPhys;
  603. unsigned SrcReg, DstReg;
  604. if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
  605. return;
  606. if (IsDstPhys && !IsSrcPhys)
  607. DstRegMap.insert(std::make_pair(SrcReg, DstReg));
  608. else if (!IsDstPhys && IsSrcPhys) {
  609. bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
  610. if (!isNew)
  611. assert(SrcRegMap[DstReg] == SrcReg &&
  612. "Can't map to two src physical registers!");
  613. SmallVector<unsigned, 4> VirtRegPairs;
  614. bool IsCopy = false;
  615. unsigned NewReg = 0;
  616. while (MachineInstr *UseMI = findOnlyInterestingUse(DstReg, MBB, MRI,TII,
  617. IsCopy, NewReg, IsDstPhys)) {
  618. if (IsCopy) {
  619. if (!Processed.insert(UseMI))
  620. break;
  621. }
  622. DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
  623. if (DI != DistanceMap.end())
  624. // Earlier in the same MBB.Reached via a back edge.
  625. break;
  626. if (IsDstPhys) {
  627. VirtRegPairs.push_back(NewReg);
  628. break;
  629. }
  630. bool isNew = SrcRegMap.insert(std::make_pair(NewReg, DstReg)).second;
  631. if (!isNew)
  632. assert(SrcRegMap[NewReg] == DstReg &&
  633. "Can't map to two src physical registers!");
  634. VirtRegPairs.push_back(NewReg);
  635. DstReg = NewReg;
  636. }
  637. if (!VirtRegPairs.empty()) {
  638. unsigned ToReg = VirtRegPairs.back();
  639. VirtRegPairs.pop_back();
  640. while (!VirtRegPairs.empty()) {
  641. unsigned FromReg = VirtRegPairs.back();
  642. VirtRegPairs.pop_back();
  643. bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
  644. if (!isNew)
  645. assert(DstRegMap[FromReg] == ToReg &&
  646. "Can't map to two dst physical registers!");
  647. ToReg = FromReg;
  648. }
  649. }
  650. }
  651. Processed.insert(MI);
  652. }
  653. /// isSafeToDelete - If the specified instruction does not produce any side
  654. /// effects and all of its defs are dead, then it's safe to delete.
  655. static bool isSafeToDelete(MachineInstr *MI, unsigned Reg,
  656. const TargetInstrInfo *TII,
  657. SmallVector<unsigned, 4> &Kills) {
  658. const TargetInstrDesc &TID = MI->getDesc();
  659. if (TID.mayStore() || TID.isCall())
  660. return false;
  661. if (TID.isTerminator() || TID.hasUnmodeledSideEffects())
  662. return false;
  663. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  664. MachineOperand &MO = MI->getOperand(i);
  665. if (!MO.isReg())
  666. continue;
  667. if (MO.isDef() && !MO.isDead())
  668. return false;
  669. if (MO.isUse() && MO.getReg() != Reg && MO.isKill())
  670. Kills.push_back(MO.getReg());
  671. }
  672. return true;
  673. }
  674. /// canUpdateDeletedKills - Check if all the registers listed in Kills are
  675. /// killed by instructions in MBB preceding the current instruction at
  676. /// position Dist. If so, return true and record information about the
  677. /// preceding kills in NewKills.
  678. bool TwoAddressInstructionPass::
  679. canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
  680. SmallVector<NewKill, 4> &NewKills,
  681. MachineBasicBlock *MBB, unsigned Dist) {
  682. while (!Kills.empty()) {
  683. unsigned Kill = Kills.back();
  684. Kills.pop_back();
  685. if (TargetRegisterInfo::isPhysicalRegister(Kill))
  686. return false;
  687. MachineInstr *LastKill = FindLastUseInMBB(Kill, MBB, Dist);
  688. if (!LastKill)
  689. return false;
  690. bool isModRef = LastKill->modifiesRegister(Kill);
  691. NewKills.push_back(std::make_pair(std::make_pair(Kill, isModRef),
  692. LastKill));
  693. }
  694. return true;
  695. }
  696. /// DeleteUnusedInstr - If an instruction with a tied register operand can
  697. /// be safely deleted, just delete it.
  698. bool
  699. TwoAddressInstructionPass::DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
  700. MachineBasicBlock::iterator &nmi,
  701. MachineFunction::iterator &mbbi,
  702. unsigned regB, unsigned regBIdx,
  703. unsigned Dist) {
  704. // Check if the instruction has no side effects and if all its defs are dead.
  705. SmallVector<unsigned, 4> Kills;
  706. if (!isSafeToDelete(mi, regB, TII, Kills))
  707. return false;
  708. // If this instruction kills some virtual registers, we need to
  709. // update the kill information. If it's not possible to do so,
  710. // then bail out.
  711. SmallVector<NewKill, 4> NewKills;
  712. if (!canUpdateDeletedKills(Kills, NewKills, &*mbbi, Dist))
  713. return false;
  714. if (LV) {
  715. while (!NewKills.empty()) {
  716. MachineInstr *NewKill = NewKills.back().second;
  717. unsigned Kill = NewKills.back().first.first;
  718. bool isDead = NewKills.back().first.second;
  719. NewKills.pop_back();
  720. if (LV->removeVirtualRegisterKilled(Kill, mi)) {
  721. if (isDead)
  722. LV->addVirtualRegisterDead(Kill, NewKill);
  723. else
  724. LV->addVirtualRegisterKilled(Kill, NewKill);
  725. }
  726. }
  727. // If regB was marked as a kill, update its Kills list.
  728. if (mi->getOperand(regBIdx).isKill())
  729. LV->removeVirtualRegisterKilled(regB, mi);
  730. }
  731. mbbi->erase(mi); // Nuke the old inst.
  732. mi = nmi;
  733. return true;
  734. }
  735. /// TryInstructionTransform - For the case where an instruction has a single
  736. /// pair of tied register operands, attempt some transformations that may
  737. /// either eliminate the tied operands or improve the opportunities for
  738. /// coalescing away the register copy. Returns true if the tied operands
  739. /// are eliminated altogether.
  740. bool TwoAddressInstructionPass::
  741. TryInstructionTransform(MachineBasicBlock::iterator &mi,
  742. MachineBasicBlock::iterator &nmi,
  743. MachineFunction::iterator &mbbi,
  744. unsigned SrcIdx, unsigned DstIdx, unsigned Dist) {
  745. const TargetInstrDesc &TID = mi->getDesc();
  746. unsigned regA = mi->getOperand(DstIdx).getReg();
  747. unsigned regB = mi->getOperand(SrcIdx).getReg();
  748. assert(TargetRegisterInfo::isVirtualRegister(regB) &&
  749. "cannot make instruction into two-address form");
  750. // If regA is dead and the instruction can be deleted, just delete
  751. // it so it doesn't clobber regB.
  752. bool regBKilled = isKilled(*mi, regB, MRI, TII);
  753. if (!regBKilled && mi->getOperand(DstIdx).isDead() &&
  754. DeleteUnusedInstr(mi, nmi, mbbi, regB, SrcIdx, Dist)) {
  755. ++NumDeletes;
  756. return true; // Done with this instruction.
  757. }
  758. // Check if it is profitable to commute the operands.
  759. unsigned SrcOp1, SrcOp2;
  760. unsigned regC = 0;
  761. unsigned regCIdx = ~0U;
  762. bool TryCommute = false;
  763. bool AggressiveCommute = false;
  764. if (TID.isCommutable() && mi->getNumOperands() >= 3 &&
  765. TII->findCommutedOpIndices(mi, SrcOp1, SrcOp2)) {
  766. if (SrcIdx == SrcOp1)
  767. regCIdx = SrcOp2;
  768. else if (SrcIdx == SrcOp2)
  769. regCIdx = SrcOp1;
  770. if (regCIdx != ~0U) {
  771. regC = mi->getOperand(regCIdx).getReg();
  772. if (!regBKilled && isKilled(*mi, regC, MRI, TII))
  773. // If C dies but B does not, swap the B and C operands.
  774. // This makes the live ranges of A and C joinable.
  775. TryCommute = true;
  776. else if (isProfitableToCommute(regB, regC, mi, mbbi, Dist)) {
  777. TryCommute = true;
  778. AggressiveCommute = true;
  779. }
  780. }
  781. }
  782. // If it's profitable to commute, try to do so.
  783. if (TryCommute && CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
  784. ++NumCommuted;
  785. if (AggressiveCommute)
  786. ++NumAggrCommuted;
  787. return false;
  788. }
  789. if (TID.isConvertibleTo3Addr()) {
  790. // This instruction is potentially convertible to a true
  791. // three-address instruction. Check if it is profitable.
  792. if (!regBKilled || isProfitableToConv3Addr(regA)) {
  793. // Try to convert it.
  794. if (ConvertInstTo3Addr(mi, nmi, mbbi, regB, Dist)) {
  795. ++NumConvertedTo3Addr;
  796. return true; // Done with this instruction.
  797. }
  798. }
  799. }
  800. return false;
  801. }
  802. /// runOnMachineFunction - Reduce two-address instructions to two operands.
  803. ///
  804. bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
  805. DEBUG(errs() << "Machine Function\n");
  806. const TargetMachine &TM = MF.getTarget();
  807. MRI = &MF.getRegInfo();
  808. TII = TM.getInstrInfo();
  809. TRI = TM.getRegisterInfo();
  810. LV = getAnalysisIfAvailable<LiveVariables>();
  811. AA = &getAnalysis<AliasAnalysis>();
  812. bool MadeChange = false;
  813. DEBUG(errs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
  814. DEBUG(errs() << "********** Function: "
  815. << MF.getFunction()->getName() << '\n');
  816. // ReMatRegs - Keep track of the registers whose def's are remat'ed.
  817. BitVector ReMatRegs;
  818. ReMatRegs.resize(MRI->getLastVirtReg()+1);
  819. typedef DenseMap<unsigned, SmallVector<std::pair<unsigned, unsigned>, 4> >
  820. TiedOperandMap;
  821. TiedOperandMap TiedOperands(4);
  822. SmallPtrSet<MachineInstr*, 8> Processed;
  823. for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
  824. mbbi != mbbe; ++mbbi) {
  825. unsigned Dist = 0;
  826. DistanceMap.clear();
  827. SrcRegMap.clear();
  828. DstRegMap.clear();
  829. Processed.clear();
  830. for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
  831. mi != me; ) {
  832. MachineBasicBlock::iterator nmi = next(mi);
  833. const TargetInstrDesc &TID = mi->getDesc();
  834. bool FirstTied = true;
  835. DistanceMap.insert(std::make_pair(mi, ++Dist));
  836. ProcessCopy(&*mi, &*mbbi, Processed);
  837. // First scan through all the tied register uses in this instruction
  838. // and record a list of pairs of tied operands for each register.
  839. unsigned NumOps = (mi->getOpcode() == TargetInstrInfo::INLINEASM)
  840. ? mi->getNumOperands() : TID.getNumOperands();
  841. for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
  842. unsigned DstIdx = 0;
  843. if (!mi->isRegTiedToDefOperand(SrcIdx, &DstIdx))
  844. continue;
  845. if (FirstTied) {
  846. FirstTied = false;
  847. ++NumTwoAddressInstrs;
  848. DEBUG(errs() << '\t' << *mi);
  849. }
  850. assert(mi->getOperand(SrcIdx).isReg() &&
  851. mi->getOperand(SrcIdx).getReg() &&
  852. mi->getOperand(SrcIdx).isUse() &&
  853. "two address instruction invalid");
  854. unsigned regB = mi->getOperand(SrcIdx).getReg();
  855. TiedOperandMap::iterator OI = TiedOperands.find(regB);
  856. if (OI == TiedOperands.end()) {
  857. SmallVector<std::pair<unsigned, unsigned>, 4> TiedPair;
  858. OI = TiedOperands.insert(std::make_pair(regB, TiedPair)).first;
  859. }
  860. OI->second.push_back(std::make_pair(SrcIdx, DstIdx));
  861. }
  862. // Now iterate over the information collected above.
  863. for (TiedOperandMap::iterator OI = TiedOperands.begin(),
  864. OE = TiedOperands.end(); OI != OE; ++OI) {
  865. SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs = OI->second;
  866. // If the instruction has a single pair of tied operands, try some
  867. // transformations that may either eliminate the tied operands or
  868. // improve the opportunities for coalescing away the register copy.
  869. if (TiedOperands.size() == 1 && TiedPairs.size() == 1) {
  870. unsigned SrcIdx = TiedPairs[0].first;
  871. unsigned DstIdx = TiedPairs[0].second;
  872. // If the registers are already equal, nothing needs to be done.
  873. if (mi->getOperand(SrcIdx).getReg() ==
  874. mi->getOperand(DstIdx).getReg())
  875. break; // Done with this instruction.
  876. if (TryInstructionTransform(mi, nmi, mbbi, SrcIdx, DstIdx, Dist))
  877. break; // The tied operands have been eliminated.
  878. }
  879. bool RemovedKillFlag = false;
  880. bool AllUsesCopied = true;
  881. unsigned LastCopiedReg = 0;
  882. unsigned regB = OI->first;
  883. for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
  884. unsigned SrcIdx = TiedPairs[tpi].first;
  885. unsigned DstIdx = TiedPairs[tpi].second;
  886. unsigned regA = mi->getOperand(DstIdx).getReg();
  887. // Grab regB from the instruction because it may have changed if the
  888. // instruction was commuted.
  889. regB = mi->getOperand(SrcIdx).getReg();
  890. if (regA == regB) {
  891. // The register is tied to multiple destinations (or else we would
  892. // not have continued this far), but this use of the register
  893. // already matches the tied destination. Leave it.
  894. AllUsesCopied = false;
  895. continue;
  896. }
  897. LastCopiedReg = regA;
  898. assert(TargetRegisterInfo::isVirtualRegister(regB) &&
  899. "cannot make instruction into two-address form");
  900. #ifndef NDEBUG
  901. // First, verify that we don't have a use of "a" in the instruction
  902. // (a = b + a for example) because our transformation will not
  903. // work. This should never occur because we are in SSA form.
  904. for (unsigned i = 0; i != mi->getNumOperands(); ++i)
  905. assert(i == DstIdx ||
  906. !mi->getOperand(i).isReg() ||
  907. mi->getOperand(i).getReg() != regA);
  908. #endif
  909. // Emit a copy or rematerialize the definition.
  910. const TargetRegisterClass *rc = MRI->getRegClass(regB);
  911. MachineInstr *DefMI = MRI->getVRegDef(regB);
  912. // If it's safe and profitable, remat the definition instead of
  913. // copying it.
  914. if (DefMI &&
  915. DefMI->getDesc().isAsCheapAsAMove() &&
  916. DefMI->isSafeToReMat(TII, regB, AA) &&
  917. isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist)){
  918. DEBUG(errs() << "2addr: REMATTING : " << *DefMI << "\n");
  919. unsigned regASubIdx = mi->getOperand(DstIdx).getSubReg();
  920. TII->reMaterialize(*mbbi, mi, regA, regASubIdx, DefMI);
  921. ReMatRegs.set(regB);
  922. ++NumReMats;
  923. } else {
  924. bool Emitted = TII->copyRegToReg(*mbbi, mi, regA, regB, rc, rc);
  925. (void)Emitted;
  926. assert(Emitted && "Unable to issue a copy instruction!\n");
  927. }
  928. MachineBasicBlock::iterator prevMI = prior(mi);
  929. // Update DistanceMap.
  930. DistanceMap.insert(std::make_pair(prevMI, Dist));
  931. DistanceMap[mi] = ++Dist;
  932. DEBUG(errs() << "\t\tprepend:\t" << *prevMI);
  933. MachineOperand &MO = mi->getOperand(SrcIdx);
  934. assert(MO.isReg() && MO.getReg() == regB && MO.isUse() &&
  935. "inconsistent operand info for 2-reg pass");
  936. if (MO.isKill()) {
  937. MO.setIsKill(false);
  938. RemovedKillFlag = true;
  939. }
  940. MO.setReg(regA);
  941. }
  942. if (AllUsesCopied) {
  943. // Replace other (un-tied) uses of regB with LastCopiedReg.
  944. for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
  945. MachineOperand &MO = mi->getOperand(i);
  946. if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
  947. if (MO.isKill()) {
  948. MO.setIsKill(false);
  949. RemovedKillFlag = true;
  950. }
  951. MO.setReg(LastCopiedReg);
  952. }
  953. }
  954. // Update live variables for regB.
  955. if (RemovedKillFlag && LV && LV->getVarInfo(regB).removeKill(mi))
  956. LV->addVirtualRegisterKilled(regB, prior(mi));
  957. } else if (RemovedKillFlag) {
  958. // Some tied uses of regB matched their destination registers, so
  959. // regB is still used in this instruction, but a kill flag was
  960. // removed from a different tied use of regB, so now we need to add
  961. // a kill flag to one of the remaining uses of regB.
  962. for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
  963. MachineOperand &MO = mi->getOperand(i);
  964. if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
  965. MO.setIsKill(true);
  966. break;
  967. }
  968. }
  969. }
  970. MadeChange = true;
  971. DEBUG(errs() << "\t\trewrite to:\t" << *mi);
  972. }
  973. // Clear TiedOperands here instead of at the top of the loop
  974. // since most instructions do not have tied operands.
  975. TiedOperands.clear();
  976. mi = nmi;
  977. }
  978. }
  979. // Some remat'ed instructions are dead.
  980. int VReg = ReMatRegs.find_first();
  981. while (VReg != -1) {
  982. if (MRI->use_empty(VReg)) {
  983. MachineInstr *DefMI = MRI->getVRegDef(VReg);
  984. DefMI->eraseFromParent();
  985. }
  986. VReg = ReMatRegs.find_next(VReg);
  987. }
  988. return MadeChange;
  989. }