InlineSpiller.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540
  1. //===- InlineSpiller.cpp - Insert spills and restores inline --------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // The inline spiller modifies the machine function directly instead of
  10. // inserting spills and restores in VirtRegMap.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "LiveRangeCalc.h"
  14. #include "Spiller.h"
  15. #include "SplitKit.h"
  16. #include "llvm/ADT/ArrayRef.h"
  17. #include "llvm/ADT/DenseMap.h"
  18. #include "llvm/ADT/MapVector.h"
  19. #include "llvm/ADT/None.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/ADT/SetVector.h"
  22. #include "llvm/ADT/SmallPtrSet.h"
  23. #include "llvm/ADT/SmallVector.h"
  24. #include "llvm/ADT/Statistic.h"
  25. #include "llvm/Analysis/AliasAnalysis.h"
  26. #include "llvm/CodeGen/LiveInterval.h"
  27. #include "llvm/CodeGen/LiveIntervals.h"
  28. #include "llvm/CodeGen/LiveRangeEdit.h"
  29. #include "llvm/CodeGen/LiveStacks.h"
  30. #include "llvm/CodeGen/MachineBasicBlock.h"
  31. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  32. #include "llvm/CodeGen/MachineDominators.h"
  33. #include "llvm/CodeGen/MachineFunction.h"
  34. #include "llvm/CodeGen/MachineFunctionPass.h"
  35. #include "llvm/CodeGen/MachineInstr.h"
  36. #include "llvm/CodeGen/MachineInstrBuilder.h"
  37. #include "llvm/CodeGen/MachineInstrBundle.h"
  38. #include "llvm/CodeGen/MachineLoopInfo.h"
  39. #include "llvm/CodeGen/MachineOperand.h"
  40. #include "llvm/CodeGen/MachineRegisterInfo.h"
  41. #include "llvm/CodeGen/SlotIndexes.h"
  42. #include "llvm/CodeGen/TargetInstrInfo.h"
  43. #include "llvm/CodeGen/TargetOpcodes.h"
  44. #include "llvm/CodeGen/TargetRegisterInfo.h"
  45. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  46. #include "llvm/CodeGen/VirtRegMap.h"
  47. #include "llvm/Config/llvm-config.h"
  48. #include "llvm/Support/BlockFrequency.h"
  49. #include "llvm/Support/BranchProbability.h"
  50. #include "llvm/Support/CommandLine.h"
  51. #include "llvm/Support/Compiler.h"
  52. #include "llvm/Support/Debug.h"
  53. #include "llvm/Support/ErrorHandling.h"
  54. #include "llvm/Support/raw_ostream.h"
  55. #include <cassert>
  56. #include <iterator>
  57. #include <tuple>
  58. #include <utility>
  59. #include <vector>
  60. using namespace llvm;
  61. #define DEBUG_TYPE "regalloc"
  62. STATISTIC(NumSpilledRanges, "Number of spilled live ranges");
  63. STATISTIC(NumSnippets, "Number of spilled snippets");
  64. STATISTIC(NumSpills, "Number of spills inserted");
  65. STATISTIC(NumSpillsRemoved, "Number of spills removed");
  66. STATISTIC(NumReloads, "Number of reloads inserted");
  67. STATISTIC(NumReloadsRemoved, "Number of reloads removed");
  68. STATISTIC(NumFolded, "Number of folded stack accesses");
  69. STATISTIC(NumFoldedLoads, "Number of folded loads");
  70. STATISTIC(NumRemats, "Number of rematerialized defs for spilling");
  71. static cl::opt<bool> DisableHoisting("disable-spill-hoist", cl::Hidden,
  72. cl::desc("Disable inline spill hoisting"));
  73. static cl::opt<bool>
  74. RestrictStatepointRemat("restrict-statepoint-remat",
  75. cl::init(false), cl::Hidden,
  76. cl::desc("Restrict remat for statepoint operands"));
  77. namespace {
  78. class HoistSpillHelper : private LiveRangeEdit::Delegate {
  79. MachineFunction &MF;
  80. LiveIntervals &LIS;
  81. LiveStacks &LSS;
  82. AliasAnalysis *AA;
  83. MachineDominatorTree &MDT;
  84. MachineLoopInfo &Loops;
  85. VirtRegMap &VRM;
  86. MachineRegisterInfo &MRI;
  87. const TargetInstrInfo &TII;
  88. const TargetRegisterInfo &TRI;
  89. const MachineBlockFrequencyInfo &MBFI;
  90. InsertPointAnalysis IPA;
  91. // Map from StackSlot to the LiveInterval of the original register.
  92. // Note the LiveInterval of the original register may have been deleted
  93. // after it is spilled. We keep a copy here to track the range where
  94. // spills can be moved.
  95. DenseMap<int, std::unique_ptr<LiveInterval>> StackSlotToOrigLI;
  96. // Map from pair of (StackSlot and Original VNI) to a set of spills which
  97. // have the same stackslot and have equal values defined by Original VNI.
  98. // These spills are mergeable and are hoist candiates.
  99. using MergeableSpillsMap =
  100. MapVector<std::pair<int, VNInfo *>, SmallPtrSet<MachineInstr *, 16>>;
  101. MergeableSpillsMap MergeableSpills;
  102. /// This is the map from original register to a set containing all its
  103. /// siblings. To hoist a spill to another BB, we need to find out a live
  104. /// sibling there and use it as the source of the new spill.
  105. DenseMap<unsigned, SmallSetVector<unsigned, 16>> Virt2SiblingsMap;
  106. bool isSpillCandBB(LiveInterval &OrigLI, VNInfo &OrigVNI,
  107. MachineBasicBlock &BB, unsigned &LiveReg);
  108. void rmRedundantSpills(
  109. SmallPtrSet<MachineInstr *, 16> &Spills,
  110. SmallVectorImpl<MachineInstr *> &SpillsToRm,
  111. DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill);
  112. void getVisitOrders(
  113. MachineBasicBlock *Root, SmallPtrSet<MachineInstr *, 16> &Spills,
  114. SmallVectorImpl<MachineDomTreeNode *> &Orders,
  115. SmallVectorImpl<MachineInstr *> &SpillsToRm,
  116. DenseMap<MachineDomTreeNode *, unsigned> &SpillsToKeep,
  117. DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill);
  118. void runHoistSpills(LiveInterval &OrigLI, VNInfo &OrigVNI,
  119. SmallPtrSet<MachineInstr *, 16> &Spills,
  120. SmallVectorImpl<MachineInstr *> &SpillsToRm,
  121. DenseMap<MachineBasicBlock *, unsigned> &SpillsToIns);
  122. public:
  123. HoistSpillHelper(MachineFunctionPass &pass, MachineFunction &mf,
  124. VirtRegMap &vrm)
  125. : MF(mf), LIS(pass.getAnalysis<LiveIntervals>()),
  126. LSS(pass.getAnalysis<LiveStacks>()),
  127. AA(&pass.getAnalysis<AAResultsWrapperPass>().getAAResults()),
  128. MDT(pass.getAnalysis<MachineDominatorTree>()),
  129. Loops(pass.getAnalysis<MachineLoopInfo>()), VRM(vrm),
  130. MRI(mf.getRegInfo()), TII(*mf.getSubtarget().getInstrInfo()),
  131. TRI(*mf.getSubtarget().getRegisterInfo()),
  132. MBFI(pass.getAnalysis<MachineBlockFrequencyInfo>()),
  133. IPA(LIS, mf.getNumBlockIDs()) {}
  134. void addToMergeableSpills(MachineInstr &Spill, int StackSlot,
  135. unsigned Original);
  136. bool rmFromMergeableSpills(MachineInstr &Spill, int StackSlot);
  137. void hoistAllSpills();
  138. void LRE_DidCloneVirtReg(unsigned, unsigned) override;
  139. };
  140. class InlineSpiller : public Spiller {
  141. MachineFunction &MF;
  142. LiveIntervals &LIS;
  143. LiveStacks &LSS;
  144. AliasAnalysis *AA;
  145. MachineDominatorTree &MDT;
  146. MachineLoopInfo &Loops;
  147. VirtRegMap &VRM;
  148. MachineRegisterInfo &MRI;
  149. const TargetInstrInfo &TII;
  150. const TargetRegisterInfo &TRI;
  151. const MachineBlockFrequencyInfo &MBFI;
  152. // Variables that are valid during spill(), but used by multiple methods.
  153. LiveRangeEdit *Edit;
  154. LiveInterval *StackInt;
  155. int StackSlot;
  156. unsigned Original;
  157. // All registers to spill to StackSlot, including the main register.
  158. SmallVector<unsigned, 8> RegsToSpill;
  159. // All COPY instructions to/from snippets.
  160. // They are ignored since both operands refer to the same stack slot.
  161. SmallPtrSet<MachineInstr*, 8> SnippetCopies;
  162. // Values that failed to remat at some point.
  163. SmallPtrSet<VNInfo*, 8> UsedValues;
  164. // Dead defs generated during spilling.
  165. SmallVector<MachineInstr*, 8> DeadDefs;
  166. // Object records spills information and does the hoisting.
  167. HoistSpillHelper HSpiller;
  168. ~InlineSpiller() override = default;
  169. public:
  170. InlineSpiller(MachineFunctionPass &pass, MachineFunction &mf, VirtRegMap &vrm)
  171. : MF(mf), LIS(pass.getAnalysis<LiveIntervals>()),
  172. LSS(pass.getAnalysis<LiveStacks>()),
  173. AA(&pass.getAnalysis<AAResultsWrapperPass>().getAAResults()),
  174. MDT(pass.getAnalysis<MachineDominatorTree>()),
  175. Loops(pass.getAnalysis<MachineLoopInfo>()), VRM(vrm),
  176. MRI(mf.getRegInfo()), TII(*mf.getSubtarget().getInstrInfo()),
  177. TRI(*mf.getSubtarget().getRegisterInfo()),
  178. MBFI(pass.getAnalysis<MachineBlockFrequencyInfo>()),
  179. HSpiller(pass, mf, vrm) {}
  180. void spill(LiveRangeEdit &) override;
  181. void postOptimization() override;
  182. private:
  183. bool isSnippet(const LiveInterval &SnipLI);
  184. void collectRegsToSpill();
  185. bool isRegToSpill(unsigned Reg) { return is_contained(RegsToSpill, Reg); }
  186. bool isSibling(unsigned Reg);
  187. bool hoistSpillInsideBB(LiveInterval &SpillLI, MachineInstr &CopyMI);
  188. void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
  189. void markValueUsed(LiveInterval*, VNInfo*);
  190. bool canGuaranteeAssignmentAfterRemat(unsigned VReg, MachineInstr &MI);
  191. bool reMaterializeFor(LiveInterval &, MachineInstr &MI);
  192. void reMaterializeAll();
  193. bool coalesceStackAccess(MachineInstr *MI, unsigned Reg);
  194. bool foldMemoryOperand(ArrayRef<std::pair<MachineInstr *, unsigned>>,
  195. MachineInstr *LoadMI = nullptr);
  196. void insertReload(unsigned VReg, SlotIndex, MachineBasicBlock::iterator MI);
  197. void insertSpill(unsigned VReg, bool isKill, MachineBasicBlock::iterator MI);
  198. void spillAroundUses(unsigned Reg);
  199. void spillAll();
  200. };
  201. } // end anonymous namespace
  202. Spiller::~Spiller() = default;
  203. void Spiller::anchor() {}
  204. Spiller *llvm::createInlineSpiller(MachineFunctionPass &pass,
  205. MachineFunction &mf,
  206. VirtRegMap &vrm) {
  207. return new InlineSpiller(pass, mf, vrm);
  208. }
  209. //===----------------------------------------------------------------------===//
  210. // Snippets
  211. //===----------------------------------------------------------------------===//
  212. // When spilling a virtual register, we also spill any snippets it is connected
  213. // to. The snippets are small live ranges that only have a single real use,
  214. // leftovers from live range splitting. Spilling them enables memory operand
  215. // folding or tightens the live range around the single use.
  216. //
  217. // This minimizes register pressure and maximizes the store-to-load distance for
  218. // spill slots which can be important in tight loops.
  219. /// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
  220. /// otherwise return 0.
  221. static unsigned isFullCopyOf(const MachineInstr &MI, unsigned Reg) {
  222. if (!MI.isFullCopy())
  223. return 0;
  224. if (MI.getOperand(0).getReg() == Reg)
  225. return MI.getOperand(1).getReg();
  226. if (MI.getOperand(1).getReg() == Reg)
  227. return MI.getOperand(0).getReg();
  228. return 0;
  229. }
  230. /// isSnippet - Identify if a live interval is a snippet that should be spilled.
  231. /// It is assumed that SnipLI is a virtual register with the same original as
  232. /// Edit->getReg().
  233. bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
  234. unsigned Reg = Edit->getReg();
  235. // A snippet is a tiny live range with only a single instruction using it
  236. // besides copies to/from Reg or spills/fills. We accept:
  237. //
  238. // %snip = COPY %Reg / FILL fi#
  239. // %snip = USE %snip
  240. // %Reg = COPY %snip / SPILL %snip, fi#
  241. //
  242. if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
  243. return false;
  244. MachineInstr *UseMI = nullptr;
  245. // Check that all uses satisfy our criteria.
  246. for (MachineRegisterInfo::reg_instr_nodbg_iterator
  247. RI = MRI.reg_instr_nodbg_begin(SnipLI.reg),
  248. E = MRI.reg_instr_nodbg_end(); RI != E; ) {
  249. MachineInstr &MI = *RI++;
  250. // Allow copies to/from Reg.
  251. if (isFullCopyOf(MI, Reg))
  252. continue;
  253. // Allow stack slot loads.
  254. int FI;
  255. if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
  256. continue;
  257. // Allow stack slot stores.
  258. if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
  259. continue;
  260. // Allow a single additional instruction.
  261. if (UseMI && &MI != UseMI)
  262. return false;
  263. UseMI = &MI;
  264. }
  265. return true;
  266. }
  267. /// collectRegsToSpill - Collect live range snippets that only have a single
  268. /// real use.
  269. void InlineSpiller::collectRegsToSpill() {
  270. unsigned Reg = Edit->getReg();
  271. // Main register always spills.
  272. RegsToSpill.assign(1, Reg);
  273. SnippetCopies.clear();
  274. // Snippets all have the same original, so there can't be any for an original
  275. // register.
  276. if (Original == Reg)
  277. return;
  278. for (MachineRegisterInfo::reg_instr_iterator
  279. RI = MRI.reg_instr_begin(Reg), E = MRI.reg_instr_end(); RI != E; ) {
  280. MachineInstr &MI = *RI++;
  281. unsigned SnipReg = isFullCopyOf(MI, Reg);
  282. if (!isSibling(SnipReg))
  283. continue;
  284. LiveInterval &SnipLI = LIS.getInterval(SnipReg);
  285. if (!isSnippet(SnipLI))
  286. continue;
  287. SnippetCopies.insert(&MI);
  288. if (isRegToSpill(SnipReg))
  289. continue;
  290. RegsToSpill.push_back(SnipReg);
  291. LLVM_DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
  292. ++NumSnippets;
  293. }
  294. }
  295. bool InlineSpiller::isSibling(unsigned Reg) {
  296. return Register::isVirtualRegister(Reg) && VRM.getOriginal(Reg) == Original;
  297. }
  298. /// It is beneficial to spill to earlier place in the same BB in case
  299. /// as follows:
  300. /// There is an alternative def earlier in the same MBB.
  301. /// Hoist the spill as far as possible in SpillMBB. This can ease
  302. /// register pressure:
  303. ///
  304. /// x = def
  305. /// y = use x
  306. /// s = copy x
  307. ///
  308. /// Hoisting the spill of s to immediately after the def removes the
  309. /// interference between x and y:
  310. ///
  311. /// x = def
  312. /// spill x
  313. /// y = use killed x
  314. ///
  315. /// This hoist only helps when the copy kills its source.
  316. ///
  317. bool InlineSpiller::hoistSpillInsideBB(LiveInterval &SpillLI,
  318. MachineInstr &CopyMI) {
  319. SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
  320. #ifndef NDEBUG
  321. VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getRegSlot());
  322. assert(VNI && VNI->def == Idx.getRegSlot() && "Not defined by copy");
  323. #endif
  324. Register SrcReg = CopyMI.getOperand(1).getReg();
  325. LiveInterval &SrcLI = LIS.getInterval(SrcReg);
  326. VNInfo *SrcVNI = SrcLI.getVNInfoAt(Idx);
  327. LiveQueryResult SrcQ = SrcLI.Query(Idx);
  328. MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(SrcVNI->def);
  329. if (DefMBB != CopyMI.getParent() || !SrcQ.isKill())
  330. return false;
  331. // Conservatively extend the stack slot range to the range of the original
  332. // value. We may be able to do better with stack slot coloring by being more
  333. // careful here.
  334. assert(StackInt && "No stack slot assigned yet.");
  335. LiveInterval &OrigLI = LIS.getInterval(Original);
  336. VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
  337. StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
  338. LLVM_DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
  339. << *StackInt << '\n');
  340. // We are going to spill SrcVNI immediately after its def, so clear out
  341. // any later spills of the same value.
  342. eliminateRedundantSpills(SrcLI, SrcVNI);
  343. MachineBasicBlock *MBB = LIS.getMBBFromIndex(SrcVNI->def);
  344. MachineBasicBlock::iterator MII;
  345. if (SrcVNI->isPHIDef())
  346. MII = MBB->SkipPHIsLabelsAndDebug(MBB->begin());
  347. else {
  348. MachineInstr *DefMI = LIS.getInstructionFromIndex(SrcVNI->def);
  349. assert(DefMI && "Defining instruction disappeared");
  350. MII = DefMI;
  351. ++MII;
  352. }
  353. // Insert spill without kill flag immediately after def.
  354. TII.storeRegToStackSlot(*MBB, MII, SrcReg, false, StackSlot,
  355. MRI.getRegClass(SrcReg), &TRI);
  356. --MII; // Point to store instruction.
  357. LIS.InsertMachineInstrInMaps(*MII);
  358. LLVM_DEBUG(dbgs() << "\thoisted: " << SrcVNI->def << '\t' << *MII);
  359. HSpiller.addToMergeableSpills(*MII, StackSlot, Original);
  360. ++NumSpills;
  361. return true;
  362. }
  363. /// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
  364. /// redundant spills of this value in SLI.reg and sibling copies.
  365. void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
  366. assert(VNI && "Missing value");
  367. SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
  368. WorkList.push_back(std::make_pair(&SLI, VNI));
  369. assert(StackInt && "No stack slot assigned yet.");
  370. do {
  371. LiveInterval *LI;
  372. std::tie(LI, VNI) = WorkList.pop_back_val();
  373. unsigned Reg = LI->reg;
  374. LLVM_DEBUG(dbgs() << "Checking redundant spills for " << VNI->id << '@'
  375. << VNI->def << " in " << *LI << '\n');
  376. // Regs to spill are taken care of.
  377. if (isRegToSpill(Reg))
  378. continue;
  379. // Add all of VNI's live range to StackInt.
  380. StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
  381. LLVM_DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n');
  382. // Find all spills and copies of VNI.
  383. for (MachineRegisterInfo::use_instr_nodbg_iterator
  384. UI = MRI.use_instr_nodbg_begin(Reg), E = MRI.use_instr_nodbg_end();
  385. UI != E; ) {
  386. MachineInstr &MI = *UI++;
  387. if (!MI.isCopy() && !MI.mayStore())
  388. continue;
  389. SlotIndex Idx = LIS.getInstructionIndex(MI);
  390. if (LI->getVNInfoAt(Idx) != VNI)
  391. continue;
  392. // Follow sibling copies down the dominator tree.
  393. if (unsigned DstReg = isFullCopyOf(MI, Reg)) {
  394. if (isSibling(DstReg)) {
  395. LiveInterval &DstLI = LIS.getInterval(DstReg);
  396. VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getRegSlot());
  397. assert(DstVNI && "Missing defined value");
  398. assert(DstVNI->def == Idx.getRegSlot() && "Wrong copy def slot");
  399. WorkList.push_back(std::make_pair(&DstLI, DstVNI));
  400. }
  401. continue;
  402. }
  403. // Erase spills.
  404. int FI;
  405. if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
  406. LLVM_DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << MI);
  407. // eliminateDeadDefs won't normally remove stores, so switch opcode.
  408. MI.setDesc(TII.get(TargetOpcode::KILL));
  409. DeadDefs.push_back(&MI);
  410. ++NumSpillsRemoved;
  411. if (HSpiller.rmFromMergeableSpills(MI, StackSlot))
  412. --NumSpills;
  413. }
  414. }
  415. } while (!WorkList.empty());
  416. }
  417. //===----------------------------------------------------------------------===//
  418. // Rematerialization
  419. //===----------------------------------------------------------------------===//
  420. /// markValueUsed - Remember that VNI failed to rematerialize, so its defining
  421. /// instruction cannot be eliminated. See through snippet copies
  422. void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
  423. SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
  424. WorkList.push_back(std::make_pair(LI, VNI));
  425. do {
  426. std::tie(LI, VNI) = WorkList.pop_back_val();
  427. if (!UsedValues.insert(VNI).second)
  428. continue;
  429. if (VNI->isPHIDef()) {
  430. MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
  431. for (MachineBasicBlock *P : MBB->predecessors()) {
  432. VNInfo *PVNI = LI->getVNInfoBefore(LIS.getMBBEndIdx(P));
  433. if (PVNI)
  434. WorkList.push_back(std::make_pair(LI, PVNI));
  435. }
  436. continue;
  437. }
  438. // Follow snippet copies.
  439. MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
  440. if (!SnippetCopies.count(MI))
  441. continue;
  442. LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
  443. assert(isRegToSpill(SnipLI.reg) && "Unexpected register in copy");
  444. VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getRegSlot(true));
  445. assert(SnipVNI && "Snippet undefined before copy");
  446. WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
  447. } while (!WorkList.empty());
  448. }
  449. bool InlineSpiller::canGuaranteeAssignmentAfterRemat(unsigned VReg,
  450. MachineInstr &MI) {
  451. if (!RestrictStatepointRemat)
  452. return true;
  453. // Here's a quick explanation of the problem we're trying to handle here:
  454. // * There are some pseudo instructions with more vreg uses than there are
  455. // physical registers on the machine.
  456. // * This is normally handled by spilling the vreg, and folding the reload
  457. // into the user instruction. (Thus decreasing the number of used vregs
  458. // until the remainder can be assigned to physregs.)
  459. // * However, since we may try to spill vregs in any order, we can end up
  460. // trying to spill each operand to the instruction, and then rematting it
  461. // instead. When that happens, the new live intervals (for the remats) are
  462. // expected to be trivially assignable (i.e. RS_Done). However, since we
  463. // may have more remats than physregs, we're guaranteed to fail to assign
  464. // one.
  465. // At the moment, we only handle this for STATEPOINTs since they're the only
  466. // psuedo op where we've seen this. If we start seeing other instructions
  467. // with the same problem, we need to revisit this.
  468. return (MI.getOpcode() != TargetOpcode::STATEPOINT);
  469. }
  470. /// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
  471. bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg, MachineInstr &MI) {
  472. // Analyze instruction
  473. SmallVector<std::pair<MachineInstr *, unsigned>, 8> Ops;
  474. MIBundleOperands::VirtRegInfo RI =
  475. MIBundleOperands(MI).analyzeVirtReg(VirtReg.reg, &Ops);
  476. if (!RI.Reads)
  477. return false;
  478. SlotIndex UseIdx = LIS.getInstructionIndex(MI).getRegSlot(true);
  479. VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx.getBaseIndex());
  480. if (!ParentVNI) {
  481. LLVM_DEBUG(dbgs() << "\tadding <undef> flags: ");
  482. for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
  483. MachineOperand &MO = MI.getOperand(i);
  484. if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg)
  485. MO.setIsUndef();
  486. }
  487. LLVM_DEBUG(dbgs() << UseIdx << '\t' << MI);
  488. return true;
  489. }
  490. if (SnippetCopies.count(&MI))
  491. return false;
  492. LiveInterval &OrigLI = LIS.getInterval(Original);
  493. VNInfo *OrigVNI = OrigLI.getVNInfoAt(UseIdx);
  494. LiveRangeEdit::Remat RM(ParentVNI);
  495. RM.OrigMI = LIS.getInstructionFromIndex(OrigVNI->def);
  496. if (!Edit->canRematerializeAt(RM, OrigVNI, UseIdx, false)) {
  497. markValueUsed(&VirtReg, ParentVNI);
  498. LLVM_DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << MI);
  499. return false;
  500. }
  501. // If the instruction also writes VirtReg.reg, it had better not require the
  502. // same register for uses and defs.
  503. if (RI.Tied) {
  504. markValueUsed(&VirtReg, ParentVNI);
  505. LLVM_DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << MI);
  506. return false;
  507. }
  508. // Before rematerializing into a register for a single instruction, try to
  509. // fold a load into the instruction. That avoids allocating a new register.
  510. if (RM.OrigMI->canFoldAsLoad() &&
  511. foldMemoryOperand(Ops, RM.OrigMI)) {
  512. Edit->markRematerialized(RM.ParentVNI);
  513. ++NumFoldedLoads;
  514. return true;
  515. }
  516. // If we can't guarantee that we'll be able to actually assign the new vreg,
  517. // we can't remat.
  518. if (!canGuaranteeAssignmentAfterRemat(VirtReg.reg, MI)) {
  519. markValueUsed(&VirtReg, ParentVNI);
  520. LLVM_DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << MI);
  521. return false;
  522. }
  523. // Allocate a new register for the remat.
  524. unsigned NewVReg = Edit->createFrom(Original);
  525. // Finally we can rematerialize OrigMI before MI.
  526. SlotIndex DefIdx =
  527. Edit->rematerializeAt(*MI.getParent(), MI, NewVReg, RM, TRI);
  528. // We take the DebugLoc from MI, since OrigMI may be attributed to a
  529. // different source location.
  530. auto *NewMI = LIS.getInstructionFromIndex(DefIdx);
  531. NewMI->setDebugLoc(MI.getDebugLoc());
  532. (void)DefIdx;
  533. LLVM_DEBUG(dbgs() << "\tremat: " << DefIdx << '\t'
  534. << *LIS.getInstructionFromIndex(DefIdx));
  535. // Replace operands
  536. for (const auto &OpPair : Ops) {
  537. MachineOperand &MO = OpPair.first->getOperand(OpPair.second);
  538. if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) {
  539. MO.setReg(NewVReg);
  540. MO.setIsKill();
  541. }
  542. }
  543. LLVM_DEBUG(dbgs() << "\t " << UseIdx << '\t' << MI << '\n');
  544. ++NumRemats;
  545. return true;
  546. }
  547. /// reMaterializeAll - Try to rematerialize as many uses as possible,
  548. /// and trim the live ranges after.
  549. void InlineSpiller::reMaterializeAll() {
  550. if (!Edit->anyRematerializable(AA))
  551. return;
  552. UsedValues.clear();
  553. // Try to remat before all uses of snippets.
  554. bool anyRemat = false;
  555. for (unsigned Reg : RegsToSpill) {
  556. LiveInterval &LI = LIS.getInterval(Reg);
  557. for (MachineRegisterInfo::reg_bundle_iterator
  558. RegI = MRI.reg_bundle_begin(Reg), E = MRI.reg_bundle_end();
  559. RegI != E; ) {
  560. MachineInstr &MI = *RegI++;
  561. // Debug values are not allowed to affect codegen.
  562. if (MI.isDebugValue())
  563. continue;
  564. assert(!MI.isDebugInstr() && "Did not expect to find a use in debug "
  565. "instruction that isn't a DBG_VALUE");
  566. anyRemat |= reMaterializeFor(LI, MI);
  567. }
  568. }
  569. if (!anyRemat)
  570. return;
  571. // Remove any values that were completely rematted.
  572. for (unsigned Reg : RegsToSpill) {
  573. LiveInterval &LI = LIS.getInterval(Reg);
  574. for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end();
  575. I != E; ++I) {
  576. VNInfo *VNI = *I;
  577. if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
  578. continue;
  579. MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
  580. MI->addRegisterDead(Reg, &TRI);
  581. if (!MI->allDefsAreDead())
  582. continue;
  583. LLVM_DEBUG(dbgs() << "All defs dead: " << *MI);
  584. DeadDefs.push_back(MI);
  585. }
  586. }
  587. // Eliminate dead code after remat. Note that some snippet copies may be
  588. // deleted here.
  589. if (DeadDefs.empty())
  590. return;
  591. LLVM_DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
  592. Edit->eliminateDeadDefs(DeadDefs, RegsToSpill, AA);
  593. // LiveRangeEdit::eliminateDeadDef is used to remove dead define instructions
  594. // after rematerialization. To remove a VNI for a vreg from its LiveInterval,
  595. // LiveIntervals::removeVRegDefAt is used. However, after non-PHI VNIs are all
  596. // removed, PHI VNI are still left in the LiveInterval.
  597. // So to get rid of unused reg, we need to check whether it has non-dbg
  598. // reference instead of whether it has non-empty interval.
  599. unsigned ResultPos = 0;
  600. for (unsigned Reg : RegsToSpill) {
  601. if (MRI.reg_nodbg_empty(Reg)) {
  602. Edit->eraseVirtReg(Reg);
  603. continue;
  604. }
  605. assert(LIS.hasInterval(Reg) &&
  606. (!LIS.getInterval(Reg).empty() || !MRI.reg_nodbg_empty(Reg)) &&
  607. "Empty and not used live-range?!");
  608. RegsToSpill[ResultPos++] = Reg;
  609. }
  610. RegsToSpill.erase(RegsToSpill.begin() + ResultPos, RegsToSpill.end());
  611. LLVM_DEBUG(dbgs() << RegsToSpill.size()
  612. << " registers to spill after remat.\n");
  613. }
  614. //===----------------------------------------------------------------------===//
  615. // Spilling
  616. //===----------------------------------------------------------------------===//
  617. /// If MI is a load or store of StackSlot, it can be removed.
  618. bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) {
  619. int FI = 0;
  620. unsigned InstrReg = TII.isLoadFromStackSlot(*MI, FI);
  621. bool IsLoad = InstrReg;
  622. if (!IsLoad)
  623. InstrReg = TII.isStoreToStackSlot(*MI, FI);
  624. // We have a stack access. Is it the right register and slot?
  625. if (InstrReg != Reg || FI != StackSlot)
  626. return false;
  627. if (!IsLoad)
  628. HSpiller.rmFromMergeableSpills(*MI, StackSlot);
  629. LLVM_DEBUG(dbgs() << "Coalescing stack access: " << *MI);
  630. LIS.RemoveMachineInstrFromMaps(*MI);
  631. MI->eraseFromParent();
  632. if (IsLoad) {
  633. ++NumReloadsRemoved;
  634. --NumReloads;
  635. } else {
  636. ++NumSpillsRemoved;
  637. --NumSpills;
  638. }
  639. return true;
  640. }
  641. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  642. LLVM_DUMP_METHOD
  643. // Dump the range of instructions from B to E with their slot indexes.
  644. static void dumpMachineInstrRangeWithSlotIndex(MachineBasicBlock::iterator B,
  645. MachineBasicBlock::iterator E,
  646. LiveIntervals const &LIS,
  647. const char *const header,
  648. unsigned VReg =0) {
  649. char NextLine = '\n';
  650. char SlotIndent = '\t';
  651. if (std::next(B) == E) {
  652. NextLine = ' ';
  653. SlotIndent = ' ';
  654. }
  655. dbgs() << '\t' << header << ": " << NextLine;
  656. for (MachineBasicBlock::iterator I = B; I != E; ++I) {
  657. SlotIndex Idx = LIS.getInstructionIndex(*I).getRegSlot();
  658. // If a register was passed in and this instruction has it as a
  659. // destination that is marked as an early clobber, print the
  660. // early-clobber slot index.
  661. if (VReg) {
  662. MachineOperand *MO = I->findRegisterDefOperand(VReg);
  663. if (MO && MO->isEarlyClobber())
  664. Idx = Idx.getRegSlot(true);
  665. }
  666. dbgs() << SlotIndent << Idx << '\t' << *I;
  667. }
  668. }
  669. #endif
  670. /// foldMemoryOperand - Try folding stack slot references in Ops into their
  671. /// instructions.
  672. ///
  673. /// @param Ops Operand indices from analyzeVirtReg().
  674. /// @param LoadMI Load instruction to use instead of stack slot when non-null.
  675. /// @return True on success.
  676. bool InlineSpiller::
  677. foldMemoryOperand(ArrayRef<std::pair<MachineInstr *, unsigned>> Ops,
  678. MachineInstr *LoadMI) {
  679. if (Ops.empty())
  680. return false;
  681. // Don't attempt folding in bundles.
  682. MachineInstr *MI = Ops.front().first;
  683. if (Ops.back().first != MI || MI->isBundled())
  684. return false;
  685. bool WasCopy = MI->isCopy();
  686. unsigned ImpReg = 0;
  687. // Spill subregs if the target allows it.
  688. // We always want to spill subregs for stackmap/patchpoint pseudos.
  689. bool SpillSubRegs = TII.isSubregFoldable() ||
  690. MI->getOpcode() == TargetOpcode::STATEPOINT ||
  691. MI->getOpcode() == TargetOpcode::PATCHPOINT ||
  692. MI->getOpcode() == TargetOpcode::STACKMAP;
  693. // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
  694. // operands.
  695. SmallVector<unsigned, 8> FoldOps;
  696. for (const auto &OpPair : Ops) {
  697. unsigned Idx = OpPair.second;
  698. assert(MI == OpPair.first && "Instruction conflict during operand folding");
  699. MachineOperand &MO = MI->getOperand(Idx);
  700. if (MO.isImplicit()) {
  701. ImpReg = MO.getReg();
  702. continue;
  703. }
  704. if (!SpillSubRegs && MO.getSubReg())
  705. return false;
  706. // We cannot fold a load instruction into a def.
  707. if (LoadMI && MO.isDef())
  708. return false;
  709. // Tied use operands should not be passed to foldMemoryOperand.
  710. if (!MI->isRegTiedToDefOperand(Idx))
  711. FoldOps.push_back(Idx);
  712. }
  713. // If we only have implicit uses, we won't be able to fold that.
  714. // Moreover, TargetInstrInfo::foldMemoryOperand will assert if we try!
  715. if (FoldOps.empty())
  716. return false;
  717. MachineInstrSpan MIS(MI, MI->getParent());
  718. MachineInstr *FoldMI =
  719. LoadMI ? TII.foldMemoryOperand(*MI, FoldOps, *LoadMI, &LIS)
  720. : TII.foldMemoryOperand(*MI, FoldOps, StackSlot, &LIS, &VRM);
  721. if (!FoldMI)
  722. return false;
  723. // Remove LIS for any dead defs in the original MI not in FoldMI.
  724. for (MIBundleOperands MO(*MI); MO.isValid(); ++MO) {
  725. if (!MO->isReg())
  726. continue;
  727. Register Reg = MO->getReg();
  728. if (!Reg || Register::isVirtualRegister(Reg) || MRI.isReserved(Reg)) {
  729. continue;
  730. }
  731. // Skip non-Defs, including undef uses and internal reads.
  732. if (MO->isUse())
  733. continue;
  734. MIBundleOperands::PhysRegInfo RI =
  735. MIBundleOperands(*FoldMI).analyzePhysReg(Reg, &TRI);
  736. if (RI.FullyDefined)
  737. continue;
  738. // FoldMI does not define this physreg. Remove the LI segment.
  739. assert(MO->isDead() && "Cannot fold physreg def");
  740. SlotIndex Idx = LIS.getInstructionIndex(*MI).getRegSlot();
  741. LIS.removePhysRegDefAt(Reg, Idx);
  742. }
  743. int FI;
  744. if (TII.isStoreToStackSlot(*MI, FI) &&
  745. HSpiller.rmFromMergeableSpills(*MI, FI))
  746. --NumSpills;
  747. LIS.ReplaceMachineInstrInMaps(*MI, *FoldMI);
  748. if (MI->isCall())
  749. MI->getMF()->updateCallSiteInfo(MI, FoldMI);
  750. MI->eraseFromParent();
  751. // Insert any new instructions other than FoldMI into the LIS maps.
  752. assert(!MIS.empty() && "Unexpected empty span of instructions!");
  753. for (MachineInstr &MI : MIS)
  754. if (&MI != FoldMI)
  755. LIS.InsertMachineInstrInMaps(MI);
  756. // TII.foldMemoryOperand may have left some implicit operands on the
  757. // instruction. Strip them.
  758. if (ImpReg)
  759. for (unsigned i = FoldMI->getNumOperands(); i; --i) {
  760. MachineOperand &MO = FoldMI->getOperand(i - 1);
  761. if (!MO.isReg() || !MO.isImplicit())
  762. break;
  763. if (MO.getReg() == ImpReg)
  764. FoldMI->RemoveOperand(i - 1);
  765. }
  766. LLVM_DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MIS.end(), LIS,
  767. "folded"));
  768. if (!WasCopy)
  769. ++NumFolded;
  770. else if (Ops.front().second == 0) {
  771. ++NumSpills;
  772. HSpiller.addToMergeableSpills(*FoldMI, StackSlot, Original);
  773. } else
  774. ++NumReloads;
  775. return true;
  776. }
  777. void InlineSpiller::insertReload(unsigned NewVReg,
  778. SlotIndex Idx,
  779. MachineBasicBlock::iterator MI) {
  780. MachineBasicBlock &MBB = *MI->getParent();
  781. MachineInstrSpan MIS(MI, &MBB);
  782. TII.loadRegFromStackSlot(MBB, MI, NewVReg, StackSlot,
  783. MRI.getRegClass(NewVReg), &TRI);
  784. LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MI);
  785. LLVM_DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MI, LIS, "reload",
  786. NewVReg));
  787. ++NumReloads;
  788. }
  789. /// Check if \p Def fully defines a VReg with an undefined value.
  790. /// If that's the case, that means the value of VReg is actually
  791. /// not relevant.
  792. static bool isFullUndefDef(const MachineInstr &Def) {
  793. if (!Def.isImplicitDef())
  794. return false;
  795. assert(Def.getNumOperands() == 1 &&
  796. "Implicit def with more than one definition");
  797. // We can say that the VReg defined by Def is undef, only if it is
  798. // fully defined by Def. Otherwise, some of the lanes may not be
  799. // undef and the value of the VReg matters.
  800. return !Def.getOperand(0).getSubReg();
  801. }
  802. /// insertSpill - Insert a spill of NewVReg after MI.
  803. void InlineSpiller::insertSpill(unsigned NewVReg, bool isKill,
  804. MachineBasicBlock::iterator MI) {
  805. MachineBasicBlock &MBB = *MI->getParent();
  806. MachineInstrSpan MIS(MI, &MBB);
  807. bool IsRealSpill = true;
  808. if (isFullUndefDef(*MI)) {
  809. // Don't spill undef value.
  810. // Anything works for undef, in particular keeping the memory
  811. // uninitialized is a viable option and it saves code size and
  812. // run time.
  813. BuildMI(MBB, std::next(MI), MI->getDebugLoc(), TII.get(TargetOpcode::KILL))
  814. .addReg(NewVReg, getKillRegState(isKill));
  815. IsRealSpill = false;
  816. } else
  817. TII.storeRegToStackSlot(MBB, std::next(MI), NewVReg, isKill, StackSlot,
  818. MRI.getRegClass(NewVReg), &TRI);
  819. LIS.InsertMachineInstrRangeInMaps(std::next(MI), MIS.end());
  820. LLVM_DEBUG(dumpMachineInstrRangeWithSlotIndex(std::next(MI), MIS.end(), LIS,
  821. "spill"));
  822. ++NumSpills;
  823. if (IsRealSpill)
  824. HSpiller.addToMergeableSpills(*std::next(MI), StackSlot, Original);
  825. }
  826. /// spillAroundUses - insert spill code around each use of Reg.
  827. void InlineSpiller::spillAroundUses(unsigned Reg) {
  828. LLVM_DEBUG(dbgs() << "spillAroundUses " << printReg(Reg) << '\n');
  829. LiveInterval &OldLI = LIS.getInterval(Reg);
  830. // Iterate over instructions using Reg.
  831. for (MachineRegisterInfo::reg_bundle_iterator
  832. RegI = MRI.reg_bundle_begin(Reg), E = MRI.reg_bundle_end();
  833. RegI != E; ) {
  834. MachineInstr *MI = &*(RegI++);
  835. // Debug values are not allowed to affect codegen.
  836. if (MI->isDebugValue()) {
  837. // Modify DBG_VALUE now that the value is in a spill slot.
  838. MachineBasicBlock *MBB = MI->getParent();
  839. LLVM_DEBUG(dbgs() << "Modifying debug info due to spill:\t" << *MI);
  840. buildDbgValueForSpill(*MBB, MI, *MI, StackSlot);
  841. MBB->erase(MI);
  842. continue;
  843. }
  844. assert(!MI->isDebugInstr() && "Did not expect to find a use in debug "
  845. "instruction that isn't a DBG_VALUE");
  846. // Ignore copies to/from snippets. We'll delete them.
  847. if (SnippetCopies.count(MI))
  848. continue;
  849. // Stack slot accesses may coalesce away.
  850. if (coalesceStackAccess(MI, Reg))
  851. continue;
  852. // Analyze instruction.
  853. SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops;
  854. MIBundleOperands::VirtRegInfo RI =
  855. MIBundleOperands(*MI).analyzeVirtReg(Reg, &Ops);
  856. // Find the slot index where this instruction reads and writes OldLI.
  857. // This is usually the def slot, except for tied early clobbers.
  858. SlotIndex Idx = LIS.getInstructionIndex(*MI).getRegSlot();
  859. if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getRegSlot(true)))
  860. if (SlotIndex::isSameInstr(Idx, VNI->def))
  861. Idx = VNI->def;
  862. // Check for a sibling copy.
  863. unsigned SibReg = isFullCopyOf(*MI, Reg);
  864. if (SibReg && isSibling(SibReg)) {
  865. // This may actually be a copy between snippets.
  866. if (isRegToSpill(SibReg)) {
  867. LLVM_DEBUG(dbgs() << "Found new snippet copy: " << *MI);
  868. SnippetCopies.insert(MI);
  869. continue;
  870. }
  871. if (RI.Writes) {
  872. if (hoistSpillInsideBB(OldLI, *MI)) {
  873. // This COPY is now dead, the value is already in the stack slot.
  874. MI->getOperand(0).setIsDead();
  875. DeadDefs.push_back(MI);
  876. continue;
  877. }
  878. } else {
  879. // This is a reload for a sib-reg copy. Drop spills downstream.
  880. LiveInterval &SibLI = LIS.getInterval(SibReg);
  881. eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
  882. // The COPY will fold to a reload below.
  883. }
  884. }
  885. // Attempt to fold memory ops.
  886. if (foldMemoryOperand(Ops))
  887. continue;
  888. // Create a new virtual register for spill/fill.
  889. // FIXME: Infer regclass from instruction alone.
  890. unsigned NewVReg = Edit->createFrom(Reg);
  891. if (RI.Reads)
  892. insertReload(NewVReg, Idx, MI);
  893. // Rewrite instruction operands.
  894. bool hasLiveDef = false;
  895. for (const auto &OpPair : Ops) {
  896. MachineOperand &MO = OpPair.first->getOperand(OpPair.second);
  897. MO.setReg(NewVReg);
  898. if (MO.isUse()) {
  899. if (!OpPair.first->isRegTiedToDefOperand(OpPair.second))
  900. MO.setIsKill();
  901. } else {
  902. if (!MO.isDead())
  903. hasLiveDef = true;
  904. }
  905. }
  906. LLVM_DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << *MI << '\n');
  907. // FIXME: Use a second vreg if instruction has no tied ops.
  908. if (RI.Writes)
  909. if (hasLiveDef)
  910. insertSpill(NewVReg, true, MI);
  911. }
  912. }
  913. /// spillAll - Spill all registers remaining after rematerialization.
  914. void InlineSpiller::spillAll() {
  915. // Update LiveStacks now that we are committed to spilling.
  916. if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
  917. StackSlot = VRM.assignVirt2StackSlot(Original);
  918. StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
  919. StackInt->getNextValue(SlotIndex(), LSS.getVNInfoAllocator());
  920. } else
  921. StackInt = &LSS.getInterval(StackSlot);
  922. if (Original != Edit->getReg())
  923. VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
  924. assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
  925. for (unsigned Reg : RegsToSpill)
  926. StackInt->MergeSegmentsInAsValue(LIS.getInterval(Reg),
  927. StackInt->getValNumInfo(0));
  928. LLVM_DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
  929. // Spill around uses of all RegsToSpill.
  930. for (unsigned Reg : RegsToSpill)
  931. spillAroundUses(Reg);
  932. // Hoisted spills may cause dead code.
  933. if (!DeadDefs.empty()) {
  934. LLVM_DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
  935. Edit->eliminateDeadDefs(DeadDefs, RegsToSpill, AA);
  936. }
  937. // Finally delete the SnippetCopies.
  938. for (unsigned Reg : RegsToSpill) {
  939. for (MachineRegisterInfo::reg_instr_iterator
  940. RI = MRI.reg_instr_begin(Reg), E = MRI.reg_instr_end();
  941. RI != E; ) {
  942. MachineInstr &MI = *(RI++);
  943. assert(SnippetCopies.count(&MI) && "Remaining use wasn't a snippet copy");
  944. // FIXME: Do this with a LiveRangeEdit callback.
  945. LIS.RemoveMachineInstrFromMaps(MI);
  946. MI.eraseFromParent();
  947. }
  948. }
  949. // Delete all spilled registers.
  950. for (unsigned Reg : RegsToSpill)
  951. Edit->eraseVirtReg(Reg);
  952. }
  953. void InlineSpiller::spill(LiveRangeEdit &edit) {
  954. ++NumSpilledRanges;
  955. Edit = &edit;
  956. assert(!Register::isStackSlot(edit.getReg()) &&
  957. "Trying to spill a stack slot.");
  958. // Share a stack slot among all descendants of Original.
  959. Original = VRM.getOriginal(edit.getReg());
  960. StackSlot = VRM.getStackSlot(Original);
  961. StackInt = nullptr;
  962. LLVM_DEBUG(dbgs() << "Inline spilling "
  963. << TRI.getRegClassName(MRI.getRegClass(edit.getReg()))
  964. << ':' << edit.getParent() << "\nFrom original "
  965. << printReg(Original) << '\n');
  966. assert(edit.getParent().isSpillable() &&
  967. "Attempting to spill already spilled value.");
  968. assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
  969. collectRegsToSpill();
  970. reMaterializeAll();
  971. // Remat may handle everything.
  972. if (!RegsToSpill.empty())
  973. spillAll();
  974. Edit->calculateRegClassAndHint(MF, Loops, MBFI);
  975. }
  976. /// Optimizations after all the reg selections and spills are done.
  977. void InlineSpiller::postOptimization() { HSpiller.hoistAllSpills(); }
  978. /// When a spill is inserted, add the spill to MergeableSpills map.
  979. void HoistSpillHelper::addToMergeableSpills(MachineInstr &Spill, int StackSlot,
  980. unsigned Original) {
  981. BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator();
  982. LiveInterval &OrigLI = LIS.getInterval(Original);
  983. // save a copy of LiveInterval in StackSlotToOrigLI because the original
  984. // LiveInterval may be cleared after all its references are spilled.
  985. if (StackSlotToOrigLI.find(StackSlot) == StackSlotToOrigLI.end()) {
  986. auto LI = std::make_unique<LiveInterval>(OrigLI.reg, OrigLI.weight);
  987. LI->assign(OrigLI, Allocator);
  988. StackSlotToOrigLI[StackSlot] = std::move(LI);
  989. }
  990. SlotIndex Idx = LIS.getInstructionIndex(Spill);
  991. VNInfo *OrigVNI = StackSlotToOrigLI[StackSlot]->getVNInfoAt(Idx.getRegSlot());
  992. std::pair<int, VNInfo *> MIdx = std::make_pair(StackSlot, OrigVNI);
  993. MergeableSpills[MIdx].insert(&Spill);
  994. }
  995. /// When a spill is removed, remove the spill from MergeableSpills map.
  996. /// Return true if the spill is removed successfully.
  997. bool HoistSpillHelper::rmFromMergeableSpills(MachineInstr &Spill,
  998. int StackSlot) {
  999. auto It = StackSlotToOrigLI.find(StackSlot);
  1000. if (It == StackSlotToOrigLI.end())
  1001. return false;
  1002. SlotIndex Idx = LIS.getInstructionIndex(Spill);
  1003. VNInfo *OrigVNI = It->second->getVNInfoAt(Idx.getRegSlot());
  1004. std::pair<int, VNInfo *> MIdx = std::make_pair(StackSlot, OrigVNI);
  1005. return MergeableSpills[MIdx].erase(&Spill);
  1006. }
  1007. /// Check BB to see if it is a possible target BB to place a hoisted spill,
  1008. /// i.e., there should be a living sibling of OrigReg at the insert point.
  1009. bool HoistSpillHelper::isSpillCandBB(LiveInterval &OrigLI, VNInfo &OrigVNI,
  1010. MachineBasicBlock &BB, unsigned &LiveReg) {
  1011. SlotIndex Idx;
  1012. unsigned OrigReg = OrigLI.reg;
  1013. MachineBasicBlock::iterator MI = IPA.getLastInsertPointIter(OrigLI, BB);
  1014. if (MI != BB.end())
  1015. Idx = LIS.getInstructionIndex(*MI);
  1016. else
  1017. Idx = LIS.getMBBEndIdx(&BB).getPrevSlot();
  1018. SmallSetVector<unsigned, 16> &Siblings = Virt2SiblingsMap[OrigReg];
  1019. assert(OrigLI.getVNInfoAt(Idx) == &OrigVNI && "Unexpected VNI");
  1020. for (auto const SibReg : Siblings) {
  1021. LiveInterval &LI = LIS.getInterval(SibReg);
  1022. VNInfo *VNI = LI.getVNInfoAt(Idx);
  1023. if (VNI) {
  1024. LiveReg = SibReg;
  1025. return true;
  1026. }
  1027. }
  1028. return false;
  1029. }
  1030. /// Remove redundant spills in the same BB. Save those redundant spills in
  1031. /// SpillsToRm, and save the spill to keep and its BB in SpillBBToSpill map.
  1032. void HoistSpillHelper::rmRedundantSpills(
  1033. SmallPtrSet<MachineInstr *, 16> &Spills,
  1034. SmallVectorImpl<MachineInstr *> &SpillsToRm,
  1035. DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill) {
  1036. // For each spill saw, check SpillBBToSpill[] and see if its BB already has
  1037. // another spill inside. If a BB contains more than one spill, only keep the
  1038. // earlier spill with smaller SlotIndex.
  1039. for (const auto CurrentSpill : Spills) {
  1040. MachineBasicBlock *Block = CurrentSpill->getParent();
  1041. MachineDomTreeNode *Node = MDT.getBase().getNode(Block);
  1042. MachineInstr *PrevSpill = SpillBBToSpill[Node];
  1043. if (PrevSpill) {
  1044. SlotIndex PIdx = LIS.getInstructionIndex(*PrevSpill);
  1045. SlotIndex CIdx = LIS.getInstructionIndex(*CurrentSpill);
  1046. MachineInstr *SpillToRm = (CIdx > PIdx) ? CurrentSpill : PrevSpill;
  1047. MachineInstr *SpillToKeep = (CIdx > PIdx) ? PrevSpill : CurrentSpill;
  1048. SpillsToRm.push_back(SpillToRm);
  1049. SpillBBToSpill[MDT.getBase().getNode(Block)] = SpillToKeep;
  1050. } else {
  1051. SpillBBToSpill[MDT.getBase().getNode(Block)] = CurrentSpill;
  1052. }
  1053. }
  1054. for (const auto SpillToRm : SpillsToRm)
  1055. Spills.erase(SpillToRm);
  1056. }
  1057. /// Starting from \p Root find a top-down traversal order of the dominator
  1058. /// tree to visit all basic blocks containing the elements of \p Spills.
  1059. /// Redundant spills will be found and put into \p SpillsToRm at the same
  1060. /// time. \p SpillBBToSpill will be populated as part of the process and
  1061. /// maps a basic block to the first store occurring in the basic block.
  1062. /// \post SpillsToRm.union(Spills\@post) == Spills\@pre
  1063. void HoistSpillHelper::getVisitOrders(
  1064. MachineBasicBlock *Root, SmallPtrSet<MachineInstr *, 16> &Spills,
  1065. SmallVectorImpl<MachineDomTreeNode *> &Orders,
  1066. SmallVectorImpl<MachineInstr *> &SpillsToRm,
  1067. DenseMap<MachineDomTreeNode *, unsigned> &SpillsToKeep,
  1068. DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill) {
  1069. // The set contains all the possible BB nodes to which we may hoist
  1070. // original spills.
  1071. SmallPtrSet<MachineDomTreeNode *, 8> WorkSet;
  1072. // Save the BB nodes on the path from the first BB node containing
  1073. // non-redundant spill to the Root node.
  1074. SmallPtrSet<MachineDomTreeNode *, 8> NodesOnPath;
  1075. // All the spills to be hoisted must originate from a single def instruction
  1076. // to the OrigReg. It means the def instruction should dominate all the spills
  1077. // to be hoisted. We choose the BB where the def instruction is located as
  1078. // the Root.
  1079. MachineDomTreeNode *RootIDomNode = MDT[Root]->getIDom();
  1080. // For every node on the dominator tree with spill, walk up on the dominator
  1081. // tree towards the Root node until it is reached. If there is other node
  1082. // containing spill in the middle of the path, the previous spill saw will
  1083. // be redundant and the node containing it will be removed. All the nodes on
  1084. // the path starting from the first node with non-redundant spill to the Root
  1085. // node will be added to the WorkSet, which will contain all the possible
  1086. // locations where spills may be hoisted to after the loop below is done.
  1087. for (const auto Spill : Spills) {
  1088. MachineBasicBlock *Block = Spill->getParent();
  1089. MachineDomTreeNode *Node = MDT[Block];
  1090. MachineInstr *SpillToRm = nullptr;
  1091. while (Node != RootIDomNode) {
  1092. // If Node dominates Block, and it already contains a spill, the spill in
  1093. // Block will be redundant.
  1094. if (Node != MDT[Block] && SpillBBToSpill[Node]) {
  1095. SpillToRm = SpillBBToSpill[MDT[Block]];
  1096. break;
  1097. /// If we see the Node already in WorkSet, the path from the Node to
  1098. /// the Root node must already be traversed by another spill.
  1099. /// Then no need to repeat.
  1100. } else if (WorkSet.count(Node)) {
  1101. break;
  1102. } else {
  1103. NodesOnPath.insert(Node);
  1104. }
  1105. Node = Node->getIDom();
  1106. }
  1107. if (SpillToRm) {
  1108. SpillsToRm.push_back(SpillToRm);
  1109. } else {
  1110. // Add a BB containing the original spills to SpillsToKeep -- i.e.,
  1111. // set the initial status before hoisting start. The value of BBs
  1112. // containing original spills is set to 0, in order to descriminate
  1113. // with BBs containing hoisted spills which will be inserted to
  1114. // SpillsToKeep later during hoisting.
  1115. SpillsToKeep[MDT[Block]] = 0;
  1116. WorkSet.insert(NodesOnPath.begin(), NodesOnPath.end());
  1117. }
  1118. NodesOnPath.clear();
  1119. }
  1120. // Sort the nodes in WorkSet in top-down order and save the nodes
  1121. // in Orders. Orders will be used for hoisting in runHoistSpills.
  1122. unsigned idx = 0;
  1123. Orders.push_back(MDT.getBase().getNode(Root));
  1124. do {
  1125. MachineDomTreeNode *Node = Orders[idx++];
  1126. const std::vector<MachineDomTreeNode *> &Children = Node->getChildren();
  1127. unsigned NumChildren = Children.size();
  1128. for (unsigned i = 0; i != NumChildren; ++i) {
  1129. MachineDomTreeNode *Child = Children[i];
  1130. if (WorkSet.count(Child))
  1131. Orders.push_back(Child);
  1132. }
  1133. } while (idx != Orders.size());
  1134. assert(Orders.size() == WorkSet.size() &&
  1135. "Orders have different size with WorkSet");
  1136. #ifndef NDEBUG
  1137. LLVM_DEBUG(dbgs() << "Orders size is " << Orders.size() << "\n");
  1138. SmallVector<MachineDomTreeNode *, 32>::reverse_iterator RIt = Orders.rbegin();
  1139. for (; RIt != Orders.rend(); RIt++)
  1140. LLVM_DEBUG(dbgs() << "BB" << (*RIt)->getBlock()->getNumber() << ",");
  1141. LLVM_DEBUG(dbgs() << "\n");
  1142. #endif
  1143. }
  1144. /// Try to hoist spills according to BB hotness. The spills to removed will
  1145. /// be saved in \p SpillsToRm. The spills to be inserted will be saved in
  1146. /// \p SpillsToIns.
  1147. void HoistSpillHelper::runHoistSpills(
  1148. LiveInterval &OrigLI, VNInfo &OrigVNI,
  1149. SmallPtrSet<MachineInstr *, 16> &Spills,
  1150. SmallVectorImpl<MachineInstr *> &SpillsToRm,
  1151. DenseMap<MachineBasicBlock *, unsigned> &SpillsToIns) {
  1152. // Visit order of dominator tree nodes.
  1153. SmallVector<MachineDomTreeNode *, 32> Orders;
  1154. // SpillsToKeep contains all the nodes where spills are to be inserted
  1155. // during hoisting. If the spill to be inserted is an original spill
  1156. // (not a hoisted one), the value of the map entry is 0. If the spill
  1157. // is a hoisted spill, the value of the map entry is the VReg to be used
  1158. // as the source of the spill.
  1159. DenseMap<MachineDomTreeNode *, unsigned> SpillsToKeep;
  1160. // Map from BB to the first spill inside of it.
  1161. DenseMap<MachineDomTreeNode *, MachineInstr *> SpillBBToSpill;
  1162. rmRedundantSpills(Spills, SpillsToRm, SpillBBToSpill);
  1163. MachineBasicBlock *Root = LIS.getMBBFromIndex(OrigVNI.def);
  1164. getVisitOrders(Root, Spills, Orders, SpillsToRm, SpillsToKeep,
  1165. SpillBBToSpill);
  1166. // SpillsInSubTreeMap keeps the map from a dom tree node to a pair of
  1167. // nodes set and the cost of all the spills inside those nodes.
  1168. // The nodes set are the locations where spills are to be inserted
  1169. // in the subtree of current node.
  1170. using NodesCostPair =
  1171. std::pair<SmallPtrSet<MachineDomTreeNode *, 16>, BlockFrequency>;
  1172. DenseMap<MachineDomTreeNode *, NodesCostPair> SpillsInSubTreeMap;
  1173. // Iterate Orders set in reverse order, which will be a bottom-up order
  1174. // in the dominator tree. Once we visit a dom tree node, we know its
  1175. // children have already been visited and the spill locations in the
  1176. // subtrees of all the children have been determined.
  1177. SmallVector<MachineDomTreeNode *, 32>::reverse_iterator RIt = Orders.rbegin();
  1178. for (; RIt != Orders.rend(); RIt++) {
  1179. MachineBasicBlock *Block = (*RIt)->getBlock();
  1180. // If Block contains an original spill, simply continue.
  1181. if (SpillsToKeep.find(*RIt) != SpillsToKeep.end() && !SpillsToKeep[*RIt]) {
  1182. SpillsInSubTreeMap[*RIt].first.insert(*RIt);
  1183. // SpillsInSubTreeMap[*RIt].second contains the cost of spill.
  1184. SpillsInSubTreeMap[*RIt].second = MBFI.getBlockFreq(Block);
  1185. continue;
  1186. }
  1187. // Collect spills in subtree of current node (*RIt) to
  1188. // SpillsInSubTreeMap[*RIt].first.
  1189. const std::vector<MachineDomTreeNode *> &Children = (*RIt)->getChildren();
  1190. unsigned NumChildren = Children.size();
  1191. for (unsigned i = 0; i != NumChildren; ++i) {
  1192. MachineDomTreeNode *Child = Children[i];
  1193. if (SpillsInSubTreeMap.find(Child) == SpillsInSubTreeMap.end())
  1194. continue;
  1195. // The stmt "SpillsInSubTree = SpillsInSubTreeMap[*RIt].first" below
  1196. // should be placed before getting the begin and end iterators of
  1197. // SpillsInSubTreeMap[Child].first, or else the iterators may be
  1198. // invalidated when SpillsInSubTreeMap[*RIt] is seen the first time
  1199. // and the map grows and then the original buckets in the map are moved.
  1200. SmallPtrSet<MachineDomTreeNode *, 16> &SpillsInSubTree =
  1201. SpillsInSubTreeMap[*RIt].first;
  1202. BlockFrequency &SubTreeCost = SpillsInSubTreeMap[*RIt].second;
  1203. SubTreeCost += SpillsInSubTreeMap[Child].second;
  1204. auto BI = SpillsInSubTreeMap[Child].first.begin();
  1205. auto EI = SpillsInSubTreeMap[Child].first.end();
  1206. SpillsInSubTree.insert(BI, EI);
  1207. SpillsInSubTreeMap.erase(Child);
  1208. }
  1209. SmallPtrSet<MachineDomTreeNode *, 16> &SpillsInSubTree =
  1210. SpillsInSubTreeMap[*RIt].first;
  1211. BlockFrequency &SubTreeCost = SpillsInSubTreeMap[*RIt].second;
  1212. // No spills in subtree, simply continue.
  1213. if (SpillsInSubTree.empty())
  1214. continue;
  1215. // Check whether Block is a possible candidate to insert spill.
  1216. unsigned LiveReg = 0;
  1217. if (!isSpillCandBB(OrigLI, OrigVNI, *Block, LiveReg))
  1218. continue;
  1219. // If there are multiple spills that could be merged, bias a little
  1220. // to hoist the spill.
  1221. BranchProbability MarginProb = (SpillsInSubTree.size() > 1)
  1222. ? BranchProbability(9, 10)
  1223. : BranchProbability(1, 1);
  1224. if (SubTreeCost > MBFI.getBlockFreq(Block) * MarginProb) {
  1225. // Hoist: Move spills to current Block.
  1226. for (const auto SpillBB : SpillsInSubTree) {
  1227. // When SpillBB is a BB contains original spill, insert the spill
  1228. // to SpillsToRm.
  1229. if (SpillsToKeep.find(SpillBB) != SpillsToKeep.end() &&
  1230. !SpillsToKeep[SpillBB]) {
  1231. MachineInstr *SpillToRm = SpillBBToSpill[SpillBB];
  1232. SpillsToRm.push_back(SpillToRm);
  1233. }
  1234. // SpillBB will not contain spill anymore, remove it from SpillsToKeep.
  1235. SpillsToKeep.erase(SpillBB);
  1236. }
  1237. // Current Block is the BB containing the new hoisted spill. Add it to
  1238. // SpillsToKeep. LiveReg is the source of the new spill.
  1239. SpillsToKeep[*RIt] = LiveReg;
  1240. LLVM_DEBUG({
  1241. dbgs() << "spills in BB: ";
  1242. for (const auto Rspill : SpillsInSubTree)
  1243. dbgs() << Rspill->getBlock()->getNumber() << " ";
  1244. dbgs() << "were promoted to BB" << (*RIt)->getBlock()->getNumber()
  1245. << "\n";
  1246. });
  1247. SpillsInSubTree.clear();
  1248. SpillsInSubTree.insert(*RIt);
  1249. SubTreeCost = MBFI.getBlockFreq(Block);
  1250. }
  1251. }
  1252. // For spills in SpillsToKeep with LiveReg set (i.e., not original spill),
  1253. // save them to SpillsToIns.
  1254. for (const auto Ent : SpillsToKeep) {
  1255. if (Ent.second)
  1256. SpillsToIns[Ent.first->getBlock()] = Ent.second;
  1257. }
  1258. }
  1259. /// For spills with equal values, remove redundant spills and hoist those left
  1260. /// to less hot spots.
  1261. ///
  1262. /// Spills with equal values will be collected into the same set in
  1263. /// MergeableSpills when spill is inserted. These equal spills are originated
  1264. /// from the same defining instruction and are dominated by the instruction.
  1265. /// Before hoisting all the equal spills, redundant spills inside in the same
  1266. /// BB are first marked to be deleted. Then starting from the spills left, walk
  1267. /// up on the dominator tree towards the Root node where the define instruction
  1268. /// is located, mark the dominated spills to be deleted along the way and
  1269. /// collect the BB nodes on the path from non-dominated spills to the define
  1270. /// instruction into a WorkSet. The nodes in WorkSet are the candidate places
  1271. /// where we are considering to hoist the spills. We iterate the WorkSet in
  1272. /// bottom-up order, and for each node, we will decide whether to hoist spills
  1273. /// inside its subtree to that node. In this way, we can get benefit locally
  1274. /// even if hoisting all the equal spills to one cold place is impossible.
  1275. void HoistSpillHelper::hoistAllSpills() {
  1276. SmallVector<unsigned, 4> NewVRegs;
  1277. LiveRangeEdit Edit(nullptr, NewVRegs, MF, LIS, &VRM, this);
  1278. for (unsigned i = 0, e = MRI.getNumVirtRegs(); i != e; ++i) {
  1279. unsigned Reg = Register::index2VirtReg(i);
  1280. unsigned Original = VRM.getPreSplitReg(Reg);
  1281. if (!MRI.def_empty(Reg))
  1282. Virt2SiblingsMap[Original].insert(Reg);
  1283. }
  1284. // Each entry in MergeableSpills contains a spill set with equal values.
  1285. for (auto &Ent : MergeableSpills) {
  1286. int Slot = Ent.first.first;
  1287. LiveInterval &OrigLI = *StackSlotToOrigLI[Slot];
  1288. VNInfo *OrigVNI = Ent.first.second;
  1289. SmallPtrSet<MachineInstr *, 16> &EqValSpills = Ent.second;
  1290. if (Ent.second.empty())
  1291. continue;
  1292. LLVM_DEBUG({
  1293. dbgs() << "\nFor Slot" << Slot << " and VN" << OrigVNI->id << ":\n"
  1294. << "Equal spills in BB: ";
  1295. for (const auto spill : EqValSpills)
  1296. dbgs() << spill->getParent()->getNumber() << " ";
  1297. dbgs() << "\n";
  1298. });
  1299. // SpillsToRm is the spill set to be removed from EqValSpills.
  1300. SmallVector<MachineInstr *, 16> SpillsToRm;
  1301. // SpillsToIns is the spill set to be newly inserted after hoisting.
  1302. DenseMap<MachineBasicBlock *, unsigned> SpillsToIns;
  1303. runHoistSpills(OrigLI, *OrigVNI, EqValSpills, SpillsToRm, SpillsToIns);
  1304. LLVM_DEBUG({
  1305. dbgs() << "Finally inserted spills in BB: ";
  1306. for (const auto Ispill : SpillsToIns)
  1307. dbgs() << Ispill.first->getNumber() << " ";
  1308. dbgs() << "\nFinally removed spills in BB: ";
  1309. for (const auto Rspill : SpillsToRm)
  1310. dbgs() << Rspill->getParent()->getNumber() << " ";
  1311. dbgs() << "\n";
  1312. });
  1313. // Stack live range update.
  1314. LiveInterval &StackIntvl = LSS.getInterval(Slot);
  1315. if (!SpillsToIns.empty() || !SpillsToRm.empty())
  1316. StackIntvl.MergeValueInAsValue(OrigLI, OrigVNI,
  1317. StackIntvl.getValNumInfo(0));
  1318. // Insert hoisted spills.
  1319. for (auto const Insert : SpillsToIns) {
  1320. MachineBasicBlock *BB = Insert.first;
  1321. unsigned LiveReg = Insert.second;
  1322. MachineBasicBlock::iterator MI = IPA.getLastInsertPointIter(OrigLI, *BB);
  1323. TII.storeRegToStackSlot(*BB, MI, LiveReg, false, Slot,
  1324. MRI.getRegClass(LiveReg), &TRI);
  1325. LIS.InsertMachineInstrRangeInMaps(std::prev(MI), MI);
  1326. ++NumSpills;
  1327. }
  1328. // Remove redundant spills or change them to dead instructions.
  1329. NumSpills -= SpillsToRm.size();
  1330. for (auto const RMEnt : SpillsToRm) {
  1331. RMEnt->setDesc(TII.get(TargetOpcode::KILL));
  1332. for (unsigned i = RMEnt->getNumOperands(); i; --i) {
  1333. MachineOperand &MO = RMEnt->getOperand(i - 1);
  1334. if (MO.isReg() && MO.isImplicit() && MO.isDef() && !MO.isDead())
  1335. RMEnt->RemoveOperand(i - 1);
  1336. }
  1337. }
  1338. Edit.eliminateDeadDefs(SpillsToRm, None, AA);
  1339. }
  1340. }
  1341. /// For VirtReg clone, the \p New register should have the same physreg or
  1342. /// stackslot as the \p old register.
  1343. void HoistSpillHelper::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
  1344. if (VRM.hasPhys(Old))
  1345. VRM.assignVirt2Phys(New, VRM.getPhys(Old));
  1346. else if (VRM.getStackSlot(Old) != VirtRegMap::NO_STACK_SLOT)
  1347. VRM.assignVirt2StackSlot(New, VRM.getStackSlot(Old));
  1348. else
  1349. llvm_unreachable("VReg should be assigned either physreg or stackslot");
  1350. }