PeepholeOptimizer.cpp 79 KB

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