PeepholeOptimizer.cpp 78 KB

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