PeepholeOptimizer.cpp 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114
  1. //===- PeepholeOptimizer.cpp - Peephole Optimizations ---------------------===//
  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. // Perform peephole optimizations on the machine code:
  10. //
  11. // - Optimize Extensions
  12. //
  13. // Optimization of sign / zero extension instructions. It may be extended to
  14. // handle other instructions with similar properties.
  15. //
  16. // On some targets, some instructions, e.g. X86 sign / zero extension, may
  17. // leave the source value in the lower part of the result. This optimization
  18. // will replace some uses of the pre-extension value with uses of the
  19. // sub-register of the results.
  20. //
  21. // - Optimize Comparisons
  22. //
  23. // Optimization of comparison instructions. For instance, in this code:
  24. //
  25. // sub r1, 1
  26. // cmp r1, 0
  27. // bz L1
  28. //
  29. // If the "sub" instruction all ready sets (or could be modified to set) the
  30. // same flag that the "cmp" instruction sets and that "bz" uses, then we can
  31. // eliminate the "cmp" instruction.
  32. //
  33. // Another instance, in this code:
  34. //
  35. // sub r1, r3 | sub r1, imm
  36. // cmp r3, r1 or cmp r1, r3 | cmp r1, imm
  37. // bge L1
  38. //
  39. // If the branch instruction can use flag from "sub", then we can replace
  40. // "sub" with "subs" and eliminate the "cmp" instruction.
  41. //
  42. // - Optimize Loads:
  43. //
  44. // Loads that can be folded into a later instruction. A load is foldable
  45. // if it loads to virtual registers and the virtual register defined has
  46. // a single use.
  47. //
  48. // - Optimize Copies and Bitcast (more generally, target specific copies):
  49. //
  50. // Rewrite copies and bitcasts to avoid cross register bank copies
  51. // when possible.
  52. // E.g., Consider the following example, where capital and lower
  53. // letters denote different register file:
  54. // b = copy A <-- cross-bank copy
  55. // C = copy b <-- cross-bank copy
  56. // =>
  57. // b = copy A <-- cross-bank copy
  58. // C = copy A <-- same-bank copy
  59. //
  60. // E.g., for bitcast:
  61. // b = bitcast A <-- cross-bank copy
  62. // C = bitcast b <-- cross-bank copy
  63. // =>
  64. // b = bitcast A <-- cross-bank copy
  65. // C = copy A <-- same-bank copy
  66. //===----------------------------------------------------------------------===//
  67. #include "llvm/ADT/DenseMap.h"
  68. #include "llvm/ADT/Optional.h"
  69. #include "llvm/ADT/SmallPtrSet.h"
  70. #include "llvm/ADT/SmallSet.h"
  71. #include "llvm/ADT/SmallVector.h"
  72. #include "llvm/ADT/Statistic.h"
  73. #include "llvm/CodeGen/MachineBasicBlock.h"
  74. #include "llvm/CodeGen/MachineDominators.h"
  75. #include "llvm/CodeGen/MachineFunction.h"
  76. #include "llvm/CodeGen/MachineFunctionPass.h"
  77. #include "llvm/CodeGen/MachineInstr.h"
  78. #include "llvm/CodeGen/MachineInstrBuilder.h"
  79. #include "llvm/CodeGen/MachineLoopInfo.h"
  80. #include "llvm/CodeGen/MachineOperand.h"
  81. #include "llvm/CodeGen/MachineRegisterInfo.h"
  82. #include "llvm/CodeGen/TargetInstrInfo.h"
  83. #include "llvm/CodeGen/TargetOpcodes.h"
  84. #include "llvm/CodeGen/TargetRegisterInfo.h"
  85. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  86. #include "llvm/MC/LaneBitmask.h"
  87. #include "llvm/MC/MCInstrDesc.h"
  88. #include "llvm/Pass.h"
  89. #include "llvm/Support/CommandLine.h"
  90. #include "llvm/Support/Debug.h"
  91. #include "llvm/Support/ErrorHandling.h"
  92. #include "llvm/Support/raw_ostream.h"
  93. #include <cassert>
  94. #include <cstdint>
  95. #include <memory>
  96. #include <utility>
  97. using namespace llvm;
  98. using RegSubRegPair = TargetInstrInfo::RegSubRegPair;
  99. using RegSubRegPairAndIdx = TargetInstrInfo::RegSubRegPairAndIdx;
  100. #define DEBUG_TYPE "peephole-opt"
  101. // Optimize Extensions
  102. static cl::opt<bool>
  103. Aggressive("aggressive-ext-opt", cl::Hidden,
  104. cl::desc("Aggressive extension optimization"));
  105. static cl::opt<bool>
  106. DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
  107. cl::desc("Disable the peephole optimizer"));
  108. /// Specifiy whether or not the value tracking looks through
  109. /// complex instructions. When this is true, the value tracker
  110. /// bails on everything that is not a copy or a bitcast.
  111. static cl::opt<bool>
  112. DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false),
  113. cl::desc("Disable advanced copy optimization"));
  114. static cl::opt<bool> DisableNAPhysCopyOpt(
  115. "disable-non-allocatable-phys-copy-opt", cl::Hidden, cl::init(false),
  116. cl::desc("Disable non-allocatable physical register copy optimization"));
  117. // Limit the number of PHI instructions to process
  118. // in PeepholeOptimizer::getNextSource.
  119. static cl::opt<unsigned> RewritePHILimit(
  120. "rewrite-phi-limit", cl::Hidden, cl::init(10),
  121. cl::desc("Limit the length of PHI chains to lookup"));
  122. // Limit the length of recurrence chain when evaluating the benefit of
  123. // commuting operands.
  124. static cl::opt<unsigned> MaxRecurrenceChain(
  125. "recurrence-chain-limit", cl::Hidden, cl::init(3),
  126. cl::desc("Maximum length of recurrence chain when evaluating the benefit "
  127. "of commuting operands"));
  128. STATISTIC(NumReuse, "Number of extension results reused");
  129. STATISTIC(NumCmps, "Number of compares eliminated");
  130. STATISTIC(NumImmFold, "Number of move immediate folded");
  131. STATISTIC(NumLoadFold, "Number of loads folded");
  132. STATISTIC(NumSelects, "Number of selects optimized");
  133. STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized");
  134. STATISTIC(NumRewrittenCopies, "Number of copies rewritten");
  135. STATISTIC(NumNAPhysCopies, "Number of non-allocatable physical copies removed");
  136. namespace {
  137. class ValueTrackerResult;
  138. class RecurrenceInstr;
  139. class PeepholeOptimizer : public MachineFunctionPass {
  140. const TargetInstrInfo *TII;
  141. const TargetRegisterInfo *TRI;
  142. MachineRegisterInfo *MRI;
  143. MachineDominatorTree *DT; // Machine dominator tree
  144. MachineLoopInfo *MLI;
  145. public:
  146. static char ID; // Pass identification
  147. PeepholeOptimizer() : MachineFunctionPass(ID) {
  148. initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
  149. }
  150. bool runOnMachineFunction(MachineFunction &MF) override;
  151. void getAnalysisUsage(AnalysisUsage &AU) const override {
  152. AU.setPreservesCFG();
  153. MachineFunctionPass::getAnalysisUsage(AU);
  154. AU.addRequired<MachineLoopInfo>();
  155. AU.addPreserved<MachineLoopInfo>();
  156. if (Aggressive) {
  157. AU.addRequired<MachineDominatorTree>();
  158. AU.addPreserved<MachineDominatorTree>();
  159. }
  160. }
  161. /// Track Def -> Use info used for rewriting copies.
  162. using RewriteMapTy = SmallDenseMap<RegSubRegPair, ValueTrackerResult>;
  163. /// Sequence of instructions that formulate recurrence cycle.
  164. using RecurrenceCycle = SmallVector<RecurrenceInstr, 4>;
  165. private:
  166. bool optimizeCmpInstr(MachineInstr &MI);
  167. bool optimizeExtInstr(MachineInstr &MI, MachineBasicBlock &MBB,
  168. SmallPtrSetImpl<MachineInstr*> &LocalMIs);
  169. bool optimizeSelect(MachineInstr &MI,
  170. SmallPtrSetImpl<MachineInstr *> &LocalMIs);
  171. bool optimizeCondBranch(MachineInstr &MI);
  172. bool optimizeCoalescableCopy(MachineInstr &MI);
  173. bool optimizeUncoalescableCopy(MachineInstr &MI,
  174. SmallPtrSetImpl<MachineInstr *> &LocalMIs);
  175. bool optimizeRecurrence(MachineInstr &PHI);
  176. bool findNextSource(RegSubRegPair RegSubReg, RewriteMapTy &RewriteMap);
  177. bool isMoveImmediate(MachineInstr &MI,
  178. SmallSet<unsigned, 4> &ImmDefRegs,
  179. DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
  180. bool foldImmediate(MachineInstr &MI, SmallSet<unsigned, 4> &ImmDefRegs,
  181. DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
  182. /// Finds recurrence cycles, but only ones that formulated around
  183. /// a def operand and a use operand that are tied. If there is a use
  184. /// operand commutable with the tied use operand, find recurrence cycle
  185. /// along that operand as well.
  186. bool findTargetRecurrence(unsigned Reg,
  187. const SmallSet<unsigned, 2> &TargetReg,
  188. RecurrenceCycle &RC);
  189. /// If copy instruction \p MI is a virtual register copy, track it in
  190. /// the set \p CopySrcRegs and \p CopyMIs. If this virtual register was
  191. /// previously seen as a copy, replace the uses of this copy with the
  192. /// previously seen copy's destination register.
  193. bool foldRedundantCopy(MachineInstr &MI,
  194. SmallSet<unsigned, 4> &CopySrcRegs,
  195. DenseMap<unsigned, MachineInstr *> &CopyMIs);
  196. /// Is the register \p Reg a non-allocatable physical register?
  197. bool isNAPhysCopy(unsigned Reg);
  198. /// If copy instruction \p MI is a non-allocatable virtual<->physical
  199. /// register copy, track it in the \p NAPhysToVirtMIs map. If this
  200. /// non-allocatable physical register was previously copied to a virtual
  201. /// registered and hasn't been clobbered, the virt->phys copy can be
  202. /// deleted.
  203. bool foldRedundantNAPhysCopy(MachineInstr &MI,
  204. DenseMap<unsigned, MachineInstr *> &NAPhysToVirtMIs);
  205. bool isLoadFoldable(MachineInstr &MI,
  206. SmallSet<unsigned, 16> &FoldAsLoadDefCandidates);
  207. /// Check whether \p MI is understood by the register coalescer
  208. /// but may require some rewriting.
  209. bool isCoalescableCopy(const MachineInstr &MI) {
  210. // SubregToRegs are not interesting, because they are already register
  211. // coalescer friendly.
  212. return MI.isCopy() || (!DisableAdvCopyOpt &&
  213. (MI.isRegSequence() || MI.isInsertSubreg() ||
  214. MI.isExtractSubreg()));
  215. }
  216. /// Check whether \p MI is a copy like instruction that is
  217. /// not recognized by the register coalescer.
  218. bool isUncoalescableCopy(const MachineInstr &MI) {
  219. return MI.isBitcast() ||
  220. (!DisableAdvCopyOpt &&
  221. (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
  222. MI.isExtractSubregLike()));
  223. }
  224. MachineInstr &rewriteSource(MachineInstr &CopyLike,
  225. RegSubRegPair Def, RewriteMapTy &RewriteMap);
  226. };
  227. /// Helper class to hold instructions that are inside recurrence cycles.
  228. /// The recurrence cycle is formulated around 1) a def operand and its
  229. /// tied use operand, or 2) a def operand and a use operand that is commutable
  230. /// with another use operand which is tied to the def operand. In the latter
  231. /// case, index of the tied use operand and the commutable use operand are
  232. /// maintained with CommutePair.
  233. class RecurrenceInstr {
  234. public:
  235. using IndexPair = std::pair<unsigned, unsigned>;
  236. RecurrenceInstr(MachineInstr *MI) : MI(MI) {}
  237. RecurrenceInstr(MachineInstr *MI, unsigned Idx1, unsigned Idx2)
  238. : MI(MI), CommutePair(std::make_pair(Idx1, Idx2)) {}
  239. MachineInstr *getMI() const { return MI; }
  240. Optional<IndexPair> getCommutePair() const { return CommutePair; }
  241. private:
  242. MachineInstr *MI;
  243. Optional<IndexPair> CommutePair;
  244. };
  245. /// Helper class to hold a reply for ValueTracker queries.
  246. /// Contains the returned sources for a given search and the instructions
  247. /// where the sources were tracked from.
  248. class ValueTrackerResult {
  249. private:
  250. /// Track all sources found by one ValueTracker query.
  251. SmallVector<RegSubRegPair, 2> RegSrcs;
  252. /// Instruction using the sources in 'RegSrcs'.
  253. const MachineInstr *Inst = nullptr;
  254. public:
  255. ValueTrackerResult() = default;
  256. ValueTrackerResult(unsigned Reg, unsigned SubReg) {
  257. addSource(Reg, SubReg);
  258. }
  259. bool isValid() const { return getNumSources() > 0; }
  260. void setInst(const MachineInstr *I) { Inst = I; }
  261. const MachineInstr *getInst() const { return Inst; }
  262. void clear() {
  263. RegSrcs.clear();
  264. Inst = nullptr;
  265. }
  266. void addSource(unsigned SrcReg, unsigned SrcSubReg) {
  267. RegSrcs.push_back(RegSubRegPair(SrcReg, SrcSubReg));
  268. }
  269. void setSource(int Idx, unsigned SrcReg, unsigned SrcSubReg) {
  270. assert(Idx < getNumSources() && "Reg pair source out of index");
  271. RegSrcs[Idx] = RegSubRegPair(SrcReg, SrcSubReg);
  272. }
  273. int getNumSources() const { return RegSrcs.size(); }
  274. RegSubRegPair getSrc(int Idx) const {
  275. return RegSrcs[Idx];
  276. }
  277. unsigned getSrcReg(int Idx) const {
  278. assert(Idx < getNumSources() && "Reg source out of index");
  279. return RegSrcs[Idx].Reg;
  280. }
  281. unsigned getSrcSubReg(int Idx) const {
  282. assert(Idx < getNumSources() && "SubReg source out of index");
  283. return RegSrcs[Idx].SubReg;
  284. }
  285. bool operator==(const ValueTrackerResult &Other) {
  286. if (Other.getInst() != getInst())
  287. return false;
  288. if (Other.getNumSources() != getNumSources())
  289. return false;
  290. for (int i = 0, e = Other.getNumSources(); i != e; ++i)
  291. if (Other.getSrcReg(i) != getSrcReg(i) ||
  292. Other.getSrcSubReg(i) != getSrcSubReg(i))
  293. return false;
  294. return true;
  295. }
  296. };
  297. /// Helper class to track the possible sources of a value defined by
  298. /// a (chain of) copy related instructions.
  299. /// Given a definition (instruction and definition index), this class
  300. /// follows the use-def chain to find successive suitable sources.
  301. /// The given source can be used to rewrite the definition into
  302. /// def = COPY src.
  303. ///
  304. /// For instance, let us consider the following snippet:
  305. /// v0 =
  306. /// v2 = INSERT_SUBREG v1, v0, sub0
  307. /// def = COPY v2.sub0
  308. ///
  309. /// Using a ValueTracker for def = COPY v2.sub0 will give the following
  310. /// suitable sources:
  311. /// v2.sub0 and v0.
  312. /// Then, def can be rewritten into def = COPY v0.
  313. class ValueTracker {
  314. private:
  315. /// The current point into the use-def chain.
  316. const MachineInstr *Def = nullptr;
  317. /// The index of the definition in Def.
  318. unsigned DefIdx = 0;
  319. /// The sub register index of the definition.
  320. unsigned DefSubReg;
  321. /// The register where the value can be found.
  322. unsigned Reg;
  323. /// MachineRegisterInfo used to perform tracking.
  324. const MachineRegisterInfo &MRI;
  325. /// Optional TargetInstrInfo used to perform some complex tracking.
  326. const TargetInstrInfo *TII;
  327. /// Dispatcher to the right underlying implementation of getNextSource.
  328. ValueTrackerResult getNextSourceImpl();
  329. /// Specialized version of getNextSource for Copy instructions.
  330. ValueTrackerResult getNextSourceFromCopy();
  331. /// Specialized version of getNextSource for Bitcast instructions.
  332. ValueTrackerResult getNextSourceFromBitcast();
  333. /// Specialized version of getNextSource for RegSequence instructions.
  334. ValueTrackerResult getNextSourceFromRegSequence();
  335. /// Specialized version of getNextSource for InsertSubreg instructions.
  336. ValueTrackerResult getNextSourceFromInsertSubreg();
  337. /// Specialized version of getNextSource for ExtractSubreg instructions.
  338. ValueTrackerResult getNextSourceFromExtractSubreg();
  339. /// Specialized version of getNextSource for SubregToReg instructions.
  340. ValueTrackerResult getNextSourceFromSubregToReg();
  341. /// Specialized version of getNextSource for PHI instructions.
  342. ValueTrackerResult getNextSourceFromPHI();
  343. public:
  344. /// Create a ValueTracker instance for the value defined by \p Reg.
  345. /// \p DefSubReg represents the sub register index the value tracker will
  346. /// track. It does not need to match the sub register index used in the
  347. /// definition of \p Reg.
  348. /// If \p Reg is a physical register, a value tracker constructed with
  349. /// this constructor will not find any alternative source.
  350. /// Indeed, when \p Reg is a physical register that constructor does not
  351. /// know which definition of \p Reg it should track.
  352. /// Use the next constructor to track a physical register.
  353. ValueTracker(unsigned Reg, unsigned DefSubReg,
  354. const MachineRegisterInfo &MRI,
  355. const TargetInstrInfo *TII = nullptr)
  356. : DefSubReg(DefSubReg), Reg(Reg), MRI(MRI), TII(TII) {
  357. if (!Register::isPhysicalRegister(Reg)) {
  358. Def = MRI.getVRegDef(Reg);
  359. DefIdx = MRI.def_begin(Reg).getOperandNo();
  360. }
  361. }
  362. /// Following the use-def chain, get the next available source
  363. /// for the tracked value.
  364. /// \return A ValueTrackerResult containing a set of registers
  365. /// and sub registers with tracked values. A ValueTrackerResult with
  366. /// an empty set of registers means no source was found.
  367. ValueTrackerResult getNextSource();
  368. };
  369. } // end anonymous namespace
  370. char PeepholeOptimizer::ID = 0;
  371. char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
  372. INITIALIZE_PASS_BEGIN(PeepholeOptimizer, DEBUG_TYPE,
  373. "Peephole Optimizations", false, false)
  374. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  375. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  376. INITIALIZE_PASS_END(PeepholeOptimizer, DEBUG_TYPE,
  377. "Peephole Optimizations", false, false)
  378. /// If instruction is a copy-like instruction, i.e. it reads a single register
  379. /// and writes a single register and it does not modify the source, and if the
  380. /// source value is preserved as a sub-register of the result, then replace all
  381. /// reachable uses of the source with the subreg of the result.
  382. ///
  383. /// Do not generate an EXTRACT that is used only in a debug use, as this changes
  384. /// the code. Since this code does not currently share EXTRACTs, just ignore all
  385. /// debug uses.
  386. bool PeepholeOptimizer::
  387. optimizeExtInstr(MachineInstr &MI, MachineBasicBlock &MBB,
  388. SmallPtrSetImpl<MachineInstr*> &LocalMIs) {
  389. unsigned SrcReg, DstReg, SubIdx;
  390. if (!TII->isCoalescableExtInstr(MI, SrcReg, DstReg, SubIdx))
  391. return false;
  392. if (Register::isPhysicalRegister(DstReg) ||
  393. Register::isPhysicalRegister(SrcReg))
  394. return false;
  395. if (MRI->hasOneNonDBGUse(SrcReg))
  396. // No other uses.
  397. return false;
  398. // Ensure DstReg can get a register class that actually supports
  399. // sub-registers. Don't change the class until we commit.
  400. const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
  401. DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx);
  402. if (!DstRC)
  403. return false;
  404. // The ext instr may be operating on a sub-register of SrcReg as well.
  405. // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
  406. // register.
  407. // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
  408. // SrcReg:SubIdx should be replaced.
  409. bool UseSrcSubIdx =
  410. TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr;
  411. // The source has other uses. See if we can replace the other uses with use of
  412. // the result of the extension.
  413. SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
  414. for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
  415. ReachedBBs.insert(UI.getParent());
  416. // Uses that are in the same BB of uses of the result of the instruction.
  417. SmallVector<MachineOperand*, 8> Uses;
  418. // Uses that the result of the instruction can reach.
  419. SmallVector<MachineOperand*, 8> ExtendedUses;
  420. bool ExtendLife = true;
  421. for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
  422. MachineInstr *UseMI = UseMO.getParent();
  423. if (UseMI == &MI)
  424. continue;
  425. if (UseMI->isPHI()) {
  426. ExtendLife = false;
  427. continue;
  428. }
  429. // Only accept uses of SrcReg:SubIdx.
  430. if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
  431. continue;
  432. // It's an error to translate this:
  433. //
  434. // %reg1025 = <sext> %reg1024
  435. // ...
  436. // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
  437. //
  438. // into this:
  439. //
  440. // %reg1025 = <sext> %reg1024
  441. // ...
  442. // %reg1027 = COPY %reg1025:4
  443. // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
  444. //
  445. // The problem here is that SUBREG_TO_REG is there to assert that an
  446. // implicit zext occurs. It doesn't insert a zext instruction. If we allow
  447. // the COPY here, it will give us the value after the <sext>, not the
  448. // original value of %reg1024 before <sext>.
  449. if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
  450. continue;
  451. MachineBasicBlock *UseMBB = UseMI->getParent();
  452. if (UseMBB == &MBB) {
  453. // Local uses that come after the extension.
  454. if (!LocalMIs.count(UseMI))
  455. Uses.push_back(&UseMO);
  456. } else if (ReachedBBs.count(UseMBB)) {
  457. // Non-local uses where the result of the extension is used. Always
  458. // replace these unless it's a PHI.
  459. Uses.push_back(&UseMO);
  460. } else if (Aggressive && DT->dominates(&MBB, UseMBB)) {
  461. // We may want to extend the live range of the extension result in order
  462. // to replace these uses.
  463. ExtendedUses.push_back(&UseMO);
  464. } else {
  465. // Both will be live out of the def MBB anyway. Don't extend live range of
  466. // the extension result.
  467. ExtendLife = false;
  468. break;
  469. }
  470. }
  471. if (ExtendLife && !ExtendedUses.empty())
  472. // Extend the liveness of the extension result.
  473. Uses.append(ExtendedUses.begin(), ExtendedUses.end());
  474. // Now replace all uses.
  475. bool Changed = false;
  476. if (!Uses.empty()) {
  477. SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
  478. // Look for PHI uses of the extended result, we don't want to extend the
  479. // liveness of a PHI input. It breaks all kinds of assumptions down
  480. // stream. A PHI use is expected to be the kill of its source values.
  481. for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
  482. if (UI.isPHI())
  483. PHIBBs.insert(UI.getParent());
  484. const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
  485. for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
  486. MachineOperand *UseMO = Uses[i];
  487. MachineInstr *UseMI = UseMO->getParent();
  488. MachineBasicBlock *UseMBB = UseMI->getParent();
  489. if (PHIBBs.count(UseMBB))
  490. continue;
  491. // About to add uses of DstReg, clear DstReg's kill flags.
  492. if (!Changed) {
  493. MRI->clearKillFlags(DstReg);
  494. MRI->constrainRegClass(DstReg, DstRC);
  495. }
  496. Register NewVR = MRI->createVirtualRegister(RC);
  497. MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
  498. TII->get(TargetOpcode::COPY), NewVR)
  499. .addReg(DstReg, 0, SubIdx);
  500. // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
  501. if (UseSrcSubIdx) {
  502. Copy->getOperand(0).setSubReg(SubIdx);
  503. Copy->getOperand(0).setIsUndef();
  504. }
  505. UseMO->setReg(NewVR);
  506. ++NumReuse;
  507. Changed = true;
  508. }
  509. }
  510. return Changed;
  511. }
  512. /// If the instruction is a compare and the previous instruction it's comparing
  513. /// against already sets (or could be modified to set) the same flag as the
  514. /// compare, then we can remove the comparison and use the flag from the
  515. /// previous instruction.
  516. bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr &MI) {
  517. // If this instruction is a comparison against zero and isn't comparing a
  518. // physical register, we can try to optimize it.
  519. unsigned SrcReg, SrcReg2;
  520. int CmpMask, CmpValue;
  521. if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
  522. Register::isPhysicalRegister(SrcReg) ||
  523. (SrcReg2 != 0 && Register::isPhysicalRegister(SrcReg2)))
  524. return false;
  525. // Attempt to optimize the comparison instruction.
  526. if (TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
  527. ++NumCmps;
  528. return true;
  529. }
  530. return false;
  531. }
  532. /// Optimize a select instruction.
  533. bool PeepholeOptimizer::optimizeSelect(MachineInstr &MI,
  534. SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
  535. unsigned TrueOp = 0;
  536. unsigned FalseOp = 0;
  537. bool Optimizable = false;
  538. SmallVector<MachineOperand, 4> Cond;
  539. if (TII->analyzeSelect(MI, Cond, TrueOp, FalseOp, Optimizable))
  540. return false;
  541. if (!Optimizable)
  542. return false;
  543. if (!TII->optimizeSelect(MI, LocalMIs))
  544. return false;
  545. MI.eraseFromParent();
  546. ++NumSelects;
  547. return true;
  548. }
  549. /// Check if a simpler conditional branch can be generated.
  550. bool PeepholeOptimizer::optimizeCondBranch(MachineInstr &MI) {
  551. return TII->optimizeCondBranch(MI);
  552. }
  553. /// Try to find the next source that share the same register file
  554. /// for the value defined by \p Reg and \p SubReg.
  555. /// When true is returned, the \p RewriteMap can be used by the client to
  556. /// retrieve all Def -> Use along the way up to the next source. Any found
  557. /// Use that is not itself a key for another entry, is the next source to
  558. /// use. During the search for the next source, multiple sources can be found
  559. /// given multiple incoming sources of a PHI instruction. In this case, we
  560. /// look in each PHI source for the next source; all found next sources must
  561. /// share the same register file as \p Reg and \p SubReg. The client should
  562. /// then be capable to rewrite all intermediate PHIs to get the next source.
  563. /// \return False if no alternative sources are available. True otherwise.
  564. bool PeepholeOptimizer::findNextSource(RegSubRegPair RegSubReg,
  565. RewriteMapTy &RewriteMap) {
  566. // Do not try to find a new source for a physical register.
  567. // So far we do not have any motivating example for doing that.
  568. // Thus, instead of maintaining untested code, we will revisit that if
  569. // that changes at some point.
  570. unsigned Reg = RegSubReg.Reg;
  571. if (Register::isPhysicalRegister(Reg))
  572. return false;
  573. const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
  574. SmallVector<RegSubRegPair, 4> SrcToLook;
  575. RegSubRegPair CurSrcPair = RegSubReg;
  576. SrcToLook.push_back(CurSrcPair);
  577. unsigned PHICount = 0;
  578. do {
  579. CurSrcPair = SrcToLook.pop_back_val();
  580. // As explained above, do not handle physical registers
  581. if (Register::isPhysicalRegister(CurSrcPair.Reg))
  582. return false;
  583. ValueTracker ValTracker(CurSrcPair.Reg, CurSrcPair.SubReg, *MRI, TII);
  584. // Follow the chain of copies until we find a more suitable source, a phi
  585. // or have to abort.
  586. while (true) {
  587. ValueTrackerResult Res = ValTracker.getNextSource();
  588. // Abort at the end of a chain (without finding a suitable source).
  589. if (!Res.isValid())
  590. return false;
  591. // Insert the Def -> Use entry for the recently found source.
  592. ValueTrackerResult CurSrcRes = RewriteMap.lookup(CurSrcPair);
  593. if (CurSrcRes.isValid()) {
  594. assert(CurSrcRes == Res && "ValueTrackerResult found must match");
  595. // An existent entry with multiple sources is a PHI cycle we must avoid.
  596. // Otherwise it's an entry with a valid next source we already found.
  597. if (CurSrcRes.getNumSources() > 1) {
  598. LLVM_DEBUG(dbgs()
  599. << "findNextSource: found PHI cycle, aborting...\n");
  600. return false;
  601. }
  602. break;
  603. }
  604. RewriteMap.insert(std::make_pair(CurSrcPair, Res));
  605. // ValueTrackerResult usually have one source unless it's the result from
  606. // a PHI instruction. Add the found PHI edges to be looked up further.
  607. unsigned NumSrcs = Res.getNumSources();
  608. if (NumSrcs > 1) {
  609. PHICount++;
  610. if (PHICount >= RewritePHILimit) {
  611. LLVM_DEBUG(dbgs() << "findNextSource: PHI limit reached\n");
  612. return false;
  613. }
  614. for (unsigned i = 0; i < NumSrcs; ++i)
  615. SrcToLook.push_back(Res.getSrc(i));
  616. break;
  617. }
  618. CurSrcPair = Res.getSrc(0);
  619. // Do not extend the live-ranges of physical registers as they add
  620. // constraints to the register allocator. Moreover, if we want to extend
  621. // the live-range of a physical register, unlike SSA virtual register,
  622. // we will have to check that they aren't redefine before the related use.
  623. if (Register::isPhysicalRegister(CurSrcPair.Reg))
  624. return false;
  625. // Keep following the chain if the value isn't any better yet.
  626. const TargetRegisterClass *SrcRC = MRI->getRegClass(CurSrcPair.Reg);
  627. if (!TRI->shouldRewriteCopySrc(DefRC, RegSubReg.SubReg, SrcRC,
  628. CurSrcPair.SubReg))
  629. continue;
  630. // We currently cannot deal with subreg operands on PHI instructions
  631. // (see insertPHI()).
  632. if (PHICount > 0 && CurSrcPair.SubReg != 0)
  633. continue;
  634. // We found a suitable source, and are done with this chain.
  635. break;
  636. }
  637. } while (!SrcToLook.empty());
  638. // If we did not find a more suitable source, there is nothing to optimize.
  639. return CurSrcPair.Reg != Reg;
  640. }
  641. /// Insert a PHI instruction with incoming edges \p SrcRegs that are
  642. /// guaranteed to have the same register class. This is necessary whenever we
  643. /// successfully traverse a PHI instruction and find suitable sources coming
  644. /// from its edges. By inserting a new PHI, we provide a rewritten PHI def
  645. /// suitable to be used in a new COPY instruction.
  646. static MachineInstr &
  647. insertPHI(MachineRegisterInfo &MRI, const TargetInstrInfo &TII,
  648. const SmallVectorImpl<RegSubRegPair> &SrcRegs,
  649. MachineInstr &OrigPHI) {
  650. assert(!SrcRegs.empty() && "No sources to create a PHI instruction?");
  651. const TargetRegisterClass *NewRC = MRI.getRegClass(SrcRegs[0].Reg);
  652. // NewRC is only correct if no subregisters are involved. findNextSource()
  653. // should have rejected those cases already.
  654. assert(SrcRegs[0].SubReg == 0 && "should not have subreg operand");
  655. Register NewVR = MRI.createVirtualRegister(NewRC);
  656. MachineBasicBlock *MBB = OrigPHI.getParent();
  657. MachineInstrBuilder MIB = BuildMI(*MBB, &OrigPHI, OrigPHI.getDebugLoc(),
  658. TII.get(TargetOpcode::PHI), NewVR);
  659. unsigned MBBOpIdx = 2;
  660. for (const RegSubRegPair &RegPair : SrcRegs) {
  661. MIB.addReg(RegPair.Reg, 0, RegPair.SubReg);
  662. MIB.addMBB(OrigPHI.getOperand(MBBOpIdx).getMBB());
  663. // Since we're extended the lifetime of RegPair.Reg, clear the
  664. // kill flags to account for that and make RegPair.Reg reaches
  665. // the new PHI.
  666. MRI.clearKillFlags(RegPair.Reg);
  667. MBBOpIdx += 2;
  668. }
  669. return *MIB;
  670. }
  671. namespace {
  672. /// Interface to query instructions amenable to copy rewriting.
  673. class Rewriter {
  674. protected:
  675. MachineInstr &CopyLike;
  676. unsigned CurrentSrcIdx = 0; ///< The index of the source being rewritten.
  677. public:
  678. Rewriter(MachineInstr &CopyLike) : CopyLike(CopyLike) {}
  679. virtual ~Rewriter() {}
  680. /// Get the next rewritable source (SrcReg, SrcSubReg) and
  681. /// the related value that it affects (DstReg, DstSubReg).
  682. /// A source is considered rewritable if its register class and the
  683. /// register class of the related DstReg may not be register
  684. /// coalescer friendly. In other words, given a copy-like instruction
  685. /// not all the arguments may be returned at rewritable source, since
  686. /// some arguments are none to be register coalescer friendly.
  687. ///
  688. /// Each call of this method moves the current source to the next
  689. /// rewritable source.
  690. /// For instance, let CopyLike be the instruction to rewrite.
  691. /// CopyLike has one definition and one source:
  692. /// dst.dstSubIdx = CopyLike src.srcSubIdx.
  693. ///
  694. /// The first call will give the first rewritable source, i.e.,
  695. /// the only source this instruction has:
  696. /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
  697. /// This source defines the whole definition, i.e.,
  698. /// (DstReg, DstSubReg) = (dst, dstSubIdx).
  699. ///
  700. /// The second and subsequent calls will return false, as there is only one
  701. /// rewritable source.
  702. ///
  703. /// \return True if a rewritable source has been found, false otherwise.
  704. /// The output arguments are valid if and only if true is returned.
  705. virtual bool getNextRewritableSource(RegSubRegPair &Src,
  706. RegSubRegPair &Dst) = 0;
  707. /// Rewrite the current source with \p NewReg and \p NewSubReg if possible.
  708. /// \return True if the rewriting was possible, false otherwise.
  709. virtual bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) = 0;
  710. };
  711. /// Rewriter for COPY instructions.
  712. class CopyRewriter : public Rewriter {
  713. public:
  714. CopyRewriter(MachineInstr &MI) : Rewriter(MI) {
  715. assert(MI.isCopy() && "Expected copy instruction");
  716. }
  717. virtual ~CopyRewriter() = default;
  718. bool getNextRewritableSource(RegSubRegPair &Src,
  719. RegSubRegPair &Dst) override {
  720. // CurrentSrcIdx > 0 means this function has already been called.
  721. if (CurrentSrcIdx > 0)
  722. return false;
  723. // This is the first call to getNextRewritableSource.
  724. // Move the CurrentSrcIdx to remember that we made that call.
  725. CurrentSrcIdx = 1;
  726. // The rewritable source is the argument.
  727. const MachineOperand &MOSrc = CopyLike.getOperand(1);
  728. Src = RegSubRegPair(MOSrc.getReg(), MOSrc.getSubReg());
  729. // What we track are the alternative sources of the definition.
  730. const MachineOperand &MODef = CopyLike.getOperand(0);
  731. Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
  732. return true;
  733. }
  734. bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
  735. if (CurrentSrcIdx != 1)
  736. return false;
  737. MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
  738. MOSrc.setReg(NewReg);
  739. MOSrc.setSubReg(NewSubReg);
  740. return true;
  741. }
  742. };
  743. /// Helper class to rewrite uncoalescable copy like instructions
  744. /// into new COPY (coalescable friendly) instructions.
  745. class UncoalescableRewriter : public Rewriter {
  746. unsigned NumDefs; ///< Number of defs in the bitcast.
  747. public:
  748. UncoalescableRewriter(MachineInstr &MI) : Rewriter(MI) {
  749. NumDefs = MI.getDesc().getNumDefs();
  750. }
  751. /// \see See Rewriter::getNextRewritableSource()
  752. /// All such sources need to be considered rewritable in order to
  753. /// rewrite a uncoalescable copy-like instruction. This method return
  754. /// each definition that must be checked if rewritable.
  755. bool getNextRewritableSource(RegSubRegPair &Src,
  756. RegSubRegPair &Dst) override {
  757. // Find the next non-dead definition and continue from there.
  758. if (CurrentSrcIdx == NumDefs)
  759. return false;
  760. while (CopyLike.getOperand(CurrentSrcIdx).isDead()) {
  761. ++CurrentSrcIdx;
  762. if (CurrentSrcIdx == NumDefs)
  763. return false;
  764. }
  765. // What we track are the alternative sources of the definition.
  766. Src = RegSubRegPair(0, 0);
  767. const MachineOperand &MODef = CopyLike.getOperand(CurrentSrcIdx);
  768. Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
  769. CurrentSrcIdx++;
  770. return true;
  771. }
  772. bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
  773. return false;
  774. }
  775. };
  776. /// Specialized rewriter for INSERT_SUBREG instruction.
  777. class InsertSubregRewriter : public Rewriter {
  778. public:
  779. InsertSubregRewriter(MachineInstr &MI) : Rewriter(MI) {
  780. assert(MI.isInsertSubreg() && "Invalid instruction");
  781. }
  782. /// \see See Rewriter::getNextRewritableSource()
  783. /// Here CopyLike has the following form:
  784. /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
  785. /// Src1 has the same register class has dst, hence, there is
  786. /// nothing to rewrite.
  787. /// Src2.src2SubIdx, may not be register coalescer friendly.
  788. /// Therefore, the first call to this method returns:
  789. /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
  790. /// (DstReg, DstSubReg) = (dst, subIdx).
  791. ///
  792. /// Subsequence calls will return false.
  793. bool getNextRewritableSource(RegSubRegPair &Src,
  794. RegSubRegPair &Dst) override {
  795. // If we already get the only source we can rewrite, return false.
  796. if (CurrentSrcIdx == 2)
  797. return false;
  798. // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
  799. CurrentSrcIdx = 2;
  800. const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
  801. Src = RegSubRegPair(MOInsertedReg.getReg(), MOInsertedReg.getSubReg());
  802. const MachineOperand &MODef = CopyLike.getOperand(0);
  803. // We want to track something that is compatible with the
  804. // partial definition.
  805. if (MODef.getSubReg())
  806. // Bail if we have to compose sub-register indices.
  807. return false;
  808. Dst = RegSubRegPair(MODef.getReg(),
  809. (unsigned)CopyLike.getOperand(3).getImm());
  810. return true;
  811. }
  812. bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
  813. if (CurrentSrcIdx != 2)
  814. return false;
  815. // We are rewriting the inserted reg.
  816. MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
  817. MO.setReg(NewReg);
  818. MO.setSubReg(NewSubReg);
  819. return true;
  820. }
  821. };
  822. /// Specialized rewriter for EXTRACT_SUBREG instruction.
  823. class ExtractSubregRewriter : public Rewriter {
  824. const TargetInstrInfo &TII;
  825. public:
  826. ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
  827. : Rewriter(MI), TII(TII) {
  828. assert(MI.isExtractSubreg() && "Invalid instruction");
  829. }
  830. /// \see Rewriter::getNextRewritableSource()
  831. /// Here CopyLike has the following form:
  832. /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
  833. /// There is only one rewritable source: Src.subIdx,
  834. /// which defines dst.dstSubIdx.
  835. bool getNextRewritableSource(RegSubRegPair &Src,
  836. RegSubRegPair &Dst) override {
  837. // If we already get the only source we can rewrite, return false.
  838. if (CurrentSrcIdx == 1)
  839. return false;
  840. // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
  841. CurrentSrcIdx = 1;
  842. const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
  843. // If we have to compose sub-register indices, bail out.
  844. if (MOExtractedReg.getSubReg())
  845. return false;
  846. Src = RegSubRegPair(MOExtractedReg.getReg(),
  847. CopyLike.getOperand(2).getImm());
  848. // We want to track something that is compatible with the definition.
  849. const MachineOperand &MODef = CopyLike.getOperand(0);
  850. Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
  851. return true;
  852. }
  853. bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
  854. // The only source we can rewrite is the input register.
  855. if (CurrentSrcIdx != 1)
  856. return false;
  857. CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
  858. // If we find a source that does not require to extract something,
  859. // rewrite the operation with a copy.
  860. if (!NewSubReg) {
  861. // Move the current index to an invalid position.
  862. // We do not want another call to this method to be able
  863. // to do any change.
  864. CurrentSrcIdx = -1;
  865. // Rewrite the operation as a COPY.
  866. // Get rid of the sub-register index.
  867. CopyLike.RemoveOperand(2);
  868. // Morph the operation into a COPY.
  869. CopyLike.setDesc(TII.get(TargetOpcode::COPY));
  870. return true;
  871. }
  872. CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
  873. return true;
  874. }
  875. };
  876. /// Specialized rewriter for REG_SEQUENCE instruction.
  877. class RegSequenceRewriter : public Rewriter {
  878. public:
  879. RegSequenceRewriter(MachineInstr &MI) : Rewriter(MI) {
  880. assert(MI.isRegSequence() && "Invalid instruction");
  881. }
  882. /// \see Rewriter::getNextRewritableSource()
  883. /// Here CopyLike has the following form:
  884. /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
  885. /// Each call will return a different source, walking all the available
  886. /// source.
  887. ///
  888. /// The first call returns:
  889. /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
  890. /// (DstReg, DstSubReg) = (dst, subIdx1).
  891. ///
  892. /// The second call returns:
  893. /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
  894. /// (DstReg, DstSubReg) = (dst, subIdx2).
  895. ///
  896. /// And so on, until all the sources have been traversed, then
  897. /// it returns false.
  898. bool getNextRewritableSource(RegSubRegPair &Src,
  899. RegSubRegPair &Dst) override {
  900. // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
  901. // If this is the first call, move to the first argument.
  902. if (CurrentSrcIdx == 0) {
  903. CurrentSrcIdx = 1;
  904. } else {
  905. // Otherwise, move to the next argument and check that it is valid.
  906. CurrentSrcIdx += 2;
  907. if (CurrentSrcIdx >= CopyLike.getNumOperands())
  908. return false;
  909. }
  910. const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
  911. Src.Reg = MOInsertedReg.getReg();
  912. // If we have to compose sub-register indices, bail out.
  913. if ((Src.SubReg = MOInsertedReg.getSubReg()))
  914. return false;
  915. // We want to track something that is compatible with the related
  916. // partial definition.
  917. Dst.SubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
  918. const MachineOperand &MODef = CopyLike.getOperand(0);
  919. Dst.Reg = MODef.getReg();
  920. // If we have to compose sub-registers, bail.
  921. return MODef.getSubReg() == 0;
  922. }
  923. bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
  924. // We cannot rewrite out of bound operands.
  925. // Moreover, rewritable sources are at odd positions.
  926. if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
  927. return false;
  928. MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
  929. MO.setReg(NewReg);
  930. MO.setSubReg(NewSubReg);
  931. return true;
  932. }
  933. };
  934. } // end anonymous namespace
  935. /// Get the appropriated Rewriter for \p MI.
  936. /// \return A pointer to a dynamically allocated Rewriter or nullptr if no
  937. /// rewriter works for \p MI.
  938. static Rewriter *getCopyRewriter(MachineInstr &MI, const TargetInstrInfo &TII) {
  939. // Handle uncoalescable copy-like instructions.
  940. if (MI.isBitcast() || MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
  941. MI.isExtractSubregLike())
  942. return new UncoalescableRewriter(MI);
  943. switch (MI.getOpcode()) {
  944. default:
  945. return nullptr;
  946. case TargetOpcode::COPY:
  947. return new CopyRewriter(MI);
  948. case TargetOpcode::INSERT_SUBREG:
  949. return new InsertSubregRewriter(MI);
  950. case TargetOpcode::EXTRACT_SUBREG:
  951. return new ExtractSubregRewriter(MI, TII);
  952. case TargetOpcode::REG_SEQUENCE:
  953. return new RegSequenceRewriter(MI);
  954. }
  955. }
  956. /// Given a \p Def.Reg and Def.SubReg pair, use \p RewriteMap to find
  957. /// the new source to use for rewrite. If \p HandleMultipleSources is true and
  958. /// multiple sources for a given \p Def are found along the way, we found a
  959. /// PHI instructions that needs to be rewritten.
  960. /// TODO: HandleMultipleSources should be removed once we test PHI handling
  961. /// with coalescable copies.
  962. static RegSubRegPair
  963. getNewSource(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
  964. RegSubRegPair Def,
  965. const PeepholeOptimizer::RewriteMapTy &RewriteMap,
  966. bool HandleMultipleSources = true) {
  967. RegSubRegPair LookupSrc(Def.Reg, Def.SubReg);
  968. while (true) {
  969. ValueTrackerResult Res = RewriteMap.lookup(LookupSrc);
  970. // If there are no entries on the map, LookupSrc is the new source.
  971. if (!Res.isValid())
  972. return LookupSrc;
  973. // There's only one source for this definition, keep searching...
  974. unsigned NumSrcs = Res.getNumSources();
  975. if (NumSrcs == 1) {
  976. LookupSrc.Reg = Res.getSrcReg(0);
  977. LookupSrc.SubReg = Res.getSrcSubReg(0);
  978. continue;
  979. }
  980. // TODO: Remove once multiple srcs w/ coalescable copies are supported.
  981. if (!HandleMultipleSources)
  982. break;
  983. // Multiple sources, recurse into each source to find a new source
  984. // for it. Then, rewrite the PHI accordingly to its new edges.
  985. SmallVector<RegSubRegPair, 4> NewPHISrcs;
  986. for (unsigned i = 0; i < NumSrcs; ++i) {
  987. RegSubRegPair PHISrc(Res.getSrcReg(i), Res.getSrcSubReg(i));
  988. NewPHISrcs.push_back(
  989. getNewSource(MRI, TII, PHISrc, RewriteMap, HandleMultipleSources));
  990. }
  991. // Build the new PHI node and return its def register as the new source.
  992. MachineInstr &OrigPHI = const_cast<MachineInstr &>(*Res.getInst());
  993. MachineInstr &NewPHI = insertPHI(*MRI, *TII, NewPHISrcs, OrigPHI);
  994. LLVM_DEBUG(dbgs() << "-- getNewSource\n");
  995. LLVM_DEBUG(dbgs() << " Replacing: " << OrigPHI);
  996. LLVM_DEBUG(dbgs() << " With: " << NewPHI);
  997. const MachineOperand &MODef = NewPHI.getOperand(0);
  998. return RegSubRegPair(MODef.getReg(), MODef.getSubReg());
  999. }
  1000. return RegSubRegPair(0, 0);
  1001. }
  1002. /// Optimize generic copy instructions to avoid cross register bank copy.
  1003. /// The optimization looks through a chain of copies and tries to find a source
  1004. /// that has a compatible register class.
  1005. /// Two register classes are considered to be compatible if they share the same
  1006. /// register bank.
  1007. /// New copies issued by this optimization are register allocator
  1008. /// friendly. This optimization does not remove any copy as it may
  1009. /// overconstrain the register allocator, but replaces some operands
  1010. /// when possible.
  1011. /// \pre isCoalescableCopy(*MI) is true.
  1012. /// \return True, when \p MI has been rewritten. False otherwise.
  1013. bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr &MI) {
  1014. assert(isCoalescableCopy(MI) && "Invalid argument");
  1015. assert(MI.getDesc().getNumDefs() == 1 &&
  1016. "Coalescer can understand multiple defs?!");
  1017. const MachineOperand &MODef = MI.getOperand(0);
  1018. // Do not rewrite physical definitions.
  1019. if (Register::isPhysicalRegister(MODef.getReg()))
  1020. return false;
  1021. bool Changed = false;
  1022. // Get the right rewriter for the current copy.
  1023. std::unique_ptr<Rewriter> CpyRewriter(getCopyRewriter(MI, *TII));
  1024. // If none exists, bail out.
  1025. if (!CpyRewriter)
  1026. return false;
  1027. // Rewrite each rewritable source.
  1028. RegSubRegPair Src;
  1029. RegSubRegPair TrackPair;
  1030. while (CpyRewriter->getNextRewritableSource(Src, TrackPair)) {
  1031. // Keep track of PHI nodes and its incoming edges when looking for sources.
  1032. RewriteMapTy RewriteMap;
  1033. // Try to find a more suitable source. If we failed to do so, or get the
  1034. // actual source, move to the next source.
  1035. if (!findNextSource(TrackPair, RewriteMap))
  1036. continue;
  1037. // Get the new source to rewrite. TODO: Only enable handling of multiple
  1038. // sources (PHIs) once we have a motivating example and testcases for it.
  1039. RegSubRegPair NewSrc = getNewSource(MRI, TII, TrackPair, RewriteMap,
  1040. /*HandleMultipleSources=*/false);
  1041. if (Src.Reg == NewSrc.Reg || NewSrc.Reg == 0)
  1042. continue;
  1043. // Rewrite source.
  1044. if (CpyRewriter->RewriteCurrentSource(NewSrc.Reg, NewSrc.SubReg)) {
  1045. // We may have extended the live-range of NewSrc, account for that.
  1046. MRI->clearKillFlags(NewSrc.Reg);
  1047. Changed = true;
  1048. }
  1049. }
  1050. // TODO: We could have a clean-up method to tidy the instruction.
  1051. // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
  1052. // => v0 = COPY v1
  1053. // Currently we haven't seen motivating example for that and we
  1054. // want to avoid untested code.
  1055. NumRewrittenCopies += Changed;
  1056. return Changed;
  1057. }
  1058. /// Rewrite the source found through \p Def, by using the \p RewriteMap
  1059. /// and create a new COPY instruction. More info about RewriteMap in
  1060. /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
  1061. /// Uncoalescable copies, since they are copy like instructions that aren't
  1062. /// recognized by the register allocator.
  1063. MachineInstr &
  1064. PeepholeOptimizer::rewriteSource(MachineInstr &CopyLike,
  1065. RegSubRegPair Def, RewriteMapTy &RewriteMap) {
  1066. assert(!Register::isPhysicalRegister(Def.Reg) &&
  1067. "We do not rewrite physical registers");
  1068. // Find the new source to use in the COPY rewrite.
  1069. RegSubRegPair NewSrc = getNewSource(MRI, TII, Def, RewriteMap);
  1070. // Insert the COPY.
  1071. const TargetRegisterClass *DefRC = MRI->getRegClass(Def.Reg);
  1072. Register NewVReg = MRI->createVirtualRegister(DefRC);
  1073. MachineInstr *NewCopy =
  1074. BuildMI(*CopyLike.getParent(), &CopyLike, CopyLike.getDebugLoc(),
  1075. TII->get(TargetOpcode::COPY), NewVReg)
  1076. .addReg(NewSrc.Reg, 0, NewSrc.SubReg);
  1077. if (Def.SubReg) {
  1078. NewCopy->getOperand(0).setSubReg(Def.SubReg);
  1079. NewCopy->getOperand(0).setIsUndef();
  1080. }
  1081. LLVM_DEBUG(dbgs() << "-- RewriteSource\n");
  1082. LLVM_DEBUG(dbgs() << " Replacing: " << CopyLike);
  1083. LLVM_DEBUG(dbgs() << " With: " << *NewCopy);
  1084. MRI->replaceRegWith(Def.Reg, NewVReg);
  1085. MRI->clearKillFlags(NewVReg);
  1086. // We extended the lifetime of NewSrc.Reg, clear the kill flags to
  1087. // account for that.
  1088. MRI->clearKillFlags(NewSrc.Reg);
  1089. return *NewCopy;
  1090. }
  1091. /// Optimize copy-like instructions to create
  1092. /// register coalescer friendly instruction.
  1093. /// The optimization tries to kill-off the \p MI by looking
  1094. /// through a chain of copies to find a source that has a compatible
  1095. /// register class.
  1096. /// If such a source is found, it replace \p MI by a generic COPY
  1097. /// operation.
  1098. /// \pre isUncoalescableCopy(*MI) is true.
  1099. /// \return True, when \p MI has been optimized. In that case, \p MI has
  1100. /// been removed from its parent.
  1101. /// All COPY instructions created, are inserted in \p LocalMIs.
  1102. bool PeepholeOptimizer::optimizeUncoalescableCopy(
  1103. MachineInstr &MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
  1104. assert(isUncoalescableCopy(MI) && "Invalid argument");
  1105. UncoalescableRewriter CpyRewriter(MI);
  1106. // Rewrite each rewritable source by generating new COPYs. This works
  1107. // differently from optimizeCoalescableCopy since it first makes sure that all
  1108. // definitions can be rewritten.
  1109. RewriteMapTy RewriteMap;
  1110. RegSubRegPair Src;
  1111. RegSubRegPair Def;
  1112. SmallVector<RegSubRegPair, 4> RewritePairs;
  1113. while (CpyRewriter.getNextRewritableSource(Src, Def)) {
  1114. // If a physical register is here, this is probably for a good reason.
  1115. // Do not rewrite that.
  1116. if (Register::isPhysicalRegister(Def.Reg))
  1117. return false;
  1118. // If we do not know how to rewrite this definition, there is no point
  1119. // in trying to kill this instruction.
  1120. if (!findNextSource(Def, RewriteMap))
  1121. return false;
  1122. RewritePairs.push_back(Def);
  1123. }
  1124. // The change is possible for all defs, do it.
  1125. for (const RegSubRegPair &Def : RewritePairs) {
  1126. // Rewrite the "copy" in a way the register coalescer understands.
  1127. MachineInstr &NewCopy = rewriteSource(MI, Def, RewriteMap);
  1128. LocalMIs.insert(&NewCopy);
  1129. }
  1130. // MI is now dead.
  1131. MI.eraseFromParent();
  1132. ++NumUncoalescableCopies;
  1133. return true;
  1134. }
  1135. /// Check whether MI is a candidate for folding into a later instruction.
  1136. /// We only fold loads to virtual registers and the virtual register defined
  1137. /// has a single user.
  1138. bool PeepholeOptimizer::isLoadFoldable(
  1139. MachineInstr &MI, SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) {
  1140. if (!MI.canFoldAsLoad() || !MI.mayLoad())
  1141. return false;
  1142. const MCInstrDesc &MCID = MI.getDesc();
  1143. if (MCID.getNumDefs() != 1)
  1144. return false;
  1145. Register Reg = MI.getOperand(0).getReg();
  1146. // To reduce compilation time, we check MRI->hasOneNonDBGUser when inserting
  1147. // loads. It should be checked when processing uses of the load, since
  1148. // uses can be removed during peephole.
  1149. if (!MI.getOperand(0).getSubReg() && Register::isVirtualRegister(Reg) &&
  1150. MRI->hasOneNonDBGUser(Reg)) {
  1151. FoldAsLoadDefCandidates.insert(Reg);
  1152. return true;
  1153. }
  1154. return false;
  1155. }
  1156. bool PeepholeOptimizer::isMoveImmediate(
  1157. MachineInstr &MI, SmallSet<unsigned, 4> &ImmDefRegs,
  1158. DenseMap<unsigned, MachineInstr *> &ImmDefMIs) {
  1159. const MCInstrDesc &MCID = MI.getDesc();
  1160. if (!MI.isMoveImmediate())
  1161. return false;
  1162. if (MCID.getNumDefs() != 1)
  1163. return false;
  1164. Register Reg = MI.getOperand(0).getReg();
  1165. if (Register::isVirtualRegister(Reg)) {
  1166. ImmDefMIs.insert(std::make_pair(Reg, &MI));
  1167. ImmDefRegs.insert(Reg);
  1168. return true;
  1169. }
  1170. return false;
  1171. }
  1172. /// Try folding register operands that are defined by move immediate
  1173. /// instructions, i.e. a trivial constant folding optimization, if
  1174. /// and only if the def and use are in the same BB.
  1175. bool PeepholeOptimizer::foldImmediate(MachineInstr &MI,
  1176. SmallSet<unsigned, 4> &ImmDefRegs,
  1177. DenseMap<unsigned, MachineInstr *> &ImmDefMIs) {
  1178. for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
  1179. MachineOperand &MO = MI.getOperand(i);
  1180. if (!MO.isReg() || MO.isDef())
  1181. continue;
  1182. // Ignore dead implicit defs.
  1183. if (MO.isImplicit() && MO.isDead())
  1184. continue;
  1185. Register Reg = MO.getReg();
  1186. if (!Register::isVirtualRegister(Reg))
  1187. continue;
  1188. if (ImmDefRegs.count(Reg) == 0)
  1189. continue;
  1190. DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
  1191. assert(II != ImmDefMIs.end() && "couldn't find immediate definition");
  1192. if (TII->FoldImmediate(MI, *II->second, Reg, MRI)) {
  1193. ++NumImmFold;
  1194. return true;
  1195. }
  1196. }
  1197. return false;
  1198. }
  1199. // FIXME: This is very simple and misses some cases which should be handled when
  1200. // motivating examples are found.
  1201. //
  1202. // The copy rewriting logic should look at uses as well as defs and be able to
  1203. // eliminate copies across blocks.
  1204. //
  1205. // Later copies that are subregister extracts will also not be eliminated since
  1206. // only the first copy is considered.
  1207. //
  1208. // e.g.
  1209. // %1 = COPY %0
  1210. // %2 = COPY %0:sub1
  1211. //
  1212. // Should replace %2 uses with %1:sub1
  1213. bool PeepholeOptimizer::foldRedundantCopy(MachineInstr &MI,
  1214. SmallSet<unsigned, 4> &CopySrcRegs,
  1215. DenseMap<unsigned, MachineInstr *> &CopyMIs) {
  1216. assert(MI.isCopy() && "expected a COPY machine instruction");
  1217. Register SrcReg = MI.getOperand(1).getReg();
  1218. if (!Register::isVirtualRegister(SrcReg))
  1219. return false;
  1220. Register DstReg = MI.getOperand(0).getReg();
  1221. if (!Register::isVirtualRegister(DstReg))
  1222. return false;
  1223. if (CopySrcRegs.insert(SrcReg).second) {
  1224. // First copy of this reg seen.
  1225. CopyMIs.insert(std::make_pair(SrcReg, &MI));
  1226. return false;
  1227. }
  1228. MachineInstr *PrevCopy = CopyMIs.find(SrcReg)->second;
  1229. unsigned SrcSubReg = MI.getOperand(1).getSubReg();
  1230. unsigned PrevSrcSubReg = PrevCopy->getOperand(1).getSubReg();
  1231. // Can't replace different subregister extracts.
  1232. if (SrcSubReg != PrevSrcSubReg)
  1233. return false;
  1234. Register PrevDstReg = PrevCopy->getOperand(0).getReg();
  1235. // Only replace if the copy register class is the same.
  1236. //
  1237. // TODO: If we have multiple copies to different register classes, we may want
  1238. // to track multiple copies of the same source register.
  1239. if (MRI->getRegClass(DstReg) != MRI->getRegClass(PrevDstReg))
  1240. return false;
  1241. MRI->replaceRegWith(DstReg, PrevDstReg);
  1242. // Lifetime of the previous copy has been extended.
  1243. MRI->clearKillFlags(PrevDstReg);
  1244. return true;
  1245. }
  1246. bool PeepholeOptimizer::isNAPhysCopy(unsigned Reg) {
  1247. return Register::isPhysicalRegister(Reg) && !MRI->isAllocatable(Reg);
  1248. }
  1249. bool PeepholeOptimizer::foldRedundantNAPhysCopy(
  1250. MachineInstr &MI, DenseMap<unsigned, MachineInstr *> &NAPhysToVirtMIs) {
  1251. assert(MI.isCopy() && "expected a COPY machine instruction");
  1252. if (DisableNAPhysCopyOpt)
  1253. return false;
  1254. Register DstReg = MI.getOperand(0).getReg();
  1255. Register SrcReg = MI.getOperand(1).getReg();
  1256. if (isNAPhysCopy(SrcReg) && Register::isVirtualRegister(DstReg)) {
  1257. // %vreg = COPY %physreg
  1258. // Avoid using a datastructure which can track multiple live non-allocatable
  1259. // phys->virt copies since LLVM doesn't seem to do this.
  1260. NAPhysToVirtMIs.insert({SrcReg, &MI});
  1261. return false;
  1262. }
  1263. if (!(Register::isVirtualRegister(SrcReg) && isNAPhysCopy(DstReg)))
  1264. return false;
  1265. // %physreg = COPY %vreg
  1266. auto PrevCopy = NAPhysToVirtMIs.find(DstReg);
  1267. if (PrevCopy == NAPhysToVirtMIs.end()) {
  1268. // We can't remove the copy: there was an intervening clobber of the
  1269. // non-allocatable physical register after the copy to virtual.
  1270. LLVM_DEBUG(dbgs() << "NAPhysCopy: intervening clobber forbids erasing "
  1271. << MI);
  1272. return false;
  1273. }
  1274. Register PrevDstReg = PrevCopy->second->getOperand(0).getReg();
  1275. if (PrevDstReg == SrcReg) {
  1276. // Remove the virt->phys copy: we saw the virtual register definition, and
  1277. // the non-allocatable physical register's state hasn't changed since then.
  1278. LLVM_DEBUG(dbgs() << "NAPhysCopy: erasing " << MI);
  1279. ++NumNAPhysCopies;
  1280. return true;
  1281. }
  1282. // Potential missed optimization opportunity: we saw a different virtual
  1283. // register get a copy of the non-allocatable physical register, and we only
  1284. // track one such copy. Avoid getting confused by this new non-allocatable
  1285. // physical register definition, and remove it from the tracked copies.
  1286. LLVM_DEBUG(dbgs() << "NAPhysCopy: missed opportunity " << MI);
  1287. NAPhysToVirtMIs.erase(PrevCopy);
  1288. return false;
  1289. }
  1290. /// \bried Returns true if \p MO is a virtual register operand.
  1291. static bool isVirtualRegisterOperand(MachineOperand &MO) {
  1292. if (!MO.isReg())
  1293. return false;
  1294. return Register::isVirtualRegister(MO.getReg());
  1295. }
  1296. bool PeepholeOptimizer::findTargetRecurrence(
  1297. unsigned Reg, const SmallSet<unsigned, 2> &TargetRegs,
  1298. RecurrenceCycle &RC) {
  1299. // Recurrence found if Reg is in TargetRegs.
  1300. if (TargetRegs.count(Reg))
  1301. return true;
  1302. // TODO: Curerntly, we only allow the last instruction of the recurrence
  1303. // cycle (the instruction that feeds the PHI instruction) to have more than
  1304. // one uses to guarantee that commuting operands does not tie registers
  1305. // with overlapping live range. Once we have actual live range info of
  1306. // each register, this constraint can be relaxed.
  1307. if (!MRI->hasOneNonDBGUse(Reg))
  1308. return false;
  1309. // Give up if the reccurrence chain length is longer than the limit.
  1310. if (RC.size() >= MaxRecurrenceChain)
  1311. return false;
  1312. MachineInstr &MI = *(MRI->use_instr_nodbg_begin(Reg));
  1313. unsigned Idx = MI.findRegisterUseOperandIdx(Reg);
  1314. // Only interested in recurrences whose instructions have only one def, which
  1315. // is a virtual register.
  1316. if (MI.getDesc().getNumDefs() != 1)
  1317. return false;
  1318. MachineOperand &DefOp = MI.getOperand(0);
  1319. if (!isVirtualRegisterOperand(DefOp))
  1320. return false;
  1321. // Check if def operand of MI is tied to any use operand. We are only
  1322. // interested in the case that all the instructions in the recurrence chain
  1323. // have there def operand tied with one of the use operand.
  1324. unsigned TiedUseIdx;
  1325. if (!MI.isRegTiedToUseOperand(0, &TiedUseIdx))
  1326. return false;
  1327. if (Idx == TiedUseIdx) {
  1328. RC.push_back(RecurrenceInstr(&MI));
  1329. return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC);
  1330. } else {
  1331. // If Idx is not TiedUseIdx, check if Idx is commutable with TiedUseIdx.
  1332. unsigned CommIdx = TargetInstrInfo::CommuteAnyOperandIndex;
  1333. if (TII->findCommutedOpIndices(MI, Idx, CommIdx) && CommIdx == TiedUseIdx) {
  1334. RC.push_back(RecurrenceInstr(&MI, Idx, CommIdx));
  1335. return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC);
  1336. }
  1337. }
  1338. return false;
  1339. }
  1340. /// Phi instructions will eventually be lowered to copy instructions.
  1341. /// If phi is in a loop header, a recurrence may formulated around the source
  1342. /// and destination of the phi. For such case commuting operands of the
  1343. /// instructions in the recurrence may enable coalescing of the copy instruction
  1344. /// generated from the phi. For example, if there is a recurrence of
  1345. ///
  1346. /// LoopHeader:
  1347. /// %1 = phi(%0, %100)
  1348. /// LoopLatch:
  1349. /// %0<def, tied1> = ADD %2<def, tied0>, %1
  1350. ///
  1351. /// , the fact that %0 and %2 are in the same tied operands set makes
  1352. /// the coalescing of copy instruction generated from the phi in
  1353. /// LoopHeader(i.e. %1 = COPY %0) impossible, because %1 and
  1354. /// %2 have overlapping live range. This introduces additional move
  1355. /// instruction to the final assembly. However, if we commute %2 and
  1356. /// %1 of ADD instruction, the redundant move instruction can be
  1357. /// avoided.
  1358. bool PeepholeOptimizer::optimizeRecurrence(MachineInstr &PHI) {
  1359. SmallSet<unsigned, 2> TargetRegs;
  1360. for (unsigned Idx = 1; Idx < PHI.getNumOperands(); Idx += 2) {
  1361. MachineOperand &MO = PHI.getOperand(Idx);
  1362. assert(isVirtualRegisterOperand(MO) && "Invalid PHI instruction");
  1363. TargetRegs.insert(MO.getReg());
  1364. }
  1365. bool Changed = false;
  1366. RecurrenceCycle RC;
  1367. if (findTargetRecurrence(PHI.getOperand(0).getReg(), TargetRegs, RC)) {
  1368. // Commutes operands of instructions in RC if necessary so that the copy to
  1369. // be generated from PHI can be coalesced.
  1370. LLVM_DEBUG(dbgs() << "Optimize recurrence chain from " << PHI);
  1371. for (auto &RI : RC) {
  1372. LLVM_DEBUG(dbgs() << "\tInst: " << *(RI.getMI()));
  1373. auto CP = RI.getCommutePair();
  1374. if (CP) {
  1375. Changed = true;
  1376. TII->commuteInstruction(*(RI.getMI()), false, (*CP).first,
  1377. (*CP).second);
  1378. LLVM_DEBUG(dbgs() << "\t\tCommuted: " << *(RI.getMI()));
  1379. }
  1380. }
  1381. }
  1382. return Changed;
  1383. }
  1384. bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
  1385. if (skipFunction(MF.getFunction()))
  1386. return false;
  1387. LLVM_DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
  1388. LLVM_DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
  1389. if (DisablePeephole)
  1390. return false;
  1391. TII = MF.getSubtarget().getInstrInfo();
  1392. TRI = MF.getSubtarget().getRegisterInfo();
  1393. MRI = &MF.getRegInfo();
  1394. DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
  1395. MLI = &getAnalysis<MachineLoopInfo>();
  1396. bool Changed = false;
  1397. for (MachineBasicBlock &MBB : MF) {
  1398. bool SeenMoveImm = false;
  1399. // During this forward scan, at some point it needs to answer the question
  1400. // "given a pointer to an MI in the current BB, is it located before or
  1401. // after the current instruction".
  1402. // To perform this, the following set keeps track of the MIs already seen
  1403. // during the scan, if a MI is not in the set, it is assumed to be located
  1404. // after. Newly created MIs have to be inserted in the set as well.
  1405. SmallPtrSet<MachineInstr*, 16> LocalMIs;
  1406. SmallSet<unsigned, 4> ImmDefRegs;
  1407. DenseMap<unsigned, MachineInstr*> ImmDefMIs;
  1408. SmallSet<unsigned, 16> FoldAsLoadDefCandidates;
  1409. // Track when a non-allocatable physical register is copied to a virtual
  1410. // register so that useless moves can be removed.
  1411. //
  1412. // %physreg is the map index; MI is the last valid `%vreg = COPY %physreg`
  1413. // without any intervening re-definition of %physreg.
  1414. DenseMap<unsigned, MachineInstr *> NAPhysToVirtMIs;
  1415. // Set of virtual registers that are copied from.
  1416. SmallSet<unsigned, 4> CopySrcRegs;
  1417. DenseMap<unsigned, MachineInstr *> CopySrcMIs;
  1418. bool IsLoopHeader = MLI->isLoopHeader(&MBB);
  1419. for (MachineBasicBlock::iterator MII = MBB.begin(), MIE = MBB.end();
  1420. MII != MIE; ) {
  1421. MachineInstr *MI = &*MII;
  1422. // We may be erasing MI below, increment MII now.
  1423. ++MII;
  1424. LocalMIs.insert(MI);
  1425. // Skip debug instructions. They should not affect this peephole optimization.
  1426. if (MI->isDebugInstr())
  1427. continue;
  1428. if (MI->isPosition())
  1429. continue;
  1430. if (IsLoopHeader && MI->isPHI()) {
  1431. if (optimizeRecurrence(*MI)) {
  1432. Changed = true;
  1433. continue;
  1434. }
  1435. }
  1436. if (!MI->isCopy()) {
  1437. for (const MachineOperand &MO : MI->operands()) {
  1438. // Visit all operands: definitions can be implicit or explicit.
  1439. if (MO.isReg()) {
  1440. Register Reg = MO.getReg();
  1441. if (MO.isDef() && isNAPhysCopy(Reg)) {
  1442. const auto &Def = NAPhysToVirtMIs.find(Reg);
  1443. if (Def != NAPhysToVirtMIs.end()) {
  1444. // A new definition of the non-allocatable physical register
  1445. // invalidates previous copies.
  1446. LLVM_DEBUG(dbgs()
  1447. << "NAPhysCopy: invalidating because of " << *MI);
  1448. NAPhysToVirtMIs.erase(Def);
  1449. }
  1450. }
  1451. } else if (MO.isRegMask()) {
  1452. const uint32_t *RegMask = MO.getRegMask();
  1453. for (auto &RegMI : NAPhysToVirtMIs) {
  1454. unsigned Def = RegMI.first;
  1455. if (MachineOperand::clobbersPhysReg(RegMask, Def)) {
  1456. LLVM_DEBUG(dbgs()
  1457. << "NAPhysCopy: invalidating because of " << *MI);
  1458. NAPhysToVirtMIs.erase(Def);
  1459. }
  1460. }
  1461. }
  1462. }
  1463. }
  1464. if (MI->isImplicitDef() || MI->isKill())
  1465. continue;
  1466. if (MI->isInlineAsm() || MI->hasUnmodeledSideEffects()) {
  1467. // Blow away all non-allocatable physical registers knowledge since we
  1468. // don't know what's correct anymore.
  1469. //
  1470. // FIXME: handle explicit asm clobbers.
  1471. LLVM_DEBUG(dbgs() << "NAPhysCopy: blowing away all info due to "
  1472. << *MI);
  1473. NAPhysToVirtMIs.clear();
  1474. }
  1475. if ((isUncoalescableCopy(*MI) &&
  1476. optimizeUncoalescableCopy(*MI, LocalMIs)) ||
  1477. (MI->isCompare() && optimizeCmpInstr(*MI)) ||
  1478. (MI->isSelect() && optimizeSelect(*MI, LocalMIs))) {
  1479. // MI is deleted.
  1480. LocalMIs.erase(MI);
  1481. Changed = true;
  1482. continue;
  1483. }
  1484. if (MI->isConditionalBranch() && optimizeCondBranch(*MI)) {
  1485. Changed = true;
  1486. continue;
  1487. }
  1488. if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(*MI)) {
  1489. // MI is just rewritten.
  1490. Changed = true;
  1491. continue;
  1492. }
  1493. if (MI->isCopy() &&
  1494. (foldRedundantCopy(*MI, CopySrcRegs, CopySrcMIs) ||
  1495. foldRedundantNAPhysCopy(*MI, NAPhysToVirtMIs))) {
  1496. LocalMIs.erase(MI);
  1497. MI->eraseFromParent();
  1498. Changed = true;
  1499. continue;
  1500. }
  1501. if (isMoveImmediate(*MI, ImmDefRegs, ImmDefMIs)) {
  1502. SeenMoveImm = true;
  1503. } else {
  1504. Changed |= optimizeExtInstr(*MI, MBB, LocalMIs);
  1505. // optimizeExtInstr might have created new instructions after MI
  1506. // and before the already incremented MII. Adjust MII so that the
  1507. // next iteration sees the new instructions.
  1508. MII = MI;
  1509. ++MII;
  1510. if (SeenMoveImm)
  1511. Changed |= foldImmediate(*MI, ImmDefRegs, ImmDefMIs);
  1512. }
  1513. // Check whether MI is a load candidate for folding into a later
  1514. // instruction. If MI is not a candidate, check whether we can fold an
  1515. // earlier load into MI.
  1516. if (!isLoadFoldable(*MI, FoldAsLoadDefCandidates) &&
  1517. !FoldAsLoadDefCandidates.empty()) {
  1518. // We visit each operand even after successfully folding a previous
  1519. // one. This allows us to fold multiple loads into a single
  1520. // instruction. We do assume that optimizeLoadInstr doesn't insert
  1521. // foldable uses earlier in the argument list. Since we don't restart
  1522. // iteration, we'd miss such cases.
  1523. const MCInstrDesc &MIDesc = MI->getDesc();
  1524. for (unsigned i = MIDesc.getNumDefs(); i != MI->getNumOperands();
  1525. ++i) {
  1526. const MachineOperand &MOp = MI->getOperand(i);
  1527. if (!MOp.isReg())
  1528. continue;
  1529. unsigned FoldAsLoadDefReg = MOp.getReg();
  1530. if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
  1531. // We need to fold load after optimizeCmpInstr, since
  1532. // optimizeCmpInstr can enable folding by converting SUB to CMP.
  1533. // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
  1534. // we need it for markUsesInDebugValueAsUndef().
  1535. unsigned FoldedReg = FoldAsLoadDefReg;
  1536. MachineInstr *DefMI = nullptr;
  1537. if (MachineInstr *FoldMI =
  1538. TII->optimizeLoadInstr(*MI, MRI, FoldAsLoadDefReg, DefMI)) {
  1539. // Update LocalMIs since we replaced MI with FoldMI and deleted
  1540. // DefMI.
  1541. LLVM_DEBUG(dbgs() << "Replacing: " << *MI);
  1542. LLVM_DEBUG(dbgs() << " With: " << *FoldMI);
  1543. LocalMIs.erase(MI);
  1544. LocalMIs.erase(DefMI);
  1545. LocalMIs.insert(FoldMI);
  1546. if (MI->isCall())
  1547. MI->getMF()->updateCallSiteInfo(MI, FoldMI);
  1548. MI->eraseFromParent();
  1549. DefMI->eraseFromParent();
  1550. MRI->markUsesInDebugValueAsUndef(FoldedReg);
  1551. FoldAsLoadDefCandidates.erase(FoldedReg);
  1552. ++NumLoadFold;
  1553. // MI is replaced with FoldMI so we can continue trying to fold
  1554. Changed = true;
  1555. MI = FoldMI;
  1556. }
  1557. }
  1558. }
  1559. }
  1560. // If we run into an instruction we can't fold across, discard
  1561. // the load candidates. Note: We might be able to fold *into* this
  1562. // instruction, so this needs to be after the folding logic.
  1563. if (MI->isLoadFoldBarrier()) {
  1564. LLVM_DEBUG(dbgs() << "Encountered load fold barrier on " << *MI);
  1565. FoldAsLoadDefCandidates.clear();
  1566. }
  1567. }
  1568. }
  1569. return Changed;
  1570. }
  1571. ValueTrackerResult ValueTracker::getNextSourceFromCopy() {
  1572. assert(Def->isCopy() && "Invalid definition");
  1573. // Copy instruction are supposed to be: Def = Src.
  1574. // If someone breaks this assumption, bad things will happen everywhere.
  1575. // There may be implicit uses preventing the copy to be moved across
  1576. // some target specific register definitions
  1577. assert(Def->getNumOperands() - Def->getNumImplicitOperands() == 2 &&
  1578. "Invalid number of operands");
  1579. assert(!Def->hasImplicitDef() && "Only implicit uses are allowed");
  1580. if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
  1581. // If we look for a different subreg, it means we want a subreg of src.
  1582. // Bails as we do not support composing subregs yet.
  1583. return ValueTrackerResult();
  1584. // Otherwise, we want the whole source.
  1585. const MachineOperand &Src = Def->getOperand(1);
  1586. if (Src.isUndef())
  1587. return ValueTrackerResult();
  1588. return ValueTrackerResult(Src.getReg(), Src.getSubReg());
  1589. }
  1590. ValueTrackerResult ValueTracker::getNextSourceFromBitcast() {
  1591. assert(Def->isBitcast() && "Invalid definition");
  1592. // Bail if there are effects that a plain copy will not expose.
  1593. if (Def->mayRaiseFPException() || Def->hasUnmodeledSideEffects())
  1594. return ValueTrackerResult();
  1595. // Bitcasts with more than one def are not supported.
  1596. if (Def->getDesc().getNumDefs() != 1)
  1597. return ValueTrackerResult();
  1598. const MachineOperand DefOp = Def->getOperand(DefIdx);
  1599. if (DefOp.getSubReg() != DefSubReg)
  1600. // If we look for a different subreg, it means we want a subreg of the src.
  1601. // Bails as we do not support composing subregs yet.
  1602. return ValueTrackerResult();
  1603. unsigned SrcIdx = Def->getNumOperands();
  1604. for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
  1605. ++OpIdx) {
  1606. const MachineOperand &MO = Def->getOperand(OpIdx);
  1607. if (!MO.isReg() || !MO.getReg())
  1608. continue;
  1609. // Ignore dead implicit defs.
  1610. if (MO.isImplicit() && MO.isDead())
  1611. continue;
  1612. assert(!MO.isDef() && "We should have skipped all the definitions by now");
  1613. if (SrcIdx != EndOpIdx)
  1614. // Multiple sources?
  1615. return ValueTrackerResult();
  1616. SrcIdx = OpIdx;
  1617. }
  1618. // In some rare case, Def has no input, SrcIdx is out of bound,
  1619. // getOperand(SrcIdx) will fail below.
  1620. if (SrcIdx >= Def->getNumOperands())
  1621. return ValueTrackerResult();
  1622. // Stop when any user of the bitcast is a SUBREG_TO_REG, replacing with a COPY
  1623. // will break the assumed guarantees for the upper bits.
  1624. for (const MachineInstr &UseMI : MRI.use_nodbg_instructions(DefOp.getReg())) {
  1625. if (UseMI.isSubregToReg())
  1626. return ValueTrackerResult();
  1627. }
  1628. const MachineOperand &Src = Def->getOperand(SrcIdx);
  1629. if (Src.isUndef())
  1630. return ValueTrackerResult();
  1631. return ValueTrackerResult(Src.getReg(), Src.getSubReg());
  1632. }
  1633. ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() {
  1634. assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
  1635. "Invalid definition");
  1636. if (Def->getOperand(DefIdx).getSubReg())
  1637. // If we are composing subregs, bail out.
  1638. // The case we are checking is Def.<subreg> = REG_SEQUENCE.
  1639. // This should almost never happen as the SSA property is tracked at
  1640. // the register level (as opposed to the subreg level).
  1641. // I.e.,
  1642. // Def.sub0 =
  1643. // Def.sub1 =
  1644. // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
  1645. // Def. Thus, it must not be generated.
  1646. // However, some code could theoretically generates a single
  1647. // Def.sub0 (i.e, not defining the other subregs) and we would
  1648. // have this case.
  1649. // If we can ascertain (or force) that this never happens, we could
  1650. // turn that into an assertion.
  1651. return ValueTrackerResult();
  1652. if (!TII)
  1653. // We could handle the REG_SEQUENCE here, but we do not want to
  1654. // duplicate the code from the generic TII.
  1655. return ValueTrackerResult();
  1656. SmallVector<RegSubRegPairAndIdx, 8> RegSeqInputRegs;
  1657. if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
  1658. return ValueTrackerResult();
  1659. // We are looking at:
  1660. // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
  1661. // Check if one of the operand defines the subreg we are interested in.
  1662. for (const RegSubRegPairAndIdx &RegSeqInput : RegSeqInputRegs) {
  1663. if (RegSeqInput.SubIdx == DefSubReg)
  1664. return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg);
  1665. }
  1666. // If the subreg we are tracking is super-defined by another subreg,
  1667. // we could follow this value. However, this would require to compose
  1668. // the subreg and we do not do that for now.
  1669. return ValueTrackerResult();
  1670. }
  1671. ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() {
  1672. assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
  1673. "Invalid definition");
  1674. if (Def->getOperand(DefIdx).getSubReg())
  1675. // If we are composing subreg, bail out.
  1676. // Same remark as getNextSourceFromRegSequence.
  1677. // I.e., this may be turned into an assert.
  1678. return ValueTrackerResult();
  1679. if (!TII)
  1680. // We could handle the REG_SEQUENCE here, but we do not want to
  1681. // duplicate the code from the generic TII.
  1682. return ValueTrackerResult();
  1683. RegSubRegPair BaseReg;
  1684. RegSubRegPairAndIdx InsertedReg;
  1685. if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
  1686. return ValueTrackerResult();
  1687. // We are looking at:
  1688. // Def = INSERT_SUBREG v0, v1, sub1
  1689. // There are two cases:
  1690. // 1. DefSubReg == sub1, get v1.
  1691. // 2. DefSubReg != sub1, the value may be available through v0.
  1692. // #1 Check if the inserted register matches the required sub index.
  1693. if (InsertedReg.SubIdx == DefSubReg) {
  1694. return ValueTrackerResult(InsertedReg.Reg, InsertedReg.SubReg);
  1695. }
  1696. // #2 Otherwise, if the sub register we are looking for is not partial
  1697. // defined by the inserted element, we can look through the main
  1698. // register (v0).
  1699. const MachineOperand &MODef = Def->getOperand(DefIdx);
  1700. // If the result register (Def) and the base register (v0) do not
  1701. // have the same register class or if we have to compose
  1702. // subregisters, bail out.
  1703. if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
  1704. BaseReg.SubReg)
  1705. return ValueTrackerResult();
  1706. // Get the TRI and check if the inserted sub-register overlaps with the
  1707. // sub-register we are tracking.
  1708. const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
  1709. if (!TRI ||
  1710. !(TRI->getSubRegIndexLaneMask(DefSubReg) &
  1711. TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)).none())
  1712. return ValueTrackerResult();
  1713. // At this point, the value is available in v0 via the same subreg
  1714. // we used for Def.
  1715. return ValueTrackerResult(BaseReg.Reg, DefSubReg);
  1716. }
  1717. ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() {
  1718. assert((Def->isExtractSubreg() ||
  1719. Def->isExtractSubregLike()) && "Invalid definition");
  1720. // We are looking at:
  1721. // Def = EXTRACT_SUBREG v0, sub0
  1722. // Bail if we have to compose sub registers.
  1723. // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
  1724. if (DefSubReg)
  1725. return ValueTrackerResult();
  1726. if (!TII)
  1727. // We could handle the EXTRACT_SUBREG here, but we do not want to
  1728. // duplicate the code from the generic TII.
  1729. return ValueTrackerResult();
  1730. RegSubRegPairAndIdx ExtractSubregInputReg;
  1731. if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
  1732. return ValueTrackerResult();
  1733. // Bail if we have to compose sub registers.
  1734. // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
  1735. if (ExtractSubregInputReg.SubReg)
  1736. return ValueTrackerResult();
  1737. // Otherwise, the value is available in the v0.sub0.
  1738. return ValueTrackerResult(ExtractSubregInputReg.Reg,
  1739. ExtractSubregInputReg.SubIdx);
  1740. }
  1741. ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() {
  1742. assert(Def->isSubregToReg() && "Invalid definition");
  1743. // We are looking at:
  1744. // Def = SUBREG_TO_REG Imm, v0, sub0
  1745. // Bail if we have to compose sub registers.
  1746. // If DefSubReg != sub0, we would have to check that all the bits
  1747. // we track are included in sub0 and if yes, we would have to
  1748. // determine the right subreg in v0.
  1749. if (DefSubReg != Def->getOperand(3).getImm())
  1750. return ValueTrackerResult();
  1751. // Bail if we have to compose sub registers.
  1752. // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
  1753. if (Def->getOperand(2).getSubReg())
  1754. return ValueTrackerResult();
  1755. return ValueTrackerResult(Def->getOperand(2).getReg(),
  1756. Def->getOperand(3).getImm());
  1757. }
  1758. /// Explore each PHI incoming operand and return its sources.
  1759. ValueTrackerResult ValueTracker::getNextSourceFromPHI() {
  1760. assert(Def->isPHI() && "Invalid definition");
  1761. ValueTrackerResult Res;
  1762. // If we look for a different subreg, bail as we do not support composing
  1763. // subregs yet.
  1764. if (Def->getOperand(0).getSubReg() != DefSubReg)
  1765. return ValueTrackerResult();
  1766. // Return all register sources for PHI instructions.
  1767. for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) {
  1768. const MachineOperand &MO = Def->getOperand(i);
  1769. assert(MO.isReg() && "Invalid PHI instruction");
  1770. // We have no code to deal with undef operands. They shouldn't happen in
  1771. // normal programs anyway.
  1772. if (MO.isUndef())
  1773. return ValueTrackerResult();
  1774. Res.addSource(MO.getReg(), MO.getSubReg());
  1775. }
  1776. return Res;
  1777. }
  1778. ValueTrackerResult ValueTracker::getNextSourceImpl() {
  1779. assert(Def && "This method needs a valid definition");
  1780. assert(((Def->getOperand(DefIdx).isDef() &&
  1781. (DefIdx < Def->getDesc().getNumDefs() ||
  1782. Def->getDesc().isVariadic())) ||
  1783. Def->getOperand(DefIdx).isImplicit()) &&
  1784. "Invalid DefIdx");
  1785. if (Def->isCopy())
  1786. return getNextSourceFromCopy();
  1787. if (Def->isBitcast())
  1788. return getNextSourceFromBitcast();
  1789. // All the remaining cases involve "complex" instructions.
  1790. // Bail if we did not ask for the advanced tracking.
  1791. if (DisableAdvCopyOpt)
  1792. return ValueTrackerResult();
  1793. if (Def->isRegSequence() || Def->isRegSequenceLike())
  1794. return getNextSourceFromRegSequence();
  1795. if (Def->isInsertSubreg() || Def->isInsertSubregLike())
  1796. return getNextSourceFromInsertSubreg();
  1797. if (Def->isExtractSubreg() || Def->isExtractSubregLike())
  1798. return getNextSourceFromExtractSubreg();
  1799. if (Def->isSubregToReg())
  1800. return getNextSourceFromSubregToReg();
  1801. if (Def->isPHI())
  1802. return getNextSourceFromPHI();
  1803. return ValueTrackerResult();
  1804. }
  1805. ValueTrackerResult ValueTracker::getNextSource() {
  1806. // If we reach a point where we cannot move up in the use-def chain,
  1807. // there is nothing we can get.
  1808. if (!Def)
  1809. return ValueTrackerResult();
  1810. ValueTrackerResult Res = getNextSourceImpl();
  1811. if (Res.isValid()) {
  1812. // Update definition, definition index, and subregister for the
  1813. // next call of getNextSource.
  1814. // Update the current register.
  1815. bool OneRegSrc = Res.getNumSources() == 1;
  1816. if (OneRegSrc)
  1817. Reg = Res.getSrcReg(0);
  1818. // Update the result before moving up in the use-def chain
  1819. // with the instruction containing the last found sources.
  1820. Res.setInst(Def);
  1821. // If we can still move up in the use-def chain, move to the next
  1822. // definition.
  1823. if (!Register::isPhysicalRegister(Reg) && OneRegSrc) {
  1824. MachineRegisterInfo::def_iterator DI = MRI.def_begin(Reg);
  1825. if (DI != MRI.def_end()) {
  1826. Def = DI->getParent();
  1827. DefIdx = DI.getOperandNo();
  1828. DefSubReg = Res.getSrcSubReg(0);
  1829. } else {
  1830. Def = nullptr;
  1831. }
  1832. return Res;
  1833. }
  1834. }
  1835. // If we end up here, this means we will not be able to find another source
  1836. // for the next iteration. Make sure any new call to getNextSource bails out
  1837. // early by cutting the use-def chain.
  1838. Def = nullptr;
  1839. return Res;
  1840. }