MachineLICM.cpp 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524
  1. //===- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ----------===//
  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. // This pass performs loop invariant code motion on machine instructions. We
  10. // attempt to remove as much code from the body of a loop as possible.
  11. //
  12. // This pass is not intended to be a replacement or a complete alternative
  13. // for the LLVM-IR-level LICM pass. It is only designed to hoist simple
  14. // constructs that are not exposed before lowering and instruction selection.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/ADT/BitVector.h"
  18. #include "llvm/ADT/DenseMap.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/SmallSet.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/ADT/Statistic.h"
  23. #include "llvm/Analysis/AliasAnalysis.h"
  24. #include "llvm/CodeGen/MachineBasicBlock.h"
  25. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  26. #include "llvm/CodeGen/MachineDominators.h"
  27. #include "llvm/CodeGen/MachineFrameInfo.h"
  28. #include "llvm/CodeGen/MachineFunction.h"
  29. #include "llvm/CodeGen/MachineFunctionPass.h"
  30. #include "llvm/CodeGen/MachineInstr.h"
  31. #include "llvm/CodeGen/MachineLoopInfo.h"
  32. #include "llvm/CodeGen/MachineMemOperand.h"
  33. #include "llvm/CodeGen/MachineOperand.h"
  34. #include "llvm/CodeGen/MachineRegisterInfo.h"
  35. #include "llvm/CodeGen/PseudoSourceValue.h"
  36. #include "llvm/CodeGen/TargetInstrInfo.h"
  37. #include "llvm/CodeGen/TargetLowering.h"
  38. #include "llvm/CodeGen/TargetRegisterInfo.h"
  39. #include "llvm/CodeGen/TargetSchedule.h"
  40. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  41. #include "llvm/IR/DebugLoc.h"
  42. #include "llvm/InitializePasses.h"
  43. #include "llvm/MC/MCInstrDesc.h"
  44. #include "llvm/MC/MCRegister.h"
  45. #include "llvm/MC/MCRegisterInfo.h"
  46. #include "llvm/Pass.h"
  47. #include "llvm/Support/Casting.h"
  48. #include "llvm/Support/CommandLine.h"
  49. #include "llvm/Support/Debug.h"
  50. #include "llvm/Support/raw_ostream.h"
  51. #include <algorithm>
  52. #include <cassert>
  53. #include <limits>
  54. #include <vector>
  55. using namespace llvm;
  56. #define DEBUG_TYPE "machinelicm"
  57. static cl::opt<bool>
  58. AvoidSpeculation("avoid-speculation",
  59. cl::desc("MachineLICM should avoid speculation"),
  60. cl::init(true), cl::Hidden);
  61. static cl::opt<bool>
  62. HoistCheapInsts("hoist-cheap-insts",
  63. cl::desc("MachineLICM should hoist even cheap instructions"),
  64. cl::init(false), cl::Hidden);
  65. static cl::opt<bool>
  66. HoistConstStores("hoist-const-stores",
  67. cl::desc("Hoist invariant stores"),
  68. cl::init(true), cl::Hidden);
  69. // The default threshold of 100 (i.e. if target block is 100 times hotter)
  70. // is based on empirical data on a single target and is subject to tuning.
  71. static cl::opt<unsigned>
  72. BlockFrequencyRatioThreshold("block-freq-ratio-threshold",
  73. cl::desc("Do not hoist instructions if target"
  74. "block is N times hotter than the source."),
  75. cl::init(100), cl::Hidden);
  76. enum class UseBFI { None, PGO, All };
  77. static cl::opt<UseBFI>
  78. DisableHoistingToHotterBlocks("disable-hoisting-to-hotter-blocks",
  79. cl::desc("Disable hoisting instructions to"
  80. " hotter blocks"),
  81. cl::init(UseBFI::PGO), cl::Hidden,
  82. cl::values(clEnumValN(UseBFI::None, "none",
  83. "disable the feature"),
  84. clEnumValN(UseBFI::PGO, "pgo",
  85. "enable the feature when using profile data"),
  86. clEnumValN(UseBFI::All, "all",
  87. "enable the feature with/wo profile data")));
  88. STATISTIC(NumHoisted,
  89. "Number of machine instructions hoisted out of loops");
  90. STATISTIC(NumLowRP,
  91. "Number of instructions hoisted in low reg pressure situation");
  92. STATISTIC(NumHighLatency,
  93. "Number of high latency instructions hoisted");
  94. STATISTIC(NumCSEed,
  95. "Number of hoisted machine instructions CSEed");
  96. STATISTIC(NumPostRAHoisted,
  97. "Number of machine instructions hoisted out of loops post regalloc");
  98. STATISTIC(NumStoreConst,
  99. "Number of stores of const phys reg hoisted out of loops");
  100. STATISTIC(NumNotHoistedDueToHotness,
  101. "Number of instructions not hoisted due to block frequency");
  102. namespace {
  103. class MachineLICMBase : public MachineFunctionPass {
  104. const TargetInstrInfo *TII;
  105. const TargetLoweringBase *TLI;
  106. const TargetRegisterInfo *TRI;
  107. const MachineFrameInfo *MFI;
  108. MachineRegisterInfo *MRI;
  109. TargetSchedModel SchedModel;
  110. bool PreRegAlloc;
  111. bool HasProfileData;
  112. // Various analyses that we use...
  113. AliasAnalysis *AA; // Alias analysis info.
  114. MachineBlockFrequencyInfo *MBFI; // Machine block frequncy info
  115. MachineLoopInfo *MLI; // Current MachineLoopInfo
  116. MachineDominatorTree *DT; // Machine dominator tree for the cur loop
  117. // State that is updated as we process loops
  118. bool Changed; // True if a loop is changed.
  119. bool FirstInLoop; // True if it's the first LICM in the loop.
  120. MachineLoop *CurLoop; // The current loop we are working on.
  121. MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
  122. // Exit blocks for CurLoop.
  123. SmallVector<MachineBasicBlock *, 8> ExitBlocks;
  124. bool isExitBlock(const MachineBasicBlock *MBB) const {
  125. return is_contained(ExitBlocks, MBB);
  126. }
  127. // Track 'estimated' register pressure.
  128. SmallSet<Register, 32> RegSeen;
  129. SmallVector<unsigned, 8> RegPressure;
  130. // Register pressure "limit" per register pressure set. If the pressure
  131. // is higher than the limit, then it's considered high.
  132. SmallVector<unsigned, 8> RegLimit;
  133. // Register pressure on path leading from loop preheader to current BB.
  134. SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
  135. // For each opcode, keep a list of potential CSE instructions.
  136. DenseMap<unsigned, std::vector<MachineInstr *>> CSEMap;
  137. enum {
  138. SpeculateFalse = 0,
  139. SpeculateTrue = 1,
  140. SpeculateUnknown = 2
  141. };
  142. // If a MBB does not dominate loop exiting blocks then it may not safe
  143. // to hoist loads from this block.
  144. // Tri-state: 0 - false, 1 - true, 2 - unknown
  145. unsigned SpeculationState;
  146. public:
  147. MachineLICMBase(char &PassID, bool PreRegAlloc)
  148. : MachineFunctionPass(PassID), PreRegAlloc(PreRegAlloc) {}
  149. bool runOnMachineFunction(MachineFunction &MF) override;
  150. void getAnalysisUsage(AnalysisUsage &AU) const override {
  151. AU.addRequired<MachineLoopInfo>();
  152. if (DisableHoistingToHotterBlocks != UseBFI::None)
  153. AU.addRequired<MachineBlockFrequencyInfo>();
  154. AU.addRequired<MachineDominatorTree>();
  155. AU.addRequired<AAResultsWrapperPass>();
  156. AU.addPreserved<MachineLoopInfo>();
  157. MachineFunctionPass::getAnalysisUsage(AU);
  158. }
  159. void releaseMemory() override {
  160. RegSeen.clear();
  161. RegPressure.clear();
  162. RegLimit.clear();
  163. BackTrace.clear();
  164. CSEMap.clear();
  165. }
  166. private:
  167. /// Keep track of information about hoisting candidates.
  168. struct CandidateInfo {
  169. MachineInstr *MI;
  170. unsigned Def;
  171. int FI;
  172. CandidateInfo(MachineInstr *mi, unsigned def, int fi)
  173. : MI(mi), Def(def), FI(fi) {}
  174. };
  175. void HoistRegionPostRA();
  176. void HoistPostRA(MachineInstr *MI, unsigned Def);
  177. void ProcessMI(MachineInstr *MI, BitVector &PhysRegDefs,
  178. BitVector &PhysRegClobbers, SmallSet<int, 32> &StoredFIs,
  179. SmallVectorImpl<CandidateInfo> &Candidates);
  180. void AddToLiveIns(MCRegister Reg);
  181. bool IsLICMCandidate(MachineInstr &I);
  182. bool IsLoopInvariantInst(MachineInstr &I);
  183. bool HasLoopPHIUse(const MachineInstr *MI) const;
  184. bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
  185. Register Reg) const;
  186. bool IsCheapInstruction(MachineInstr &MI) const;
  187. bool CanCauseHighRegPressure(const DenseMap<unsigned, int> &Cost,
  188. bool Cheap);
  189. void UpdateBackTraceRegPressure(const MachineInstr *MI);
  190. bool IsProfitableToHoist(MachineInstr &MI);
  191. bool IsGuaranteedToExecute(MachineBasicBlock *BB);
  192. bool isTriviallyReMaterializable(const MachineInstr &MI,
  193. AAResults *AA) const;
  194. void EnterScope(MachineBasicBlock *MBB);
  195. void ExitScope(MachineBasicBlock *MBB);
  196. void ExitScopeIfDone(
  197. MachineDomTreeNode *Node,
  198. DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren,
  199. DenseMap<MachineDomTreeNode *, MachineDomTreeNode *> &ParentMap);
  200. void HoistOutOfLoop(MachineDomTreeNode *HeaderN);
  201. void InitRegPressure(MachineBasicBlock *BB);
  202. DenseMap<unsigned, int> calcRegisterCost(const MachineInstr *MI,
  203. bool ConsiderSeen,
  204. bool ConsiderUnseenAsDef);
  205. void UpdateRegPressure(const MachineInstr *MI,
  206. bool ConsiderUnseenAsDef = false);
  207. MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
  208. MachineInstr *LookForDuplicate(const MachineInstr *MI,
  209. std::vector<MachineInstr *> &PrevMIs);
  210. bool
  211. EliminateCSE(MachineInstr *MI,
  212. DenseMap<unsigned, std::vector<MachineInstr *>>::iterator &CI);
  213. bool MayCSE(MachineInstr *MI);
  214. bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
  215. void InitCSEMap(MachineBasicBlock *BB);
  216. bool isTgtHotterThanSrc(MachineBasicBlock *SrcBlock,
  217. MachineBasicBlock *TgtBlock);
  218. MachineBasicBlock *getCurPreheader();
  219. };
  220. class MachineLICM : public MachineLICMBase {
  221. public:
  222. static char ID;
  223. MachineLICM() : MachineLICMBase(ID, false) {
  224. initializeMachineLICMPass(*PassRegistry::getPassRegistry());
  225. }
  226. };
  227. class EarlyMachineLICM : public MachineLICMBase {
  228. public:
  229. static char ID;
  230. EarlyMachineLICM() : MachineLICMBase(ID, true) {
  231. initializeEarlyMachineLICMPass(*PassRegistry::getPassRegistry());
  232. }
  233. };
  234. } // end anonymous namespace
  235. char MachineLICM::ID;
  236. char EarlyMachineLICM::ID;
  237. char &llvm::MachineLICMID = MachineLICM::ID;
  238. char &llvm::EarlyMachineLICMID = EarlyMachineLICM::ID;
  239. INITIALIZE_PASS_BEGIN(MachineLICM, DEBUG_TYPE,
  240. "Machine Loop Invariant Code Motion", false, false)
  241. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  242. INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
  243. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  244. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  245. INITIALIZE_PASS_END(MachineLICM, DEBUG_TYPE,
  246. "Machine Loop Invariant Code Motion", false, false)
  247. INITIALIZE_PASS_BEGIN(EarlyMachineLICM, "early-machinelicm",
  248. "Early Machine Loop Invariant Code Motion", false, false)
  249. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  250. INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
  251. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  252. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  253. INITIALIZE_PASS_END(EarlyMachineLICM, "early-machinelicm",
  254. "Early Machine Loop Invariant Code Motion", false, false)
  255. /// Test if the given loop is the outer-most loop that has a unique predecessor.
  256. static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
  257. // Check whether this loop even has a unique predecessor.
  258. if (!CurLoop->getLoopPredecessor())
  259. return false;
  260. // Ok, now check to see if any of its outer loops do.
  261. for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
  262. if (L->getLoopPredecessor())
  263. return false;
  264. // None of them did, so this is the outermost with a unique predecessor.
  265. return true;
  266. }
  267. bool MachineLICMBase::runOnMachineFunction(MachineFunction &MF) {
  268. if (skipFunction(MF.getFunction()))
  269. return false;
  270. Changed = FirstInLoop = false;
  271. const TargetSubtargetInfo &ST = MF.getSubtarget();
  272. TII = ST.getInstrInfo();
  273. TLI = ST.getTargetLowering();
  274. TRI = ST.getRegisterInfo();
  275. MFI = &MF.getFrameInfo();
  276. MRI = &MF.getRegInfo();
  277. SchedModel.init(&ST);
  278. PreRegAlloc = MRI->isSSA();
  279. HasProfileData = MF.getFunction().hasProfileData();
  280. if (PreRegAlloc)
  281. LLVM_DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
  282. else
  283. LLVM_DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
  284. LLVM_DEBUG(dbgs() << MF.getName() << " ********\n");
  285. if (PreRegAlloc) {
  286. // Estimate register pressure during pre-regalloc pass.
  287. unsigned NumRPS = TRI->getNumRegPressureSets();
  288. RegPressure.resize(NumRPS);
  289. std::fill(RegPressure.begin(), RegPressure.end(), 0);
  290. RegLimit.resize(NumRPS);
  291. for (unsigned i = 0, e = NumRPS; i != e; ++i)
  292. RegLimit[i] = TRI->getRegPressureSetLimit(MF, i);
  293. }
  294. // Get our Loop information...
  295. if (DisableHoistingToHotterBlocks != UseBFI::None)
  296. MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
  297. MLI = &getAnalysis<MachineLoopInfo>();
  298. DT = &getAnalysis<MachineDominatorTree>();
  299. AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  300. SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
  301. while (!Worklist.empty()) {
  302. CurLoop = Worklist.pop_back_val();
  303. CurPreheader = nullptr;
  304. ExitBlocks.clear();
  305. // If this is done before regalloc, only visit outer-most preheader-sporting
  306. // loops.
  307. if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
  308. Worklist.append(CurLoop->begin(), CurLoop->end());
  309. continue;
  310. }
  311. CurLoop->getExitBlocks(ExitBlocks);
  312. if (!PreRegAlloc)
  313. HoistRegionPostRA();
  314. else {
  315. // CSEMap is initialized for loop header when the first instruction is
  316. // being hoisted.
  317. MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
  318. FirstInLoop = true;
  319. HoistOutOfLoop(N);
  320. CSEMap.clear();
  321. }
  322. }
  323. return Changed;
  324. }
  325. /// Return true if instruction stores to the specified frame.
  326. static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
  327. // Check mayStore before memory operands so that e.g. DBG_VALUEs will return
  328. // true since they have no memory operands.
  329. if (!MI->mayStore())
  330. return false;
  331. // If we lost memory operands, conservatively assume that the instruction
  332. // writes to all slots.
  333. if (MI->memoperands_empty())
  334. return true;
  335. for (const MachineMemOperand *MemOp : MI->memoperands()) {
  336. if (!MemOp->isStore() || !MemOp->getPseudoValue())
  337. continue;
  338. if (const FixedStackPseudoSourceValue *Value =
  339. dyn_cast<FixedStackPseudoSourceValue>(MemOp->getPseudoValue())) {
  340. if (Value->getFrameIndex() == FI)
  341. return true;
  342. }
  343. }
  344. return false;
  345. }
  346. /// Examine the instruction for potentai LICM candidate. Also
  347. /// gather register def and frame object update information.
  348. void MachineLICMBase::ProcessMI(MachineInstr *MI,
  349. BitVector &PhysRegDefs,
  350. BitVector &PhysRegClobbers,
  351. SmallSet<int, 32> &StoredFIs,
  352. SmallVectorImpl<CandidateInfo> &Candidates) {
  353. bool RuledOut = false;
  354. bool HasNonInvariantUse = false;
  355. unsigned Def = 0;
  356. for (const MachineOperand &MO : MI->operands()) {
  357. if (MO.isFI()) {
  358. // Remember if the instruction stores to the frame index.
  359. int FI = MO.getIndex();
  360. if (!StoredFIs.count(FI) &&
  361. MFI->isSpillSlotObjectIndex(FI) &&
  362. InstructionStoresToFI(MI, FI))
  363. StoredFIs.insert(FI);
  364. HasNonInvariantUse = true;
  365. continue;
  366. }
  367. // We can't hoist an instruction defining a physreg that is clobbered in
  368. // the loop.
  369. if (MO.isRegMask()) {
  370. PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
  371. continue;
  372. }
  373. if (!MO.isReg())
  374. continue;
  375. Register Reg = MO.getReg();
  376. if (!Reg)
  377. continue;
  378. assert(Register::isPhysicalRegister(Reg) &&
  379. "Not expecting virtual register!");
  380. if (!MO.isDef()) {
  381. if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
  382. // If it's using a non-loop-invariant register, then it's obviously not
  383. // safe to hoist.
  384. HasNonInvariantUse = true;
  385. continue;
  386. }
  387. if (MO.isImplicit()) {
  388. for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
  389. PhysRegClobbers.set(*AI);
  390. if (!MO.isDead())
  391. // Non-dead implicit def? This cannot be hoisted.
  392. RuledOut = true;
  393. // No need to check if a dead implicit def is also defined by
  394. // another instruction.
  395. continue;
  396. }
  397. // FIXME: For now, avoid instructions with multiple defs, unless
  398. // it's a dead implicit def.
  399. if (Def)
  400. RuledOut = true;
  401. else
  402. Def = Reg;
  403. // If we have already seen another instruction that defines the same
  404. // register, then this is not safe. Two defs is indicated by setting a
  405. // PhysRegClobbers bit.
  406. for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
  407. if (PhysRegDefs.test(*AS))
  408. PhysRegClobbers.set(*AS);
  409. }
  410. // Need a second loop because MCRegAliasIterator can visit the same
  411. // register twice.
  412. for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS)
  413. PhysRegDefs.set(*AS);
  414. if (PhysRegClobbers.test(Reg))
  415. // MI defined register is seen defined by another instruction in
  416. // the loop, it cannot be a LICM candidate.
  417. RuledOut = true;
  418. }
  419. // Only consider reloads for now and remats which do not have register
  420. // operands. FIXME: Consider unfold load folding instructions.
  421. if (Def && !RuledOut) {
  422. int FI = std::numeric_limits<int>::min();
  423. if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
  424. (TII->isLoadFromStackSlot(*MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
  425. Candidates.push_back(CandidateInfo(MI, Def, FI));
  426. }
  427. }
  428. /// Walk the specified region of the CFG and hoist loop invariants out to the
  429. /// preheader.
  430. void MachineLICMBase::HoistRegionPostRA() {
  431. MachineBasicBlock *Preheader = getCurPreheader();
  432. if (!Preheader)
  433. return;
  434. unsigned NumRegs = TRI->getNumRegs();
  435. BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
  436. BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
  437. SmallVector<CandidateInfo, 32> Candidates;
  438. SmallSet<int, 32> StoredFIs;
  439. // Walk the entire region, count number of defs for each register, and
  440. // collect potential LICM candidates.
  441. for (MachineBasicBlock *BB : CurLoop->getBlocks()) {
  442. // If the header of the loop containing this basic block is a landing pad,
  443. // then don't try to hoist instructions out of this loop.
  444. const MachineLoop *ML = MLI->getLoopFor(BB);
  445. if (ML && ML->getHeader()->isEHPad()) continue;
  446. // Conservatively treat live-in's as an external def.
  447. // FIXME: That means a reload that're reused in successor block(s) will not
  448. // be LICM'ed.
  449. for (const auto &LI : BB->liveins()) {
  450. for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI)
  451. PhysRegDefs.set(*AI);
  452. }
  453. SpeculationState = SpeculateUnknown;
  454. for (MachineInstr &MI : *BB)
  455. ProcessMI(&MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
  456. }
  457. // Gather the registers read / clobbered by the terminator.
  458. BitVector TermRegs(NumRegs);
  459. MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
  460. if (TI != Preheader->end()) {
  461. for (const MachineOperand &MO : TI->operands()) {
  462. if (!MO.isReg())
  463. continue;
  464. Register Reg = MO.getReg();
  465. if (!Reg)
  466. continue;
  467. for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
  468. TermRegs.set(*AI);
  469. }
  470. }
  471. // Now evaluate whether the potential candidates qualify.
  472. // 1. Check if the candidate defined register is defined by another
  473. // instruction in the loop.
  474. // 2. If the candidate is a load from stack slot (always true for now),
  475. // check if the slot is stored anywhere in the loop.
  476. // 3. Make sure candidate def should not clobber
  477. // registers read by the terminator. Similarly its def should not be
  478. // clobbered by the terminator.
  479. for (CandidateInfo &Candidate : Candidates) {
  480. if (Candidate.FI != std::numeric_limits<int>::min() &&
  481. StoredFIs.count(Candidate.FI))
  482. continue;
  483. unsigned Def = Candidate.Def;
  484. if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
  485. bool Safe = true;
  486. MachineInstr *MI = Candidate.MI;
  487. for (const MachineOperand &MO : MI->operands()) {
  488. if (!MO.isReg() || MO.isDef() || !MO.getReg())
  489. continue;
  490. Register Reg = MO.getReg();
  491. if (PhysRegDefs.test(Reg) ||
  492. PhysRegClobbers.test(Reg)) {
  493. // If it's using a non-loop-invariant register, then it's obviously
  494. // not safe to hoist.
  495. Safe = false;
  496. break;
  497. }
  498. }
  499. if (Safe)
  500. HoistPostRA(MI, Candidate.Def);
  501. }
  502. }
  503. }
  504. /// Add register 'Reg' to the livein sets of BBs in the current loop, and make
  505. /// sure it is not killed by any instructions in the loop.
  506. void MachineLICMBase::AddToLiveIns(MCRegister Reg) {
  507. for (MachineBasicBlock *BB : CurLoop->getBlocks()) {
  508. if (!BB->isLiveIn(Reg))
  509. BB->addLiveIn(Reg);
  510. for (MachineInstr &MI : *BB) {
  511. for (MachineOperand &MO : MI.operands()) {
  512. if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
  513. if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
  514. MO.setIsKill(false);
  515. }
  516. }
  517. }
  518. }
  519. /// When an instruction is found to only use loop invariant operands that is
  520. /// safe to hoist, this instruction is called to do the dirty work.
  521. void MachineLICMBase::HoistPostRA(MachineInstr *MI, unsigned Def) {
  522. MachineBasicBlock *Preheader = getCurPreheader();
  523. // Now move the instructions to the predecessor, inserting it before any
  524. // terminator instructions.
  525. LLVM_DEBUG(dbgs() << "Hoisting to " << printMBBReference(*Preheader)
  526. << " from " << printMBBReference(*MI->getParent()) << ": "
  527. << *MI);
  528. // Splice the instruction to the preheader.
  529. MachineBasicBlock *MBB = MI->getParent();
  530. Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
  531. // Since we are moving the instruction out of its basic block, we do not
  532. // retain its debug location. Doing so would degrade the debugging
  533. // experience and adversely affect the accuracy of profiling information.
  534. assert(!MI->isDebugInstr() && "Should not hoist debug inst");
  535. MI->setDebugLoc(DebugLoc());
  536. // Add register to livein list to all the BBs in the current loop since a
  537. // loop invariant must be kept live throughout the whole loop. This is
  538. // important to ensure later passes do not scavenge the def register.
  539. AddToLiveIns(Def);
  540. ++NumPostRAHoisted;
  541. Changed = true;
  542. }
  543. /// Check if this mbb is guaranteed to execute. If not then a load from this mbb
  544. /// may not be safe to hoist.
  545. bool MachineLICMBase::IsGuaranteedToExecute(MachineBasicBlock *BB) {
  546. if (SpeculationState != SpeculateUnknown)
  547. return SpeculationState == SpeculateFalse;
  548. if (BB != CurLoop->getHeader()) {
  549. // Check loop exiting blocks.
  550. SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
  551. CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
  552. for (MachineBasicBlock *CurrentLoopExitingBlock : CurrentLoopExitingBlocks)
  553. if (!DT->dominates(BB, CurrentLoopExitingBlock)) {
  554. SpeculationState = SpeculateTrue;
  555. return false;
  556. }
  557. }
  558. SpeculationState = SpeculateFalse;
  559. return true;
  560. }
  561. /// Check if \p MI is trivially remateralizable and if it does not have any
  562. /// virtual register uses. Even though rematerializable RA might not actually
  563. /// rematerialize it in this scenario. In that case we do not want to hoist such
  564. /// instruction out of the loop in a belief RA will sink it back if needed.
  565. bool MachineLICMBase::isTriviallyReMaterializable(const MachineInstr &MI,
  566. AAResults *AA) const {
  567. if (!TII->isTriviallyReMaterializable(MI, AA))
  568. return false;
  569. for (const MachineOperand &MO : MI.operands()) {
  570. if (MO.isReg() && MO.isUse() && MO.getReg().isVirtual())
  571. return false;
  572. }
  573. return true;
  574. }
  575. void MachineLICMBase::EnterScope(MachineBasicBlock *MBB) {
  576. LLVM_DEBUG(dbgs() << "Entering " << printMBBReference(*MBB) << '\n');
  577. // Remember livein register pressure.
  578. BackTrace.push_back(RegPressure);
  579. }
  580. void MachineLICMBase::ExitScope(MachineBasicBlock *MBB) {
  581. LLVM_DEBUG(dbgs() << "Exiting " << printMBBReference(*MBB) << '\n');
  582. BackTrace.pop_back();
  583. }
  584. /// Destroy scope for the MBB that corresponds to the given dominator tree node
  585. /// if its a leaf or all of its children are done. Walk up the dominator tree to
  586. /// destroy ancestors which are now done.
  587. void MachineLICMBase::ExitScopeIfDone(MachineDomTreeNode *Node,
  588. DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
  589. DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
  590. if (OpenChildren[Node])
  591. return;
  592. // Pop scope.
  593. ExitScope(Node->getBlock());
  594. // Now traverse upwards to pop ancestors whose offsprings are all done.
  595. while (MachineDomTreeNode *Parent = ParentMap[Node]) {
  596. unsigned Left = --OpenChildren[Parent];
  597. if (Left != 0)
  598. break;
  599. ExitScope(Parent->getBlock());
  600. Node = Parent;
  601. }
  602. }
  603. /// Walk the specified loop in the CFG (defined by all blocks dominated by the
  604. /// specified header block, and that are in the current loop) in depth first
  605. /// order w.r.t the DominatorTree. This allows us to visit definitions before
  606. /// uses, allowing us to hoist a loop body in one pass without iteration.
  607. void MachineLICMBase::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
  608. MachineBasicBlock *Preheader = getCurPreheader();
  609. if (!Preheader)
  610. return;
  611. SmallVector<MachineDomTreeNode*, 32> Scopes;
  612. SmallVector<MachineDomTreeNode*, 8> WorkList;
  613. DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
  614. DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
  615. // Perform a DFS walk to determine the order of visit.
  616. WorkList.push_back(HeaderN);
  617. while (!WorkList.empty()) {
  618. MachineDomTreeNode *Node = WorkList.pop_back_val();
  619. assert(Node && "Null dominator tree node?");
  620. MachineBasicBlock *BB = Node->getBlock();
  621. // If the header of the loop containing this basic block is a landing pad,
  622. // then don't try to hoist instructions out of this loop.
  623. const MachineLoop *ML = MLI->getLoopFor(BB);
  624. if (ML && ML->getHeader()->isEHPad())
  625. continue;
  626. // If this subregion is not in the top level loop at all, exit.
  627. if (!CurLoop->contains(BB))
  628. continue;
  629. Scopes.push_back(Node);
  630. unsigned NumChildren = Node->getNumChildren();
  631. // Don't hoist things out of a large switch statement. This often causes
  632. // code to be hoisted that wasn't going to be executed, and increases
  633. // register pressure in a situation where it's likely to matter.
  634. if (BB->succ_size() >= 25)
  635. NumChildren = 0;
  636. OpenChildren[Node] = NumChildren;
  637. if (NumChildren) {
  638. // Add children in reverse order as then the next popped worklist node is
  639. // the first child of this node. This means we ultimately traverse the
  640. // DOM tree in exactly the same order as if we'd recursed.
  641. for (MachineDomTreeNode *Child : reverse(Node->children())) {
  642. ParentMap[Child] = Node;
  643. WorkList.push_back(Child);
  644. }
  645. }
  646. }
  647. if (Scopes.size() == 0)
  648. return;
  649. // Compute registers which are livein into the loop headers.
  650. RegSeen.clear();
  651. BackTrace.clear();
  652. InitRegPressure(Preheader);
  653. // Now perform LICM.
  654. for (MachineDomTreeNode *Node : Scopes) {
  655. MachineBasicBlock *MBB = Node->getBlock();
  656. EnterScope(MBB);
  657. // Process the block
  658. SpeculationState = SpeculateUnknown;
  659. for (MachineInstr &MI : llvm::make_early_inc_range(*MBB)) {
  660. if (!Hoist(&MI, Preheader))
  661. UpdateRegPressure(&MI);
  662. // If we have hoisted an instruction that may store, it can only be a
  663. // constant store.
  664. }
  665. // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
  666. ExitScopeIfDone(Node, OpenChildren, ParentMap);
  667. }
  668. }
  669. static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
  670. return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
  671. }
  672. /// Find all virtual register references that are liveout of the preheader to
  673. /// initialize the starting "register pressure". Note this does not count live
  674. /// through (livein but not used) registers.
  675. void MachineLICMBase::InitRegPressure(MachineBasicBlock *BB) {
  676. std::fill(RegPressure.begin(), RegPressure.end(), 0);
  677. // If the preheader has only a single predecessor and it ends with a
  678. // fallthrough or an unconditional branch, then scan its predecessor for live
  679. // defs as well. This happens whenever the preheader is created by splitting
  680. // the critical edge from the loop predecessor to the loop header.
  681. if (BB->pred_size() == 1) {
  682. MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
  683. SmallVector<MachineOperand, 4> Cond;
  684. if (!TII->analyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
  685. InitRegPressure(*BB->pred_begin());
  686. }
  687. for (const MachineInstr &MI : *BB)
  688. UpdateRegPressure(&MI, /*ConsiderUnseenAsDef=*/true);
  689. }
  690. /// Update estimate of register pressure after the specified instruction.
  691. void MachineLICMBase::UpdateRegPressure(const MachineInstr *MI,
  692. bool ConsiderUnseenAsDef) {
  693. auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/true, ConsiderUnseenAsDef);
  694. for (const auto &RPIdAndCost : Cost) {
  695. unsigned Class = RPIdAndCost.first;
  696. if (static_cast<int>(RegPressure[Class]) < -RPIdAndCost.second)
  697. RegPressure[Class] = 0;
  698. else
  699. RegPressure[Class] += RPIdAndCost.second;
  700. }
  701. }
  702. /// Calculate the additional register pressure that the registers used in MI
  703. /// cause.
  704. ///
  705. /// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to
  706. /// figure out which usages are live-ins.
  707. /// FIXME: Figure out a way to consider 'RegSeen' from all code paths.
  708. DenseMap<unsigned, int>
  709. MachineLICMBase::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen,
  710. bool ConsiderUnseenAsDef) {
  711. DenseMap<unsigned, int> Cost;
  712. if (MI->isImplicitDef())
  713. return Cost;
  714. for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
  715. const MachineOperand &MO = MI->getOperand(i);
  716. if (!MO.isReg() || MO.isImplicit())
  717. continue;
  718. Register Reg = MO.getReg();
  719. if (!Register::isVirtualRegister(Reg))
  720. continue;
  721. // FIXME: It seems bad to use RegSeen only for some of these calculations.
  722. bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false;
  723. const TargetRegisterClass *RC = MRI->getRegClass(Reg);
  724. RegClassWeight W = TRI->getRegClassWeight(RC);
  725. int RCCost = 0;
  726. if (MO.isDef())
  727. RCCost = W.RegWeight;
  728. else {
  729. bool isKill = isOperandKill(MO, MRI);
  730. if (isNew && !isKill && ConsiderUnseenAsDef)
  731. // Haven't seen this, it must be a livein.
  732. RCCost = W.RegWeight;
  733. else if (!isNew && isKill)
  734. RCCost = -W.RegWeight;
  735. }
  736. if (RCCost == 0)
  737. continue;
  738. const int *PS = TRI->getRegClassPressureSets(RC);
  739. for (; *PS != -1; ++PS) {
  740. if (Cost.find(*PS) == Cost.end())
  741. Cost[*PS] = RCCost;
  742. else
  743. Cost[*PS] += RCCost;
  744. }
  745. }
  746. return Cost;
  747. }
  748. /// Return true if this machine instruction loads from global offset table or
  749. /// constant pool.
  750. static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) {
  751. assert(MI.mayLoad() && "Expected MI that loads!");
  752. // If we lost memory operands, conservatively assume that the instruction
  753. // reads from everything..
  754. if (MI.memoperands_empty())
  755. return true;
  756. for (MachineMemOperand *MemOp : MI.memoperands())
  757. if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
  758. if (PSV->isGOT() || PSV->isConstantPool())
  759. return true;
  760. return false;
  761. }
  762. // This function iterates through all the operands of the input store MI and
  763. // checks that each register operand statisfies isCallerPreservedPhysReg.
  764. // This means, the value being stored and the address where it is being stored
  765. // is constant throughout the body of the function (not including prologue and
  766. // epilogue). When called with an MI that isn't a store, it returns false.
  767. // A future improvement can be to check if the store registers are constant
  768. // throughout the loop rather than throughout the funtion.
  769. static bool isInvariantStore(const MachineInstr &MI,
  770. const TargetRegisterInfo *TRI,
  771. const MachineRegisterInfo *MRI) {
  772. bool FoundCallerPresReg = false;
  773. if (!MI.mayStore() || MI.hasUnmodeledSideEffects() ||
  774. (MI.getNumOperands() == 0))
  775. return false;
  776. // Check that all register operands are caller-preserved physical registers.
  777. for (const MachineOperand &MO : MI.operands()) {
  778. if (MO.isReg()) {
  779. Register Reg = MO.getReg();
  780. // If operand is a virtual register, check if it comes from a copy of a
  781. // physical register.
  782. if (Register::isVirtualRegister(Reg))
  783. Reg = TRI->lookThruCopyLike(MO.getReg(), MRI);
  784. if (Register::isVirtualRegister(Reg))
  785. return false;
  786. if (!TRI->isCallerPreservedPhysReg(Reg.asMCReg(), *MI.getMF()))
  787. return false;
  788. else
  789. FoundCallerPresReg = true;
  790. } else if (!MO.isImm()) {
  791. return false;
  792. }
  793. }
  794. return FoundCallerPresReg;
  795. }
  796. // Return true if the input MI is a copy instruction that feeds an invariant
  797. // store instruction. This means that the src of the copy has to satisfy
  798. // isCallerPreservedPhysReg and atleast one of it's users should satisfy
  799. // isInvariantStore.
  800. static bool isCopyFeedingInvariantStore(const MachineInstr &MI,
  801. const MachineRegisterInfo *MRI,
  802. const TargetRegisterInfo *TRI) {
  803. // FIXME: If targets would like to look through instructions that aren't
  804. // pure copies, this can be updated to a query.
  805. if (!MI.isCopy())
  806. return false;
  807. const MachineFunction *MF = MI.getMF();
  808. // Check that we are copying a constant physical register.
  809. Register CopySrcReg = MI.getOperand(1).getReg();
  810. if (Register::isVirtualRegister(CopySrcReg))
  811. return false;
  812. if (!TRI->isCallerPreservedPhysReg(CopySrcReg.asMCReg(), *MF))
  813. return false;
  814. Register CopyDstReg = MI.getOperand(0).getReg();
  815. // Check if any of the uses of the copy are invariant stores.
  816. assert(Register::isVirtualRegister(CopyDstReg) &&
  817. "copy dst is not a virtual reg");
  818. for (MachineInstr &UseMI : MRI->use_instructions(CopyDstReg)) {
  819. if (UseMI.mayStore() && isInvariantStore(UseMI, TRI, MRI))
  820. return true;
  821. }
  822. return false;
  823. }
  824. /// Returns true if the instruction may be a suitable candidate for LICM.
  825. /// e.g. If the instruction is a call, then it's obviously not safe to hoist it.
  826. bool MachineLICMBase::IsLICMCandidate(MachineInstr &I) {
  827. // Check if it's safe to move the instruction.
  828. bool DontMoveAcrossStore = true;
  829. if ((!I.isSafeToMove(AA, DontMoveAcrossStore)) &&
  830. !(HoistConstStores && isInvariantStore(I, TRI, MRI))) {
  831. LLVM_DEBUG(dbgs() << "LICM: Instruction not safe to move.\n");
  832. return false;
  833. }
  834. // If it is a load then check if it is guaranteed to execute by making sure
  835. // that it dominates all exiting blocks. If it doesn't, then there is a path
  836. // out of the loop which does not execute this load, so we can't hoist it.
  837. // Loads from constant memory are safe to speculate, for example indexed load
  838. // from a jump table.
  839. // Stores and side effects are already checked by isSafeToMove.
  840. if (I.mayLoad() && !mayLoadFromGOTOrConstantPool(I) &&
  841. !IsGuaranteedToExecute(I.getParent())) {
  842. LLVM_DEBUG(dbgs() << "LICM: Load not guaranteed to execute.\n");
  843. return false;
  844. }
  845. // Convergent attribute has been used on operations that involve inter-thread
  846. // communication which results are implicitly affected by the enclosing
  847. // control flows. It is not safe to hoist or sink such operations across
  848. // control flow.
  849. if (I.isConvergent())
  850. return false;
  851. return true;
  852. }
  853. /// Returns true if the instruction is loop invariant.
  854. bool MachineLICMBase::IsLoopInvariantInst(MachineInstr &I) {
  855. if (!IsLICMCandidate(I)) {
  856. LLVM_DEBUG(dbgs() << "LICM: Instruction not a LICM candidate\n");
  857. return false;
  858. }
  859. return CurLoop->isLoopInvariant(I);
  860. }
  861. /// Return true if the specified instruction is used by a phi node and hoisting
  862. /// it could cause a copy to be inserted.
  863. bool MachineLICMBase::HasLoopPHIUse(const MachineInstr *MI) const {
  864. SmallVector<const MachineInstr*, 8> Work(1, MI);
  865. do {
  866. MI = Work.pop_back_val();
  867. for (const MachineOperand &MO : MI->operands()) {
  868. if (!MO.isReg() || !MO.isDef())
  869. continue;
  870. Register Reg = MO.getReg();
  871. if (!Register::isVirtualRegister(Reg))
  872. continue;
  873. for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
  874. // A PHI may cause a copy to be inserted.
  875. if (UseMI.isPHI()) {
  876. // A PHI inside the loop causes a copy because the live range of Reg is
  877. // extended across the PHI.
  878. if (CurLoop->contains(&UseMI))
  879. return true;
  880. // A PHI in an exit block can cause a copy to be inserted if the PHI
  881. // has multiple predecessors in the loop with different values.
  882. // For now, approximate by rejecting all exit blocks.
  883. if (isExitBlock(UseMI.getParent()))
  884. return true;
  885. continue;
  886. }
  887. // Look past copies as well.
  888. if (UseMI.isCopy() && CurLoop->contains(&UseMI))
  889. Work.push_back(&UseMI);
  890. }
  891. }
  892. } while (!Work.empty());
  893. return false;
  894. }
  895. /// Compute operand latency between a def of 'Reg' and an use in the current
  896. /// loop, return true if the target considered it high.
  897. bool MachineLICMBase::HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
  898. Register Reg) const {
  899. if (MRI->use_nodbg_empty(Reg))
  900. return false;
  901. for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
  902. if (UseMI.isCopyLike())
  903. continue;
  904. if (!CurLoop->contains(UseMI.getParent()))
  905. continue;
  906. for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
  907. const MachineOperand &MO = UseMI.getOperand(i);
  908. if (!MO.isReg() || !MO.isUse())
  909. continue;
  910. Register MOReg = MO.getReg();
  911. if (MOReg != Reg)
  912. continue;
  913. if (TII->hasHighOperandLatency(SchedModel, MRI, MI, DefIdx, UseMI, i))
  914. return true;
  915. }
  916. // Only look at the first in loop use.
  917. break;
  918. }
  919. return false;
  920. }
  921. /// Return true if the instruction is marked "cheap" or the operand latency
  922. /// between its def and a use is one or less.
  923. bool MachineLICMBase::IsCheapInstruction(MachineInstr &MI) const {
  924. if (TII->isAsCheapAsAMove(MI) || MI.isCopyLike())
  925. return true;
  926. bool isCheap = false;
  927. unsigned NumDefs = MI.getDesc().getNumDefs();
  928. for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
  929. MachineOperand &DefMO = MI.getOperand(i);
  930. if (!DefMO.isReg() || !DefMO.isDef())
  931. continue;
  932. --NumDefs;
  933. Register Reg = DefMO.getReg();
  934. if (Register::isPhysicalRegister(Reg))
  935. continue;
  936. if (!TII->hasLowDefLatency(SchedModel, MI, i))
  937. return false;
  938. isCheap = true;
  939. }
  940. return isCheap;
  941. }
  942. /// Visit BBs from header to current BB, check if hoisting an instruction of the
  943. /// given cost matrix can cause high register pressure.
  944. bool
  945. MachineLICMBase::CanCauseHighRegPressure(const DenseMap<unsigned, int>& Cost,
  946. bool CheapInstr) {
  947. for (const auto &RPIdAndCost : Cost) {
  948. if (RPIdAndCost.second <= 0)
  949. continue;
  950. unsigned Class = RPIdAndCost.first;
  951. int Limit = RegLimit[Class];
  952. // Don't hoist cheap instructions if they would increase register pressure,
  953. // even if we're under the limit.
  954. if (CheapInstr && !HoistCheapInsts)
  955. return true;
  956. for (const auto &RP : BackTrace)
  957. if (static_cast<int>(RP[Class]) + RPIdAndCost.second >= Limit)
  958. return true;
  959. }
  960. return false;
  961. }
  962. /// Traverse the back trace from header to the current block and update their
  963. /// register pressures to reflect the effect of hoisting MI from the current
  964. /// block to the preheader.
  965. void MachineLICMBase::UpdateBackTraceRegPressure(const MachineInstr *MI) {
  966. // First compute the 'cost' of the instruction, i.e. its contribution
  967. // to register pressure.
  968. auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/false,
  969. /*ConsiderUnseenAsDef=*/false);
  970. // Update register pressure of blocks from loop header to current block.
  971. for (auto &RP : BackTrace)
  972. for (const auto &RPIdAndCost : Cost)
  973. RP[RPIdAndCost.first] += RPIdAndCost.second;
  974. }
  975. /// Return true if it is potentially profitable to hoist the given loop
  976. /// invariant.
  977. bool MachineLICMBase::IsProfitableToHoist(MachineInstr &MI) {
  978. if (MI.isImplicitDef())
  979. return true;
  980. // Besides removing computation from the loop, hoisting an instruction has
  981. // these effects:
  982. //
  983. // - The value defined by the instruction becomes live across the entire
  984. // loop. This increases register pressure in the loop.
  985. //
  986. // - If the value is used by a PHI in the loop, a copy will be required for
  987. // lowering the PHI after extending the live range.
  988. //
  989. // - When hoisting the last use of a value in the loop, that value no longer
  990. // needs to be live in the loop. This lowers register pressure in the loop.
  991. if (HoistConstStores && isCopyFeedingInvariantStore(MI, MRI, TRI))
  992. return true;
  993. bool CheapInstr = IsCheapInstruction(MI);
  994. bool CreatesCopy = HasLoopPHIUse(&MI);
  995. // Don't hoist a cheap instruction if it would create a copy in the loop.
  996. if (CheapInstr && CreatesCopy) {
  997. LLVM_DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
  998. return false;
  999. }
  1000. // Rematerializable instructions should always be hoisted providing the
  1001. // register allocator can just pull them down again when needed.
  1002. if (isTriviallyReMaterializable(MI, AA))
  1003. return true;
  1004. // FIXME: If there are long latency loop-invariant instructions inside the
  1005. // loop at this point, why didn't the optimizer's LICM hoist them?
  1006. for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
  1007. const MachineOperand &MO = MI.getOperand(i);
  1008. if (!MO.isReg() || MO.isImplicit())
  1009. continue;
  1010. Register Reg = MO.getReg();
  1011. if (!Register::isVirtualRegister(Reg))
  1012. continue;
  1013. if (MO.isDef() && HasHighOperandLatency(MI, i, Reg)) {
  1014. LLVM_DEBUG(dbgs() << "Hoist High Latency: " << MI);
  1015. ++NumHighLatency;
  1016. return true;
  1017. }
  1018. }
  1019. // Estimate register pressure to determine whether to LICM the instruction.
  1020. // In low register pressure situation, we can be more aggressive about
  1021. // hoisting. Also, favors hoisting long latency instructions even in
  1022. // moderately high pressure situation.
  1023. // Cheap instructions will only be hoisted if they don't increase register
  1024. // pressure at all.
  1025. auto Cost = calcRegisterCost(&MI, /*ConsiderSeen=*/false,
  1026. /*ConsiderUnseenAsDef=*/false);
  1027. // Visit BBs from header to current BB, if hoisting this doesn't cause
  1028. // high register pressure, then it's safe to proceed.
  1029. if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
  1030. LLVM_DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
  1031. ++NumLowRP;
  1032. return true;
  1033. }
  1034. // Don't risk increasing register pressure if it would create copies.
  1035. if (CreatesCopy) {
  1036. LLVM_DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
  1037. return false;
  1038. }
  1039. // Do not "speculate" in high register pressure situation. If an
  1040. // instruction is not guaranteed to be executed in the loop, it's best to be
  1041. // conservative.
  1042. if (AvoidSpeculation &&
  1043. (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
  1044. LLVM_DEBUG(dbgs() << "Won't speculate: " << MI);
  1045. return false;
  1046. }
  1047. // High register pressure situation, only hoist if the instruction is going
  1048. // to be remat'ed.
  1049. if (!isTriviallyReMaterializable(MI, AA) &&
  1050. !MI.isDereferenceableInvariantLoad(AA)) {
  1051. LLVM_DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
  1052. return false;
  1053. }
  1054. return true;
  1055. }
  1056. /// Unfold a load from the given machineinstr if the load itself could be
  1057. /// hoisted. Return the unfolded and hoistable load, or null if the load
  1058. /// couldn't be unfolded or if it wouldn't be hoistable.
  1059. MachineInstr *MachineLICMBase::ExtractHoistableLoad(MachineInstr *MI) {
  1060. // Don't unfold simple loads.
  1061. if (MI->canFoldAsLoad())
  1062. return nullptr;
  1063. // If not, we may be able to unfold a load and hoist that.
  1064. // First test whether the instruction is loading from an amenable
  1065. // memory location.
  1066. if (!MI->isDereferenceableInvariantLoad(AA))
  1067. return nullptr;
  1068. // Next determine the register class for a temporary register.
  1069. unsigned LoadRegIndex;
  1070. unsigned NewOpc =
  1071. TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
  1072. /*UnfoldLoad=*/true,
  1073. /*UnfoldStore=*/false,
  1074. &LoadRegIndex);
  1075. if (NewOpc == 0) return nullptr;
  1076. const MCInstrDesc &MID = TII->get(NewOpc);
  1077. MachineFunction &MF = *MI->getMF();
  1078. const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
  1079. // Ok, we're unfolding. Create a temporary register and do the unfold.
  1080. Register Reg = MRI->createVirtualRegister(RC);
  1081. SmallVector<MachineInstr *, 2> NewMIs;
  1082. bool Success = TII->unfoldMemoryOperand(MF, *MI, Reg,
  1083. /*UnfoldLoad=*/true,
  1084. /*UnfoldStore=*/false, NewMIs);
  1085. (void)Success;
  1086. assert(Success &&
  1087. "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
  1088. "succeeded!");
  1089. assert(NewMIs.size() == 2 &&
  1090. "Unfolded a load into multiple instructions!");
  1091. MachineBasicBlock *MBB = MI->getParent();
  1092. MachineBasicBlock::iterator Pos = MI;
  1093. MBB->insert(Pos, NewMIs[0]);
  1094. MBB->insert(Pos, NewMIs[1]);
  1095. // If unfolding produced a load that wasn't loop-invariant or profitable to
  1096. // hoist, discard the new instructions and bail.
  1097. if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
  1098. NewMIs[0]->eraseFromParent();
  1099. NewMIs[1]->eraseFromParent();
  1100. return nullptr;
  1101. }
  1102. // Update register pressure for the unfolded instruction.
  1103. UpdateRegPressure(NewMIs[1]);
  1104. // Otherwise we successfully unfolded a load that we can hoist.
  1105. // Update the call site info.
  1106. if (MI->shouldUpdateCallSiteInfo())
  1107. MF.eraseCallSiteInfo(MI);
  1108. MI->eraseFromParent();
  1109. return NewMIs[0];
  1110. }
  1111. /// Initialize the CSE map with instructions that are in the current loop
  1112. /// preheader that may become duplicates of instructions that are hoisted
  1113. /// out of the loop.
  1114. void MachineLICMBase::InitCSEMap(MachineBasicBlock *BB) {
  1115. for (MachineInstr &MI : *BB)
  1116. CSEMap[MI.getOpcode()].push_back(&MI);
  1117. }
  1118. /// Find an instruction amount PrevMIs that is a duplicate of MI.
  1119. /// Return this instruction if it's found.
  1120. MachineInstr *
  1121. MachineLICMBase::LookForDuplicate(const MachineInstr *MI,
  1122. std::vector<MachineInstr *> &PrevMIs) {
  1123. for (MachineInstr *PrevMI : PrevMIs)
  1124. if (TII->produceSameValue(*MI, *PrevMI, (PreRegAlloc ? MRI : nullptr)))
  1125. return PrevMI;
  1126. return nullptr;
  1127. }
  1128. /// Given a LICM'ed instruction, look for an instruction on the preheader that
  1129. /// computes the same value. If it's found, do a RAU on with the definition of
  1130. /// the existing instruction rather than hoisting the instruction to the
  1131. /// preheader.
  1132. bool MachineLICMBase::EliminateCSE(
  1133. MachineInstr *MI,
  1134. DenseMap<unsigned, std::vector<MachineInstr *>>::iterator &CI) {
  1135. // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
  1136. // the undef property onto uses.
  1137. if (CI == CSEMap.end() || MI->isImplicitDef())
  1138. return false;
  1139. if (MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
  1140. LLVM_DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
  1141. // Replace virtual registers defined by MI by their counterparts defined
  1142. // by Dup.
  1143. SmallVector<unsigned, 2> Defs;
  1144. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  1145. const MachineOperand &MO = MI->getOperand(i);
  1146. // Physical registers may not differ here.
  1147. assert((!MO.isReg() || MO.getReg() == 0 ||
  1148. !Register::isPhysicalRegister(MO.getReg()) ||
  1149. MO.getReg() == Dup->getOperand(i).getReg()) &&
  1150. "Instructions with different phys regs are not identical!");
  1151. if (MO.isReg() && MO.isDef() &&
  1152. !Register::isPhysicalRegister(MO.getReg()))
  1153. Defs.push_back(i);
  1154. }
  1155. SmallVector<const TargetRegisterClass*, 2> OrigRCs;
  1156. for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
  1157. unsigned Idx = Defs[i];
  1158. Register Reg = MI->getOperand(Idx).getReg();
  1159. Register DupReg = Dup->getOperand(Idx).getReg();
  1160. OrigRCs.push_back(MRI->getRegClass(DupReg));
  1161. if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
  1162. // Restore old RCs if more than one defs.
  1163. for (unsigned j = 0; j != i; ++j)
  1164. MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
  1165. return false;
  1166. }
  1167. }
  1168. for (unsigned Idx : Defs) {
  1169. Register Reg = MI->getOperand(Idx).getReg();
  1170. Register DupReg = Dup->getOperand(Idx).getReg();
  1171. MRI->replaceRegWith(Reg, DupReg);
  1172. MRI->clearKillFlags(DupReg);
  1173. // Clear Dup dead flag if any, we reuse it for Reg.
  1174. if (!MRI->use_nodbg_empty(DupReg))
  1175. Dup->getOperand(Idx).setIsDead(false);
  1176. }
  1177. MI->eraseFromParent();
  1178. ++NumCSEed;
  1179. return true;
  1180. }
  1181. return false;
  1182. }
  1183. /// Return true if the given instruction will be CSE'd if it's hoisted out of
  1184. /// the loop.
  1185. bool MachineLICMBase::MayCSE(MachineInstr *MI) {
  1186. unsigned Opcode = MI->getOpcode();
  1187. DenseMap<unsigned, std::vector<MachineInstr *>>::iterator CI =
  1188. CSEMap.find(Opcode);
  1189. // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
  1190. // the undef property onto uses.
  1191. if (CI == CSEMap.end() || MI->isImplicitDef())
  1192. return false;
  1193. return LookForDuplicate(MI, CI->second) != nullptr;
  1194. }
  1195. /// When an instruction is found to use only loop invariant operands
  1196. /// that are safe to hoist, this instruction is called to do the dirty work.
  1197. /// It returns true if the instruction is hoisted.
  1198. bool MachineLICMBase::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
  1199. MachineBasicBlock *SrcBlock = MI->getParent();
  1200. // Disable the instruction hoisting due to block hotness
  1201. if ((DisableHoistingToHotterBlocks == UseBFI::All ||
  1202. (DisableHoistingToHotterBlocks == UseBFI::PGO && HasProfileData)) &&
  1203. isTgtHotterThanSrc(SrcBlock, Preheader)) {
  1204. ++NumNotHoistedDueToHotness;
  1205. return false;
  1206. }
  1207. // First check whether we should hoist this instruction.
  1208. if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
  1209. // If not, try unfolding a hoistable load.
  1210. MI = ExtractHoistableLoad(MI);
  1211. if (!MI) return false;
  1212. }
  1213. // If we have hoisted an instruction that may store, it can only be a constant
  1214. // store.
  1215. if (MI->mayStore())
  1216. NumStoreConst++;
  1217. // Now move the instructions to the predecessor, inserting it before any
  1218. // terminator instructions.
  1219. LLVM_DEBUG({
  1220. dbgs() << "Hoisting " << *MI;
  1221. if (MI->getParent()->getBasicBlock())
  1222. dbgs() << " from " << printMBBReference(*MI->getParent());
  1223. if (Preheader->getBasicBlock())
  1224. dbgs() << " to " << printMBBReference(*Preheader);
  1225. dbgs() << "\n";
  1226. });
  1227. // If this is the first instruction being hoisted to the preheader,
  1228. // initialize the CSE map with potential common expressions.
  1229. if (FirstInLoop) {
  1230. InitCSEMap(Preheader);
  1231. FirstInLoop = false;
  1232. }
  1233. // Look for opportunity to CSE the hoisted instruction.
  1234. unsigned Opcode = MI->getOpcode();
  1235. DenseMap<unsigned, std::vector<MachineInstr *>>::iterator CI =
  1236. CSEMap.find(Opcode);
  1237. if (!EliminateCSE(MI, CI)) {
  1238. // Otherwise, splice the instruction to the preheader.
  1239. Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
  1240. // Since we are moving the instruction out of its basic block, we do not
  1241. // retain its debug location. Doing so would degrade the debugging
  1242. // experience and adversely affect the accuracy of profiling information.
  1243. assert(!MI->isDebugInstr() && "Should not hoist debug inst");
  1244. MI->setDebugLoc(DebugLoc());
  1245. // Update register pressure for BBs from header to this block.
  1246. UpdateBackTraceRegPressure(MI);
  1247. // Clear the kill flags of any register this instruction defines,
  1248. // since they may need to be live throughout the entire loop
  1249. // rather than just live for part of it.
  1250. for (MachineOperand &MO : MI->operands())
  1251. if (MO.isReg() && MO.isDef() && !MO.isDead())
  1252. MRI->clearKillFlags(MO.getReg());
  1253. // Add to the CSE map.
  1254. if (CI != CSEMap.end())
  1255. CI->second.push_back(MI);
  1256. else
  1257. CSEMap[Opcode].push_back(MI);
  1258. }
  1259. ++NumHoisted;
  1260. Changed = true;
  1261. return true;
  1262. }
  1263. /// Get the preheader for the current loop, splitting a critical edge if needed.
  1264. MachineBasicBlock *MachineLICMBase::getCurPreheader() {
  1265. // Determine the block to which to hoist instructions. If we can't find a
  1266. // suitable loop predecessor, we can't do any hoisting.
  1267. // If we've tried to get a preheader and failed, don't try again.
  1268. if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
  1269. return nullptr;
  1270. if (!CurPreheader) {
  1271. CurPreheader = CurLoop->getLoopPreheader();
  1272. if (!CurPreheader) {
  1273. MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
  1274. if (!Pred) {
  1275. CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
  1276. return nullptr;
  1277. }
  1278. CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), *this);
  1279. if (!CurPreheader) {
  1280. CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
  1281. return nullptr;
  1282. }
  1283. }
  1284. }
  1285. return CurPreheader;
  1286. }
  1287. /// Is the target basic block at least "BlockFrequencyRatioThreshold"
  1288. /// times hotter than the source basic block.
  1289. bool MachineLICMBase::isTgtHotterThanSrc(MachineBasicBlock *SrcBlock,
  1290. MachineBasicBlock *TgtBlock) {
  1291. // Parse source and target basic block frequency from MBFI
  1292. uint64_t SrcBF = MBFI->getBlockFreq(SrcBlock).getFrequency();
  1293. uint64_t DstBF = MBFI->getBlockFreq(TgtBlock).getFrequency();
  1294. // Disable the hoisting if source block frequency is zero
  1295. if (!SrcBF)
  1296. return true;
  1297. double Ratio = (double)DstBF / SrcBF;
  1298. // Compare the block frequency ratio with the threshold
  1299. return Ratio > BlockFrequencyRatioThreshold;
  1300. }