TwoAddressInstructionPass.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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/Target/TargetRegisterInfo.h"
  37. #include "llvm/Target/TargetInstrInfo.h"
  38. #include "llvm/Target/TargetMachine.h"
  39. #include "llvm/Support/Compiler.h"
  40. #include "llvm/Support/Debug.h"
  41. #include "llvm/ADT/BitVector.h"
  42. #include "llvm/ADT/DenseMap.h"
  43. #include "llvm/ADT/SmallPtrSet.h"
  44. #include "llvm/ADT/Statistic.h"
  45. #include "llvm/ADT/STLExtras.h"
  46. using namespace llvm;
  47. STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
  48. STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
  49. STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
  50. STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
  51. STATISTIC(NumReMats, "Number of instructions re-materialized");
  52. namespace {
  53. class VISIBILITY_HIDDEN TwoAddressInstructionPass
  54. : public MachineFunctionPass {
  55. const TargetInstrInfo *TII;
  56. const TargetRegisterInfo *TRI;
  57. MachineRegisterInfo *MRI;
  58. LiveVariables *LV;
  59. bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
  60. unsigned Reg,
  61. MachineBasicBlock::iterator OldPos);
  62. bool isProfitableToReMat(unsigned Reg, const TargetRegisterClass *RC,
  63. MachineInstr *MI, MachineInstr *DefMI,
  64. MachineBasicBlock *MBB, unsigned Loc,
  65. DenseMap<MachineInstr*, unsigned> &DistanceMap);
  66. public:
  67. static char ID; // Pass identification, replacement for typeid
  68. TwoAddressInstructionPass() : MachineFunctionPass(&ID) {}
  69. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  70. AU.addPreserved<LiveVariables>();
  71. AU.addPreservedID(MachineLoopInfoID);
  72. AU.addPreservedID(MachineDominatorsID);
  73. AU.addPreservedID(PHIEliminationID);
  74. MachineFunctionPass::getAnalysisUsage(AU);
  75. }
  76. /// runOnMachineFunction - Pass entry point.
  77. bool runOnMachineFunction(MachineFunction&);
  78. };
  79. }
  80. char TwoAddressInstructionPass::ID = 0;
  81. static RegisterPass<TwoAddressInstructionPass>
  82. X("twoaddressinstruction", "Two-Address instruction pass");
  83. const PassInfo *const llvm::TwoAddressInstructionPassID = &X;
  84. /// Sink3AddrInstruction - A two-address instruction has been converted to a
  85. /// three-address instruction to avoid clobbering a register. Try to sink it
  86. /// past the instruction that would kill the above mentioned register to reduce
  87. /// register pressure.
  88. bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
  89. MachineInstr *MI, unsigned SavedReg,
  90. MachineBasicBlock::iterator OldPos) {
  91. // Check if it's safe to move this instruction.
  92. bool SeenStore = true; // Be conservative.
  93. if (!MI->isSafeToMove(TII, SeenStore))
  94. return false;
  95. unsigned DefReg = 0;
  96. SmallSet<unsigned, 4> UseRegs;
  97. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  98. const MachineOperand &MO = MI->getOperand(i);
  99. if (!MO.isRegister())
  100. continue;
  101. unsigned MOReg = MO.getReg();
  102. if (!MOReg)
  103. continue;
  104. if (MO.isUse() && MOReg != SavedReg)
  105. UseRegs.insert(MO.getReg());
  106. if (!MO.isDef())
  107. continue;
  108. if (MO.isImplicit())
  109. // Don't try to move it if it implicitly defines a register.
  110. return false;
  111. if (DefReg)
  112. // For now, don't move any instructions that define multiple registers.
  113. return false;
  114. DefReg = MO.getReg();
  115. }
  116. // Find the instruction that kills SavedReg.
  117. MachineInstr *KillMI = NULL;
  118. for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SavedReg),
  119. UE = MRI->use_end(); UI != UE; ++UI) {
  120. MachineOperand &UseMO = UI.getOperand();
  121. if (!UseMO.isKill())
  122. continue;
  123. KillMI = UseMO.getParent();
  124. break;
  125. }
  126. if (!KillMI || KillMI->getParent() != MBB)
  127. return false;
  128. // If any of the definitions are used by another instruction between the
  129. // position and the kill use, then it's not safe to sink it.
  130. //
  131. // FIXME: This can be sped up if there is an easy way to query whether an
  132. // instruction is before or after another instruction. Then we can use
  133. // MachineRegisterInfo def / use instead.
  134. MachineOperand *KillMO = NULL;
  135. MachineBasicBlock::iterator KillPos = KillMI;
  136. ++KillPos;
  137. unsigned NumVisited = 0;
  138. for (MachineBasicBlock::iterator I = next(OldPos); I != KillPos; ++I) {
  139. MachineInstr *OtherMI = I;
  140. if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
  141. return false;
  142. ++NumVisited;
  143. for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
  144. MachineOperand &MO = OtherMI->getOperand(i);
  145. if (!MO.isRegister())
  146. continue;
  147. unsigned MOReg = MO.getReg();
  148. if (!MOReg)
  149. continue;
  150. if (DefReg == MOReg)
  151. return false;
  152. if (MO.isKill()) {
  153. if (OtherMI == KillMI && MOReg == SavedReg)
  154. // Save the operand that kills the register. We want to unset the kill
  155. // marker if we can sink MI past it.
  156. KillMO = &MO;
  157. else if (UseRegs.count(MOReg))
  158. // One of the uses is killed before the destination.
  159. return false;
  160. }
  161. }
  162. }
  163. // Update kill and LV information.
  164. KillMO->setIsKill(false);
  165. KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
  166. KillMO->setIsKill(true);
  167. if (LV)
  168. LV->replaceKillInstruction(SavedReg, KillMI, MI);
  169. // Move instruction to its destination.
  170. MBB->remove(MI);
  171. MBB->insert(KillPos, MI);
  172. ++Num3AddrSunk;
  173. return true;
  174. }
  175. /// isTwoAddrUse - Return true if the specified MI is using the specified
  176. /// register as a two-address operand.
  177. static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) {
  178. const TargetInstrDesc &TID = UseMI->getDesc();
  179. for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
  180. MachineOperand &MO = UseMI->getOperand(i);
  181. if (MO.isRegister() && MO.getReg() == Reg &&
  182. (MO.isDef() || TID.getOperandConstraint(i, TOI::TIED_TO) != -1))
  183. // Earlier use is a two-address one.
  184. return true;
  185. }
  186. return false;
  187. }
  188. /// isProfitableToReMat - Return true if the heuristics determines it is likely
  189. /// to be profitable to re-materialize the definition of Reg rather than copy
  190. /// the register.
  191. bool
  192. TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg,
  193. const TargetRegisterClass *RC,
  194. MachineInstr *MI, MachineInstr *DefMI,
  195. MachineBasicBlock *MBB, unsigned Loc,
  196. DenseMap<MachineInstr*, unsigned> &DistanceMap){
  197. bool OtherUse = false;
  198. for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
  199. UE = MRI->use_end(); UI != UE; ++UI) {
  200. MachineOperand &UseMO = UI.getOperand();
  201. if (!UseMO.isUse())
  202. continue;
  203. MachineInstr *UseMI = UseMO.getParent();
  204. MachineBasicBlock *UseMBB = UseMI->getParent();
  205. if (UseMBB == MBB) {
  206. DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
  207. if (DI != DistanceMap.end() && DI->second == Loc)
  208. continue; // Current use.
  209. OtherUse = true;
  210. // There is at least one other use in the MBB that will clobber the
  211. // register.
  212. if (isTwoAddrUse(UseMI, Reg))
  213. return true;
  214. }
  215. }
  216. // If other uses in MBB are not two-address uses, then don't remat.
  217. if (OtherUse)
  218. return false;
  219. // No other uses in the same block, remat if it's defined in the same
  220. // block so it does not unnecessarily extend the live range.
  221. return MBB == DefMI->getParent();
  222. }
  223. /// runOnMachineFunction - Reduce two-address instructions to two operands.
  224. ///
  225. bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
  226. DOUT << "Machine Function\n";
  227. const TargetMachine &TM = MF.getTarget();
  228. MRI = &MF.getRegInfo();
  229. TII = TM.getInstrInfo();
  230. TRI = TM.getRegisterInfo();
  231. LV = getAnalysisToUpdate<LiveVariables>();
  232. bool MadeChange = false;
  233. DOUT << "********** REWRITING TWO-ADDR INSTRS **********\n";
  234. DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
  235. // ReMatRegs - Keep track of the registers whose def's are remat'ed.
  236. BitVector ReMatRegs;
  237. ReMatRegs.resize(MRI->getLastVirtReg()+1);
  238. // DistanceMap - Keep track the distance of a MI from the start of the
  239. // current basic block.
  240. DenseMap<MachineInstr*, unsigned> DistanceMap;
  241. for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
  242. mbbi != mbbe; ++mbbi) {
  243. unsigned Dist = 0;
  244. DistanceMap.clear();
  245. for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
  246. mi != me; ) {
  247. MachineBasicBlock::iterator nmi = next(mi);
  248. const TargetInstrDesc &TID = mi->getDesc();
  249. bool FirstTied = true;
  250. DistanceMap.insert(std::make_pair(mi, ++Dist));
  251. for (unsigned si = 1, e = TID.getNumOperands(); si < e; ++si) {
  252. int ti = TID.getOperandConstraint(si, TOI::TIED_TO);
  253. if (ti == -1)
  254. continue;
  255. if (FirstTied) {
  256. ++NumTwoAddressInstrs;
  257. DOUT << '\t'; DEBUG(mi->print(*cerr.stream(), &TM));
  258. }
  259. FirstTied = false;
  260. assert(mi->getOperand(si).isRegister() && mi->getOperand(si).getReg() &&
  261. mi->getOperand(si).isUse() && "two address instruction invalid");
  262. // If the two operands are the same we just remove the use
  263. // and mark the def as def&use, otherwise we have to insert a copy.
  264. if (mi->getOperand(ti).getReg() != mi->getOperand(si).getReg()) {
  265. // Rewrite:
  266. // a = b op c
  267. // to:
  268. // a = b
  269. // a = a op c
  270. unsigned regA = mi->getOperand(ti).getReg();
  271. unsigned regB = mi->getOperand(si).getReg();
  272. assert(TargetRegisterInfo::isVirtualRegister(regA) &&
  273. TargetRegisterInfo::isVirtualRegister(regB) &&
  274. "cannot update physical register live information");
  275. #ifndef NDEBUG
  276. // First, verify that we don't have a use of a in the instruction (a =
  277. // b + a for example) because our transformation will not work. This
  278. // should never occur because we are in SSA form.
  279. for (unsigned i = 0; i != mi->getNumOperands(); ++i)
  280. assert((int)i == ti ||
  281. !mi->getOperand(i).isRegister() ||
  282. mi->getOperand(i).getReg() != regA);
  283. #endif
  284. // If this instruction is not the killing user of B, see if we can
  285. // rearrange the code to make it so. Making it the killing user will
  286. // allow us to coalesce A and B together, eliminating the copy we are
  287. // about to insert.
  288. if (!mi->killsRegister(regB)) {
  289. // If this instruction is commutative, check to see if C dies. If
  290. // so, swap the B and C operands. This makes the live ranges of A
  291. // and C joinable.
  292. // FIXME: This code also works for A := B op C instructions.
  293. if (TID.isCommutable() && mi->getNumOperands() >= 3) {
  294. assert(mi->getOperand(3-si).isRegister() &&
  295. "Not a proper commutative instruction!");
  296. unsigned regC = mi->getOperand(3-si).getReg();
  297. if (mi->killsRegister(regC)) {
  298. DOUT << "2addr: COMMUTING : " << *mi;
  299. MachineInstr *NewMI = TII->commuteInstruction(mi);
  300. if (NewMI == 0) {
  301. DOUT << "2addr: COMMUTING FAILED!\n";
  302. } else {
  303. DOUT << "2addr: COMMUTED TO: " << *NewMI;
  304. // If the instruction changed to commute it, update livevar.
  305. if (NewMI != mi) {
  306. if (LV)
  307. // Update live variables
  308. LV->replaceKillInstruction(regC, mi, NewMI);
  309. mbbi->insert(mi, NewMI); // Insert the new inst
  310. mbbi->erase(mi); // Nuke the old inst.
  311. mi = NewMI;
  312. DistanceMap.insert(std::make_pair(NewMI, Dist));
  313. }
  314. ++NumCommuted;
  315. regB = regC;
  316. goto InstructionRearranged;
  317. }
  318. }
  319. }
  320. // If this instruction is potentially convertible to a true
  321. // three-address instruction,
  322. if (TID.isConvertibleTo3Addr()) {
  323. // FIXME: This assumes there are no more operands which are tied
  324. // to another register.
  325. #ifndef NDEBUG
  326. for (unsigned i = si + 1, e = TID.getNumOperands(); i < e; ++i)
  327. assert(TID.getOperandConstraint(i, TOI::TIED_TO) == -1);
  328. #endif
  329. MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
  330. if (NewMI) {
  331. DOUT << "2addr: CONVERTING 2-ADDR: " << *mi;
  332. DOUT << "2addr: TO 3-ADDR: " << *NewMI;
  333. bool Sunk = false;
  334. if (NewMI->findRegisterUseOperand(regB, false, TRI))
  335. // FIXME: Temporary workaround. If the new instruction doesn't
  336. // uses regB, convertToThreeAddress must have created more
  337. // then one instruction.
  338. Sunk = Sink3AddrInstruction(mbbi, NewMI, regB, mi);
  339. mbbi->erase(mi); // Nuke the old inst.
  340. if (!Sunk) {
  341. DistanceMap.insert(std::make_pair(NewMI, Dist));
  342. mi = NewMI;
  343. nmi = next(mi);
  344. }
  345. ++NumConvertedTo3Addr;
  346. break; // Done with this instruction.
  347. }
  348. }
  349. }
  350. InstructionRearranged:
  351. const TargetRegisterClass* rc = MRI->getRegClass(regA);
  352. MachineInstr *DefMI = MRI->getVRegDef(regB);
  353. // If it's safe and profitable, remat the definition instead of
  354. // copying it.
  355. if (DefMI &&
  356. DefMI->getDesc().isAsCheapAsAMove() &&
  357. DefMI->isSafeToReMat(TII, regB) &&
  358. isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist,DistanceMap)){
  359. DEBUG(cerr << "2addr: REMATTING : " << *DefMI << "\n");
  360. TII->reMaterialize(*mbbi, mi, regA, DefMI);
  361. ReMatRegs.set(regB);
  362. ++NumReMats;
  363. } else {
  364. TII->copyRegToReg(*mbbi, mi, regA, regB, rc, rc);
  365. }
  366. MachineBasicBlock::iterator prevMi = prior(mi);
  367. DOUT << "\t\tprepend:\t"; DEBUG(prevMi->print(*cerr.stream(), &TM));
  368. // Update live variables for regB.
  369. if (LV) {
  370. LiveVariables::VarInfo& varInfoB = LV->getVarInfo(regB);
  371. // regB is used in this BB.
  372. varInfoB.UsedBlocks[mbbi->getNumber()] = true;
  373. if (LV->removeVirtualRegisterKilled(regB, mi))
  374. LV->addVirtualRegisterKilled(regB, prevMi);
  375. if (LV->removeVirtualRegisterDead(regB, mi))
  376. LV->addVirtualRegisterDead(regB, prevMi);
  377. }
  378. // Replace all occurences of regB with regA.
  379. for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
  380. if (mi->getOperand(i).isRegister() &&
  381. mi->getOperand(i).getReg() == regB)
  382. mi->getOperand(i).setReg(regA);
  383. }
  384. }
  385. assert(mi->getOperand(ti).isDef() && mi->getOperand(si).isUse());
  386. mi->getOperand(ti).setReg(mi->getOperand(si).getReg());
  387. MadeChange = true;
  388. DOUT << "\t\trewrite to:\t"; DEBUG(mi->print(*cerr.stream(), &TM));
  389. }
  390. mi = nmi;
  391. }
  392. }
  393. // Some remat'ed instructions are dead.
  394. int VReg = ReMatRegs.find_first();
  395. while (VReg != -1) {
  396. if (MRI->use_empty(VReg)) {
  397. MachineInstr *DefMI = MRI->getVRegDef(VReg);
  398. DefMI->eraseFromParent();
  399. }
  400. VReg = ReMatRegs.find_next(VReg);
  401. }
  402. return MadeChange;
  403. }