2
0

TwoAddressInstructionPass.cpp 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795
  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. #include "llvm/CodeGen/Passes.h"
  30. #include "llvm/ADT/BitVector.h"
  31. #include "llvm/ADT/DenseMap.h"
  32. #include "llvm/ADT/STLExtras.h"
  33. #include "llvm/ADT/SmallSet.h"
  34. #include "llvm/ADT/Statistic.h"
  35. #include "llvm/Analysis/AliasAnalysis.h"
  36. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  37. #include "llvm/CodeGen/LiveVariables.h"
  38. #include "llvm/CodeGen/MachineFunctionPass.h"
  39. #include "llvm/CodeGen/MachineInstr.h"
  40. #include "llvm/CodeGen/MachineInstrBuilder.h"
  41. #include "llvm/CodeGen/MachineRegisterInfo.h"
  42. #include "llvm/IR/Function.h"
  43. #include "llvm/MC/MCInstrItineraries.h"
  44. #include "llvm/Support/CommandLine.h"
  45. #include "llvm/Support/Debug.h"
  46. #include "llvm/Support/ErrorHandling.h"
  47. #include "llvm/Support/raw_ostream.h"
  48. #include "llvm/Target/TargetInstrInfo.h"
  49. #include "llvm/Target/TargetMachine.h"
  50. #include "llvm/Target/TargetRegisterInfo.h"
  51. #include "llvm/Target/TargetSubtargetInfo.h"
  52. using namespace llvm;
  53. #define DEBUG_TYPE "twoaddrinstr"
  54. STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
  55. STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
  56. STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
  57. STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
  58. STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
  59. STATISTIC(NumReSchedUps, "Number of instructions re-scheduled up");
  60. STATISTIC(NumReSchedDowns, "Number of instructions re-scheduled down");
  61. // Temporary flag to disable rescheduling.
  62. static cl::opt<bool>
  63. EnableRescheduling("twoaddr-reschedule",
  64. cl::desc("Coalesce copies by rescheduling (default=true)"),
  65. cl::init(true), cl::Hidden);
  66. namespace {
  67. class TwoAddressInstructionPass : public MachineFunctionPass {
  68. MachineFunction *MF;
  69. const TargetInstrInfo *TII;
  70. const TargetRegisterInfo *TRI;
  71. const InstrItineraryData *InstrItins;
  72. MachineRegisterInfo *MRI;
  73. LiveVariables *LV;
  74. LiveIntervals *LIS;
  75. AliasAnalysis *AA;
  76. CodeGenOpt::Level OptLevel;
  77. // The current basic block being processed.
  78. MachineBasicBlock *MBB;
  79. // DistanceMap - Keep track the distance of a MI from the start of the
  80. // current basic block.
  81. DenseMap<MachineInstr*, unsigned> DistanceMap;
  82. // Set of already processed instructions in the current block.
  83. SmallPtrSet<MachineInstr*, 8> Processed;
  84. // SrcRegMap - A map from virtual registers to physical registers which are
  85. // likely targets to be coalesced to due to copies from physical registers to
  86. // virtual registers. e.g. v1024 = move r0.
  87. DenseMap<unsigned, unsigned> SrcRegMap;
  88. // DstRegMap - A map from virtual registers to physical registers which are
  89. // likely targets to be coalesced to due to copies to physical registers from
  90. // virtual registers. e.g. r1 = move v1024.
  91. DenseMap<unsigned, unsigned> DstRegMap;
  92. bool sink3AddrInstruction(MachineInstr *MI, unsigned Reg,
  93. MachineBasicBlock::iterator OldPos);
  94. bool isRevCopyChain(unsigned FromReg, unsigned ToReg, int Maxlen);
  95. bool noUseAfterLastDef(unsigned Reg, unsigned Dist, unsigned &LastDef);
  96. bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
  97. MachineInstr *MI, unsigned Dist);
  98. bool commuteInstruction(MachineBasicBlock::iterator &mi,
  99. unsigned RegB, unsigned RegC, unsigned Dist);
  100. bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
  101. bool convertInstTo3Addr(MachineBasicBlock::iterator &mi,
  102. MachineBasicBlock::iterator &nmi,
  103. unsigned RegA, unsigned RegB, unsigned Dist);
  104. bool isDefTooClose(unsigned Reg, unsigned Dist, MachineInstr *MI);
  105. bool rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
  106. MachineBasicBlock::iterator &nmi,
  107. unsigned Reg);
  108. bool rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
  109. MachineBasicBlock::iterator &nmi,
  110. unsigned Reg);
  111. bool tryInstructionTransform(MachineBasicBlock::iterator &mi,
  112. MachineBasicBlock::iterator &nmi,
  113. unsigned SrcIdx, unsigned DstIdx,
  114. unsigned Dist, bool shouldOnlyCommute);
  115. void scanUses(unsigned DstReg);
  116. void processCopy(MachineInstr *MI);
  117. typedef SmallVector<std::pair<unsigned, unsigned>, 4> TiedPairList;
  118. typedef SmallDenseMap<unsigned, TiedPairList> TiedOperandMap;
  119. bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
  120. void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
  121. void eliminateRegSequence(MachineBasicBlock::iterator&);
  122. public:
  123. static char ID; // Pass identification, replacement for typeid
  124. TwoAddressInstructionPass() : MachineFunctionPass(ID) {
  125. initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
  126. }
  127. void getAnalysisUsage(AnalysisUsage &AU) const override {
  128. AU.setPreservesCFG();
  129. AU.addRequired<AliasAnalysis>();
  130. AU.addPreserved<LiveVariables>();
  131. AU.addPreserved<SlotIndexes>();
  132. AU.addPreserved<LiveIntervals>();
  133. AU.addPreservedID(MachineLoopInfoID);
  134. AU.addPreservedID(MachineDominatorsID);
  135. MachineFunctionPass::getAnalysisUsage(AU);
  136. }
  137. /// runOnMachineFunction - Pass entry point.
  138. bool runOnMachineFunction(MachineFunction&) override;
  139. };
  140. } // end anonymous namespace
  141. char TwoAddressInstructionPass::ID = 0;
  142. INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
  143. "Two-Address instruction pass", false, false)
  144. INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
  145. INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
  146. "Two-Address instruction pass", false, false)
  147. char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
  148. static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg, LiveIntervals *LIS);
  149. /// sink3AddrInstruction - A two-address instruction has been converted to a
  150. /// three-address instruction to avoid clobbering a register. Try to sink it
  151. /// past the instruction that would kill the above mentioned register to reduce
  152. /// register pressure.
  153. bool TwoAddressInstructionPass::
  154. sink3AddrInstruction(MachineInstr *MI, unsigned SavedReg,
  155. MachineBasicBlock::iterator OldPos) {
  156. // FIXME: Shouldn't we be trying to do this before we three-addressify the
  157. // instruction? After this transformation is done, we no longer need
  158. // the instruction to be in three-address form.
  159. // Check if it's safe to move this instruction.
  160. bool SeenStore = true; // Be conservative.
  161. if (!MI->isSafeToMove(AA, SeenStore))
  162. return false;
  163. unsigned DefReg = 0;
  164. SmallSet<unsigned, 4> UseRegs;
  165. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  166. const MachineOperand &MO = MI->getOperand(i);
  167. if (!MO.isReg())
  168. continue;
  169. unsigned MOReg = MO.getReg();
  170. if (!MOReg)
  171. continue;
  172. if (MO.isUse() && MOReg != SavedReg)
  173. UseRegs.insert(MO.getReg());
  174. if (!MO.isDef())
  175. continue;
  176. if (MO.isImplicit())
  177. // Don't try to move it if it implicitly defines a register.
  178. return false;
  179. if (DefReg)
  180. // For now, don't move any instructions that define multiple registers.
  181. return false;
  182. DefReg = MO.getReg();
  183. }
  184. // Find the instruction that kills SavedReg.
  185. MachineInstr *KillMI = nullptr;
  186. if (LIS) {
  187. LiveInterval &LI = LIS->getInterval(SavedReg);
  188. assert(LI.end() != LI.begin() &&
  189. "Reg should not have empty live interval.");
  190. SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
  191. LiveInterval::const_iterator I = LI.find(MBBEndIdx);
  192. if (I != LI.end() && I->start < MBBEndIdx)
  193. return false;
  194. --I;
  195. KillMI = LIS->getInstructionFromIndex(I->end);
  196. }
  197. if (!KillMI) {
  198. for (MachineRegisterInfo::use_nodbg_iterator
  199. UI = MRI->use_nodbg_begin(SavedReg),
  200. UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
  201. MachineOperand &UseMO = *UI;
  202. if (!UseMO.isKill())
  203. continue;
  204. KillMI = UseMO.getParent();
  205. break;
  206. }
  207. }
  208. // If we find the instruction that kills SavedReg, and it is in an
  209. // appropriate location, we can try to sink the current instruction
  210. // past it.
  211. if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
  212. KillMI == OldPos || KillMI->isTerminator())
  213. return false;
  214. // If any of the definitions are used by another instruction between the
  215. // position and the kill use, then it's not safe to sink it.
  216. //
  217. // FIXME: This can be sped up if there is an easy way to query whether an
  218. // instruction is before or after another instruction. Then we can use
  219. // MachineRegisterInfo def / use instead.
  220. MachineOperand *KillMO = nullptr;
  221. MachineBasicBlock::iterator KillPos = KillMI;
  222. ++KillPos;
  223. unsigned NumVisited = 0;
  224. for (MachineBasicBlock::iterator I = std::next(OldPos); I != KillPos; ++I) {
  225. MachineInstr *OtherMI = I;
  226. // DBG_VALUE cannot be counted against the limit.
  227. if (OtherMI->isDebugValue())
  228. continue;
  229. if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
  230. return false;
  231. ++NumVisited;
  232. for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
  233. MachineOperand &MO = OtherMI->getOperand(i);
  234. if (!MO.isReg())
  235. continue;
  236. unsigned MOReg = MO.getReg();
  237. if (!MOReg)
  238. continue;
  239. if (DefReg == MOReg)
  240. return false;
  241. if (MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))) {
  242. if (OtherMI == KillMI && MOReg == SavedReg)
  243. // Save the operand that kills the register. We want to unset the kill
  244. // marker if we can sink MI past it.
  245. KillMO = &MO;
  246. else if (UseRegs.count(MOReg))
  247. // One of the uses is killed before the destination.
  248. return false;
  249. }
  250. }
  251. }
  252. assert(KillMO && "Didn't find kill");
  253. if (!LIS) {
  254. // Update kill and LV information.
  255. KillMO->setIsKill(false);
  256. KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
  257. KillMO->setIsKill(true);
  258. if (LV)
  259. LV->replaceKillInstruction(SavedReg, KillMI, MI);
  260. }
  261. // Move instruction to its destination.
  262. MBB->remove(MI);
  263. MBB->insert(KillPos, MI);
  264. if (LIS)
  265. LIS->handleMove(MI);
  266. ++Num3AddrSunk;
  267. return true;
  268. }
  269. /// getSingleDef -- return the MachineInstr* if it is the single def of the Reg
  270. /// in current BB.
  271. static MachineInstr *getSingleDef(unsigned Reg, MachineBasicBlock *BB,
  272. const MachineRegisterInfo *MRI) {
  273. MachineInstr *Ret = nullptr;
  274. for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
  275. if (DefMI.getParent() != BB || DefMI.isDebugValue())
  276. continue;
  277. if (!Ret)
  278. Ret = &DefMI;
  279. else if (Ret != &DefMI)
  280. return nullptr;
  281. }
  282. return Ret;
  283. }
  284. /// Check if there is a reversed copy chain from FromReg to ToReg:
  285. /// %Tmp1 = copy %Tmp2;
  286. /// %FromReg = copy %Tmp1;
  287. /// %ToReg = add %FromReg ...
  288. /// %Tmp2 = copy %ToReg;
  289. /// MaxLen specifies the maximum length of the copy chain the func
  290. /// can walk through.
  291. bool TwoAddressInstructionPass::isRevCopyChain(unsigned FromReg, unsigned ToReg,
  292. int Maxlen) {
  293. unsigned TmpReg = FromReg;
  294. for (int i = 0; i < Maxlen; i++) {
  295. MachineInstr *Def = getSingleDef(TmpReg, MBB, MRI);
  296. if (!Def || !Def->isCopy())
  297. return false;
  298. TmpReg = Def->getOperand(1).getReg();
  299. if (TmpReg == ToReg)
  300. return true;
  301. }
  302. return false;
  303. }
  304. /// noUseAfterLastDef - Return true if there are no intervening uses between the
  305. /// last instruction in the MBB that defines the specified register and the
  306. /// two-address instruction which is being processed. It also returns the last
  307. /// def location by reference
  308. bool TwoAddressInstructionPass::noUseAfterLastDef(unsigned Reg, unsigned Dist,
  309. unsigned &LastDef) {
  310. LastDef = 0;
  311. unsigned LastUse = Dist;
  312. for (MachineOperand &MO : MRI->reg_operands(Reg)) {
  313. MachineInstr *MI = MO.getParent();
  314. if (MI->getParent() != MBB || MI->isDebugValue())
  315. continue;
  316. DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
  317. if (DI == DistanceMap.end())
  318. continue;
  319. if (MO.isUse() && DI->second < LastUse)
  320. LastUse = DI->second;
  321. if (MO.isDef() && DI->second > LastDef)
  322. LastDef = DI->second;
  323. }
  324. return !(LastUse > LastDef && LastUse < Dist);
  325. }
  326. /// isCopyToReg - Return true if the specified MI is a copy instruction or
  327. /// a extract_subreg instruction. It also returns the source and destination
  328. /// registers and whether they are physical registers by reference.
  329. static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
  330. unsigned &SrcReg, unsigned &DstReg,
  331. bool &IsSrcPhys, bool &IsDstPhys) {
  332. SrcReg = 0;
  333. DstReg = 0;
  334. if (MI.isCopy()) {
  335. DstReg = MI.getOperand(0).getReg();
  336. SrcReg = MI.getOperand(1).getReg();
  337. } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
  338. DstReg = MI.getOperand(0).getReg();
  339. SrcReg = MI.getOperand(2).getReg();
  340. } else
  341. return false;
  342. IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
  343. IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
  344. return true;
  345. }
  346. /// isPLainlyKilled - Test if the given register value, which is used by the
  347. // given instruction, is killed by the given instruction.
  348. static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg,
  349. LiveIntervals *LIS) {
  350. if (LIS && TargetRegisterInfo::isVirtualRegister(Reg) &&
  351. !LIS->isNotInMIMap(MI)) {
  352. // FIXME: Sometimes tryInstructionTransform() will add instructions and
  353. // test whether they can be folded before keeping them. In this case it
  354. // sets a kill before recursively calling tryInstructionTransform() again.
  355. // If there is no interval available, we assume that this instruction is
  356. // one of those. A kill flag is manually inserted on the operand so the
  357. // check below will handle it.
  358. LiveInterval &LI = LIS->getInterval(Reg);
  359. // This is to match the kill flag version where undefs don't have kill
  360. // flags.
  361. if (!LI.hasAtLeastOneValue())
  362. return false;
  363. SlotIndex useIdx = LIS->getInstructionIndex(MI);
  364. LiveInterval::const_iterator I = LI.find(useIdx);
  365. assert(I != LI.end() && "Reg must be live-in to use.");
  366. return !I->end.isBlock() && SlotIndex::isSameInstr(I->end, useIdx);
  367. }
  368. return MI->killsRegister(Reg);
  369. }
  370. /// isKilled - Test if the given register value, which is used by the given
  371. /// instruction, is killed by the given instruction. This looks through
  372. /// coalescable copies to see if the original value is potentially not killed.
  373. ///
  374. /// For example, in this code:
  375. ///
  376. /// %reg1034 = copy %reg1024
  377. /// %reg1035 = copy %reg1025<kill>
  378. /// %reg1036 = add %reg1034<kill>, %reg1035<kill>
  379. ///
  380. /// %reg1034 is not considered to be killed, since it is copied from a
  381. /// register which is not killed. Treating it as not killed lets the
  382. /// normal heuristics commute the (two-address) add, which lets
  383. /// coalescing eliminate the extra copy.
  384. ///
  385. /// If allowFalsePositives is true then likely kills are treated as kills even
  386. /// if it can't be proven that they are kills.
  387. static bool isKilled(MachineInstr &MI, unsigned Reg,
  388. const MachineRegisterInfo *MRI,
  389. const TargetInstrInfo *TII,
  390. LiveIntervals *LIS,
  391. bool allowFalsePositives) {
  392. MachineInstr *DefMI = &MI;
  393. for (;;) {
  394. // All uses of physical registers are likely to be kills.
  395. if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
  396. (allowFalsePositives || MRI->hasOneUse(Reg)))
  397. return true;
  398. if (!isPlainlyKilled(DefMI, Reg, LIS))
  399. return false;
  400. if (TargetRegisterInfo::isPhysicalRegister(Reg))
  401. return true;
  402. MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
  403. // If there are multiple defs, we can't do a simple analysis, so just
  404. // go with what the kill flag says.
  405. if (std::next(Begin) != MRI->def_end())
  406. return true;
  407. DefMI = Begin->getParent();
  408. bool IsSrcPhys, IsDstPhys;
  409. unsigned SrcReg, DstReg;
  410. // If the def is something other than a copy, then it isn't going to
  411. // be coalesced, so follow the kill flag.
  412. if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
  413. return true;
  414. Reg = SrcReg;
  415. }
  416. }
  417. /// isTwoAddrUse - Return true if the specified MI uses the specified register
  418. /// as a two-address use. If so, return the destination register by reference.
  419. static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
  420. for (unsigned i = 0, NumOps = MI.getNumOperands(); i != NumOps; ++i) {
  421. const MachineOperand &MO = MI.getOperand(i);
  422. if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
  423. continue;
  424. unsigned ti;
  425. if (MI.isRegTiedToDefOperand(i, &ti)) {
  426. DstReg = MI.getOperand(ti).getReg();
  427. return true;
  428. }
  429. }
  430. return false;
  431. }
  432. /// findOnlyInterestingUse - Given a register, if has a single in-basic block
  433. /// use, return the use instruction if it's a copy or a two-address use.
  434. static
  435. MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
  436. MachineRegisterInfo *MRI,
  437. const TargetInstrInfo *TII,
  438. bool &IsCopy,
  439. unsigned &DstReg, bool &IsDstPhys) {
  440. if (!MRI->hasOneNonDBGUse(Reg))
  441. // None or more than one use.
  442. return nullptr;
  443. MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(Reg);
  444. if (UseMI.getParent() != MBB)
  445. return nullptr;
  446. unsigned SrcReg;
  447. bool IsSrcPhys;
  448. if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
  449. IsCopy = true;
  450. return &UseMI;
  451. }
  452. IsDstPhys = false;
  453. if (isTwoAddrUse(UseMI, Reg, DstReg)) {
  454. IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
  455. return &UseMI;
  456. }
  457. return nullptr;
  458. }
  459. /// getMappedReg - Return the physical register the specified virtual register
  460. /// might be mapped to.
  461. static unsigned
  462. getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
  463. while (TargetRegisterInfo::isVirtualRegister(Reg)) {
  464. DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
  465. if (SI == RegMap.end())
  466. return 0;
  467. Reg = SI->second;
  468. }
  469. if (TargetRegisterInfo::isPhysicalRegister(Reg))
  470. return Reg;
  471. return 0;
  472. }
  473. /// regsAreCompatible - Return true if the two registers are equal or aliased.
  474. ///
  475. static bool
  476. regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
  477. if (RegA == RegB)
  478. return true;
  479. if (!RegA || !RegB)
  480. return false;
  481. return TRI->regsOverlap(RegA, RegB);
  482. }
  483. /// isProfitableToCommute - Return true if it's potentially profitable to commute
  484. /// the two-address instruction that's being processed.
  485. bool
  486. TwoAddressInstructionPass::
  487. isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
  488. MachineInstr *MI, unsigned Dist) {
  489. if (OptLevel == CodeGenOpt::None)
  490. return false;
  491. // Determine if it's profitable to commute this two address instruction. In
  492. // general, we want no uses between this instruction and the definition of
  493. // the two-address register.
  494. // e.g.
  495. // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
  496. // %reg1029<def> = MOV8rr %reg1028
  497. // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
  498. // insert => %reg1030<def> = MOV8rr %reg1028
  499. // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
  500. // In this case, it might not be possible to coalesce the second MOV8rr
  501. // instruction if the first one is coalesced. So it would be profitable to
  502. // commute it:
  503. // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
  504. // %reg1029<def> = MOV8rr %reg1028
  505. // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
  506. // insert => %reg1030<def> = MOV8rr %reg1029
  507. // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
  508. if (!isPlainlyKilled(MI, regC, LIS))
  509. return false;
  510. // Ok, we have something like:
  511. // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
  512. // let's see if it's worth commuting it.
  513. // Look for situations like this:
  514. // %reg1024<def> = MOV r1
  515. // %reg1025<def> = MOV r0
  516. // %reg1026<def> = ADD %reg1024, %reg1025
  517. // r0 = MOV %reg1026
  518. // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
  519. unsigned ToRegA = getMappedReg(regA, DstRegMap);
  520. if (ToRegA) {
  521. unsigned FromRegB = getMappedReg(regB, SrcRegMap);
  522. unsigned FromRegC = getMappedReg(regC, SrcRegMap);
  523. bool CompB = FromRegB && regsAreCompatible(FromRegB, ToRegA, TRI);
  524. bool CompC = FromRegC && regsAreCompatible(FromRegC, ToRegA, TRI);
  525. // Compute if any of the following are true:
  526. // -RegB is not tied to a register and RegC is compatible with RegA.
  527. // -RegB is tied to the wrong physical register, but RegC is.
  528. // -RegB is tied to the wrong physical register, and RegC isn't tied.
  529. if ((!FromRegB && CompC) || (FromRegB && !CompB && (!FromRegC || CompC)))
  530. return true;
  531. // Don't compute if any of the following are true:
  532. // -RegC is not tied to a register and RegB is compatible with RegA.
  533. // -RegC is tied to the wrong physical register, but RegB is.
  534. // -RegC is tied to the wrong physical register, and RegB isn't tied.
  535. if ((!FromRegC && CompB) || (FromRegC && !CompC && (!FromRegB || CompB)))
  536. return false;
  537. }
  538. // If there is a use of regC between its last def (could be livein) and this
  539. // instruction, then bail.
  540. unsigned LastDefC = 0;
  541. if (!noUseAfterLastDef(regC, Dist, LastDefC))
  542. return false;
  543. // If there is a use of regB between its last def (could be livein) and this
  544. // instruction, then go ahead and make this transformation.
  545. unsigned LastDefB = 0;
  546. if (!noUseAfterLastDef(regB, Dist, LastDefB))
  547. return true;
  548. // Look for situation like this:
  549. // %reg101 = MOV %reg100
  550. // %reg102 = ...
  551. // %reg103 = ADD %reg102, %reg101
  552. // ... = %reg103 ...
  553. // %reg100 = MOV %reg103
  554. // If there is a reversed copy chain from reg101 to reg103, commute the ADD
  555. // to eliminate an otherwise unavoidable copy.
  556. // FIXME:
  557. // We can extend the logic further: If an pair of operands in an insn has
  558. // been merged, the insn could be regarded as a virtual copy, and the virtual
  559. // copy could also be used to construct a copy chain.
  560. // To more generally minimize register copies, ideally the logic of two addr
  561. // instruction pass should be integrated with register allocation pass where
  562. // interference graph is available.
  563. if (isRevCopyChain(regC, regA, 3))
  564. return true;
  565. if (isRevCopyChain(regB, regA, 3))
  566. return false;
  567. // Since there are no intervening uses for both registers, then commute
  568. // if the def of regC is closer. Its live interval is shorter.
  569. return LastDefB && LastDefC && LastDefC > LastDefB;
  570. }
  571. /// commuteInstruction - Commute a two-address instruction and update the basic
  572. /// block, distance map, and live variables if needed. Return true if it is
  573. /// successful.
  574. bool TwoAddressInstructionPass::
  575. commuteInstruction(MachineBasicBlock::iterator &mi,
  576. unsigned RegB, unsigned RegC, unsigned Dist) {
  577. MachineInstr *MI = mi;
  578. DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
  579. MachineInstr *NewMI = TII->commuteInstruction(MI);
  580. if (NewMI == nullptr) {
  581. DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
  582. return false;
  583. }
  584. DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
  585. assert(NewMI == MI &&
  586. "TargetInstrInfo::commuteInstruction() should not return a new "
  587. "instruction unless it was requested.");
  588. // Update source register map.
  589. unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
  590. if (FromRegC) {
  591. unsigned RegA = MI->getOperand(0).getReg();
  592. SrcRegMap[RegA] = FromRegC;
  593. }
  594. return true;
  595. }
  596. /// isProfitableToConv3Addr - Return true if it is profitable to convert the
  597. /// given 2-address instruction to a 3-address one.
  598. bool
  599. TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
  600. // Look for situations like this:
  601. // %reg1024<def> = MOV r1
  602. // %reg1025<def> = MOV r0
  603. // %reg1026<def> = ADD %reg1024, %reg1025
  604. // r2 = MOV %reg1026
  605. // Turn ADD into a 3-address instruction to avoid a copy.
  606. unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
  607. if (!FromRegB)
  608. return false;
  609. unsigned ToRegA = getMappedReg(RegA, DstRegMap);
  610. return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
  611. }
  612. /// convertInstTo3Addr - Convert the specified two-address instruction into a
  613. /// three address one. Return true if this transformation was successful.
  614. bool
  615. TwoAddressInstructionPass::convertInstTo3Addr(MachineBasicBlock::iterator &mi,
  616. MachineBasicBlock::iterator &nmi,
  617. unsigned RegA, unsigned RegB,
  618. unsigned Dist) {
  619. // FIXME: Why does convertToThreeAddress() need an iterator reference?
  620. MachineFunction::iterator MFI = MBB;
  621. MachineInstr *NewMI = TII->convertToThreeAddress(MFI, mi, LV);
  622. assert(MBB == MFI && "convertToThreeAddress changed iterator reference");
  623. if (!NewMI)
  624. return false;
  625. DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
  626. DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
  627. bool Sunk = false;
  628. if (LIS)
  629. LIS->ReplaceMachineInstrInMaps(mi, NewMI);
  630. if (NewMI->findRegisterUseOperand(RegB, false, TRI))
  631. // FIXME: Temporary workaround. If the new instruction doesn't
  632. // uses RegB, convertToThreeAddress must have created more
  633. // then one instruction.
  634. Sunk = sink3AddrInstruction(NewMI, RegB, mi);
  635. MBB->erase(mi); // Nuke the old inst.
  636. if (!Sunk) {
  637. DistanceMap.insert(std::make_pair(NewMI, Dist));
  638. mi = NewMI;
  639. nmi = std::next(mi);
  640. }
  641. // Update source and destination register maps.
  642. SrcRegMap.erase(RegA);
  643. DstRegMap.erase(RegB);
  644. return true;
  645. }
  646. /// scanUses - Scan forward recursively for only uses, update maps if the use
  647. /// is a copy or a two-address instruction.
  648. void
  649. TwoAddressInstructionPass::scanUses(unsigned DstReg) {
  650. SmallVector<unsigned, 4> VirtRegPairs;
  651. bool IsDstPhys;
  652. bool IsCopy = false;
  653. unsigned NewReg = 0;
  654. unsigned Reg = DstReg;
  655. while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
  656. NewReg, IsDstPhys)) {
  657. if (IsCopy && !Processed.insert(UseMI).second)
  658. break;
  659. DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
  660. if (DI != DistanceMap.end())
  661. // Earlier in the same MBB.Reached via a back edge.
  662. break;
  663. if (IsDstPhys) {
  664. VirtRegPairs.push_back(NewReg);
  665. break;
  666. }
  667. bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
  668. if (!isNew)
  669. assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
  670. VirtRegPairs.push_back(NewReg);
  671. Reg = NewReg;
  672. }
  673. if (!VirtRegPairs.empty()) {
  674. unsigned ToReg = VirtRegPairs.back();
  675. VirtRegPairs.pop_back();
  676. while (!VirtRegPairs.empty()) {
  677. unsigned FromReg = VirtRegPairs.back();
  678. VirtRegPairs.pop_back();
  679. bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
  680. if (!isNew)
  681. assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
  682. ToReg = FromReg;
  683. }
  684. bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
  685. if (!isNew)
  686. assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
  687. }
  688. }
  689. /// processCopy - If the specified instruction is not yet processed, process it
  690. /// if it's a copy. For a copy instruction, we find the physical registers the
  691. /// source and destination registers might be mapped to. These are kept in
  692. /// point-to maps used to determine future optimizations. e.g.
  693. /// v1024 = mov r0
  694. /// v1025 = mov r1
  695. /// v1026 = add v1024, v1025
  696. /// r1 = mov r1026
  697. /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
  698. /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
  699. /// potentially joined with r1 on the output side. It's worthwhile to commute
  700. /// 'add' to eliminate a copy.
  701. void TwoAddressInstructionPass::processCopy(MachineInstr *MI) {
  702. if (Processed.count(MI))
  703. return;
  704. bool IsSrcPhys, IsDstPhys;
  705. unsigned SrcReg, DstReg;
  706. if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
  707. return;
  708. if (IsDstPhys && !IsSrcPhys)
  709. DstRegMap.insert(std::make_pair(SrcReg, DstReg));
  710. else if (!IsDstPhys && IsSrcPhys) {
  711. bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
  712. if (!isNew)
  713. assert(SrcRegMap[DstReg] == SrcReg &&
  714. "Can't map to two src physical registers!");
  715. scanUses(DstReg);
  716. }
  717. Processed.insert(MI);
  718. return;
  719. }
  720. /// rescheduleMIBelowKill - If there is one more local instruction that reads
  721. /// 'Reg' and it kills 'Reg, consider moving the instruction below the kill
  722. /// instruction in order to eliminate the need for the copy.
  723. bool TwoAddressInstructionPass::
  724. rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
  725. MachineBasicBlock::iterator &nmi,
  726. unsigned Reg) {
  727. // Bail immediately if we don't have LV or LIS available. We use them to find
  728. // kills efficiently.
  729. if (!LV && !LIS)
  730. return false;
  731. MachineInstr *MI = &*mi;
  732. DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
  733. if (DI == DistanceMap.end())
  734. // Must be created from unfolded load. Don't waste time trying this.
  735. return false;
  736. MachineInstr *KillMI = nullptr;
  737. if (LIS) {
  738. LiveInterval &LI = LIS->getInterval(Reg);
  739. assert(LI.end() != LI.begin() &&
  740. "Reg should not have empty live interval.");
  741. SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
  742. LiveInterval::const_iterator I = LI.find(MBBEndIdx);
  743. if (I != LI.end() && I->start < MBBEndIdx)
  744. return false;
  745. --I;
  746. KillMI = LIS->getInstructionFromIndex(I->end);
  747. } else {
  748. KillMI = LV->getVarInfo(Reg).findKill(MBB);
  749. }
  750. if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
  751. // Don't mess with copies, they may be coalesced later.
  752. return false;
  753. if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
  754. KillMI->isBranch() || KillMI->isTerminator())
  755. // Don't move pass calls, etc.
  756. return false;
  757. unsigned DstReg;
  758. if (isTwoAddrUse(*KillMI, Reg, DstReg))
  759. return false;
  760. bool SeenStore = true;
  761. if (!MI->isSafeToMove(AA, SeenStore))
  762. return false;
  763. if (TII->getInstrLatency(InstrItins, MI) > 1)
  764. // FIXME: Needs more sophisticated heuristics.
  765. return false;
  766. SmallSet<unsigned, 2> Uses;
  767. SmallSet<unsigned, 2> Kills;
  768. SmallSet<unsigned, 2> Defs;
  769. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  770. const MachineOperand &MO = MI->getOperand(i);
  771. if (!MO.isReg())
  772. continue;
  773. unsigned MOReg = MO.getReg();
  774. if (!MOReg)
  775. continue;
  776. if (MO.isDef())
  777. Defs.insert(MOReg);
  778. else {
  779. Uses.insert(MOReg);
  780. if (MOReg != Reg && (MO.isKill() ||
  781. (LIS && isPlainlyKilled(MI, MOReg, LIS))))
  782. Kills.insert(MOReg);
  783. }
  784. }
  785. // Move the copies connected to MI down as well.
  786. MachineBasicBlock::iterator Begin = MI;
  787. MachineBasicBlock::iterator AfterMI = std::next(Begin);
  788. MachineBasicBlock::iterator End = AfterMI;
  789. while (End->isCopy() && Defs.count(End->getOperand(1).getReg())) {
  790. Defs.insert(End->getOperand(0).getReg());
  791. ++End;
  792. }
  793. // Check if the reschedule will not break depedencies.
  794. unsigned NumVisited = 0;
  795. MachineBasicBlock::iterator KillPos = KillMI;
  796. ++KillPos;
  797. for (MachineBasicBlock::iterator I = End; I != KillPos; ++I) {
  798. MachineInstr *OtherMI = I;
  799. // DBG_VALUE cannot be counted against the limit.
  800. if (OtherMI->isDebugValue())
  801. continue;
  802. if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
  803. return false;
  804. ++NumVisited;
  805. if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
  806. OtherMI->isBranch() || OtherMI->isTerminator())
  807. // Don't move pass calls, etc.
  808. return false;
  809. for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
  810. const MachineOperand &MO = OtherMI->getOperand(i);
  811. if (!MO.isReg())
  812. continue;
  813. unsigned MOReg = MO.getReg();
  814. if (!MOReg)
  815. continue;
  816. if (MO.isDef()) {
  817. if (Uses.count(MOReg))
  818. // Physical register use would be clobbered.
  819. return false;
  820. if (!MO.isDead() && Defs.count(MOReg))
  821. // May clobber a physical register def.
  822. // FIXME: This may be too conservative. It's ok if the instruction
  823. // is sunken completely below the use.
  824. return false;
  825. } else {
  826. if (Defs.count(MOReg))
  827. return false;
  828. bool isKill = MO.isKill() ||
  829. (LIS && isPlainlyKilled(OtherMI, MOReg, LIS));
  830. if (MOReg != Reg &&
  831. ((isKill && Uses.count(MOReg)) || Kills.count(MOReg)))
  832. // Don't want to extend other live ranges and update kills.
  833. return false;
  834. if (MOReg == Reg && !isKill)
  835. // We can't schedule across a use of the register in question.
  836. return false;
  837. // Ensure that if this is register in question, its the kill we expect.
  838. assert((MOReg != Reg || OtherMI == KillMI) &&
  839. "Found multiple kills of a register in a basic block");
  840. }
  841. }
  842. }
  843. // Move debug info as well.
  844. while (Begin != MBB->begin() && std::prev(Begin)->isDebugValue())
  845. --Begin;
  846. nmi = End;
  847. MachineBasicBlock::iterator InsertPos = KillPos;
  848. if (LIS) {
  849. // We have to move the copies first so that the MBB is still well-formed
  850. // when calling handleMove().
  851. for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) {
  852. MachineInstr *CopyMI = MBBI;
  853. ++MBBI;
  854. MBB->splice(InsertPos, MBB, CopyMI);
  855. LIS->handleMove(CopyMI);
  856. InsertPos = CopyMI;
  857. }
  858. End = std::next(MachineBasicBlock::iterator(MI));
  859. }
  860. // Copies following MI may have been moved as well.
  861. MBB->splice(InsertPos, MBB, Begin, End);
  862. DistanceMap.erase(DI);
  863. // Update live variables
  864. if (LIS) {
  865. LIS->handleMove(MI);
  866. } else {
  867. LV->removeVirtualRegisterKilled(Reg, KillMI);
  868. LV->addVirtualRegisterKilled(Reg, MI);
  869. }
  870. DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
  871. return true;
  872. }
  873. /// isDefTooClose - Return true if the re-scheduling will put the given
  874. /// instruction too close to the defs of its register dependencies.
  875. bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
  876. MachineInstr *MI) {
  877. for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
  878. if (DefMI.getParent() != MBB || DefMI.isCopy() || DefMI.isCopyLike())
  879. continue;
  880. if (&DefMI == MI)
  881. return true; // MI is defining something KillMI uses
  882. DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(&DefMI);
  883. if (DDI == DistanceMap.end())
  884. return true; // Below MI
  885. unsigned DefDist = DDI->second;
  886. assert(Dist > DefDist && "Visited def already?");
  887. if (TII->getInstrLatency(InstrItins, &DefMI) > (Dist - DefDist))
  888. return true;
  889. }
  890. return false;
  891. }
  892. /// rescheduleKillAboveMI - If there is one more local instruction that reads
  893. /// 'Reg' and it kills 'Reg, consider moving the kill instruction above the
  894. /// current two-address instruction in order to eliminate the need for the
  895. /// copy.
  896. bool TwoAddressInstructionPass::
  897. rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
  898. MachineBasicBlock::iterator &nmi,
  899. unsigned Reg) {
  900. // Bail immediately if we don't have LV or LIS available. We use them to find
  901. // kills efficiently.
  902. if (!LV && !LIS)
  903. return false;
  904. MachineInstr *MI = &*mi;
  905. DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
  906. if (DI == DistanceMap.end())
  907. // Must be created from unfolded load. Don't waste time trying this.
  908. return false;
  909. MachineInstr *KillMI = nullptr;
  910. if (LIS) {
  911. LiveInterval &LI = LIS->getInterval(Reg);
  912. assert(LI.end() != LI.begin() &&
  913. "Reg should not have empty live interval.");
  914. SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
  915. LiveInterval::const_iterator I = LI.find(MBBEndIdx);
  916. if (I != LI.end() && I->start < MBBEndIdx)
  917. return false;
  918. --I;
  919. KillMI = LIS->getInstructionFromIndex(I->end);
  920. } else {
  921. KillMI = LV->getVarInfo(Reg).findKill(MBB);
  922. }
  923. if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
  924. // Don't mess with copies, they may be coalesced later.
  925. return false;
  926. unsigned DstReg;
  927. if (isTwoAddrUse(*KillMI, Reg, DstReg))
  928. return false;
  929. bool SeenStore = true;
  930. if (!KillMI->isSafeToMove(AA, SeenStore))
  931. return false;
  932. SmallSet<unsigned, 2> Uses;
  933. SmallSet<unsigned, 2> Kills;
  934. SmallSet<unsigned, 2> Defs;
  935. SmallSet<unsigned, 2> LiveDefs;
  936. for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
  937. const MachineOperand &MO = KillMI->getOperand(i);
  938. if (!MO.isReg())
  939. continue;
  940. unsigned MOReg = MO.getReg();
  941. if (MO.isUse()) {
  942. if (!MOReg)
  943. continue;
  944. if (isDefTooClose(MOReg, DI->second, MI))
  945. return false;
  946. bool isKill = MO.isKill() || (LIS && isPlainlyKilled(KillMI, MOReg, LIS));
  947. if (MOReg == Reg && !isKill)
  948. return false;
  949. Uses.insert(MOReg);
  950. if (isKill && MOReg != Reg)
  951. Kills.insert(MOReg);
  952. } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
  953. Defs.insert(MOReg);
  954. if (!MO.isDead())
  955. LiveDefs.insert(MOReg);
  956. }
  957. }
  958. // Check if the reschedule will not break depedencies.
  959. unsigned NumVisited = 0;
  960. MachineBasicBlock::iterator KillPos = KillMI;
  961. for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) {
  962. MachineInstr *OtherMI = I;
  963. // DBG_VALUE cannot be counted against the limit.
  964. if (OtherMI->isDebugValue())
  965. continue;
  966. if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
  967. return false;
  968. ++NumVisited;
  969. if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
  970. OtherMI->isBranch() || OtherMI->isTerminator())
  971. // Don't move pass calls, etc.
  972. return false;
  973. SmallVector<unsigned, 2> OtherDefs;
  974. for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
  975. const MachineOperand &MO = OtherMI->getOperand(i);
  976. if (!MO.isReg())
  977. continue;
  978. unsigned MOReg = MO.getReg();
  979. if (!MOReg)
  980. continue;
  981. if (MO.isUse()) {
  982. if (Defs.count(MOReg))
  983. // Moving KillMI can clobber the physical register if the def has
  984. // not been seen.
  985. return false;
  986. if (Kills.count(MOReg))
  987. // Don't want to extend other live ranges and update kills.
  988. return false;
  989. if (OtherMI != MI && MOReg == Reg &&
  990. !(MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))))
  991. // We can't schedule across a use of the register in question.
  992. return false;
  993. } else {
  994. OtherDefs.push_back(MOReg);
  995. }
  996. }
  997. for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
  998. unsigned MOReg = OtherDefs[i];
  999. if (Uses.count(MOReg))
  1000. return false;
  1001. if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
  1002. LiveDefs.count(MOReg))
  1003. return false;
  1004. // Physical register def is seen.
  1005. Defs.erase(MOReg);
  1006. }
  1007. }
  1008. // Move the old kill above MI, don't forget to move debug info as well.
  1009. MachineBasicBlock::iterator InsertPos = mi;
  1010. while (InsertPos != MBB->begin() && std::prev(InsertPos)->isDebugValue())
  1011. --InsertPos;
  1012. MachineBasicBlock::iterator From = KillMI;
  1013. MachineBasicBlock::iterator To = std::next(From);
  1014. while (std::prev(From)->isDebugValue())
  1015. --From;
  1016. MBB->splice(InsertPos, MBB, From, To);
  1017. nmi = std::prev(InsertPos); // Backtrack so we process the moved instr.
  1018. DistanceMap.erase(DI);
  1019. // Update live variables
  1020. if (LIS) {
  1021. LIS->handleMove(KillMI);
  1022. } else {
  1023. LV->removeVirtualRegisterKilled(Reg, KillMI);
  1024. LV->addVirtualRegisterKilled(Reg, MI);
  1025. }
  1026. DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
  1027. return true;
  1028. }
  1029. /// tryInstructionTransform - For the case where an instruction has a single
  1030. /// pair of tied register operands, attempt some transformations that may
  1031. /// either eliminate the tied operands or improve the opportunities for
  1032. /// coalescing away the register copy. Returns true if no copy needs to be
  1033. /// inserted to untie mi's operands (either because they were untied, or
  1034. /// because mi was rescheduled, and will be visited again later). If the
  1035. /// shouldOnlyCommute flag is true, only instruction commutation is attempted.
  1036. bool TwoAddressInstructionPass::
  1037. tryInstructionTransform(MachineBasicBlock::iterator &mi,
  1038. MachineBasicBlock::iterator &nmi,
  1039. unsigned SrcIdx, unsigned DstIdx,
  1040. unsigned Dist, bool shouldOnlyCommute) {
  1041. if (OptLevel == CodeGenOpt::None)
  1042. return false;
  1043. MachineInstr &MI = *mi;
  1044. unsigned regA = MI.getOperand(DstIdx).getReg();
  1045. unsigned regB = MI.getOperand(SrcIdx).getReg();
  1046. assert(TargetRegisterInfo::isVirtualRegister(regB) &&
  1047. "cannot make instruction into two-address form");
  1048. bool regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
  1049. if (TargetRegisterInfo::isVirtualRegister(regA))
  1050. scanUses(regA);
  1051. // Check if it is profitable to commute the operands.
  1052. unsigned SrcOp1, SrcOp2;
  1053. unsigned regC = 0;
  1054. unsigned regCIdx = ~0U;
  1055. bool TryCommute = false;
  1056. bool AggressiveCommute = false;
  1057. if (MI.isCommutable() && MI.getNumOperands() >= 3 &&
  1058. TII->findCommutedOpIndices(&MI, SrcOp1, SrcOp2)) {
  1059. if (SrcIdx == SrcOp1)
  1060. regCIdx = SrcOp2;
  1061. else if (SrcIdx == SrcOp2)
  1062. regCIdx = SrcOp1;
  1063. if (regCIdx != ~0U) {
  1064. regC = MI.getOperand(regCIdx).getReg();
  1065. if (!regBKilled && isKilled(MI, regC, MRI, TII, LIS, false))
  1066. // If C dies but B does not, swap the B and C operands.
  1067. // This makes the live ranges of A and C joinable.
  1068. TryCommute = true;
  1069. else if (isProfitableToCommute(regA, regB, regC, &MI, Dist)) {
  1070. TryCommute = true;
  1071. AggressiveCommute = true;
  1072. }
  1073. }
  1074. }
  1075. // If the instruction is convertible to 3 Addr, instead
  1076. // of returning try 3 Addr transformation aggresively and
  1077. // use this variable to check later. Because it might be better.
  1078. // For example, we can just use `leal (%rsi,%rdi), %eax` and `ret`
  1079. // instead of the following code.
  1080. // addl %esi, %edi
  1081. // movl %edi, %eax
  1082. // ret
  1083. bool Commuted = false;
  1084. // If it's profitable to commute, try to do so.
  1085. if (TryCommute && commuteInstruction(mi, regB, regC, Dist)) {
  1086. Commuted = true;
  1087. ++NumCommuted;
  1088. if (AggressiveCommute)
  1089. ++NumAggrCommuted;
  1090. if (!MI.isConvertibleTo3Addr())
  1091. return false;
  1092. }
  1093. if (shouldOnlyCommute)
  1094. return false;
  1095. // If there is one more use of regB later in the same MBB, consider
  1096. // re-schedule this MI below it.
  1097. if (!Commuted && EnableRescheduling && rescheduleMIBelowKill(mi, nmi, regB)) {
  1098. ++NumReSchedDowns;
  1099. return true;
  1100. }
  1101. if (MI.isConvertibleTo3Addr()) {
  1102. // This instruction is potentially convertible to a true
  1103. // three-address instruction. Check if it is profitable.
  1104. if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
  1105. // Try to convert it.
  1106. if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
  1107. ++NumConvertedTo3Addr;
  1108. return true; // Done with this instruction.
  1109. }
  1110. }
  1111. }
  1112. // Return if it is commuted but 3 addr conversion is failed.
  1113. if (Commuted)
  1114. return false;
  1115. // If there is one more use of regB later in the same MBB, consider
  1116. // re-schedule it before this MI if it's legal.
  1117. if (EnableRescheduling && rescheduleKillAboveMI(mi, nmi, regB)) {
  1118. ++NumReSchedUps;
  1119. return true;
  1120. }
  1121. // If this is an instruction with a load folded into it, try unfolding
  1122. // the load, e.g. avoid this:
  1123. // movq %rdx, %rcx
  1124. // addq (%rax), %rcx
  1125. // in favor of this:
  1126. // movq (%rax), %rcx
  1127. // addq %rdx, %rcx
  1128. // because it's preferable to schedule a load than a register copy.
  1129. if (MI.mayLoad() && !regBKilled) {
  1130. // Determine if a load can be unfolded.
  1131. unsigned LoadRegIndex;
  1132. unsigned NewOpc =
  1133. TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
  1134. /*UnfoldLoad=*/true,
  1135. /*UnfoldStore=*/false,
  1136. &LoadRegIndex);
  1137. if (NewOpc != 0) {
  1138. const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
  1139. if (UnfoldMCID.getNumDefs() == 1) {
  1140. // Unfold the load.
  1141. DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
  1142. const TargetRegisterClass *RC =
  1143. TRI->getAllocatableClass(
  1144. TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF));
  1145. unsigned Reg = MRI->createVirtualRegister(RC);
  1146. SmallVector<MachineInstr *, 2> NewMIs;
  1147. if (!TII->unfoldMemoryOperand(*MF, &MI, Reg,
  1148. /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
  1149. NewMIs)) {
  1150. DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
  1151. return false;
  1152. }
  1153. assert(NewMIs.size() == 2 &&
  1154. "Unfolded a load into multiple instructions!");
  1155. // The load was previously folded, so this is the only use.
  1156. NewMIs[1]->addRegisterKilled(Reg, TRI);
  1157. // Tentatively insert the instructions into the block so that they
  1158. // look "normal" to the transformation logic.
  1159. MBB->insert(mi, NewMIs[0]);
  1160. MBB->insert(mi, NewMIs[1]);
  1161. DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
  1162. << "2addr: NEW INST: " << *NewMIs[1]);
  1163. // Transform the instruction, now that it no longer has a load.
  1164. unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
  1165. unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
  1166. MachineBasicBlock::iterator NewMI = NewMIs[1];
  1167. bool TransformResult =
  1168. tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true);
  1169. (void)TransformResult;
  1170. assert(!TransformResult &&
  1171. "tryInstructionTransform() should return false.");
  1172. if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
  1173. // Success, or at least we made an improvement. Keep the unfolded
  1174. // instructions and discard the original.
  1175. if (LV) {
  1176. for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
  1177. MachineOperand &MO = MI.getOperand(i);
  1178. if (MO.isReg() &&
  1179. TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
  1180. if (MO.isUse()) {
  1181. if (MO.isKill()) {
  1182. if (NewMIs[0]->killsRegister(MO.getReg()))
  1183. LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]);
  1184. else {
  1185. assert(NewMIs[1]->killsRegister(MO.getReg()) &&
  1186. "Kill missing after load unfold!");
  1187. LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]);
  1188. }
  1189. }
  1190. } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) {
  1191. if (NewMIs[1]->registerDefIsDead(MO.getReg()))
  1192. LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
  1193. else {
  1194. assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
  1195. "Dead flag missing after load unfold!");
  1196. LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
  1197. }
  1198. }
  1199. }
  1200. }
  1201. LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
  1202. }
  1203. SmallVector<unsigned, 4> OrigRegs;
  1204. if (LIS) {
  1205. for (MachineInstr::const_mop_iterator MOI = MI.operands_begin(),
  1206. MOE = MI.operands_end(); MOI != MOE; ++MOI) {
  1207. if (MOI->isReg())
  1208. OrigRegs.push_back(MOI->getReg());
  1209. }
  1210. }
  1211. MI.eraseFromParent();
  1212. // Update LiveIntervals.
  1213. if (LIS) {
  1214. MachineBasicBlock::iterator Begin(NewMIs[0]);
  1215. MachineBasicBlock::iterator End(NewMIs[1]);
  1216. LIS->repairIntervalsInRange(MBB, Begin, End, OrigRegs);
  1217. }
  1218. mi = NewMIs[1];
  1219. } else {
  1220. // Transforming didn't eliminate the tie and didn't lead to an
  1221. // improvement. Clean up the unfolded instructions and keep the
  1222. // original.
  1223. DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
  1224. NewMIs[0]->eraseFromParent();
  1225. NewMIs[1]->eraseFromParent();
  1226. }
  1227. }
  1228. }
  1229. }
  1230. return false;
  1231. }
  1232. // Collect tied operands of MI that need to be handled.
  1233. // Rewrite trivial cases immediately.
  1234. // Return true if any tied operands where found, including the trivial ones.
  1235. bool TwoAddressInstructionPass::
  1236. collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) {
  1237. const MCInstrDesc &MCID = MI->getDesc();
  1238. bool AnyOps = false;
  1239. unsigned NumOps = MI->getNumOperands();
  1240. for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
  1241. unsigned DstIdx = 0;
  1242. if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
  1243. continue;
  1244. AnyOps = true;
  1245. MachineOperand &SrcMO = MI->getOperand(SrcIdx);
  1246. MachineOperand &DstMO = MI->getOperand(DstIdx);
  1247. unsigned SrcReg = SrcMO.getReg();
  1248. unsigned DstReg = DstMO.getReg();
  1249. // Tied constraint already satisfied?
  1250. if (SrcReg == DstReg)
  1251. continue;
  1252. assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
  1253. // Deal with <undef> uses immediately - simply rewrite the src operand.
  1254. if (SrcMO.isUndef() && !DstMO.getSubReg()) {
  1255. // Constrain the DstReg register class if required.
  1256. if (TargetRegisterInfo::isVirtualRegister(DstReg))
  1257. if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
  1258. TRI, *MF))
  1259. MRI->constrainRegClass(DstReg, RC);
  1260. SrcMO.setReg(DstReg);
  1261. SrcMO.setSubReg(0);
  1262. DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
  1263. continue;
  1264. }
  1265. TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
  1266. }
  1267. return AnyOps;
  1268. }
  1269. // Process a list of tied MI operands that all use the same source register.
  1270. // The tied pairs are of the form (SrcIdx, DstIdx).
  1271. void
  1272. TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI,
  1273. TiedPairList &TiedPairs,
  1274. unsigned &Dist) {
  1275. bool IsEarlyClobber = false;
  1276. for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
  1277. const MachineOperand &DstMO = MI->getOperand(TiedPairs[tpi].second);
  1278. IsEarlyClobber |= DstMO.isEarlyClobber();
  1279. }
  1280. bool RemovedKillFlag = false;
  1281. bool AllUsesCopied = true;
  1282. unsigned LastCopiedReg = 0;
  1283. SlotIndex LastCopyIdx;
  1284. unsigned RegB = 0;
  1285. unsigned SubRegB = 0;
  1286. for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
  1287. unsigned SrcIdx = TiedPairs[tpi].first;
  1288. unsigned DstIdx = TiedPairs[tpi].second;
  1289. const MachineOperand &DstMO = MI->getOperand(DstIdx);
  1290. unsigned RegA = DstMO.getReg();
  1291. // Grab RegB from the instruction because it may have changed if the
  1292. // instruction was commuted.
  1293. RegB = MI->getOperand(SrcIdx).getReg();
  1294. SubRegB = MI->getOperand(SrcIdx).getSubReg();
  1295. if (RegA == RegB) {
  1296. // The register is tied to multiple destinations (or else we would
  1297. // not have continued this far), but this use of the register
  1298. // already matches the tied destination. Leave it.
  1299. AllUsesCopied = false;
  1300. continue;
  1301. }
  1302. LastCopiedReg = RegA;
  1303. assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
  1304. "cannot make instruction into two-address form");
  1305. #ifndef NDEBUG
  1306. // First, verify that we don't have a use of "a" in the instruction
  1307. // (a = b + a for example) because our transformation will not
  1308. // work. This should never occur because we are in SSA form.
  1309. for (unsigned i = 0; i != MI->getNumOperands(); ++i)
  1310. assert(i == DstIdx ||
  1311. !MI->getOperand(i).isReg() ||
  1312. MI->getOperand(i).getReg() != RegA);
  1313. #endif
  1314. // Emit a copy.
  1315. MachineInstrBuilder MIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
  1316. TII->get(TargetOpcode::COPY), RegA);
  1317. // If this operand is folding a truncation, the truncation now moves to the
  1318. // copy so that the register classes remain valid for the operands.
  1319. MIB.addReg(RegB, 0, SubRegB);
  1320. const TargetRegisterClass *RC = MRI->getRegClass(RegB);
  1321. if (SubRegB) {
  1322. if (TargetRegisterInfo::isVirtualRegister(RegA)) {
  1323. assert(TRI->getMatchingSuperRegClass(RC, MRI->getRegClass(RegA),
  1324. SubRegB) &&
  1325. "tied subregister must be a truncation");
  1326. // The superreg class will not be used to constrain the subreg class.
  1327. RC = nullptr;
  1328. }
  1329. else {
  1330. assert(TRI->getMatchingSuperReg(RegA, SubRegB, MRI->getRegClass(RegB))
  1331. && "tied subregister must be a truncation");
  1332. }
  1333. }
  1334. // Update DistanceMap.
  1335. MachineBasicBlock::iterator PrevMI = MI;
  1336. --PrevMI;
  1337. DistanceMap.insert(std::make_pair(PrevMI, Dist));
  1338. DistanceMap[MI] = ++Dist;
  1339. if (LIS) {
  1340. LastCopyIdx = LIS->InsertMachineInstrInMaps(PrevMI).getRegSlot();
  1341. if (TargetRegisterInfo::isVirtualRegister(RegA)) {
  1342. LiveInterval &LI = LIS->getInterval(RegA);
  1343. VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
  1344. SlotIndex endIdx =
  1345. LIS->getInstructionIndex(MI).getRegSlot(IsEarlyClobber);
  1346. LI.addSegment(LiveInterval::Segment(LastCopyIdx, endIdx, VNI));
  1347. }
  1348. }
  1349. DEBUG(dbgs() << "\t\tprepend:\t" << *MIB);
  1350. MachineOperand &MO = MI->getOperand(SrcIdx);
  1351. assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
  1352. "inconsistent operand info for 2-reg pass");
  1353. if (MO.isKill()) {
  1354. MO.setIsKill(false);
  1355. RemovedKillFlag = true;
  1356. }
  1357. // Make sure regA is a legal regclass for the SrcIdx operand.
  1358. if (TargetRegisterInfo::isVirtualRegister(RegA) &&
  1359. TargetRegisterInfo::isVirtualRegister(RegB))
  1360. MRI->constrainRegClass(RegA, RC);
  1361. MO.setReg(RegA);
  1362. // The getMatchingSuper asserts guarantee that the register class projected
  1363. // by SubRegB is compatible with RegA with no subregister. So regardless of
  1364. // whether the dest oper writes a subreg, the source oper should not.
  1365. MO.setSubReg(0);
  1366. // Propagate SrcRegMap.
  1367. SrcRegMap[RegA] = RegB;
  1368. }
  1369. if (AllUsesCopied) {
  1370. if (!IsEarlyClobber) {
  1371. // Replace other (un-tied) uses of regB with LastCopiedReg.
  1372. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  1373. MachineOperand &MO = MI->getOperand(i);
  1374. if (MO.isReg() && MO.getReg() == RegB && MO.getSubReg() == SubRegB &&
  1375. MO.isUse()) {
  1376. if (MO.isKill()) {
  1377. MO.setIsKill(false);
  1378. RemovedKillFlag = true;
  1379. }
  1380. MO.setReg(LastCopiedReg);
  1381. MO.setSubReg(0);
  1382. }
  1383. }
  1384. }
  1385. // Update live variables for regB.
  1386. if (RemovedKillFlag && LV && LV->getVarInfo(RegB).removeKill(MI)) {
  1387. MachineBasicBlock::iterator PrevMI = MI;
  1388. --PrevMI;
  1389. LV->addVirtualRegisterKilled(RegB, PrevMI);
  1390. }
  1391. // Update LiveIntervals.
  1392. if (LIS) {
  1393. LiveInterval &LI = LIS->getInterval(RegB);
  1394. SlotIndex MIIdx = LIS->getInstructionIndex(MI);
  1395. LiveInterval::const_iterator I = LI.find(MIIdx);
  1396. assert(I != LI.end() && "RegB must be live-in to use.");
  1397. SlotIndex UseIdx = MIIdx.getRegSlot(IsEarlyClobber);
  1398. if (I->end == UseIdx)
  1399. LI.removeSegment(LastCopyIdx, UseIdx);
  1400. }
  1401. } else if (RemovedKillFlag) {
  1402. // Some tied uses of regB matched their destination registers, so
  1403. // regB is still used in this instruction, but a kill flag was
  1404. // removed from a different tied use of regB, so now we need to add
  1405. // a kill flag to one of the remaining uses of regB.
  1406. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  1407. MachineOperand &MO = MI->getOperand(i);
  1408. if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
  1409. MO.setIsKill(true);
  1410. break;
  1411. }
  1412. }
  1413. }
  1414. }
  1415. /// runOnMachineFunction - Reduce two-address instructions to two operands.
  1416. ///
  1417. bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) {
  1418. MF = &Func;
  1419. const TargetMachine &TM = MF->getTarget();
  1420. MRI = &MF->getRegInfo();
  1421. TII = MF->getSubtarget().getInstrInfo();
  1422. TRI = MF->getSubtarget().getRegisterInfo();
  1423. InstrItins = MF->getSubtarget().getInstrItineraryData();
  1424. LV = getAnalysisIfAvailable<LiveVariables>();
  1425. LIS = getAnalysisIfAvailable<LiveIntervals>();
  1426. AA = &getAnalysis<AliasAnalysis>();
  1427. OptLevel = TM.getOptLevel();
  1428. bool MadeChange = false;
  1429. DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
  1430. DEBUG(dbgs() << "********** Function: "
  1431. << MF->getName() << '\n');
  1432. // This pass takes the function out of SSA form.
  1433. MRI->leaveSSA();
  1434. TiedOperandMap TiedOperands;
  1435. for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
  1436. MBBI != MBBE; ++MBBI) {
  1437. MBB = MBBI;
  1438. unsigned Dist = 0;
  1439. DistanceMap.clear();
  1440. SrcRegMap.clear();
  1441. DstRegMap.clear();
  1442. Processed.clear();
  1443. for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();
  1444. mi != me; ) {
  1445. MachineBasicBlock::iterator nmi = std::next(mi);
  1446. if (mi->isDebugValue()) {
  1447. mi = nmi;
  1448. continue;
  1449. }
  1450. // Expand REG_SEQUENCE instructions. This will position mi at the first
  1451. // expanded instruction.
  1452. if (mi->isRegSequence())
  1453. eliminateRegSequence(mi);
  1454. DistanceMap.insert(std::make_pair(mi, ++Dist));
  1455. processCopy(&*mi);
  1456. // First scan through all the tied register uses in this instruction
  1457. // and record a list of pairs of tied operands for each register.
  1458. if (!collectTiedOperands(mi, TiedOperands)) {
  1459. mi = nmi;
  1460. continue;
  1461. }
  1462. ++NumTwoAddressInstrs;
  1463. MadeChange = true;
  1464. DEBUG(dbgs() << '\t' << *mi);
  1465. // If the instruction has a single pair of tied operands, try some
  1466. // transformations that may either eliminate the tied operands or
  1467. // improve the opportunities for coalescing away the register copy.
  1468. if (TiedOperands.size() == 1) {
  1469. SmallVectorImpl<std::pair<unsigned, unsigned> > &TiedPairs
  1470. = TiedOperands.begin()->second;
  1471. if (TiedPairs.size() == 1) {
  1472. unsigned SrcIdx = TiedPairs[0].first;
  1473. unsigned DstIdx = TiedPairs[0].second;
  1474. unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
  1475. unsigned DstReg = mi->getOperand(DstIdx).getReg();
  1476. if (SrcReg != DstReg &&
  1477. tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) {
  1478. // The tied operands have been eliminated or shifted further down the
  1479. // block to ease elimination. Continue processing with 'nmi'.
  1480. TiedOperands.clear();
  1481. mi = nmi;
  1482. continue;
  1483. }
  1484. }
  1485. }
  1486. // Now iterate over the information collected above.
  1487. for (TiedOperandMap::iterator OI = TiedOperands.begin(),
  1488. OE = TiedOperands.end(); OI != OE; ++OI) {
  1489. processTiedPairs(mi, OI->second, Dist);
  1490. DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
  1491. }
  1492. // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
  1493. if (mi->isInsertSubreg()) {
  1494. // From %reg = INSERT_SUBREG %reg, %subreg, subidx
  1495. // To %reg:subidx = COPY %subreg
  1496. unsigned SubIdx = mi->getOperand(3).getImm();
  1497. mi->RemoveOperand(3);
  1498. assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
  1499. mi->getOperand(0).setSubReg(SubIdx);
  1500. mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
  1501. mi->RemoveOperand(1);
  1502. mi->setDesc(TII->get(TargetOpcode::COPY));
  1503. DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
  1504. }
  1505. // Clear TiedOperands here instead of at the top of the loop
  1506. // since most instructions do not have tied operands.
  1507. TiedOperands.clear();
  1508. mi = nmi;
  1509. }
  1510. }
  1511. if (LIS)
  1512. MF->verify(this, "After two-address instruction pass");
  1513. return MadeChange;
  1514. }
  1515. /// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process.
  1516. ///
  1517. /// The instruction is turned into a sequence of sub-register copies:
  1518. ///
  1519. /// %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1
  1520. ///
  1521. /// Becomes:
  1522. ///
  1523. /// %dst:ssub0<def,undef> = COPY %v1
  1524. /// %dst:ssub1<def> = COPY %v2
  1525. ///
  1526. void TwoAddressInstructionPass::
  1527. eliminateRegSequence(MachineBasicBlock::iterator &MBBI) {
  1528. MachineInstr *MI = MBBI;
  1529. unsigned DstReg = MI->getOperand(0).getReg();
  1530. if (MI->getOperand(0).getSubReg() ||
  1531. TargetRegisterInfo::isPhysicalRegister(DstReg) ||
  1532. !(MI->getNumOperands() & 1)) {
  1533. DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
  1534. llvm_unreachable(nullptr);
  1535. }
  1536. SmallVector<unsigned, 4> OrigRegs;
  1537. if (LIS) {
  1538. OrigRegs.push_back(MI->getOperand(0).getReg());
  1539. for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2)
  1540. OrigRegs.push_back(MI->getOperand(i).getReg());
  1541. }
  1542. bool DefEmitted = false;
  1543. for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
  1544. MachineOperand &UseMO = MI->getOperand(i);
  1545. unsigned SrcReg = UseMO.getReg();
  1546. unsigned SubIdx = MI->getOperand(i+1).getImm();
  1547. // Nothing needs to be inserted for <undef> operands.
  1548. if (UseMO.isUndef())
  1549. continue;
  1550. // Defer any kill flag to the last operand using SrcReg. Otherwise, we
  1551. // might insert a COPY that uses SrcReg after is was killed.
  1552. bool isKill = UseMO.isKill();
  1553. if (isKill)
  1554. for (unsigned j = i + 2; j < e; j += 2)
  1555. if (MI->getOperand(j).getReg() == SrcReg) {
  1556. MI->getOperand(j).setIsKill();
  1557. UseMO.setIsKill(false);
  1558. isKill = false;
  1559. break;
  1560. }
  1561. // Insert the sub-register copy.
  1562. MachineInstr *CopyMI = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
  1563. TII->get(TargetOpcode::COPY))
  1564. .addReg(DstReg, RegState::Define, SubIdx)
  1565. .addOperand(UseMO);
  1566. // The first def needs an <undef> flag because there is no live register
  1567. // before it.
  1568. if (!DefEmitted) {
  1569. CopyMI->getOperand(0).setIsUndef(true);
  1570. // Return an iterator pointing to the first inserted instr.
  1571. MBBI = CopyMI;
  1572. }
  1573. DefEmitted = true;
  1574. // Update LiveVariables' kill info.
  1575. if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
  1576. LV->replaceKillInstruction(SrcReg, MI, CopyMI);
  1577. DEBUG(dbgs() << "Inserted: " << *CopyMI);
  1578. }
  1579. MachineBasicBlock::iterator EndMBBI =
  1580. std::next(MachineBasicBlock::iterator(MI));
  1581. if (!DefEmitted) {
  1582. DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
  1583. MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
  1584. for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
  1585. MI->RemoveOperand(j);
  1586. } else {
  1587. DEBUG(dbgs() << "Eliminated: " << *MI);
  1588. MI->eraseFromParent();
  1589. }
  1590. // Udpate LiveIntervals.
  1591. if (LIS)
  1592. LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs);
  1593. }